You're Invited:Meet the Socket Team at RSAC and BSidesSF 2026, March 23–26.RSVP
Socket
Book a DemoSign in
Socket

vercel

Package Overview
Dependencies
Maintainers
3
Versions
932
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

vercel - npm Package Compare versions

Comparing version
50.31.3
to
50.32.1
dist/chunks/chunk-2NPVSUA5.js

Sorry, the diff of this file is too big to display

+91
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
require_lib
} from "./chunk-QNEHY3TU.js";
import {
packageName
} from "./chunk-ZLCMHY2G.js";
import {
__toESM
} from "./chunk-TZ2YI2VH.js";
// src/util/get-update-command.ts
var import_fs_extra = __toESM(require_lib(), 1);
import { sep, dirname, join, resolve } from "path";
import { scanParentDirs } from "@vercel/build-utils";
async function getConfigPrefix() {
const paths = [
process.env.npm_config_userconfig || process.env.NPM_CONFIG_USERCONFIG,
join(process.env.HOME || "/", ".npmrc"),
process.env.npm_config_globalconfig || process.env.NPM_CONFIG_GLOBALCONFIG
].filter(Boolean);
for (const configPath of paths) {
if (!configPath) {
continue;
}
const content = await (0, import_fs_extra.readFile)(configPath).then((buffer) => buffer.toString()).catch(() => null);
if (content) {
const [prefix] = content.split("\n").map((line) => line && line.trim()).filter((line) => line && line.startsWith("prefix")).map((line) => line.slice(line.indexOf("=") + 1).trim());
if (prefix) {
return prefix;
}
}
}
return null;
}
async function isGlobal() {
try {
if (dirname(process.argv[0]) === dirname(process.argv[1])) {
return true;
}
const isWindows = process.platform === "win32";
const defaultPath = isWindows ? process.env.APPDATA : "/usr/local/lib";
const installPath = await (0, import_fs_extra.realpath)(resolve(__dirname));
if (installPath.includes(["", "yarn", "global", "node_modules", ""].join(sep))) {
return true;
}
if (installPath.includes(["", "pnpm", "global", ""].join(sep))) {
return true;
}
if (installPath.includes(["", "fnm", "node-versions", ""].join(sep))) {
return true;
}
const prefixPath = process.env.PREFIX || process.env.npm_config_prefix || process.env.NPM_CONFIG_PREFIX || await getConfigPrefix() || defaultPath;
if (!prefixPath) {
return true;
}
return installPath.startsWith(await (0, import_fs_extra.realpath)(prefixPath));
} catch (_) {
return true;
}
}
async function getUpdateCommand() {
const pkgAndVersion = `${packageName}@latest`;
const entrypoint = await (0, import_fs_extra.realpath)(process.argv[1]);
let { cliType, lockfilePath } = await scanParentDirs(
dirname(dirname(entrypoint))
);
if (!lockfilePath) {
cliType = "npm";
}
const yarn = cliType === "yarn";
let install = yarn ? "add" : "i";
if (await isGlobal()) {
if (yarn) {
install = "global add";
} else {
install = "i -g";
}
}
return `${cliType} ${install} ${pkgAndVersion}`;
}
export {
isGlobal,
getUpdateCommand
};

Sorry, the diff of this file is too big to display

import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
setupAndLink
} from "./chunk-MHB67DKL.js";
import {
buildCommandWithYes,
getLinkedProject,
outputActionRequired,
param,
resolveProjectCwd
} from "./chunk-QNEHY3TU.js";
import {
getCommandName,
getCommandNamePlain
} from "./chunk-ZLCMHY2G.js";
import {
output_manager_default
} from "./chunk-FDJURQMQ.js";
// src/util/link/ensure-link.ts
async function ensureLink(commandName, client, cwd, opts = {}) {
cwd = await resolveProjectCwd(cwd);
let { link } = opts;
const nonInteractive = opts.nonInteractive ?? client.nonInteractive ?? false;
opts.nonInteractive = nonInteractive;
if (!link) {
if (opts.forceDelete) {
link = { status: "not_linked", org: null, project: null };
} else {
link = await getLinkedProject(client, cwd);
}
opts.link = link;
}
if (link.status === "linked" && opts.forceDelete || link.status === "not_linked") {
link = await setupAndLink(client, cwd, opts);
if (link.status === "not_linked") {
return 0;
}
}
if (link.status === "error") {
if (link.reason === "HEADLESS") {
if (nonInteractive) {
outputActionRequired(
client,
{
status: "action_required",
reason: "confirmation_required",
message: `Command ${getCommandNamePlain(commandName)} requires confirmation. Use option --yes to confirm.`,
next: [
{
command: buildCommandWithYes(client.argv),
when: "Confirm and run"
}
]
},
link.exitCode
);
} else {
output_manager_default.error(
`Command ${getCommandName(
commandName
)} requires confirmation. Use option ${param("--yes")} to confirm.`
);
}
}
if (nonInteractive) {
process.exit(link.exitCode);
}
return link.exitCode;
}
return link;
}
export {
ensureLink
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
writeProjectSettings
} from "./chunk-6TUTMN4G.js";
import {
ensureLink
} from "./chunk-5KMQD57B.js";
import {
pullCommand
} from "./chunk-QEEF7TLY.js";
import {
help
} from "./chunk-DOBFJJLK.js";
import {
VERCEL_DIR,
VERCEL_DIR_PROJECT,
envPullCommandLogic,
humanizePath,
parseTarget
} from "./chunk-QNEHY3TU.js";
import {
TelemetryClient
} from "./chunk-XB2KZC2B.js";
import {
stamp_default
} from "./chunk-SOTR4CXR.js";
import {
getFlagsSpecification,
parseArguments,
printError
} from "./chunk-ZLCMHY2G.js";
import {
emoji,
output_manager_default,
prependEmoji
} from "./chunk-FDJURQMQ.js";
import {
require_source
} from "./chunk-S7KYDPEM.js";
import {
__toESM
} from "./chunk-TZ2YI2VH.js";
// src/commands/pull/index.ts
var import_chalk = __toESM(require_source(), 1);
import { join } from "path";
// src/util/telemetry/commands/pull/index.ts
var PullTelemetryClient = class extends TelemetryClient {
trackCliArgumentProjectPath(value) {
if (value) {
this.trackCliArgument({
arg: "projectPath",
value: this.redactedValue
});
}
}
trackCliOptionEnvironment(environment) {
if (environment) {
this.trackCliOption({
option: "environment",
value: this.redactedTargetName(environment)
});
}
}
trackCliOptionGitBranch(gitBranch) {
if (gitBranch) {
this.trackCliOption({
option: "git-branch",
value: this.redactedValue
});
}
}
trackCliFlagProd(isProduction) {
if (isProduction) {
this.trackCliFlag("prod");
}
}
trackCliFlagYes(yes) {
if (yes) {
this.trackCliFlag("yes");
}
}
};
// src/commands/pull/index.ts
async function pullAllEnvFiles(environment, client, link, flags, cwd) {
const environmentFile = `.env.${environment}.local`;
await envPullCommandLogic(
client,
join(".vercel", environmentFile),
!!flags["--yes"],
environment,
link,
flags["--git-branch"],
cwd,
"vercel-cli:pull"
);
return 0;
}
async function main(client) {
let parsedArgs = null;
const flagsSpecification = getFlagsSpecification(pullCommand.options);
try {
parsedArgs = parseArguments(client.argv.slice(2), flagsSpecification);
} catch (error) {
printError(error);
return 1;
}
const telemetryClient = new PullTelemetryClient({
opts: {
store: client.telemetryEventStore
}
});
if (parsedArgs.flags["--help"]) {
telemetryClient.trackCliFlagHelp("pull");
output_manager_default.print(help(pullCommand, { columns: client.stderr.columns }));
return 2;
}
const cwd = parsedArgs.args[1] || client.cwd;
const autoConfirm = Boolean(parsedArgs.flags["--yes"]);
const isProduction = Boolean(parsedArgs.flags["--prod"]);
const environment = parseTarget({
flagName: "environment",
flags: parsedArgs.flags
}) || "development";
telemetryClient.trackCliArgumentProjectPath(parsedArgs.args[1]);
telemetryClient.trackCliFlagYes(autoConfirm);
telemetryClient.trackCliFlagProd(isProduction);
telemetryClient.trackCliOptionGitBranch(parsedArgs.flags["--git-branch"]);
telemetryClient.trackCliOptionEnvironment(parsedArgs.flags["--environment"]);
const returnCode = await pullCommandLogic(
client,
cwd,
autoConfirm,
environment,
parsedArgs.flags
);
return returnCode;
}
async function pullCommandLogic(client, cwd, autoConfirm, environment, flags) {
const link = await ensureLink("pull", client, cwd, {
autoConfirm,
pullEnv: false
});
if (typeof link === "number") {
return link;
}
const { project, org, repoRoot } = link;
let currentDirectory;
if (repoRoot) {
currentDirectory = join(repoRoot, project.rootDirectory || "");
} else {
currentDirectory = cwd;
}
client.config.currentTeam = org.type === "team" ? org.id : void 0;
const pullResultCode = await pullAllEnvFiles(
environment,
client,
link,
flags,
currentDirectory
);
if (pullResultCode !== 0) {
return pullResultCode;
}
output_manager_default.print("\n");
output_manager_default.log("Downloading project settings");
const isRepoLinked = typeof repoRoot === "string";
await writeProjectSettings(currentDirectory, project, org, isRepoLinked);
const settingsStamp = stamp_default();
output_manager_default.print(
`${prependEmoji(
`Downloaded project settings to ${import_chalk.default.bold(
humanizePath(join(currentDirectory, VERCEL_DIR, VERCEL_DIR_PROJECT))
)} ${import_chalk.default.gray(settingsStamp())}`,
emoji("success")
)}
`
);
return 0;
}
export {
main,
pullCommandLogic
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
VERCEL_DIR
} from "./chunk-QNEHY3TU.js";
import {
ConflictingConfigFiles
} from "./chunk-ZLCMHY2G.js";
import {
output_manager_default
} from "./chunk-FDJURQMQ.js";
import {
__commonJS,
__require,
__toESM
} from "./chunk-TZ2YI2VH.js";
// ../../node_modules/.pnpm/dotenv@4.0.0/node_modules/dotenv/lib/main.js
var require_main = __commonJS({
"../../node_modules/.pnpm/dotenv@4.0.0/node_modules/dotenv/lib/main.js"(exports, module) {
"use strict";
var fs = __require("fs");
function parse(src) {
var obj = {};
src.toString().split("\n").forEach(function(line) {
var keyValueArr = line.match(/^\s*([\w\.\-]+)\s*=\s*(.*)?\s*$/);
if (keyValueArr != null) {
var key = keyValueArr[1];
var value = keyValueArr[2] ? keyValueArr[2] : "";
var len = value ? value.length : 0;
if (len > 0 && value.charAt(0) === '"' && value.charAt(len - 1) === '"') {
value = value.replace(/\\n/gm, "\n");
}
value = value.replace(/(^['"]|['"]$)/g, "").trim();
obj[key] = value;
}
});
return obj;
}
function config(options) {
var path = ".env";
var encoding = "utf8";
if (options) {
if (options.path) {
path = options.path;
}
if (options.encoding) {
encoding = options.encoding;
}
}
try {
var parsedObj = parse(fs.readFileSync(path, { encoding }));
Object.keys(parsedObj).forEach(function(key) {
process.env[key] = process.env[key] || parsedObj[key];
});
return { parsed: parsedObj };
} catch (e) {
return { error: e };
}
}
module.exports.config = config;
module.exports.load = config;
module.exports.parse = parse;
}
});
// src/util/compile-vercel-config.ts
var import_dotenv = __toESM(require_main(), 1);
import { mkdir, writeFile, unlink, access } from "fs/promises";
import { join, basename } from "path";
import { fork } from "child_process";
import { NowBuildError } from "@vercel/build-utils";
function toRouteFormat(item) {
if ("src" in item)
return item;
const { source, destination, headers, statusCode, permanent, ...rest } = item;
const route = {
src: source,
...rest
};
if (destination)
route.dest = destination;
if (headers)
route.headers = Object.fromEntries(headers.map((h) => [h.key, h.value]));
if (statusCode !== void 0) {
route.status = statusCode;
} else if (permanent !== void 0) {
route.status = permanent ? 308 : 307;
}
return route;
}
function normalizeConfig(config) {
const normalized = { ...config };
const { rewrites, redirects, headers } = normalized;
let allRoutes = normalized.routes || [];
const hasRoutes = allRoutes.length > 0;
const hasRewrites = (rewrites?.length ?? 0) > 0;
const hasRedirects = (redirects?.length ?? 0) > 0;
const hasHeaders = (headers?.length ?? 0) > 0;
function hasRouteFormat(items) {
return items?.some((item) => "src" in item) ?? false;
}
if (hasRoutes && (hasRewrites || hasRedirects || hasHeaders)) {
return normalized;
}
const shouldConvertRewrites = hasRewrites && hasRouteFormat(rewrites);
const shouldConvertRedirects = hasRedirects && hasRouteFormat(redirects);
const shouldConvertHeaders = hasHeaders && hasRouteFormat(headers);
const someWillConvert = shouldConvertRewrites || shouldConvertRedirects || shouldConvertHeaders;
const someWontConvert = hasRewrites && !shouldConvertRewrites || hasRedirects && !shouldConvertRedirects || hasHeaders && !shouldConvertHeaders;
if (someWillConvert && someWontConvert) {
throw new NowBuildError({
code: "INVALID_VERCEL_CONFIG",
message: "Transforms (e.g., requestHeaders) require the `routes` format, which cannot be used alongside `rewrites`, `redirects`, or `headers`. Move everything into the `routes` array instead.",
link: "https://vercel.com/docs/projects/project-configuration#routes"
});
}
if (rewrites && shouldConvertRewrites) {
allRoutes = [...allRoutes, ...rewrites.map(toRouteFormat)];
delete normalized.rewrites;
}
if (redirects && shouldConvertRedirects) {
allRoutes = [...allRoutes, ...redirects.map(toRouteFormat)];
delete normalized.redirects;
}
if (headers && shouldConvertHeaders) {
allRoutes = [...allRoutes, ...headers.map(toRouteFormat)];
delete normalized.headers;
}
if (allRoutes.length > 0) {
normalized.routes = allRoutes.map(toRouteFormat);
}
return normalized;
}
var VERCEL_CONFIG_EXTENSIONS = [
"ts",
"mts",
"js",
"mjs",
"cjs"
];
var DEFAULT_VERCEL_CONFIG_FILENAME = "Vercel config";
async function fileExists(filePath) {
try {
await access(filePath);
return true;
} catch {
return false;
}
}
async function findAllVercelConfigFiles(workPath) {
const foundFiles = [];
for (const ext of VERCEL_CONFIG_EXTENSIONS) {
const configPath = join(workPath, `vercel.${ext}`);
if (await fileExists(configPath)) {
foundFiles.push(configPath);
}
}
return foundFiles;
}
async function findSourceVercelConfigFile(workPath) {
for (const ext of VERCEL_CONFIG_EXTENSIONS) {
const configPath = join(workPath, `vercel.${ext}`);
if (await fileExists(configPath)) {
return basename(configPath);
}
}
return null;
}
async function findVercelConfigFile(workPath) {
const foundFiles = await findAllVercelConfigFiles(workPath);
if (foundFiles.length > 1) {
throw new ConflictingConfigFiles(
foundFiles,
"Multiple vercel config files found. Please use only one configuration file.",
"https://vercel.com/docs/projects/project-configuration"
);
}
return foundFiles[0] || null;
}
function parseConfigLoaderError(stderr) {
if (!stderr.trim()) {
return "";
}
const moduleNotFoundMatch = stderr.match(
/Error \[ERR_MODULE_NOT_FOUND\]: Cannot find package '([^']+)'/
);
if (moduleNotFoundMatch) {
const packageName = moduleNotFoundMatch[1];
return `Cannot find package '${packageName}'. Make sure it's installed in your project dependencies.`;
}
const syntaxErrorMatch = stderr.match(/SyntaxError: (.+?)(?:\n|$)/);
if (syntaxErrorMatch) {
return `Syntax error: ${syntaxErrorMatch[1]}`;
}
const errorMatch = stderr.match(
/^(?:Error|TypeError|ReferenceError): (.+?)(?:\n|$)/m
);
if (errorMatch) {
return errorMatch[1];
}
return stderr.trim();
}
async function compileVercelConfig(workPath) {
const vercelJsonPath = join(workPath, "vercel.json");
const nowJsonPath = join(workPath, "now.json");
const hasVercelJson = await fileExists(vercelJsonPath);
const hasNowJson = await fileExists(nowJsonPath);
if (hasVercelJson && hasNowJson) {
throw new ConflictingConfigFiles([vercelJsonPath, nowJsonPath]);
}
const vercelConfigPath = await findVercelConfigFile(workPath);
const vercelDir = join(workPath, VERCEL_DIR);
const compiledConfigPath = join(vercelDir, "vercel.json");
if (vercelConfigPath && hasNowJson) {
throw new ConflictingConfigFiles(
[vercelConfigPath, nowJsonPath],
`Both ${basename(vercelConfigPath)} and now.json exist in your project. Please use only one configuration method.`,
"https://vercel.com/docs/projects/project-configuration"
);
}
if (vercelConfigPath && hasVercelJson) {
throw new ConflictingConfigFiles(
[vercelConfigPath, vercelJsonPath],
`Both ${basename(vercelConfigPath)} and vercel.json exist in your project. Please use only one configuration method.`,
"https://vercel.com/docs/projects/project-configuration"
);
}
if (!vercelConfigPath) {
if (hasVercelJson) {
return {
configPath: vercelJsonPath,
wasCompiled: false
};
}
if (hasNowJson) {
return {
configPath: nowJsonPath,
wasCompiled: false
};
}
if (await fileExists(compiledConfigPath)) {
return {
configPath: compiledConfigPath,
wasCompiled: true,
sourceFile: await findSourceVercelConfigFile(workPath) ?? void 0
};
}
return {
configPath: null,
wasCompiled: false
};
}
(0, import_dotenv.config)({ path: join(workPath, ".env") });
(0, import_dotenv.config)({ path: join(workPath, ".env.local") });
const tempOutPath = join(vercelDir, "vercel-temp.mjs");
const loaderPath = join(vercelDir, "vercel-loader.mjs");
try {
const { build } = await import("esbuild");
await mkdir(vercelDir, { recursive: true });
await build({
entryPoints: [vercelConfigPath],
bundle: true,
platform: "node",
format: "esm",
outfile: tempOutPath,
packages: "external",
target: "node20",
sourcemap: "inline"
});
const loaderScript = `
import { pathToFileURL } from 'url';
const configModule = await import(pathToFileURL(process.argv[2]).href);
const config = ('default' in configModule) ? configModule.default : ('config' in configModule) ? configModule.config : configModule;
process.send(config);
`;
await writeFile(loaderPath, loaderScript, "utf-8");
const config = await new Promise((resolve, reject) => {
const child = fork(loaderPath, [tempOutPath], {
stdio: ["pipe", "pipe", "pipe", "ipc"]
});
let stderrOutput = "";
let stdoutOutput = "";
if (child.stderr) {
child.stderr.on("data", (data) => {
stderrOutput += data.toString();
});
}
if (child.stdout) {
child.stdout.on("data", (data) => {
stdoutOutput += data.toString();
});
}
const timeout = setTimeout(() => {
child.kill();
reject(new Error("Config loader timed out after 10 seconds"));
}, 1e4);
child.on("message", (message) => {
clearTimeout(timeout);
child.kill();
resolve(message);
});
child.on("error", (err) => {
clearTimeout(timeout);
reject(err);
});
child.on("exit", (code) => {
clearTimeout(timeout);
if (code !== 0) {
if (stderrOutput.trim()) {
output_manager_default.log(stderrOutput);
}
if (stdoutOutput.trim()) {
output_manager_default.log(stdoutOutput);
}
const parsedError = parseConfigLoaderError(stderrOutput);
if (parsedError) {
reject(new Error(parsedError));
} else if (stdoutOutput.trim()) {
reject(new Error(stdoutOutput.trim()));
} else {
reject(new Error(`Config loader exited with code ${code}`));
}
}
});
});
const normalizedConfig = normalizeConfig(config);
await writeFile(
compiledConfigPath,
JSON.stringify(normalizedConfig, null, 2),
"utf-8"
);
output_manager_default.debug(`Compiled ${vercelConfigPath} -> ${compiledConfigPath}`);
return {
configPath: compiledConfigPath,
wasCompiled: true,
sourceFile: await findSourceVercelConfigFile(workPath) ?? void 0
};
} catch (error) {
throw new NowBuildError({
code: error.code ?? "vercel_ts_compilation_failed",
message: `Failed to compile ${basename(vercelConfigPath)}: ${error.message}`,
link: error.link ?? "https://vercel.com/docs/projects/project-configuration"
});
} finally {
await Promise.all([
unlink(tempOutPath).catch((err) => {
if (err.code !== "ENOENT") {
output_manager_default.debug(`Failed to cleanup temp file: ${err}`);
}
}),
unlink(loaderPath).catch((err) => {
if (err.code !== "ENOENT") {
output_manager_default.debug(`Failed to cleanup loader file: ${err}`);
}
})
]);
}
}
async function getVercelConfigPath(workPath) {
const vercelJsonPath = join(workPath, "vercel.json");
const nowJsonPath = join(workPath, "now.json");
const compiledConfigPath = join(workPath, VERCEL_DIR, "vercel.json");
if (await fileExists(vercelJsonPath)) {
return vercelJsonPath;
}
if (await fileExists(nowJsonPath)) {
return nowJsonPath;
}
if (await fileExists(compiledConfigPath)) {
return compiledConfigPath;
}
return nowJsonPath;
}
export {
require_main,
normalizeConfig,
VERCEL_CONFIG_EXTENSIONS,
DEFAULT_VERCEL_CONFIG_FILENAME,
findSourceVercelConfigFile,
compileVercelConfig,
getVercelConfigPath
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
VERCEL_DIR,
VERCEL_DIR_PROJECT,
require_lib
} from "./chunk-QNEHY3TU.js";
import {
require_dist
} from "./chunk-FDJURQMQ.js";
import {
__toESM
} from "./chunk-TZ2YI2VH.js";
// src/util/projects/project-settings.ts
var import_fs_extra = __toESM(require_lib(), 1);
import { join } from "path";
var import_error_utils = __toESM(require_dist(), 1);
async function writeProjectSettings(cwd, project, org, isRepoLinked) {
let analyticsId;
if (project.analytics?.id && (!project.analytics.disabledAt || project.analytics.enabledAt && project.analytics.enabledAt > project.analytics.disabledAt)) {
analyticsId = project.analytics.id;
}
const projectLinkAndSettings = {
projectId: isRepoLinked ? void 0 : project.id,
orgId: isRepoLinked ? void 0 : org.id,
projectName: isRepoLinked ? void 0 : project.name,
settings: {
createdAt: project.createdAt,
framework: project.framework,
devCommand: project.devCommand,
installCommand: project.installCommand,
buildCommand: project.buildCommand,
outputDirectory: project.outputDirectory,
rootDirectory: project.rootDirectory,
directoryListing: project.directoryListing,
nodeVersion: project.nodeVersion,
analyticsId
}
};
const path = join(cwd, VERCEL_DIR, VERCEL_DIR_PROJECT);
return await (0, import_fs_extra.outputJSON)(path, projectLinkAndSettings, {
spaces: 2
});
}
async function readProjectSettings(vercelDir) {
try {
return JSON.parse(
await (0, import_fs_extra.readFile)(join(vercelDir, VERCEL_DIR_PROJECT), "utf8")
);
} catch (err) {
if ((0, import_error_utils.isErrnoException)(err) && err.code && ["ENOENT", "ENOTDIR"].includes(err.code)) {
return null;
}
if ((0, import_error_utils.isError)(err) && err.name === "SyntaxError") {
return null;
}
throw err;
}
}
function pickOverrides(vercelConfig) {
const overrides = {};
for (const prop of [
"buildCommand",
"devCommand",
"framework",
"ignoreCommand",
"installCommand",
"outputDirectory"
]) {
if (typeof vercelConfig[prop] !== "undefined") {
if (prop === "ignoreCommand") {
overrides.commandForIgnoringBuildStep = vercelConfig[prop];
} else {
overrides[prop] = vercelConfig[prop];
}
}
}
return overrides;
}
export {
writeProjectSettings,
readProjectSettings,
pickOverrides
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
formatCondition,
formatTransform
} from "./chunk-OJOIUL2M.js";
import {
output_manager_default
} from "./chunk-FDJURQMQ.js";
import {
require_source
} from "./chunk-S7KYDPEM.js";
import {
__toESM
} from "./chunk-TZ2YI2VH.js";
// src/util/routes/env.ts
function extractEnvVarNames(value) {
const names = /* @__PURE__ */ new Set();
for (const m of value.matchAll(/\$\{?([A-Z_][A-Z0-9_]*)\}?/g)) {
names.add(m[1]);
}
return Array.from(names);
}
function populateRouteEnv(route) {
const routeEnv = /* @__PURE__ */ new Set();
if (route.dest) {
for (const name of extractEnvVarNames(route.dest)) {
routeEnv.add(name);
}
}
if (route.headers) {
for (const value of Object.values(route.headers)) {
for (const name of extractEnvVarNames(value)) {
routeEnv.add(name);
}
}
}
route.env = routeEnv.size > 0 ? Array.from(routeEnv) : void 0;
if (route.transforms) {
for (const transform of route.transforms) {
if (transform.args) {
const argsStr = Array.isArray(transform.args) ? transform.args.join(" ") : transform.args;
const names = extractEnvVarNames(argsStr);
transform.env = names.length > 0 ? names : void 0;
}
}
}
}
// src/util/routes/generate-route.ts
async function generateRoute(client, projectId, input, options = {}) {
const { teamId } = options;
const query = new URLSearchParams();
if (teamId)
query.set("teamId", teamId);
const queryString = query.toString();
const url = `/v1/projects/${projectId}/routes/generate${queryString ? `?${queryString}` : ""}`;
return await client.fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(input)
});
}
// src/util/routes/parse-transforms.ts
function parseTransforms(values, type, op) {
return values.map((value) => parseTransform(value, type, op));
}
function parseTransform(input, type, op) {
if (op === "delete") {
const key2 = input.trim();
if (!key2) {
throw new Error("Delete operation requires a key");
}
return {
type,
op,
target: { key: key2 }
};
}
const eqIndex = input.indexOf("=");
if (eqIndex === -1) {
throw new Error(`Invalid format: "${input}". Expected format: key=value`);
}
const key = input.slice(0, eqIndex).trim();
const args = input.slice(eqIndex + 1);
if (!key) {
throw new Error("Transform key cannot be empty");
}
return {
type,
op,
target: { key },
args
};
}
function collectTransforms(flags) {
const transforms = [];
if (flags.setResponseHeader) {
transforms.push(
...parseTransforms(flags.setResponseHeader, "response.headers", "set")
);
}
if (flags.appendResponseHeader) {
transforms.push(
...parseTransforms(
flags.appendResponseHeader,
"response.headers",
"append"
)
);
}
if (flags.deleteResponseHeader) {
transforms.push(
...parseTransforms(
flags.deleteResponseHeader,
"response.headers",
"delete"
)
);
}
if (flags.setRequestHeader) {
transforms.push(
...parseTransforms(flags.setRequestHeader, "request.headers", "set")
);
}
if (flags.appendRequestHeader) {
transforms.push(
...parseTransforms(flags.appendRequestHeader, "request.headers", "append")
);
}
if (flags.deleteRequestHeader) {
transforms.push(
...parseTransforms(flags.deleteRequestHeader, "request.headers", "delete")
);
}
if (flags.setRequestQuery) {
transforms.push(
...parseTransforms(flags.setRequestQuery, "request.query", "set")
);
}
if (flags.appendRequestQuery) {
transforms.push(
...parseTransforms(flags.appendRequestQuery, "request.query", "append")
);
}
if (flags.deleteRequestQuery) {
transforms.push(
...parseTransforms(flags.deleteRequestQuery, "request.query", "delete")
);
}
return transforms;
}
function collectResponseHeaders(setHeaders) {
const headers = {};
for (const input of setHeaders) {
const eqIndex = input.indexOf("=");
if (eqIndex === -1) {
throw new Error(
`Invalid header format: "${input}". Expected format: key=value`
);
}
const key = input.slice(0, eqIndex).trim();
const value = input.slice(eqIndex + 1);
if (!key) {
throw new Error("Header key cannot be empty");
}
headers[key] = value;
}
return headers;
}
// src/util/routes/interactive.ts
var MAX_NAME_LENGTH = 256;
var MAX_DESCRIPTION_LENGTH = 1024;
var MAX_CONDITIONS = 16;
var VALID_SYNTAXES = [
"regex",
"path-to-regexp",
"equals"
];
var REDIRECT_STATUS_CODES = [301, 302, 303, 307, 308];
var VALID_ACTION_TYPES = [
"rewrite",
"redirect",
"set-status"
];
var ALL_ACTION_CHOICES = [
{ name: "Rewrite", value: "rewrite", exclusive: true },
{ name: "Redirect", value: "redirect", exclusive: true },
{ name: "Set Status Code", value: "set-status", exclusive: true },
{ name: "Response Headers", value: "response-headers" },
{ name: "Request Headers", value: "request-headers" },
{ name: "Request Query", value: "request-query" }
];
function stripQuotes(str) {
if (str.startsWith('"') && str.endsWith('"') && str.length >= 2) {
return str.slice(1, -1);
}
if (str.startsWith("'") && str.endsWith("'") && str.length >= 2) {
return str.slice(1, -1);
}
return str;
}
function extractTransformFlags(flags) {
return {
setResponseHeader: flags["--set-response-header"],
appendResponseHeader: flags["--append-response-header"],
deleteResponseHeader: flags["--delete-response-header"],
setRequestHeader: flags["--set-request-header"],
appendRequestHeader: flags["--append-request-header"],
deleteRequestHeader: flags["--delete-request-header"],
setRequestQuery: flags["--set-request-query"],
appendRequestQuery: flags["--append-request-query"],
deleteRequestQuery: flags["--delete-request-query"]
};
}
function collectHeadersAndTransforms(transformFlags) {
const headers = transformFlags.setResponseHeader ? collectResponseHeaders(transformFlags.setResponseHeader) : {};
const transforms = collectTransforms({
...transformFlags,
setResponseHeader: void 0
// Already handled in headers
});
return { headers, transforms };
}
function hasAnyTransformFlags(flags) {
const tf = extractTransformFlags(flags);
return !!(tf.setResponseHeader || tf.appendResponseHeader || tf.deleteResponseHeader || tf.setRequestHeader || tf.appendRequestHeader || tf.deleteRequestHeader || tf.setRequestQuery || tf.appendRequestQuery || tf.deleteRequestQuery);
}
function validateActionFlags(action, dest, status) {
if (!action) {
if (dest || status !== void 0) {
return "--action is required when using --dest or --status. Use --action rewrite, --action redirect, or --action set-status.";
}
return null;
}
if (!VALID_ACTION_TYPES.includes(action)) {
return `Invalid action type: "${action}". Valid types: ${VALID_ACTION_TYPES.join(", ")}`;
}
switch (action) {
case "rewrite":
if (!dest)
return "--action rewrite requires --dest.";
if (status !== void 0)
return "--action rewrite does not accept --status.";
break;
case "redirect":
if (!dest)
return "--action redirect requires --dest.";
if (status === void 0)
return `--action redirect requires --status (${REDIRECT_STATUS_CODES.join(", ")}).`;
if (!REDIRECT_STATUS_CODES.includes(status))
return `Invalid redirect status: ${status}. Must be one of: ${REDIRECT_STATUS_CODES.join(", ")}`;
break;
case "set-status":
if (dest)
return "--action set-status does not accept --dest.";
if (status === void 0)
return "--action set-status requires --status.";
if (status < 100 || status > 599)
return "Status code must be between 100 and 599.";
break;
}
return null;
}
async function collectActionDetails(client, actionType, flags) {
switch (actionType) {
case "rewrite": {
const dest = await client.input.text({
message: "Destination URL:",
validate: (val) => val ? true : "Destination is required"
});
Object.assign(flags, { "--dest": dest });
break;
}
case "redirect": {
const dest = await client.input.text({
message: "Destination URL:",
validate: (val) => val ? true : "Destination is required"
});
const status = await client.input.select({
message: "Status code:",
choices: [
{ name: "307 - Temporary Redirect", value: 307 },
{ name: "308 - Permanent Redirect", value: 308 },
{ name: "301 - Moved Permanently", value: 301 },
{ name: "302 - Found", value: 302 },
{ name: "303 - See Other", value: 303 }
]
});
Object.assign(flags, { "--dest": dest, "--status": status });
break;
}
case "set-status": {
const statusCode = await client.input.text({
message: "HTTP status code:",
validate: (val) => {
const num = parseInt(val, 10);
if (isNaN(num) || num < 100 || num > 599) {
return "Status code must be between 100 and 599";
}
return true;
}
});
Object.assign(flags, { "--status": parseInt(statusCode, 10) });
break;
}
case "response-headers": {
await collectInteractiveHeaders(client, "response", flags);
break;
}
case "request-headers": {
await collectInteractiveHeaders(client, "request-header", flags);
break;
}
case "request-query": {
await collectInteractiveHeaders(client, "request-query", flags);
break;
}
}
}
async function collectInteractiveConditions(client, flags) {
let addMore = true;
while (addMore) {
const currentHas = flags["--has"] || [];
const currentMissing = flags["--missing"] || [];
if (currentHas.length > 0 || currentMissing.length > 0) {
output_manager_default.log("\nCurrent conditions:");
for (const c of currentHas) {
output_manager_default.print(` has: ${c}
`);
}
for (const c of currentMissing) {
output_manager_default.print(` does not have: ${c}
`);
}
output_manager_default.print("\n");
}
const conditionType = await client.input.select({
message: "Condition type:",
choices: [
{ name: "has - Request must have this", value: "has" },
{
name: "does not have - Request must NOT have this",
value: "missing"
}
]
});
const targetType = await client.input.select({
message: "What to check:",
choices: [
{ name: "Header", value: "header" },
{ name: "Cookie", value: "cookie" },
{ name: "Query Parameter", value: "query" },
{ name: "Host", value: "host" }
]
});
let conditionValue;
if (targetType === "host") {
const operator = await client.input.select({
message: "How to match the host:",
choices: [
{ name: "Equals", value: "eq" },
{ name: "Contains", value: "contains" },
{ name: "Matches (regex)", value: "re" }
]
});
const hostInput = await client.input.text({
message: operator === "re" ? "Host pattern (regex):" : "Host value:",
validate: (val) => {
if (!val)
return "Host value is required";
if (operator === "re") {
try {
new RegExp(val);
return true;
} catch {
return "Invalid regex pattern";
}
}
return true;
}
});
conditionValue = `host:${operator}=${hostInput}`;
} else {
const key = await client.input.text({
message: `${targetType.charAt(0).toUpperCase() + targetType.slice(1)} name:`,
validate: (val) => val ? true : `${targetType} name is required`
});
const operator = await client.input.select({
message: "How to match the value:",
choices: [
{ name: "Exists (any value)", value: "exists" },
{ name: "Equals", value: "eq" },
{ name: "Contains", value: "contains" },
{ name: "Matches (regex)", value: "re" }
]
});
if (operator === "exists") {
conditionValue = `${targetType}:${key}:exists`;
} else {
const valueInput = await client.input.text({
message: operator === "re" ? "Value pattern (regex):" : "Value:",
validate: (val) => {
if (!val)
return "Value is required";
if (operator === "re") {
try {
new RegExp(val);
return true;
} catch {
return "Invalid regex pattern";
}
}
return true;
}
});
conditionValue = `${targetType}:${key}:${operator}=${valueInput}`;
}
}
const flagName = conditionType === "has" ? "--has" : "--missing";
const existing = flags[flagName] || [];
flags[flagName] = [...existing, conditionValue];
const totalConditions = (flags["--has"] || []).length + (flags["--missing"] || []).length;
if (totalConditions >= MAX_CONDITIONS) {
output_manager_default.warn(`Maximum ${MAX_CONDITIONS} conditions reached.`);
break;
}
addMore = await client.input.confirm("Add another condition?", false);
}
}
function formatCollectedItems(flags, type) {
const items = [];
const prefix = type === "response" ? "response-header" : type === "request-header" ? "request-header" : "request-query";
const setItems = flags[`--set-${prefix}`] || [];
const appendItems = flags[`--append-${prefix}`] || [];
const deleteItems = flags[`--delete-${prefix}`] || [];
for (const item of setItems) {
items.push(` set: ${item}`);
}
for (const item of appendItems) {
items.push(` append: ${item}`);
}
for (const item of deleteItems) {
items.push(` delete: ${item}`);
}
return items;
}
async function collectInteractiveHeaders(client, type, flags) {
const flagName = type === "response" ? "--set-response-header" : type === "request-header" ? "--set-request-header" : "--set-request-query";
const sectionName = type === "response" ? "Response Headers" : type === "request-header" ? "Request Headers" : "Request Query Parameters";
const itemName = type === "response" ? "response header" : type === "request-header" ? "request header" : "query parameter";
output_manager_default.log(`
--- ${sectionName} ---`);
let addMore = true;
while (addMore) {
const collected = formatCollectedItems(flags, type);
if (collected.length > 0) {
output_manager_default.log(`
Current ${sectionName.toLowerCase()}:`);
for (const item of collected) {
output_manager_default.print(`${item}
`);
}
output_manager_default.print("\n");
}
const op = await client.input.select({
message: `${sectionName} operation:`,
choices: [
{ name: "Set", value: "set" },
{ name: "Append", value: "append" },
{ name: "Delete", value: "delete" }
]
});
const key = await client.input.text({
message: `${itemName.charAt(0).toUpperCase() + itemName.slice(1)} name:`,
validate: (val) => val ? true : `${itemName} name is required`
});
if (op === "delete") {
const opFlagName = flagName.replace("--set-", "--delete-");
const existing = flags[opFlagName] || [];
flags[opFlagName] = [...existing, key];
} else {
const value = await client.input.text({
message: `${itemName.charAt(0).toUpperCase() + itemName.slice(1)} value:`
});
const opFlagName = op === "append" ? flagName.replace("--set-", "--append-") : flagName;
const existing = flags[opFlagName] || [];
flags[opFlagName] = [...existing, `${key}=${value}`];
}
addMore = await client.input.confirm(`Add another ${itemName}?`, false);
}
}
// src/util/routes/ai-transform.ts
var import_chalk = __toESM(require_source(), 1);
// src/util/routes/parse-conditions.ts
var CONDITION_OPERATORS = [
"eq",
"contains",
"re",
"exists"
];
function escapeRegExp(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function buildConditionValue(operator, value) {
if (operator === "exists")
return void 0;
if (operator === "re")
return value;
const escapedValue = escapeRegExp(value);
if (operator === "contains")
return `.*${escapedValue}.*`;
return `^${escapedValue}$`;
}
function validateRegexPattern(pattern, context) {
try {
new RegExp(pattern);
} catch (e) {
throw new Error(
`Invalid regex in ${context}: "${pattern}". ${e instanceof Error ? e.message : ""}`
);
}
}
function parseOperatorValue(valuePart) {
if (valuePart === "exists") {
return { operator: "exists", rawValue: "" };
}
const eqIdx = valuePart.indexOf("=");
if (eqIdx === -1)
return null;
const maybeOp = valuePart.slice(0, eqIdx);
if (CONDITION_OPERATORS.includes(maybeOp)) {
return {
operator: maybeOp,
rawValue: valuePart.slice(eqIdx + 1)
};
}
return null;
}
function parseConditions(conditions) {
return conditions.map(parseCondition);
}
function parseCondition(condition) {
const parts = condition.split(":");
if (parts.length < 2) {
throw new Error(
`Invalid condition format: "${condition}". Expected format: type:key or type:key:value`
);
}
const type = parts[0].toLowerCase();
const validTypes = ["header", "cookie", "query", "host"];
if (!validTypes.includes(type)) {
throw new Error(
`Invalid condition type: "${type}". Valid types: ${validTypes.join(", ")}`
);
}
if (type === "host") {
const rawValue = parts.slice(1).join(":");
if (!rawValue) {
throw new Error("Host condition requires a value");
}
const opResult2 = parseOperatorValue(rawValue);
if (opResult2) {
if (opResult2.operator === "exists") {
throw new Error(
'Host condition does not support "exists" operator (host always has a value)'
);
}
if (opResult2.operator !== "re" && !opResult2.rawValue) {
throw new Error(
`Host condition with "${opResult2.operator}" operator requires a value`
);
}
const compiledValue = buildConditionValue(
opResult2.operator,
opResult2.rawValue
);
if (compiledValue !== void 0) {
validateRegexPattern(compiledValue, "host condition");
}
return { type: "host", value: compiledValue };
}
validateRegexPattern(rawValue, "host condition");
return { type: "host", value: rawValue };
}
const key = parts[1];
if (!key) {
throw new Error(`${type} condition requires a key`);
}
const valuePart = parts.length > 2 ? parts.slice(2).join(":") : void 0;
if (valuePart === void 0) {
return { type, key };
}
const opResult = parseOperatorValue(valuePart);
if (opResult) {
if (opResult.operator === "exists") {
return { type, key };
}
if (opResult.operator !== "re" && !opResult.rawValue) {
throw new Error(
`Condition "${opResult.operator}" operator requires a value after "="`
);
}
const compiledValue = buildConditionValue(
opResult.operator,
opResult.rawValue
);
if (compiledValue !== void 0) {
validateRegexPattern(compiledValue, `${type} condition value`);
}
return {
type,
key,
...compiledValue !== void 0 && { value: compiledValue }
};
}
validateRegexPattern(valuePart, `${type} condition value`);
return {
type,
key,
value: valuePart
};
}
function formatCondition2(field) {
if (field.type === "host") {
return `host:${field.value}`;
}
if (field.value) {
return `${field.type}:${field.key}:${field.value}`;
}
return `${field.type}:${field.key}`;
}
// src/util/routes/ai-transform.ts
function generatedRouteToAddInput(generated) {
const hasConditions = [];
const missingConditions = [];
const headers = {};
const transforms = [];
let dest;
let status;
if (generated.conditions) {
for (const c of generated.conditions) {
const compiledValue = c.value !== void 0 ? buildConditionValue(c.operator, c.value) : void 0;
const field = c.field === "host" ? { type: "host", value: compiledValue ?? c.value ?? "" } : {
type: c.field,
key: c.key ?? "",
...compiledValue !== void 0 && { value: compiledValue }
};
if (c.missing) {
missingConditions.push(field);
} else {
hasConditions.push(field);
}
}
}
for (const action of generated.actions) {
switch (action.type) {
case "rewrite":
dest = action.dest;
break;
case "redirect":
dest = action.dest;
status = action.status;
break;
case "set-status":
status = action.status;
break;
case "modify": {
if (!action.headers)
break;
if (action.subType === "response-headers") {
for (const h of action.headers) {
if (h.op === "set") {
headers[h.key] = h.value ?? "";
} else {
transforms.push({
type: "response.headers",
op: h.op,
target: { key: h.key },
...h.op !== "delete" && h.value && { args: h.value }
});
}
}
} else if (action.subType === "transform-request-header") {
for (const h of action.headers) {
transforms.push({
type: "request.headers",
op: h.op,
target: { key: h.key },
...h.op !== "delete" && h.value && { args: h.value }
});
}
} else if (action.subType === "transform-request-query") {
for (const h of action.headers) {
transforms.push({
type: "request.query",
op: h.op,
target: { key: h.key },
...h.op !== "delete" && h.value && { args: h.value }
});
}
}
break;
}
}
}
return {
name: generated.name,
description: generated.description || void 0,
srcSyntax: generated.pathCondition.syntax,
route: {
src: generated.pathCondition.value,
...dest !== void 0 && { dest },
...status !== void 0 && { status },
...Object.keys(headers).length > 0 && { headers },
...transforms.length > 0 && { transforms },
...hasConditions.length > 0 && { has: hasConditions },
...missingConditions.length > 0 && { missing: missingConditions }
}
};
}
function convertRouteToCurrentRoute(generated) {
return {
name: generated.name,
description: generated.description || void 0,
pathCondition: generated.pathCondition,
conditions: generated.conditions,
actions: generated.actions
};
}
function routingRuleToCurrentRoute(rule) {
const conditions = [];
const actions = [];
if (rule.route.has) {
for (const c of rule.route.has) {
conditions.push({
field: c.type,
operator: c.value !== void 0 ? "re" : "exists",
key: c.key,
value: c.value !== void 0 ? typeof c.value === "string" ? c.value : JSON.stringify(c.value) : void 0,
missing: false
});
}
}
if (rule.route.missing) {
for (const c of rule.route.missing) {
conditions.push({
field: c.type,
operator: c.value !== void 0 ? "re" : "exists",
key: c.key,
value: c.value !== void 0 ? typeof c.value === "string" ? c.value : JSON.stringify(c.value) : void 0,
missing: true
});
}
}
const isRedirect = rule.route.dest && rule.route.status && REDIRECT_STATUS_CODES.includes(rule.route.status);
if (isRedirect) {
actions.push({
type: "redirect",
dest: rule.route.dest,
status: rule.route.status
});
} else if (rule.route.dest) {
actions.push({ type: "rewrite", dest: rule.route.dest });
} else if (rule.route.status) {
actions.push({ type: "set-status", status: rule.route.status });
}
const responseHeaders = rule.route.headers ? Object.entries(rule.route.headers).map(([key, value]) => ({
key,
value,
op: "set"
})) : [];
const allTransforms = rule.route.transforms ?? [];
const responseHeaderTransforms = allTransforms.filter((t) => t.type === "response.headers").map((t) => ({
key: typeof t.target.key === "string" ? t.target.key : String(t.target.key),
value: t.args,
op: t.op
}));
const allResponseHeaders = [...responseHeaders, ...responseHeaderTransforms];
if (allResponseHeaders.length > 0) {
actions.push({
type: "modify",
subType: "response-headers",
headers: allResponseHeaders
});
}
const requestHeaders = allTransforms.filter((t) => t.type === "request.headers").map((t) => ({
key: typeof t.target.key === "string" ? t.target.key : String(t.target.key),
value: t.args,
op: t.op
}));
if (requestHeaders.length > 0) {
actions.push({
type: "modify",
subType: "transform-request-header",
headers: requestHeaders
});
}
const requestQuery = allTransforms.filter((t) => t.type === "request.query").map((t) => ({
key: typeof t.target.key === "string" ? t.target.key : String(t.target.key),
value: t.args,
op: t.op
}));
if (requestQuery.length > 0) {
actions.push({
type: "modify",
subType: "transform-request-query",
headers: requestQuery
});
}
return {
name: rule.name,
description: rule.description,
pathCondition: {
value: rule.route.src,
syntax: rule.srcSyntax ?? "regex"
},
...conditions.length > 0 && { conditions },
actions
};
}
function printGeneratedRoutePreview(generated) {
output_manager_default.print("\n");
output_manager_default.print(` ${import_chalk.default.bold("Generated Route:")}
`);
output_manager_default.print(` ${import_chalk.default.cyan("Name:")} ${generated.name}
`);
if (generated.description) {
output_manager_default.print(` ${import_chalk.default.cyan("Description:")} ${generated.description}
`);
}
output_manager_default.print(
` ${import_chalk.default.cyan("Source:")} ${generated.pathCondition.value}
`
);
if (generated.conditions && generated.conditions.length > 0) {
output_manager_default.print(` ${import_chalk.default.cyan("Conditions:")}
`);
for (const c of generated.conditions) {
const prefix = c.missing ? "does not have" : "has";
const operatorLabel = c.operator === "eq" ? "equal to" : c.operator === "contains" ? "containing" : c.operator === "re" ? "matching" : "";
const key = c.key ? ` ${import_chalk.default.cyan(`"${c.key}"`)}` : "";
const value = c.operator === "exists" || !c.value ? "" : ` ${operatorLabel} ${import_chalk.default.cyan(`"${c.value}"`)}`;
output_manager_default.print(` ${import_chalk.default.gray(prefix)} ${c.field}${key}${value}
`);
}
}
for (const action of generated.actions) {
if (action.type === "rewrite" && action.dest) {
output_manager_default.print(
` ${import_chalk.default.cyan("Action:")} Rewrite \u2192 ${action.dest}
`
);
} else if (action.type === "redirect" && action.dest) {
output_manager_default.print(
` ${import_chalk.default.cyan("Action:")} Redirect \u2192 ${action.dest} (${action.status})
`
);
} else if (action.type === "set-status" && action.status) {
output_manager_default.print(
` ${import_chalk.default.cyan("Action:")} Set Status ${action.status}
`
);
}
}
for (const action of generated.actions) {
if (action.type === "modify" && action.headers) {
const label = action.subType === "response-headers" ? "Response Headers" : action.subType === "transform-request-header" ? "Request Headers" : "Request Query";
output_manager_default.print(` ${import_chalk.default.cyan(`${label}:`)}
`);
for (const h of action.headers) {
if (h.op === "delete") {
output_manager_default.print(` ${import_chalk.default.yellow(h.op)} ${import_chalk.default.cyan(h.key)}
`);
} else {
output_manager_default.print(
` ${import_chalk.default.yellow(h.op)} ${import_chalk.default.cyan(h.key)} = ${h.value}
`
);
}
}
}
}
output_manager_default.print("\n");
}
// src/commands/routes/edit-interactive.ts
var import_chalk2 = __toESM(require_source(), 1);
function getPrimaryActionType(route) {
const { dest, status } = route.route;
if (dest && status && REDIRECT_STATUS_CODES.includes(status)) {
return "redirect";
}
if (dest)
return "rewrite";
if (status)
return "set-status";
return null;
}
function getPrimaryActionLabel(route) {
const actionType = getPrimaryActionType(route);
switch (actionType) {
case "rewrite":
return `Rewrite \u2192 ${route.route.dest}`;
case "redirect":
return `Redirect \u2192 ${route.route.dest} (${route.route.status})`;
case "set-status":
return `Set Status ${route.route.status}`;
default:
return "(none)";
}
}
function getResponseHeaders(route) {
const headers = route.route.headers ?? {};
return Object.entries(headers).map(([key, value]) => ({ key, value }));
}
function getTransformsByType(route, type) {
const transforms = route.route.transforms ?? [];
return transforms.filter((t) => t.type === type);
}
function printRouteConfig(route) {
output_manager_default.print("\n");
output_manager_default.print(` ${import_chalk2.default.cyan("Name:")} ${route.name}
`);
if (route.description) {
output_manager_default.print(` ${import_chalk2.default.cyan("Description:")} ${route.description}
`);
}
output_manager_default.print(
` ${import_chalk2.default.cyan("Source:")} ${route.route.src} ${import_chalk2.default.gray(`(${route.srcSyntax ?? "regex"})`)}
`
);
output_manager_default.print(
` ${import_chalk2.default.cyan("Status:")} ${route.enabled === false ? import_chalk2.default.red("Disabled") : import_chalk2.default.green("Enabled")}
`
);
const actionLabel = getPrimaryActionLabel(route);
output_manager_default.print(` ${import_chalk2.default.cyan("Action:")} ${actionLabel}
`);
const hasConds = route.route.has ?? [];
if (hasConds.length > 0) {
output_manager_default.print(`
${import_chalk2.default.cyan("Has conditions:")}
`);
for (const c of hasConds) {
output_manager_default.print(` ${formatCondition(c)}
`);
}
}
const missingConds = route.route.missing ?? [];
if (missingConds.length > 0) {
output_manager_default.print(`
${import_chalk2.default.cyan("Does not have conditions:")}
`);
for (const c of missingConds) {
output_manager_default.print(` ${formatCondition(c)}
`);
}
}
const responseHeaders = getResponseHeaders(route);
if (responseHeaders.length > 0) {
output_manager_default.print(`
${import_chalk2.default.cyan("Response Headers:")}
`);
for (const h of responseHeaders) {
output_manager_default.print(` ${import_chalk2.default.cyan(h.key)} = ${h.value}
`);
}
}
const requestHeaders = getTransformsByType(route, "request.headers");
if (requestHeaders.length > 0) {
output_manager_default.print(`
${import_chalk2.default.cyan("Request Headers:")}
`);
for (const t of requestHeaders) {
output_manager_default.print(` ${formatTransform(t)}
`);
}
}
const requestQuery = getTransformsByType(route, "request.query");
if (requestQuery.length > 0) {
output_manager_default.print(`
${import_chalk2.default.cyan("Request Query:")}
`);
for (const t of requestQuery) {
output_manager_default.print(` ${formatTransform(t)}
`);
}
}
output_manager_default.print("\n");
}
function cloneRoute(route) {
return JSON.parse(JSON.stringify(route));
}
function applyFlagMutations(route, flags) {
if (flags["--name"] !== void 0) {
const name = flags["--name"];
if (name.length > MAX_NAME_LENGTH) {
return `Name must be ${MAX_NAME_LENGTH} characters or less.`;
}
route.name = name;
}
if (flags["--description"] !== void 0) {
const desc = flags["--description"];
if (desc.length > MAX_DESCRIPTION_LENGTH) {
return `Description must be ${MAX_DESCRIPTION_LENGTH} characters or less.`;
}
route.description = desc || void 0;
}
if (flags["--src"] !== void 0) {
route.route.src = stripQuotes(flags["--src"]);
}
if (flags["--src-syntax"] !== void 0) {
const syntax = flags["--src-syntax"];
if (!VALID_SYNTAXES.includes(syntax)) {
return `Invalid syntax: "${syntax}". Valid options: ${VALID_SYNTAXES.join(", ")}`;
}
route.srcSyntax = syntax;
}
const actionFlag = flags["--action"];
const destFlag = flags["--dest"];
const statusFlag = flags["--status"];
const noDest = flags["--no-dest"];
const noStatus = flags["--no-status"];
if (actionFlag) {
if (!VALID_ACTION_TYPES.includes(actionFlag)) {
return `Invalid action type: "${actionFlag}". Valid types: ${VALID_ACTION_TYPES.join(", ")}`;
}
switch (actionFlag) {
case "rewrite": {
const dest = destFlag ? stripQuotes(destFlag) : void 0;
if (!dest)
return "--action rewrite requires --dest.";
route.route.dest = dest;
delete route.route.status;
break;
}
case "redirect": {
const dest = destFlag ? stripQuotes(destFlag) : void 0;
if (!dest)
return "--action redirect requires --dest.";
if (statusFlag === void 0)
return `--action redirect requires --status (${REDIRECT_STATUS_CODES.join(", ")}).`;
if (!REDIRECT_STATUS_CODES.includes(statusFlag))
return `Invalid redirect status: ${statusFlag}. Must be one of: ${REDIRECT_STATUS_CODES.join(", ")}`;
route.route.dest = dest;
route.route.status = statusFlag;
break;
}
case "set-status": {
if (statusFlag === void 0)
return "--action set-status requires --status.";
if (statusFlag < 100 || statusFlag > 599)
return "Status code must be between 100 and 599.";
delete route.route.dest;
route.route.status = statusFlag;
break;
}
}
} else {
if (destFlag !== void 0) {
route.route.dest = stripQuotes(destFlag);
}
if (statusFlag !== void 0) {
route.route.status = statusFlag;
}
if (noDest) {
delete route.route.dest;
}
if (noStatus) {
delete route.route.status;
}
}
if (flags["--clear-conditions"]) {
route.route.has = [];
route.route.missing = [];
}
if (flags["--clear-headers"]) {
route.route.headers = {};
}
if (flags["--clear-transforms"]) {
route.route.transforms = [];
}
const transformFlags = extractTransformFlags(flags);
try {
const { headers, transforms } = collectHeadersAndTransforms(transformFlags);
if (Object.keys(headers).length > 0) {
route.route.headers = {
...route.route.headers ?? {},
...headers
};
}
if (transforms.length > 0) {
const existing = route.route.transforms ?? [];
route.route.transforms = [...existing, ...transforms];
}
} catch (e) {
return `Invalid transform format. ${e instanceof Error ? e.message : ""}`;
}
const hasFlags = flags["--has"];
const missingFlags = flags["--missing"];
try {
if (hasFlags) {
const newHas = parseConditions(hasFlags);
const existingHas = route.route.has ?? [];
route.route.has = [...existingHas, ...newHas];
}
if (missingFlags) {
const newMissing = parseConditions(missingFlags);
const existingMissing = route.route.missing ?? [];
route.route.missing = [...existingMissing, ...newMissing];
}
} catch (e) {
return e instanceof Error ? e.message : "Invalid condition format";
}
const totalConditions = (route.route.has ?? []).length + (route.route.missing ?? []).length;
if (totalConditions > MAX_CONDITIONS) {
return `Too many conditions: ${totalConditions}. Maximum is ${MAX_CONDITIONS}.`;
}
const hasDest = !!route.route.dest;
const hasStatus = !!route.route.status;
const hasHeaders = Object.keys(route.route.headers ?? {}).length > 0;
const hasTransforms = (route.route.transforms ?? []).length > 0;
if (!hasDest && !hasStatus && !hasHeaders && !hasTransforms) {
return "This edit would leave the route with no action. Add --action, headers, or transforms.";
}
return null;
}
async function runInteractiveEditLoop(client, route) {
for (; ; ) {
const hasConds = (route.route.has ?? []).length;
const missingConds = (route.route.missing ?? []).length;
const responseHeaders = getAllResponseHeaders(route).length;
const requestHeaders = getTransformsByType(route, "request.headers").length;
const requestQuery = getTransformsByType(route, "request.query").length;
const syntaxLabel = route.srcSyntax === "path-to-regexp" ? "Pattern" : route.srcSyntax === "equals" ? "Exact" : "Regex";
const descriptionPreview = route.description ? route.description.length > 40 ? route.description.slice(0, 40) + "..." : route.description : "";
const editChoices = [
{ name: `Name (${route.name})`, value: "name" },
{
name: descriptionPreview ? `Description (${descriptionPreview})` : "Description",
value: "description"
},
{
name: `Source (${syntaxLabel}: ${route.route.src})`,
value: "source"
},
{
name: `Primary action (${getPrimaryActionLabel(route)})`,
value: "action"
},
{
name: `Conditions (${hasConds} has, ${missingConds} missing)`,
value: "conditions"
},
{
name: `Response Headers (${responseHeaders})`,
value: "response-headers"
},
{
name: `Request Headers (${requestHeaders})`,
value: "request-headers"
},
{
name: `Request Query (${requestQuery})`,
value: "request-query"
},
{ name: "Done - save changes", value: "done" }
];
const choice = await client.input.select({
message: "What would you like to edit?",
choices: editChoices,
pageSize: editChoices.length,
loop: false
});
switch (choice) {
case "name":
await editName(client, route);
break;
case "description":
await editDescription(client, route);
break;
case "source":
await editSource(client, route);
break;
case "action":
await editPrimaryAction(client, route);
break;
case "conditions":
await editConditions(client, route);
break;
case "response-headers":
await editResponseHeaders(client, route);
break;
case "request-headers":
await editTransformsByType(
client,
route,
"request.headers",
"request-header"
);
break;
case "request-query":
await editTransformsByType(
client,
route,
"request.query",
"request-query"
);
break;
case "done":
break;
}
if (choice === "done") {
const hasDest = !!route.route.dest;
const hasStatus = !!route.route.status;
const hasHeaders = Object.keys(route.route.headers ?? {}).length > 0;
const hasTransforms = (route.route.transforms ?? []).length > 0;
if (!hasDest && !hasStatus && !hasHeaders && !hasTransforms) {
output_manager_default.warn(
"Route has no action (no destination, status, or headers). Add an action before saving."
);
continue;
}
break;
}
}
}
async function editName(client, route) {
const name = await client.input.text({
message: `Name (current: ${route.name}):`,
validate: (val) => {
if (!val)
return "Route name is required";
if (val.length > MAX_NAME_LENGTH)
return `Name must be ${MAX_NAME_LENGTH} characters or less`;
return true;
}
});
route.name = name;
}
async function editDescription(client, route) {
const desc = await client.input.text({
message: `Description${route.description ? ` (current: ${route.description})` : ""}:`,
validate: (val) => val && val.length > MAX_DESCRIPTION_LENGTH ? `Description must be ${MAX_DESCRIPTION_LENGTH} characters or less` : true
});
route.description = desc || void 0;
}
async function editSource(client, route) {
const syntaxChoice = await client.input.select({
message: `Path syntax (current: ${route.srcSyntax ?? "regex"}):`,
choices: [
{
name: "Path pattern (e.g., /api/:version/users/:id)",
value: "path-to-regexp"
},
{ name: "Exact match (e.g., /about)", value: "equals" },
{ name: "Regular expression (e.g., ^/api/(.*)$)", value: "regex" }
]
});
route.srcSyntax = syntaxChoice;
const src = await client.input.text({
message: `Path pattern (current: ${route.route.src}):`,
validate: (val) => {
if (!val)
return "Path pattern is required";
return true;
}
});
route.route.src = src;
}
async function editPrimaryAction(client, route) {
const currentType = getPrimaryActionType(route);
const choices = [];
if (currentType === "rewrite" || currentType === "redirect") {
choices.push({ name: "Change destination", value: "change-dest" });
}
if (currentType === "redirect" || currentType === "set-status") {
choices.push({ name: "Change status code", value: "change-status" });
}
if (currentType !== "rewrite") {
choices.push({ name: "Switch to Rewrite", value: "switch-rewrite" });
}
if (currentType !== "redirect") {
choices.push({ name: "Switch to Redirect", value: "switch-redirect" });
}
if (currentType !== "set-status") {
choices.push({
name: "Switch to Set Status Code",
value: "switch-set-status"
});
}
if (currentType) {
choices.push({
name: "Remove primary action",
value: "remove"
});
} else {
choices.push({ name: "Add Rewrite", value: "switch-rewrite" });
choices.push({ name: "Add Redirect", value: "switch-redirect" });
choices.push({ name: "Add Set Status Code", value: "switch-set-status" });
}
choices.push({ name: "Back", value: "back" });
const action = await client.input.select({
message: `Primary action (current: ${getPrimaryActionLabel(route)}):`,
choices
});
const flags = {};
switch (action) {
case "change-dest": {
const dest = await client.input.text({
message: `Destination (current: ${route.route.dest}):`,
validate: (val) => val ? true : "Destination is required"
});
route.route.dest = dest;
break;
}
case "change-status": {
if (currentType === "redirect") {
const status = await client.input.select({
message: `Status code (current: ${route.route.status}):`,
choices: [
{ name: "307 - Temporary Redirect", value: 307 },
{ name: "308 - Permanent Redirect", value: 308 },
{ name: "301 - Moved Permanently", value: 301 },
{ name: "302 - Found", value: 302 },
{ name: "303 - See Other", value: 303 }
]
});
route.route.status = status;
} else {
const statusCode = await client.input.text({
message: `Status code (current: ${route.route.status}):`,
validate: (val) => {
const num = parseInt(val, 10);
if (isNaN(num) || num < 100 || num > 599) {
return "Status code must be between 100 and 599";
}
return true;
}
});
route.route.status = parseInt(statusCode, 10);
}
break;
}
case "switch-rewrite": {
await collectActionDetails(client, "rewrite", flags);
route.route.dest = flags["--dest"];
delete route.route.status;
break;
}
case "switch-redirect": {
await collectActionDetails(client, "redirect", flags);
route.route.dest = flags["--dest"];
route.route.status = flags["--status"];
break;
}
case "switch-set-status": {
await collectActionDetails(client, "set-status", flags);
delete route.route.dest;
route.route.status = flags["--status"];
break;
}
case "remove": {
delete route.route.dest;
delete route.route.status;
break;
}
}
}
async function editConditions(client, route) {
for (; ; ) {
const hasConds = route.route.has ?? [];
const missingConds = route.route.missing ?? [];
if (hasConds.length > 0 || missingConds.length > 0) {
output_manager_default.print("\n");
if (hasConds.length > 0) {
output_manager_default.print(` ${import_chalk2.default.cyan("Has conditions:")}
`);
hasConds.forEach((c, i) => {
output_manager_default.print(
` ${import_chalk2.default.gray(`${i + 1}.`)} ${formatCondition(c)}
`
);
});
}
if (missingConds.length > 0) {
output_manager_default.print(` ${import_chalk2.default.cyan("Does not have conditions:")}
`);
missingConds.forEach((c, i) => {
output_manager_default.print(
` ${import_chalk2.default.gray(`${hasConds.length + i + 1}.`)} ${formatCondition(c)}
`
);
});
}
output_manager_default.print("\n");
} else {
output_manager_default.print("\n No conditions set.\n\n");
}
const choices = [];
if (hasConds.length > 0 || missingConds.length > 0) {
choices.push({ name: "Remove a condition", value: "remove" });
}
choices.push({ name: "Add a new condition", value: "add" });
choices.push({ name: "Back", value: "back" });
const action = await client.input.select({
message: "Conditions:",
choices
});
if (action === "back")
break;
if (action === "remove") {
const allConds = [
...hasConds.map((c, i) => ({
label: `[has] ${formatCondition(c)}`,
idx: i,
kind: "has"
})),
...missingConds.map((c, i) => ({
label: `[does not have] ${formatCondition(c)}`,
idx: i,
kind: "missing"
}))
];
const toRemove = await client.input.select({
message: "Select condition to remove:",
choices: [
...allConds.map((c, i) => ({
name: c.label,
value: i
})),
{ name: "Cancel", value: -1 }
]
});
if (toRemove !== -1) {
const selected = allConds[toRemove];
if (selected.kind === "has") {
hasConds.splice(selected.idx, 1);
route.route.has = hasConds;
} else {
missingConds.splice(selected.idx, 1);
route.route.missing = missingConds;
}
}
}
if (action === "add") {
const existingHasStrings = hasConds.map(
(c) => formatCondition2(c)
);
const existingMissingStrings = missingConds.map(
(c) => formatCondition2(c)
);
const tempFlags = {
"--has": existingHasStrings.length > 0 ? existingHasStrings : void 0,
"--missing": existingMissingStrings.length > 0 ? existingMissingStrings : void 0
};
const hasBefore = existingHasStrings.length;
const missingBefore = existingMissingStrings.length;
await collectInteractiveConditions(client, tempFlags);
const allHas = tempFlags["--has"] || [];
const allMissing = tempFlags["--missing"] || [];
const newHas = allHas.slice(hasBefore);
const newMissing = allMissing.slice(missingBefore);
if (newHas.length > 0) {
const parsed = parseConditions(newHas);
const existing = route.route.has ?? [];
route.route.has = [...existing, ...parsed];
}
if (newMissing.length > 0) {
const parsed = parseConditions(newMissing);
const existing = route.route.missing ?? [];
route.route.missing = [...existing, ...parsed];
}
break;
}
}
}
function getAllResponseHeaders(route) {
const items = [];
for (const [key, value] of Object.entries(route.route.headers ?? {})) {
items.push({ op: "set", key, value, source: "headers" });
}
const transforms = route.route.transforms ?? [];
for (const t of transforms) {
if (t.type === "response.headers") {
items.push({
op: t.op,
key: typeof t.target.key === "string" ? t.target.key : JSON.stringify(t.target.key),
value: typeof t.args === "string" ? t.args : void 0,
source: "transform"
});
}
}
return items;
}
function formatResponseHeaderItem(item) {
if (item.op === "delete") {
return `${import_chalk2.default.yellow(item.op)} ${import_chalk2.default.cyan(item.key)}`;
}
return `${import_chalk2.default.yellow(item.op)} ${import_chalk2.default.cyan(item.key)} = ${item.value}`;
}
async function editResponseHeaders(client, route) {
for (; ; ) {
const allHeaders = getAllResponseHeaders(route);
if (allHeaders.length > 0) {
output_manager_default.print("\n");
output_manager_default.print(` ${import_chalk2.default.cyan("Response Headers:")}
`);
allHeaders.forEach((h, i) => {
output_manager_default.print(
` ${import_chalk2.default.gray(`${i + 1}.`)} ${formatResponseHeaderItem(h)}
`
);
});
output_manager_default.print("\n");
} else {
output_manager_default.print("\n No response headers set.\n\n");
}
const choices = [];
if (allHeaders.length > 0) {
choices.push({ name: "Remove a response header", value: "remove" });
}
choices.push({ name: "Add a response header", value: "add" });
choices.push({ name: "Back", value: "back" });
const action = await client.input.select({
message: "Response Headers:",
choices
});
if (action === "back")
break;
if (action === "remove") {
const toRemove = await client.input.select({
message: "Select response header to remove:",
choices: [
...allHeaders.map((h, i) => ({
name: h.op === "delete" ? `${h.op} ${h.key}` : `${h.op} ${h.key} = ${h.value}`,
value: i
})),
{ name: "Cancel", value: -1 }
]
});
if (toRemove !== -1) {
const item = allHeaders[toRemove];
if (item.source === "headers") {
const currentHeaders = { ...route.route.headers ?? {} };
delete currentHeaders[item.key];
route.route.headers = currentHeaders;
} else {
const transforms = route.route.transforms ?? [];
const idx = transforms.findIndex(
(t) => t.type === "response.headers" && t.op === item.op && (typeof t.target.key === "string" ? t.target.key : JSON.stringify(t.target.key)) === item.key
);
if (idx !== -1) {
transforms.splice(idx, 1);
route.route.transforms = transforms;
}
}
}
}
if (action === "add") {
const tempFlags = {};
await collectInteractiveHeaders(client, "response", tempFlags);
const setHeaders = tempFlags["--set-response-header"] || [];
for (const h of setHeaders) {
const eqIdx = h.indexOf("=");
if (eqIdx !== -1) {
const key = h.slice(0, eqIdx).trim();
const value = h.slice(eqIdx + 1);
route.route.headers = {
...route.route.headers ?? {},
[key]: value
};
}
}
const appendHeaders = tempFlags["--append-response-header"] || [];
const deleteHeaders = tempFlags["--delete-response-header"] || [];
const existing = route.route.transforms ?? [];
const newTransforms = [];
for (const h of appendHeaders) {
const eqIdx = h.indexOf("=");
if (eqIdx !== -1) {
newTransforms.push({
type: "response.headers",
op: "append",
target: { key: h.slice(0, eqIdx).trim() },
args: h.slice(eqIdx + 1)
});
}
}
for (const key of deleteHeaders) {
newTransforms.push({
type: "response.headers",
op: "delete",
target: { key: key.trim() }
});
}
if (newTransforms.length > 0) {
route.route.transforms = [...existing, ...newTransforms];
}
break;
}
}
}
async function editTransformsByType(client, route, transformType, headerType) {
const label = transformType === "request.headers" ? "Request Headers" : "Request Query";
const itemName = transformType === "request.headers" ? "request header" : "query parameter";
for (; ; ) {
const allTransforms = route.route.transforms ?? [];
const matching = allTransforms.filter((t) => t.type === transformType);
if (matching.length > 0) {
output_manager_default.print("\n");
output_manager_default.print(` ${import_chalk2.default.cyan(`${label}:`)}
`);
matching.forEach((t, i) => {
output_manager_default.print(
` ${import_chalk2.default.gray(`${i + 1}.`)} ${formatTransform(t)}
`
);
});
output_manager_default.print("\n");
} else {
output_manager_default.print(`
No ${label.toLowerCase()} set.
`);
}
const choices = [];
if (matching.length > 0) {
choices.push({ name: `Remove a ${itemName}`, value: "remove" });
}
choices.push({ name: `Add a ${itemName}`, value: "add" });
choices.push({ name: "Back", value: "back" });
const action = await client.input.select({
message: `${label}:`,
choices
});
if (action === "back")
break;
if (action === "remove") {
const toRemove = await client.input.select({
message: `Select ${itemName} to remove:`,
choices: [
...matching.map((t, i) => ({
name: formatTransform(t),
value: i
})),
{ name: "Cancel", value: -1 }
]
});
if (toRemove !== -1) {
let matchIdx = 0;
const removeIdx = allTransforms.findIndex((t) => {
if (t.type === transformType) {
if (matchIdx === toRemove)
return true;
matchIdx++;
}
return false;
});
if (removeIdx !== -1) {
allTransforms.splice(removeIdx, 1);
route.route.transforms = allTransforms;
}
}
}
if (action === "add") {
const tempFlags = {};
await collectInteractiveHeaders(client, headerType, tempFlags);
const tfFlags = extractTransformFlags(tempFlags);
const { transforms } = collectHeadersAndTransforms(tfFlags);
if (transforms.length > 0) {
route.route.transforms = [...allTransforms, ...transforms];
}
break;
}
}
}
export {
parseConditions,
populateRouteEnv,
generateRoute,
MAX_NAME_LENGTH,
MAX_DESCRIPTION_LENGTH,
MAX_CONDITIONS,
VALID_SYNTAXES,
REDIRECT_STATUS_CODES,
ALL_ACTION_CHOICES,
stripQuotes,
extractTransformFlags,
collectHeadersAndTransforms,
hasAnyTransformFlags,
validateActionFlags,
collectActionDetails,
collectInteractiveConditions,
generatedRouteToAddInput,
convertRouteToCurrentRoute,
routingRuleToCurrentRoute,
printGeneratedRoutePreview,
printRouteConfig,
cloneRoute,
applyFlagMutations,
runInteractiveEditLoop
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
STANDARD_ENVIRONMENTS
} from "./chunk-QNEHY3TU.js";
import {
getCommandName,
require_lib
} from "./chunk-ZLCMHY2G.js";
import {
output_manager_default
} from "./chunk-FDJURQMQ.js";
import {
require_source
} from "./chunk-S7KYDPEM.js";
import {
__toESM
} from "./chunk-TZ2YI2VH.js";
// src/util/target/format-environment.ts
var import_chalk = __toESM(require_source(), 1);
var import_title = __toESM(require_lib(), 1);
function formatEnvironment(orgSlug, projectSlug, environment) {
const projectUrl = `https://vercel.com/${orgSlug}/${projectSlug}`;
const boldName = import_chalk.default.bold(
STANDARD_ENVIRONMENTS.includes(environment.slug) ? (0, import_title.default)(environment.slug) : environment.slug
);
return output_manager_default.link(
boldName,
`${projectUrl}/settings/environments/${environment.slug}`,
{ fallback: () => boldName, color: false }
);
}
// src/util/validate-ls-args.ts
var import_chalk2 = __toESM(require_source(), 1);
function validateLsArgs(options) {
const { commandName, args, maxArgs = 0, exitCode = 1, usageString } = options;
if (args.length > maxArgs) {
const usage = usageString || getCommandName(commandName);
output_manager_default.error(`Invalid number of arguments. Usage: ${import_chalk2.default.cyan(usage)}`);
return exitCode;
}
return 0;
}
export {
formatEnvironment,
validateLsArgs
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
require_end_of_stream
} from "./chunk-Y3EHOMJ3.js";
import {
require_once
} from "./chunk-QNEHY3TU.js";
import {
require_signal_exit
} from "./chunk-FDJURQMQ.js";
import {
__commonJS,
__require
} from "./chunk-TZ2YI2VH.js";
// ../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/windows.js
var require_windows = __commonJS({
"../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/windows.js"(exports, module) {
module.exports = isexe;
isexe.sync = sync;
var fs = __require("fs");
function checkPathExt(path, options) {
var pathext = options.pathExt !== void 0 ? options.pathExt : process.env.PATHEXT;
if (!pathext) {
return true;
}
pathext = pathext.split(";");
if (pathext.indexOf("") !== -1) {
return true;
}
for (var i = 0; i < pathext.length; i++) {
var p = pathext[i].toLowerCase();
if (p && path.substr(-p.length).toLowerCase() === p) {
return true;
}
}
return false;
}
function checkStat(stat, path, options) {
if (!stat.isSymbolicLink() && !stat.isFile()) {
return false;
}
return checkPathExt(path, options);
}
function isexe(path, options, cb) {
fs.stat(path, function(er, stat) {
cb(er, er ? false : checkStat(stat, path, options));
});
}
function sync(path, options) {
return checkStat(fs.statSync(path), path, options);
}
}
});
// ../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/mode.js
var require_mode = __commonJS({
"../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/mode.js"(exports, module) {
module.exports = isexe;
isexe.sync = sync;
var fs = __require("fs");
function isexe(path, options, cb) {
fs.stat(path, function(er, stat) {
cb(er, er ? false : checkStat(stat, options));
});
}
function sync(path, options) {
return checkStat(fs.statSync(path), options);
}
function checkStat(stat, options) {
return stat.isFile() && checkMode(stat, options);
}
function checkMode(stat, options) {
var mod = stat.mode;
var uid = stat.uid;
var gid = stat.gid;
var myUid = options.uid !== void 0 ? options.uid : process.getuid && process.getuid();
var myGid = options.gid !== void 0 ? options.gid : process.getgid && process.getgid();
var u = parseInt("100", 8);
var g = parseInt("010", 8);
var o = parseInt("001", 8);
var ug = u | g;
var ret = mod & o || mod & g && gid === myGid || mod & u && uid === myUid || mod & ug && myUid === 0;
return ret;
}
}
});
// ../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/index.js
var require_isexe = __commonJS({
"../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/index.js"(exports, module) {
var fs = __require("fs");
var core;
if (process.platform === "win32" || global.TESTING_WINDOWS) {
core = require_windows();
} else {
core = require_mode();
}
module.exports = isexe;
isexe.sync = sync;
function isexe(path, options, cb) {
if (typeof options === "function") {
cb = options;
options = {};
}
if (!cb) {
if (typeof Promise !== "function") {
throw new TypeError("callback not provided");
}
return new Promise(function(resolve, reject) {
isexe(path, options || {}, function(er, is) {
if (er) {
reject(er);
} else {
resolve(is);
}
});
});
}
core(path, options || {}, function(er, is) {
if (er) {
if (er.code === "EACCES" || options && options.ignoreErrors) {
er = null;
is = false;
}
}
cb(er, is);
});
}
function sync(path, options) {
try {
return core.sync(path, options || {});
} catch (er) {
if (options && options.ignoreErrors || er.code === "EACCES") {
return false;
} else {
throw er;
}
}
}
}
});
// ../../node_modules/.pnpm/which@2.0.2/node_modules/which/which.js
var require_which = __commonJS({
"../../node_modules/.pnpm/which@2.0.2/node_modules/which/which.js"(exports, module) {
var isWindows = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys";
var path = __require("path");
var COLON = isWindows ? ";" : ":";
var isexe = require_isexe();
var getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: "ENOENT" });
var getPathInfo = (cmd, opt) => {
const colon = opt.colon || COLON;
const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [""] : [
// windows always checks the cwd first
...isWindows ? [process.cwd()] : [],
...(opt.path || process.env.PATH || /* istanbul ignore next: very unusual */
"").split(colon)
];
const pathExtExe = isWindows ? opt.pathExt || process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM" : "";
const pathExt = isWindows ? pathExtExe.split(colon) : [""];
if (isWindows) {
if (cmd.indexOf(".") !== -1 && pathExt[0] !== "")
pathExt.unshift("");
}
return {
pathEnv,
pathExt,
pathExtExe
};
};
var which = (cmd, opt, cb) => {
if (typeof opt === "function") {
cb = opt;
opt = {};
}
if (!opt)
opt = {};
const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
const found = [];
const step = (i) => new Promise((resolve, reject) => {
if (i === pathEnv.length)
return opt.all && found.length ? resolve(found) : reject(getNotFoundError(cmd));
const ppRaw = pathEnv[i];
const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
const pCmd = path.join(pathPart, cmd);
const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
resolve(subStep(p, i, 0));
});
const subStep = (p, i, ii) => new Promise((resolve, reject) => {
if (ii === pathExt.length)
return resolve(step(i + 1));
const ext = pathExt[ii];
isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {
if (!er && is) {
if (opt.all)
found.push(p + ext);
else
return resolve(p + ext);
}
return resolve(subStep(p, i, ii + 1));
});
});
return cb ? step(0).then((res) => cb(null, res), cb) : step(0);
};
var whichSync = (cmd, opt) => {
opt = opt || {};
const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
const found = [];
for (let i = 0; i < pathEnv.length; i++) {
const ppRaw = pathEnv[i];
const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
const pCmd = path.join(pathPart, cmd);
const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
for (let j = 0; j < pathExt.length; j++) {
const cur = p + pathExt[j];
try {
const is = isexe.sync(cur, { pathExt: pathExtExe });
if (is) {
if (opt.all)
found.push(cur);
else
return cur;
}
} catch (ex) {
}
}
}
if (opt.all && found.length)
return found;
if (opt.nothrow)
return null;
throw getNotFoundError(cmd);
};
module.exports = which;
which.sync = whichSync;
}
});
// ../../node_modules/.pnpm/path-key@3.1.1/node_modules/path-key/index.js
var require_path_key = __commonJS({
"../../node_modules/.pnpm/path-key@3.1.1/node_modules/path-key/index.js"(exports, module) {
"use strict";
var pathKey = (options = {}) => {
const environment = options.env || process.env;
const platform = options.platform || process.platform;
if (platform !== "win32") {
return "PATH";
}
return Object.keys(environment).reverse().find((key) => key.toUpperCase() === "PATH") || "Path";
};
module.exports = pathKey;
module.exports.default = pathKey;
}
});
// ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js
var require_resolveCommand = __commonJS({
"../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js"(exports, module) {
"use strict";
var path = __require("path");
var which = require_which();
var getPathKey = require_path_key();
function resolveCommandAttempt(parsed, withoutPathExt) {
const env = parsed.options.env || process.env;
const cwd = process.cwd();
const hasCustomCwd = parsed.options.cwd != null;
const shouldSwitchCwd = hasCustomCwd && process.chdir !== void 0 && !process.chdir.disabled;
if (shouldSwitchCwd) {
try {
process.chdir(parsed.options.cwd);
} catch (err) {
}
}
let resolved;
try {
resolved = which.sync(parsed.command, {
path: env[getPathKey({ env })],
pathExt: withoutPathExt ? path.delimiter : void 0
});
} catch (e) {
} finally {
if (shouldSwitchCwd) {
process.chdir(cwd);
}
}
if (resolved) {
resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
}
return resolved;
}
function resolveCommand(parsed) {
return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);
}
module.exports = resolveCommand;
}
});
// ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/escape.js
var require_escape = __commonJS({
"../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/escape.js"(exports, module) {
"use strict";
var metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
function escapeCommand(arg) {
arg = arg.replace(metaCharsRegExp, "^$1");
return arg;
}
function escapeArgument(arg, doubleEscapeMetaChars) {
arg = `${arg}`;
arg = arg.replace(/(?=(\\+?)?)\1"/g, '$1$1\\"');
arg = arg.replace(/(?=(\\+?)?)\1$/, "$1$1");
arg = `"${arg}"`;
arg = arg.replace(metaCharsRegExp, "^$1");
if (doubleEscapeMetaChars) {
arg = arg.replace(metaCharsRegExp, "^$1");
}
return arg;
}
module.exports.command = escapeCommand;
module.exports.argument = escapeArgument;
}
});
// ../../node_modules/.pnpm/shebang-regex@3.0.0/node_modules/shebang-regex/index.js
var require_shebang_regex = __commonJS({
"../../node_modules/.pnpm/shebang-regex@3.0.0/node_modules/shebang-regex/index.js"(exports, module) {
"use strict";
module.exports = /^#!(.*)/;
}
});
// ../../node_modules/.pnpm/shebang-command@2.0.0/node_modules/shebang-command/index.js
var require_shebang_command = __commonJS({
"../../node_modules/.pnpm/shebang-command@2.0.0/node_modules/shebang-command/index.js"(exports, module) {
"use strict";
var shebangRegex = require_shebang_regex();
module.exports = (string = "") => {
const match = string.match(shebangRegex);
if (!match) {
return null;
}
const [path, argument] = match[0].replace(/#! ?/, "").split(" ");
const binary = path.split("/").pop();
if (binary === "env") {
return argument;
}
return argument ? `${binary} ${argument}` : binary;
};
}
});
// ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js
var require_readShebang = __commonJS({
"../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js"(exports, module) {
"use strict";
var fs = __require("fs");
var shebangCommand = require_shebang_command();
function readShebang(command) {
const size = 150;
const buffer = Buffer.alloc(size);
let fd;
try {
fd = fs.openSync(command, "r");
fs.readSync(fd, buffer, 0, size, 0);
fs.closeSync(fd);
} catch (e) {
}
return shebangCommand(buffer.toString());
}
module.exports = readShebang;
}
});
// ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js
var require_parse = __commonJS({
"../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js"(exports, module) {
"use strict";
var path = __require("path");
var resolveCommand = require_resolveCommand();
var escape = require_escape();
var readShebang = require_readShebang();
var isWin = process.platform === "win32";
var isExecutableRegExp = /\.(?:com|exe)$/i;
var isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;
function detectShebang(parsed) {
parsed.file = resolveCommand(parsed);
const shebang = parsed.file && readShebang(parsed.file);
if (shebang) {
parsed.args.unshift(parsed.file);
parsed.command = shebang;
return resolveCommand(parsed);
}
return parsed.file;
}
function parseNonShell(parsed) {
if (!isWin) {
return parsed;
}
const commandFile = detectShebang(parsed);
const needsShell = !isExecutableRegExp.test(commandFile);
if (parsed.options.forceShell || needsShell) {
const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
parsed.command = path.normalize(parsed.command);
parsed.command = escape.command(parsed.command);
parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));
const shellCommand = [parsed.command].concat(parsed.args).join(" ");
parsed.args = ["/d", "/s", "/c", `"${shellCommand}"`];
parsed.command = process.env.comspec || "cmd.exe";
parsed.options.windowsVerbatimArguments = true;
}
return parsed;
}
function parse(command, args, options) {
if (args && !Array.isArray(args)) {
options = args;
args = null;
}
args = args ? args.slice(0) : [];
options = Object.assign({}, options);
const parsed = {
command,
args,
options,
file: void 0,
original: {
command,
args
}
};
return options.shell ? parsed : parseNonShell(parsed);
}
module.exports = parse;
}
});
// ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/enoent.js
var require_enoent = __commonJS({
"../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/enoent.js"(exports, module) {
"use strict";
var isWin = process.platform === "win32";
function notFoundError(original, syscall) {
return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), {
code: "ENOENT",
errno: "ENOENT",
syscall: `${syscall} ${original.command}`,
path: original.command,
spawnargs: original.args
});
}
function hookChildProcess(cp, parsed) {
if (!isWin) {
return;
}
const originalEmit = cp.emit;
cp.emit = function(name, arg1) {
if (name === "exit") {
const err = verifyENOENT(arg1, parsed);
if (err) {
return originalEmit.call(cp, "error", err);
}
}
return originalEmit.apply(cp, arguments);
};
}
function verifyENOENT(status, parsed) {
if (isWin && status === 1 && !parsed.file) {
return notFoundError(parsed.original, "spawn");
}
return null;
}
function verifyENOENTSync(status, parsed) {
if (isWin && status === 1 && !parsed.file) {
return notFoundError(parsed.original, "spawnSync");
}
return null;
}
module.exports = {
hookChildProcess,
verifyENOENT,
verifyENOENTSync,
notFoundError
};
}
});
// ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/index.js
var require_cross_spawn = __commonJS({
"../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/index.js"(exports, module) {
"use strict";
var cp = __require("child_process");
var parse = require_parse();
var enoent = require_enoent();
function spawn(command, args, options) {
const parsed = parse(command, args, options);
const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
enoent.hookChildProcess(spawned, parsed);
return spawned;
}
function spawnSync(command, args, options) {
const parsed = parse(command, args, options);
const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);
result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
return result;
}
module.exports = spawn;
module.exports.spawn = spawn;
module.exports.sync = spawnSync;
module.exports._parse = parse;
module.exports._enoent = enoent;
}
});
// ../../node_modules/.pnpm/strip-final-newline@2.0.0/node_modules/strip-final-newline/index.js
var require_strip_final_newline = __commonJS({
"../../node_modules/.pnpm/strip-final-newline@2.0.0/node_modules/strip-final-newline/index.js"(exports, module) {
"use strict";
module.exports = (input) => {
const LF = typeof input === "string" ? "\n" : "\n".charCodeAt();
const CR = typeof input === "string" ? "\r" : "\r".charCodeAt();
if (input[input.length - 1] === LF) {
input = input.slice(0, input.length - 1);
}
if (input[input.length - 1] === CR) {
input = input.slice(0, input.length - 1);
}
return input;
};
}
});
// ../../node_modules/.pnpm/npm-run-path@4.0.1/node_modules/npm-run-path/index.js
var require_npm_run_path = __commonJS({
"../../node_modules/.pnpm/npm-run-path@4.0.1/node_modules/npm-run-path/index.js"(exports, module) {
"use strict";
var path = __require("path");
var pathKey = require_path_key();
var npmRunPath = (options) => {
options = {
cwd: process.cwd(),
path: process.env[pathKey()],
execPath: process.execPath,
...options
};
let previous;
let cwdPath = path.resolve(options.cwd);
const result = [];
while (previous !== cwdPath) {
result.push(path.join(cwdPath, "node_modules/.bin"));
previous = cwdPath;
cwdPath = path.resolve(cwdPath, "..");
}
const execPathDir = path.resolve(options.cwd, options.execPath, "..");
result.push(execPathDir);
return result.concat(options.path).join(path.delimiter);
};
module.exports = npmRunPath;
module.exports.default = npmRunPath;
module.exports.env = (options) => {
options = {
env: process.env,
...options
};
const env = { ...options.env };
const path2 = pathKey({ env });
options.path = env[path2];
env[path2] = module.exports(options);
return env;
};
}
});
// ../../node_modules/.pnpm/mimic-fn@2.1.0/node_modules/mimic-fn/index.js
var require_mimic_fn = __commonJS({
"../../node_modules/.pnpm/mimic-fn@2.1.0/node_modules/mimic-fn/index.js"(exports, module) {
"use strict";
var mimicFn = (to, from) => {
for (const prop of Reflect.ownKeys(from)) {
Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop));
}
return to;
};
module.exports = mimicFn;
module.exports.default = mimicFn;
}
});
// ../../node_modules/.pnpm/onetime@5.1.2/node_modules/onetime/index.js
var require_onetime = __commonJS({
"../../node_modules/.pnpm/onetime@5.1.2/node_modules/onetime/index.js"(exports, module) {
"use strict";
var mimicFn = require_mimic_fn();
var calledFunctions = /* @__PURE__ */ new WeakMap();
var onetime = (function_, options = {}) => {
if (typeof function_ !== "function") {
throw new TypeError("Expected a function");
}
let returnValue;
let callCount = 0;
const functionName = function_.displayName || function_.name || "<anonymous>";
const onetime2 = function(...arguments_) {
calledFunctions.set(onetime2, ++callCount);
if (callCount === 1) {
returnValue = function_.apply(this, arguments_);
function_ = null;
} else if (options.throw === true) {
throw new Error(`Function \`${functionName}\` can only be called once`);
}
return returnValue;
};
mimicFn(onetime2, function_);
calledFunctions.set(onetime2, callCount);
return onetime2;
};
module.exports = onetime;
module.exports.default = onetime;
module.exports.callCount = (function_) => {
if (!calledFunctions.has(function_)) {
throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`);
}
return calledFunctions.get(function_);
};
}
});
// ../../node_modules/.pnpm/human-signals@1.1.1/node_modules/human-signals/build/src/core.js
var require_core = __commonJS({
"../../node_modules/.pnpm/human-signals@1.1.1/node_modules/human-signals/build/src/core.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SIGNALS = void 0;
var SIGNALS = [
{
name: "SIGHUP",
number: 1,
action: "terminate",
description: "Terminal closed",
standard: "posix"
},
{
name: "SIGINT",
number: 2,
action: "terminate",
description: "User interruption with CTRL-C",
standard: "ansi"
},
{
name: "SIGQUIT",
number: 3,
action: "core",
description: "User interruption with CTRL-\\",
standard: "posix"
},
{
name: "SIGILL",
number: 4,
action: "core",
description: "Invalid machine instruction",
standard: "ansi"
},
{
name: "SIGTRAP",
number: 5,
action: "core",
description: "Debugger breakpoint",
standard: "posix"
},
{
name: "SIGABRT",
number: 6,
action: "core",
description: "Aborted",
standard: "ansi"
},
{
name: "SIGIOT",
number: 6,
action: "core",
description: "Aborted",
standard: "bsd"
},
{
name: "SIGBUS",
number: 7,
action: "core",
description: "Bus error due to misaligned, non-existing address or paging error",
standard: "bsd"
},
{
name: "SIGEMT",
number: 7,
action: "terminate",
description: "Command should be emulated but is not implemented",
standard: "other"
},
{
name: "SIGFPE",
number: 8,
action: "core",
description: "Floating point arithmetic error",
standard: "ansi"
},
{
name: "SIGKILL",
number: 9,
action: "terminate",
description: "Forced termination",
standard: "posix",
forced: true
},
{
name: "SIGUSR1",
number: 10,
action: "terminate",
description: "Application-specific signal",
standard: "posix"
},
{
name: "SIGSEGV",
number: 11,
action: "core",
description: "Segmentation fault",
standard: "ansi"
},
{
name: "SIGUSR2",
number: 12,
action: "terminate",
description: "Application-specific signal",
standard: "posix"
},
{
name: "SIGPIPE",
number: 13,
action: "terminate",
description: "Broken pipe or socket",
standard: "posix"
},
{
name: "SIGALRM",
number: 14,
action: "terminate",
description: "Timeout or timer",
standard: "posix"
},
{
name: "SIGTERM",
number: 15,
action: "terminate",
description: "Termination",
standard: "ansi"
},
{
name: "SIGSTKFLT",
number: 16,
action: "terminate",
description: "Stack is empty or overflowed",
standard: "other"
},
{
name: "SIGCHLD",
number: 17,
action: "ignore",
description: "Child process terminated, paused or unpaused",
standard: "posix"
},
{
name: "SIGCLD",
number: 17,
action: "ignore",
description: "Child process terminated, paused or unpaused",
standard: "other"
},
{
name: "SIGCONT",
number: 18,
action: "unpause",
description: "Unpaused",
standard: "posix",
forced: true
},
{
name: "SIGSTOP",
number: 19,
action: "pause",
description: "Paused",
standard: "posix",
forced: true
},
{
name: "SIGTSTP",
number: 20,
action: "pause",
description: 'Paused using CTRL-Z or "suspend"',
standard: "posix"
},
{
name: "SIGTTIN",
number: 21,
action: "pause",
description: "Background process cannot read terminal input",
standard: "posix"
},
{
name: "SIGBREAK",
number: 21,
action: "terminate",
description: "User interruption with CTRL-BREAK",
standard: "other"
},
{
name: "SIGTTOU",
number: 22,
action: "pause",
description: "Background process cannot write to terminal output",
standard: "posix"
},
{
name: "SIGURG",
number: 23,
action: "ignore",
description: "Socket received out-of-band data",
standard: "bsd"
},
{
name: "SIGXCPU",
number: 24,
action: "core",
description: "Process timed out",
standard: "bsd"
},
{
name: "SIGXFSZ",
number: 25,
action: "core",
description: "File too big",
standard: "bsd"
},
{
name: "SIGVTALRM",
number: 26,
action: "terminate",
description: "Timeout or timer",
standard: "bsd"
},
{
name: "SIGPROF",
number: 27,
action: "terminate",
description: "Timeout or timer",
standard: "bsd"
},
{
name: "SIGWINCH",
number: 28,
action: "ignore",
description: "Terminal window size changed",
standard: "bsd"
},
{
name: "SIGIO",
number: 29,
action: "terminate",
description: "I/O is available",
standard: "other"
},
{
name: "SIGPOLL",
number: 29,
action: "terminate",
description: "Watched event",
standard: "other"
},
{
name: "SIGINFO",
number: 29,
action: "ignore",
description: "Request for process information",
standard: "other"
},
{
name: "SIGPWR",
number: 30,
action: "terminate",
description: "Device running out of power",
standard: "systemv"
},
{
name: "SIGSYS",
number: 31,
action: "core",
description: "Invalid system call",
standard: "other"
},
{
name: "SIGUNUSED",
number: 31,
action: "terminate",
description: "Invalid system call",
standard: "other"
}
];
exports.SIGNALS = SIGNALS;
}
});
// ../../node_modules/.pnpm/human-signals@1.1.1/node_modules/human-signals/build/src/realtime.js
var require_realtime = __commonJS({
"../../node_modules/.pnpm/human-signals@1.1.1/node_modules/human-signals/build/src/realtime.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SIGRTMAX = exports.getRealtimeSignals = void 0;
var getRealtimeSignals = function() {
const length = SIGRTMAX - SIGRTMIN + 1;
return Array.from({ length }, getRealtimeSignal);
};
exports.getRealtimeSignals = getRealtimeSignals;
var getRealtimeSignal = function(value, index) {
return {
name: `SIGRT${index + 1}`,
number: SIGRTMIN + index,
action: "terminate",
description: "Application-specific signal (realtime)",
standard: "posix"
};
};
var SIGRTMIN = 34;
var SIGRTMAX = 64;
exports.SIGRTMAX = SIGRTMAX;
}
});
// ../../node_modules/.pnpm/human-signals@1.1.1/node_modules/human-signals/build/src/signals.js
var require_signals = __commonJS({
"../../node_modules/.pnpm/human-signals@1.1.1/node_modules/human-signals/build/src/signals.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getSignals = void 0;
var _os = __require("os");
var _core = require_core();
var _realtime = require_realtime();
var getSignals = function() {
const realtimeSignals = (0, _realtime.getRealtimeSignals)();
const signals = [..._core.SIGNALS, ...realtimeSignals].map(normalizeSignal);
return signals;
};
exports.getSignals = getSignals;
var normalizeSignal = function({
name,
number: defaultNumber,
description,
action,
forced = false,
standard
}) {
const {
signals: { [name]: constantSignal }
} = _os.constants;
const supported = constantSignal !== void 0;
const number = supported ? constantSignal : defaultNumber;
return { name, number, description, supported, action, forced, standard };
};
}
});
// ../../node_modules/.pnpm/human-signals@1.1.1/node_modules/human-signals/build/src/main.js
var require_main = __commonJS({
"../../node_modules/.pnpm/human-signals@1.1.1/node_modules/human-signals/build/src/main.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.signalsByNumber = exports.signalsByName = void 0;
var _os = __require("os");
var _signals = require_signals();
var _realtime = require_realtime();
var getSignalsByName = function() {
const signals = (0, _signals.getSignals)();
return signals.reduce(getSignalByName, {});
};
var getSignalByName = function(signalByNameMemo, { name, number, description, supported, action, forced, standard }) {
return {
...signalByNameMemo,
[name]: { name, number, description, supported, action, forced, standard }
};
};
var signalsByName = getSignalsByName();
exports.signalsByName = signalsByName;
var getSignalsByNumber = function() {
const signals = (0, _signals.getSignals)();
const length = _realtime.SIGRTMAX + 1;
const signalsA = Array.from({ length }, (value, number) => getSignalByNumber(number, signals));
return Object.assign({}, ...signalsA);
};
var getSignalByNumber = function(number, signals) {
const signal = findSignalByNumber(number, signals);
if (signal === void 0) {
return {};
}
const { name, description, supported, action, forced, standard } = signal;
return {
[number]: {
name,
number,
description,
supported,
action,
forced,
standard
}
};
};
var findSignalByNumber = function(number, signals) {
const signal = signals.find(({ name }) => _os.constants.signals[name] === number);
if (signal !== void 0) {
return signal;
}
return signals.find((signalA) => signalA.number === number);
};
var signalsByNumber = getSignalsByNumber();
exports.signalsByNumber = signalsByNumber;
}
});
// ../../node_modules/.pnpm/execa@3.2.0/node_modules/execa/lib/error.js
var require_error = __commonJS({
"../../node_modules/.pnpm/execa@3.2.0/node_modules/execa/lib/error.js"(exports, module) {
"use strict";
var { signalsByName } = require_main();
var getErrorPrefix = ({ timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled }) => {
if (timedOut) {
return `timed out after ${timeout} milliseconds`;
}
if (isCanceled) {
return "was canceled";
}
if (errorCode !== void 0) {
return `failed with ${errorCode}`;
}
if (signal !== void 0) {
return `was killed with ${signal} (${signalDescription})`;
}
if (exitCode !== void 0) {
return `failed with exit code ${exitCode}`;
}
return "failed";
};
var makeError = ({
stdout,
stderr,
all,
error,
signal,
exitCode,
command,
timedOut,
isCanceled,
killed,
parsed: { options: { timeout } }
}) => {
exitCode = exitCode === null ? void 0 : exitCode;
signal = signal === null ? void 0 : signal;
const signalDescription = signal === void 0 ? void 0 : signalsByName[signal].description;
const errorCode = error && error.code;
const prefix = getErrorPrefix({ timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled });
const message = `Command ${prefix}: ${command}`;
if (error instanceof Error) {
error.originalMessage = error.message;
error.message = `${message}
${error.message}`;
} else {
error = new Error(message);
}
error.command = command;
error.exitCode = exitCode;
error.signal = signal;
error.signalDescription = signalDescription;
error.stdout = stdout;
error.stderr = stderr;
if (all !== void 0) {
error.all = all;
}
if ("bufferedData" in error) {
delete error.bufferedData;
}
error.failed = true;
error.timedOut = Boolean(timedOut);
error.isCanceled = isCanceled;
error.killed = killed && !timedOut;
return error;
};
module.exports = makeError;
}
});
// ../../node_modules/.pnpm/execa@3.2.0/node_modules/execa/lib/stdio.js
var require_stdio = __commonJS({
"../../node_modules/.pnpm/execa@3.2.0/node_modules/execa/lib/stdio.js"(exports, module) {
"use strict";
var aliases = ["stdin", "stdout", "stderr"];
var hasAlias = (opts) => aliases.some((alias) => opts[alias] !== void 0);
var normalizeStdio = (opts) => {
if (!opts) {
return;
}
const { stdio } = opts;
if (stdio === void 0) {
return aliases.map((alias) => opts[alias]);
}
if (hasAlias(opts)) {
throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${aliases.map((alias) => `\`${alias}\``).join(", ")}`);
}
if (typeof stdio === "string") {
return stdio;
}
if (!Array.isArray(stdio)) {
throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``);
}
const length = Math.max(stdio.length, aliases.length);
return Array.from({ length }, (value, index) => stdio[index]);
};
module.exports = normalizeStdio;
module.exports.node = (opts) => {
const stdio = normalizeStdio(opts);
if (stdio === "ipc") {
return "ipc";
}
if (stdio === void 0 || typeof stdio === "string") {
return [stdio, stdio, stdio, "ipc"];
}
if (stdio.includes("ipc")) {
return stdio;
}
return [...stdio, "ipc"];
};
}
});
// ../../node_modules/.pnpm/p-finally@2.0.1/node_modules/p-finally/index.js
var require_p_finally = __commonJS({
"../../node_modules/.pnpm/p-finally@2.0.1/node_modules/p-finally/index.js"(exports, module) {
"use strict";
module.exports = async (promise, onFinally = () => {
}) => {
let value;
try {
value = await promise;
} catch (error) {
await onFinally();
throw error;
}
await onFinally();
return value;
};
}
});
// ../../node_modules/.pnpm/execa@3.2.0/node_modules/execa/lib/kill.js
var require_kill = __commonJS({
"../../node_modules/.pnpm/execa@3.2.0/node_modules/execa/lib/kill.js"(exports, module) {
"use strict";
var os = __require("os");
var onExit = require_signal_exit();
var pFinally = require_p_finally();
var DEFAULT_FORCE_KILL_TIMEOUT = 1e3 * 5;
var spawnedKill = (kill, signal = "SIGTERM", options = {}) => {
const killResult = kill(signal);
setKillTimeout(kill, signal, options, killResult);
return killResult;
};
var setKillTimeout = (kill, signal, options, killResult) => {
if (!shouldForceKill(signal, options, killResult)) {
return;
}
const timeout = getForceKillAfterTimeout(options);
setTimeout(() => {
kill("SIGKILL");
}, timeout).unref();
};
var shouldForceKill = (signal, { forceKillAfterTimeout }, killResult) => {
return isSigterm(signal) && forceKillAfterTimeout !== false && killResult;
};
var isSigterm = (signal) => {
return signal === os.constants.signals.SIGTERM || typeof signal === "string" && signal.toUpperCase() === "SIGTERM";
};
var getForceKillAfterTimeout = ({ forceKillAfterTimeout = true }) => {
if (forceKillAfterTimeout === true) {
return DEFAULT_FORCE_KILL_TIMEOUT;
}
if (!Number.isInteger(forceKillAfterTimeout) || forceKillAfterTimeout < 0) {
throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${forceKillAfterTimeout}\` (${typeof forceKillAfterTimeout})`);
}
return forceKillAfterTimeout;
};
var spawnedCancel = (spawned, context) => {
const killResult = spawned.kill();
if (killResult) {
context.isCanceled = true;
}
};
var timeoutKill = (spawned, signal, reject) => {
spawned.kill(signal);
reject(Object.assign(new Error("Timed out"), { timedOut: true, signal }));
};
var setupTimeout = (spawned, { timeout, killSignal = "SIGTERM" }, spawnedPromise) => {
if (timeout === 0 || timeout === void 0) {
return spawnedPromise;
}
if (!Number.isInteger(timeout) || timeout < 0) {
throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`);
}
let timeoutId;
const timeoutPromise = new Promise((resolve, reject) => {
timeoutId = setTimeout(() => {
timeoutKill(spawned, killSignal, reject);
}, timeout);
});
const safeSpawnedPromise = pFinally(spawnedPromise, () => {
clearTimeout(timeoutId);
});
return Promise.race([timeoutPromise, safeSpawnedPromise]);
};
var setExitHandler = (spawned, { cleanup, detached }, timedPromise) => {
if (!cleanup || detached) {
return timedPromise;
}
const removeExitHandler = onExit(() => {
spawned.kill();
});
return pFinally(timedPromise, removeExitHandler);
};
module.exports = {
spawnedKill,
spawnedCancel,
setupTimeout,
setExitHandler
};
}
});
// ../../node_modules/.pnpm/is-stream@2.0.1/node_modules/is-stream/index.js
var require_is_stream = __commonJS({
"../../node_modules/.pnpm/is-stream@2.0.1/node_modules/is-stream/index.js"(exports, module) {
"use strict";
var isStream = (stream) => stream !== null && typeof stream === "object" && typeof stream.pipe === "function";
isStream.writable = (stream) => isStream(stream) && stream.writable !== false && typeof stream._write === "function" && typeof stream._writableState === "object";
isStream.readable = (stream) => isStream(stream) && stream.readable !== false && typeof stream._read === "function" && typeof stream._readableState === "object";
isStream.duplex = (stream) => isStream.writable(stream) && isStream.readable(stream);
isStream.transform = (stream) => isStream.duplex(stream) && typeof stream._transform === "function";
module.exports = isStream;
}
});
// ../../node_modules/.pnpm/pump@3.0.2/node_modules/pump/index.js
var require_pump = __commonJS({
"../../node_modules/.pnpm/pump@3.0.2/node_modules/pump/index.js"(exports, module) {
var once = require_once();
var eos = require_end_of_stream();
var fs;
try {
fs = __require("fs");
} catch (e) {
}
var noop = function() {
};
var ancient = /^v?\.0/.test(process.version);
var isFn = function(fn) {
return typeof fn === "function";
};
var isFS = function(stream) {
if (!ancient)
return false;
if (!fs)
return false;
return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close);
};
var isRequest = function(stream) {
return stream.setHeader && isFn(stream.abort);
};
var destroyer = function(stream, reading, writing, callback) {
callback = once(callback);
var closed = false;
stream.on("close", function() {
closed = true;
});
eos(stream, { readable: reading, writable: writing }, function(err) {
if (err)
return callback(err);
closed = true;
callback();
});
var destroyed = false;
return function(err) {
if (closed)
return;
if (destroyed)
return;
destroyed = true;
if (isFS(stream))
return stream.close(noop);
if (isRequest(stream))
return stream.abort();
if (isFn(stream.destroy))
return stream.destroy();
callback(err || new Error("stream was destroyed"));
};
};
var call = function(fn) {
fn();
};
var pipe = function(from, to) {
return from.pipe(to);
};
var pump = function() {
var streams = Array.prototype.slice.call(arguments);
var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop;
if (Array.isArray(streams[0]))
streams = streams[0];
if (streams.length < 2)
throw new Error("pump requires two streams per minimum");
var error;
var destroys = streams.map(function(stream, i) {
var reading = i < streams.length - 1;
var writing = i > 0;
return destroyer(stream, reading, writing, function(err) {
if (!error)
error = err;
if (err)
destroys.forEach(call);
if (reading)
return;
destroys.forEach(call);
callback(error);
});
});
return streams.reduce(pipe);
};
module.exports = pump;
}
});
// ../../node_modules/.pnpm/get-stream@5.2.0/node_modules/get-stream/buffer-stream.js
var require_buffer_stream = __commonJS({
"../../node_modules/.pnpm/get-stream@5.2.0/node_modules/get-stream/buffer-stream.js"(exports, module) {
"use strict";
var { PassThrough: PassThroughStream } = __require("stream");
module.exports = (options) => {
options = { ...options };
const { array } = options;
let { encoding } = options;
const isBuffer = encoding === "buffer";
let objectMode = false;
if (array) {
objectMode = !(encoding || isBuffer);
} else {
encoding = encoding || "utf8";
}
if (isBuffer) {
encoding = null;
}
const stream = new PassThroughStream({ objectMode });
if (encoding) {
stream.setEncoding(encoding);
}
let length = 0;
const chunks = [];
stream.on("data", (chunk) => {
chunks.push(chunk);
if (objectMode) {
length = chunks.length;
} else {
length += chunk.length;
}
});
stream.getBufferedValue = () => {
if (array) {
return chunks;
}
return isBuffer ? Buffer.concat(chunks, length) : chunks.join("");
};
stream.getBufferedLength = () => length;
return stream;
};
}
});
// ../../node_modules/.pnpm/get-stream@5.2.0/node_modules/get-stream/index.js
var require_get_stream = __commonJS({
"../../node_modules/.pnpm/get-stream@5.2.0/node_modules/get-stream/index.js"(exports, module) {
"use strict";
var { constants: BufferConstants } = __require("buffer");
var pump = require_pump();
var bufferStream = require_buffer_stream();
var MaxBufferError = class extends Error {
constructor() {
super("maxBuffer exceeded");
this.name = "MaxBufferError";
}
};
async function getStream(inputStream, options) {
if (!inputStream) {
return Promise.reject(new Error("Expected a stream"));
}
options = {
maxBuffer: Infinity,
...options
};
const { maxBuffer } = options;
let stream;
await new Promise((resolve, reject) => {
const rejectPromise = (error) => {
if (error && stream.getBufferedLength() <= BufferConstants.MAX_LENGTH) {
error.bufferedData = stream.getBufferedValue();
}
reject(error);
};
stream = pump(inputStream, bufferStream(options), (error) => {
if (error) {
rejectPromise(error);
return;
}
resolve();
});
stream.on("data", () => {
if (stream.getBufferedLength() > maxBuffer) {
rejectPromise(new MaxBufferError());
}
});
});
return stream.getBufferedValue();
}
module.exports = getStream;
module.exports.default = getStream;
module.exports.buffer = (stream, options) => getStream(stream, { ...options, encoding: "buffer" });
module.exports.array = (stream, options) => getStream(stream, { ...options, array: true });
module.exports.MaxBufferError = MaxBufferError;
}
});
// ../../node_modules/.pnpm/merge-stream@2.0.0/node_modules/merge-stream/index.js
var require_merge_stream = __commonJS({
"../../node_modules/.pnpm/merge-stream@2.0.0/node_modules/merge-stream/index.js"(exports, module) {
"use strict";
var { PassThrough } = __require("stream");
module.exports = function() {
var sources = [];
var output = new PassThrough({ objectMode: true });
output.setMaxListeners(0);
output.add = add;
output.isEmpty = isEmpty;
output.on("unpipe", remove);
Array.prototype.slice.call(arguments).forEach(add);
return output;
function add(source) {
if (Array.isArray(source)) {
source.forEach(add);
return this;
}
sources.push(source);
source.once("end", remove.bind(null, source));
source.once("error", output.emit.bind(output, "error"));
source.pipe(output, { end: false });
return this;
}
function isEmpty() {
return sources.length == 0;
}
function remove(source) {
sources = sources.filter(function(it) {
return it !== source;
});
if (!sources.length && output.readable) {
output.end();
}
}
};
}
});
// ../../node_modules/.pnpm/execa@3.2.0/node_modules/execa/lib/stream.js
var require_stream = __commonJS({
"../../node_modules/.pnpm/execa@3.2.0/node_modules/execa/lib/stream.js"(exports, module) {
"use strict";
var isStream = require_is_stream();
var getStream = require_get_stream();
var mergeStream = require_merge_stream();
var handleInput = (spawned, input) => {
if (input === void 0 || spawned.stdin === void 0) {
return;
}
if (isStream(input)) {
input.pipe(spawned.stdin);
} else {
spawned.stdin.end(input);
}
};
var makeAllStream = (spawned, { all }) => {
if (!all || !spawned.stdout && !spawned.stderr) {
return;
}
const mixed = mergeStream();
if (spawned.stdout) {
mixed.add(spawned.stdout);
}
if (spawned.stderr) {
mixed.add(spawned.stderr);
}
return mixed;
};
var getBufferedData = async (stream, streamPromise) => {
if (!stream) {
return;
}
stream.destroy();
try {
return await streamPromise;
} catch (error) {
return error.bufferedData;
}
};
var getStreamPromise = (stream, { encoding, buffer, maxBuffer }) => {
if (!stream || !buffer) {
return;
}
if (encoding) {
return getStream(stream, { encoding, maxBuffer });
}
return getStream.buffer(stream, { maxBuffer });
};
var getSpawnedResult = async ({ stdout, stderr, all }, { encoding, buffer, maxBuffer }, processDone) => {
const stdoutPromise = getStreamPromise(stdout, { encoding, buffer, maxBuffer });
const stderrPromise = getStreamPromise(stderr, { encoding, buffer, maxBuffer });
const allPromise = getStreamPromise(all, { encoding, buffer, maxBuffer: maxBuffer * 2 });
try {
return await Promise.all([processDone, stdoutPromise, stderrPromise, allPromise]);
} catch (error) {
return Promise.all([
{ error, signal: error.signal, timedOut: error.timedOut },
getBufferedData(stdout, stdoutPromise),
getBufferedData(stderr, stderrPromise),
getBufferedData(all, allPromise)
]);
}
};
var validateInputSync = ({ input }) => {
if (isStream(input)) {
throw new TypeError("The `input` option cannot be a stream in sync mode");
}
};
module.exports = {
handleInput,
makeAllStream,
getSpawnedResult,
validateInputSync
};
}
});
// ../../node_modules/.pnpm/execa@3.2.0/node_modules/execa/lib/promise.js
var require_promise = __commonJS({
"../../node_modules/.pnpm/execa@3.2.0/node_modules/execa/lib/promise.js"(exports, module) {
"use strict";
var mergePromiseProperty = (spawned, promise, property) => {
const value = typeof promise === "function" ? (...args) => promise()[property](...args) : promise[property].bind(promise);
Object.defineProperty(spawned, property, {
value,
writable: true,
enumerable: false,
configurable: true
});
};
var mergePromise = (spawned, promise) => {
mergePromiseProperty(spawned, promise, "then");
mergePromiseProperty(spawned, promise, "catch");
if (Promise.prototype.finally) {
mergePromiseProperty(spawned, promise, "finally");
}
return spawned;
};
var getSpawnedPromise = (spawned) => {
return new Promise((resolve, reject) => {
spawned.on("exit", (exitCode, signal) => {
resolve({ exitCode, signal });
});
spawned.on("error", (error) => {
reject(error);
});
if (spawned.stdin) {
spawned.stdin.on("error", (error) => {
reject(error);
});
}
});
};
module.exports = {
mergePromise,
getSpawnedPromise
};
}
});
// ../../node_modules/.pnpm/execa@3.2.0/node_modules/execa/lib/command.js
var require_command = __commonJS({
"../../node_modules/.pnpm/execa@3.2.0/node_modules/execa/lib/command.js"(exports, module) {
"use strict";
var SPACES_REGEXP = / +/g;
var joinCommand = (file, args = []) => {
if (!Array.isArray(args)) {
return file;
}
return [file, ...args].join(" ");
};
var handleEscaping = (tokens, token, index) => {
if (index === 0) {
return [token];
}
const previousToken = tokens[tokens.length - 1];
if (previousToken.endsWith("\\")) {
return [...tokens.slice(0, -1), `${previousToken.slice(0, -1)} ${token}`];
}
return [...tokens, token];
};
var parseCommand = (command) => {
return command.trim().split(SPACES_REGEXP).reduce(handleEscaping, []);
};
module.exports = {
joinCommand,
parseCommand
};
}
});
// ../../node_modules/.pnpm/execa@3.2.0/node_modules/execa/index.js
var require_execa = __commonJS({
"../../node_modules/.pnpm/execa@3.2.0/node_modules/execa/index.js"(exports, module) {
"use strict";
var path = __require("path");
var childProcess = __require("child_process");
var crossSpawn = require_cross_spawn();
var stripFinalNewline = require_strip_final_newline();
var npmRunPath = require_npm_run_path();
var onetime = require_onetime();
var makeError = require_error();
var normalizeStdio = require_stdio();
var { spawnedKill, spawnedCancel, setupTimeout, setExitHandler } = require_kill();
var { handleInput, getSpawnedResult, makeAllStream, validateInputSync } = require_stream();
var { mergePromise, getSpawnedPromise } = require_promise();
var { joinCommand, parseCommand } = require_command();
var DEFAULT_MAX_BUFFER = 1e3 * 1e3 * 100;
var getEnv = ({ env: envOption, extendEnv, preferLocal, localDir, execPath }) => {
const env = extendEnv ? { ...process.env, ...envOption } : envOption;
if (preferLocal) {
return npmRunPath.env({ env, cwd: localDir, execPath });
}
return env;
};
var handleArgs = (file, args, options = {}) => {
const parsed = crossSpawn._parse(file, args, options);
file = parsed.command;
args = parsed.args;
options = parsed.options;
options = {
maxBuffer: DEFAULT_MAX_BUFFER,
buffer: true,
stripFinalNewline: true,
extendEnv: true,
preferLocal: false,
localDir: options.cwd || process.cwd(),
execPath: process.execPath,
encoding: "utf8",
reject: true,
cleanup: true,
all: false,
...options,
windowsHide: true
};
options.env = getEnv(options);
options.stdio = normalizeStdio(options);
if (process.platform === "win32" && path.basename(file, ".exe") === "cmd") {
args.unshift("/q");
}
return { file, args, options, parsed };
};
var handleOutput = (options, value, error) => {
if (typeof value !== "string" && !Buffer.isBuffer(value)) {
return error === void 0 ? void 0 : "";
}
if (options.stripFinalNewline) {
return stripFinalNewline(value);
}
return value;
};
var execa = (file, args, options) => {
const parsed = handleArgs(file, args, options);
const command = joinCommand(file, args);
let spawned;
try {
spawned = childProcess.spawn(parsed.file, parsed.args, parsed.options);
} catch (error) {
const dummySpawned = new childProcess.ChildProcess();
const errorPromise = Promise.reject(makeError({
error,
stdout: "",
stderr: "",
all: "",
command,
parsed,
timedOut: false,
isCanceled: false,
killed: false
}));
return mergePromise(dummySpawned, errorPromise);
}
const spawnedPromise = getSpawnedPromise(spawned);
const timedPromise = setupTimeout(spawned, parsed.options, spawnedPromise);
const processDone = setExitHandler(spawned, parsed.options, timedPromise);
const context = { isCanceled: false };
spawned.kill = spawnedKill.bind(null, spawned.kill.bind(spawned));
spawned.cancel = spawnedCancel.bind(null, spawned, context);
const handlePromise = async () => {
const [{ error, exitCode, signal, timedOut }, stdoutResult, stderrResult, allResult] = await getSpawnedResult(spawned, parsed.options, processDone);
const stdout = handleOutput(parsed.options, stdoutResult);
const stderr = handleOutput(parsed.options, stderrResult);
const all = handleOutput(parsed.options, allResult);
if (error || exitCode !== 0 || signal !== null) {
const returnedError = makeError({
error,
exitCode,
signal,
stdout,
stderr,
all,
command,
parsed,
timedOut,
isCanceled: context.isCanceled,
killed: spawned.killed
});
if (!parsed.options.reject) {
return returnedError;
}
throw returnedError;
}
return {
command,
exitCode: 0,
stdout,
stderr,
all,
failed: false,
timedOut: false,
isCanceled: false,
killed: false
};
};
const handlePromiseOnce = onetime(handlePromise);
crossSpawn._enoent.hookChildProcess(spawned, parsed.parsed);
handleInput(spawned, parsed.options.input);
spawned.all = makeAllStream(spawned, parsed.options);
return mergePromise(spawned, handlePromiseOnce);
};
module.exports = execa;
module.exports.sync = (file, args, options) => {
const parsed = handleArgs(file, args, options);
const command = joinCommand(file, args);
validateInputSync(parsed.options);
let result;
try {
result = childProcess.spawnSync(parsed.file, parsed.args, parsed.options);
} catch (error) {
throw makeError({
error,
stdout: "",
stderr: "",
all: "",
command,
parsed,
timedOut: false,
isCanceled: false,
killed: false
});
}
const stdout = handleOutput(parsed.options, result.stdout, result.error);
const stderr = handleOutput(parsed.options, result.stderr, result.error);
if (result.error || result.status !== 0 || result.signal !== null) {
const error = makeError({
stdout,
stderr,
error: result.error,
signal: result.signal,
exitCode: result.status,
command,
parsed,
timedOut: result.error && result.error.code === "ETIMEDOUT",
isCanceled: false,
killed: result.signal !== null
});
if (!parsed.options.reject) {
return error;
}
throw error;
}
return {
command,
exitCode: 0,
stdout,
stderr,
failed: false,
timedOut: false,
isCanceled: false,
killed: false
};
};
module.exports.command = (command, options) => {
const [file, ...args] = parseCommand(command);
return execa(file, args, options);
};
module.exports.commandSync = (command, options) => {
const [file, ...args] = parseCommand(command);
return execa.sync(file, args, options);
};
module.exports.node = (scriptPath, args, options = {}) => {
if (args && !Array.isArray(args) && typeof args === "object") {
options = args;
args = [];
}
const stdio = normalizeStdio.node(options);
const { nodePath = process.execPath, nodeOptions = process.execArgv } = options;
return execa(
nodePath,
[
...nodeOptions,
scriptPath,
...Array.isArray(args) ? args : []
],
{
...options,
stdin: void 0,
stdout: void 0,
stderr: void 0,
stdio,
shell: false
}
);
};
}
});
export {
require_isexe,
require_execa
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
getTeamById,
getUser
} from "./chunk-QNEHY3TU.js";
import {
TeamDeleted
} from "./chunk-ZLCMHY2G.js";
// src/util/get-scope.ts
async function getScope(client, opts = {}) {
const user = await getUser(client);
let contextName = user.username || user.email;
let team = null;
const defaultTeamId = user.version === "northstar" ? user.defaultTeamId : void 0;
const currentTeamOrDefaultTeamId = client.config.currentTeam || defaultTeamId;
if (currentTeamOrDefaultTeamId && opts.getTeam !== false) {
team = await getTeamById(client, currentTeamOrDefaultTeamId);
if (!team) {
throw new TeamDeleted();
}
contextName = team.slug;
}
return { contextName, team, user };
}
export {
getScope
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
VERCEL_DIR
} from "./chunk-QNEHY3TU.js";
import {
ConflictingConfigFiles,
InvalidLocalConfig,
getArgs
} from "./chunk-ZLCMHY2G.js";
// src/util/config/local-path.ts
import path from "path";
import { existsSync } from "fs";
function getLocalPathConfig(prefix) {
const argv = getArgs(process.argv.slice(2), {}, { permissive: true });
const customPath = argv["--local-config"];
if (customPath) {
if (typeof customPath !== "string") {
throw new InvalidLocalConfig(customPath);
}
return path.resolve(prefix, customPath);
}
const vercelConfigPath = path.join(prefix, "vercel.json");
const nowConfigPath = path.join(prefix, "now.json");
const vercelConfigExists = existsSync(vercelConfigPath);
const nowConfigExists = existsSync(nowConfigPath);
if (nowConfigExists && vercelConfigExists) {
throw new ConflictingConfigFiles([vercelConfigPath, nowConfigPath]);
}
const compiledConfigPath = path.join(prefix, VERCEL_DIR, "vercel.json");
const compiledConfigExists = existsSync(compiledConfigPath);
if (compiledConfigExists) {
return compiledConfigPath;
}
if (nowConfigExists) {
return nowConfigPath;
}
return vercelConfigPath;
}
export {
getLocalPathConfig
};

Sorry, the diff of this file is too big to display

import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
getLocalPathConfig
} from "./chunk-HP3P6UCH.js";
import {
compileVercelConfig
} from "./chunk-6LQRDWWM.js";
import {
VERCEL_DIR_PROJECT,
VERCEL_DIR_README,
checkExistsAndConnect,
createProject,
detectProjects,
getLinkedProject,
getProjectByNameOrId,
getVercelDirectory,
humanizePath,
isDirectory,
linkFolderToProject,
parseGitConfig,
pluckRemoteUrls,
readJSONFile,
require_frameworks,
require_lib,
require_slugify,
selectAndParseRemoteUrl,
selectOrg,
tryDetectServices
} from "./chunk-QNEHY3TU.js";
import {
table
} from "./chunk-LWBSOTJP.js";
import {
CantParseJSONFile,
ProjectNotFound,
isAPIError,
printError
} from "./chunk-ZLCMHY2G.js";
import {
output_manager_default
} from "./chunk-FDJURQMQ.js";
import {
require_source
} from "./chunk-S7KYDPEM.js";
import {
__toESM
} from "./chunk-TZ2YI2VH.js";
// src/util/validate-paths.ts
var import_fs_extra = __toESM(require_lib(), 1);
var import_chalk = __toESM(require_source(), 1);
import { homedir } from "os";
async function validateRootDirectory(cwd, path2, errorSuffix = "") {
const pathStat = await (0, import_fs_extra.lstat)(path2).catch(() => null);
const suffix = errorSuffix ? ` ${errorSuffix}` : "";
if (!pathStat) {
output_manager_default.error(
`The provided path ${import_chalk.default.cyan(
`\u201C${humanizePath(path2)}\u201D`
)} does not exist.${suffix}`
);
return false;
}
if (!pathStat.isDirectory()) {
output_manager_default.error(
`The provided path ${import_chalk.default.cyan(
`\u201C${humanizePath(path2)}\u201D`
)} is a file, but expected a directory.${suffix}`
);
return false;
}
if (!path2.startsWith(cwd)) {
output_manager_default.error(
`The provided path ${import_chalk.default.cyan(
`\u201C${humanizePath(path2)}\u201D`
)} is outside of the project.${suffix}`
);
return false;
}
return true;
}
async function validatePaths(client, paths) {
if (paths.length > 1) {
output_manager_default.error(`Can't deploy more than one path.`);
return { valid: false, exitCode: 1 };
}
const path2 = paths[0];
const pathStat = await (0, import_fs_extra.lstat)(path2).catch(() => null);
if (!pathStat) {
output_manager_default.error(`Could not find ${import_chalk.default.cyan(`\u201C${humanizePath(path2)}\u201D`)}`);
return { valid: false, exitCode: 1 };
}
if (!pathStat.isDirectory()) {
output_manager_default.prettyError({
message: "Support for single file deployments has been removed.",
link: "https://vercel.link/no-single-file-deployments"
});
return { valid: false, exitCode: 1 };
}
if (path2 === homedir()) {
const shouldDeployHomeDirectory = await client.input.confirm(
`You are deploying your home directory. Do you want to continue?`,
false
);
if (!shouldDeployHomeDirectory) {
output_manager_default.print(`Canceled
`);
return { valid: false, exitCode: 0 };
}
}
return { valid: true, path: path2 };
}
// src/util/config/read-config.ts
async function readConfig(dir) {
let pkgFilePath;
try {
const compileResult = await compileVercelConfig(dir);
pkgFilePath = compileResult.configPath || getLocalPathConfig(dir);
} catch (err) {
if (err instanceof Error) {
return err;
}
throw err;
}
const result = await readJSONFile(pkgFilePath);
if (result instanceof CantParseJSONFile) {
return result;
}
if (result) {
return result;
}
return null;
}
// src/util/input/display-services.ts
var import_frameworks = __toESM(require_frameworks(), 1);
var chalk2 = require_source();
var frameworksBySlug = new Map(import_frameworks.frameworkList.map((f) => [f.slug, f]));
var frameworkColors = {
// JavaScript/TypeScript frameworks
nextjs: chalk2.white,
vite: chalk2.magenta,
nuxtjs: chalk2.green,
remix: chalk2.cyan,
astro: chalk2.magenta,
gatsby: chalk2.magenta,
svelte: chalk2.red,
sveltekit: chalk2.red,
solidstart: chalk2.blue,
angular: chalk2.red,
vue: chalk2.green,
ember: chalk2.red,
preact: chalk2.magenta,
// Python frameworks
fastapi: chalk2.green,
flask: chalk2.cyan,
// Node frameworks
express: chalk2.yellow,
nest: chalk2.red,
hono: chalk2.yellowBright
};
var runtimeColors = {
node: chalk2.green,
python: chalk2.blue,
go: chalk2.cyan,
ruby: chalk2.red,
rust: chalk2.yellowBright
};
function getFrameworkName(slug) {
if (!slug)
return void 0;
return frameworksBySlug.get(slug)?.name;
}
function formatRoutePrefix(routePrefix) {
if (routePrefix === "/") {
return "/";
}
const normalized = routePrefix.startsWith("/") ? routePrefix : `/${routePrefix}`;
return `${normalized}/*`;
}
function getServiceDescriptionInfo(service) {
const frameworkName = getFrameworkName(service.framework);
if (frameworkName && service.framework) {
const colorFn = frameworkColors[service.framework] || chalk2.cyan;
return { label: frameworkName, colorFn };
} else if (service.runtime) {
const normalizedRuntime = service.runtime.toLowerCase().replace(/@.*$/, "");
const colorFn = runtimeColors[normalizedRuntime] || chalk2.yellow;
return { label: service.runtime, colorFn };
} else if (service.builder?.use) {
return { label: service.builder.use, colorFn: chalk2.magenta };
}
return { label: "unknown", colorFn: chalk2.dim };
}
function getServiceTarget(service) {
switch (service.type) {
case "cron":
return `schedule: ${service.schedule ?? "none"}`;
case "worker":
return `topic: ${service.topic ?? "none"}`;
default:
return service.routePrefix ? formatRoutePrefix(service.routePrefix) : "no route";
}
}
function displayDetectedServices(services) {
output_manager_default.print(`Multiple services detected. Project Settings:
`);
const rows = services.map((service) => {
const descInfo = getServiceDescriptionInfo(service);
const target = getServiceTarget(service);
return [
`\u2022 ${service.name}`,
descInfo.colorFn(`[${descInfo.label}]`),
chalk2.dim("\u2192"),
target
];
});
const tableOutput = table(rows, { align: ["l", "l", "l", "l"], hsep: 2 });
output_manager_default.print(`${tableOutput}
`);
}
function displayServicesConfigNote() {
output_manager_default.print(
`
${chalk2.dim("Services (experimental) are configured via vercel.json.")}
`
);
}
function displayServiceErrors(errors) {
for (const error of errors) {
output_manager_default.warn(error.message);
}
}
// src/util/link/setup-and-link.ts
var import_chalk6 = __toESM(require_source(), 1);
var import_fs_extra2 = __toESM(require_lib(), 1);
import { join, basename } from "path";
// src/util/input/input-project.ts
var import_chalk2 = __toESM(require_source(), 1);
var import_slugify = __toESM(require_slugify(), 1);
async function inputProject(client, org, detectedProjectName, autoConfirm = false) {
const slugifiedName = (0, import_slugify.default)(detectedProjectName);
let detectedProject = null;
output_manager_default.spinner("Searching for existing projects\u2026", 1e3);
const [project, slugifiedProject] = await Promise.all([
getProjectByNameOrId(client, detectedProjectName, org.id),
slugifiedName !== detectedProjectName ? getProjectByNameOrId(client, slugifiedName, org.id) : null
]);
detectedProject = !(project instanceof ProjectNotFound) ? project : !(slugifiedProject instanceof ProjectNotFound) ? slugifiedProject : null;
if (detectedProject && !detectedProject.id) {
throw new Error(`Detected linked project does not have "id".`);
}
output_manager_default.stopSpinner();
if (autoConfirm) {
return detectedProject || detectedProjectName;
}
if (client.nonInteractive) {
const err = new Error("Confirmation required");
err.code = "HEADLESS";
throw err;
}
let shouldLinkProject;
if (!detectedProject) {
shouldLinkProject = await client.input.confirm(
`Link to existing project?`,
false
);
} else {
if (await client.input.confirm(
`Found project ${import_chalk2.default.cyan(
`\u201C${org.slug}/${detectedProject.name}\u201D`
)}. Link to it?`,
true
)) {
return detectedProject;
}
shouldLinkProject = await client.input.confirm(
`Link to different existing project?`,
true
);
}
if (shouldLinkProject) {
const firstPage = await client.fetch(`/v9/projects?limit=100`, { accountId: org.id });
const projects = firstPage.projects;
const hasMoreProjects = firstPage.pagination.next !== null;
if (projects.length === 0) {
output_manager_default.log(
`No existing projects found under ${import_chalk2.default.bold(org.slug)}. Creating new project.`
);
} else if (hasMoreProjects) {
let toLink;
await client.input.text({
message: "What's the name of your existing project?",
validate: async (val) => {
if (!val) {
return "Project name cannot be empty";
}
const project2 = await getProjectByNameOrId(client, val, org.id);
if (project2 instanceof ProjectNotFound) {
return "Project not found";
}
toLink = project2;
return true;
}
});
return toLink;
} else {
const choices = projects.sort((a, b) => b.updatedAt - a.updatedAt).map((project2) => ({
name: project2.name,
value: project2
}));
const toLink = await client.input.select({
message: "Which existing project do you want to link?",
choices
});
return toLink;
}
}
return await client.input.text({
message: `What\u2019s your project\u2019s name?`,
default: !detectedProject ? slugifiedName : void 0,
validate: async (val) => {
if (!val) {
return "Project name cannot be empty";
}
const project2 = await getProjectByNameOrId(client, val, org.id);
if (!(project2 instanceof ProjectNotFound)) {
return "Project already exists";
}
return true;
}
});
}
// src/util/input/input-root-directory.ts
var import_chalk3 = __toESM(require_source(), 1);
import path from "path";
async function inputRootDirectory(client, cwd, autoConfirm = false) {
if (autoConfirm) {
return null;
}
while (true) {
const rootDirectory = await client.input.text({
message: `In which directory is your code located?`,
transformer: (input) => {
return `${import_chalk3.default.dim(`./`)}${input}`;
}
});
if (!rootDirectory) {
return null;
}
const normal = path.normalize(rootDirectory);
if (normal === "." || normal === "./") {
return null;
}
const fullPath = path.join(cwd, normal);
if (await validateRootDirectory(
cwd,
fullPath,
"Please choose a different one."
) === false) {
continue;
}
return normal;
}
}
// src/util/input/edit-project-settings.ts
var import_chalk4 = __toESM(require_source(), 1);
var import_frameworks2 = __toESM(require_frameworks(), 1);
// src/util/is-setting-value.ts
function isSettingValue(setting) {
return setting && typeof setting.value === "string";
}
// src/util/input/edit-project-settings.ts
var settingMap = {
buildCommand: "Build Command",
devCommand: "Development Command",
commandForIgnoringBuildStep: "Ignore Command",
installCommand: "Install Command",
outputDirectory: "Output Directory",
framework: "Framework"
};
var settingKeys = Object.keys(settingMap).sort();
async function editProjectSettings(client, projectSettings, framework, autoConfirm, localConfigurationOverrides) {
const settings = Object.assign(
{
buildCommand: null,
devCommand: null,
framework: null,
commandForIgnoringBuildStep: null,
installCommand: null,
outputDirectory: null
},
projectSettings
);
const hasLocalConfigurationOverrides = localConfigurationOverrides && Object.values(localConfigurationOverrides ?? {}).some(Boolean);
if (hasLocalConfigurationOverrides) {
for (const setting of settingKeys) {
const localConfigValue = localConfigurationOverrides[setting];
if (localConfigValue)
settings[setting] = localConfigValue;
}
output_manager_default.print("Local settings detected in vercel.json:\n");
for (const setting of settingKeys) {
const override = localConfigurationOverrides[setting];
if (override) {
output_manager_default.print(
`${import_chalk4.default.dim(
`- ${import_chalk4.default.bold(`${settingMap[setting]}:`)} ${override}`
)}
`
);
}
}
if (localConfigurationOverrides.framework) {
const overrideFramework = import_frameworks2.frameworkList.find(
(f) => f.slug === localConfigurationOverrides.framework
);
if (overrideFramework) {
framework = overrideFramework;
output_manager_default.print(
`Merging default Project Settings for ${framework.name}. Previously listed overrides are prioritized.
`
);
}
}
}
if (!framework) {
settings.framework = null;
return settings;
}
const styledFramework = (frameworkName) => {
const frameworkStyle = {
text: frameworkName,
color: import_chalk4.default.blue
};
if (frameworkName === "Hono") {
frameworkStyle.text = "\u{1F525} Hono";
frameworkStyle.color = import_chalk4.default.hex("#FFA500");
}
return import_chalk4.default.bold(frameworkStyle.color(frameworkStyle.text));
};
output_manager_default.log(
!framework.slug ? `No framework detected. Default Project Settings:
` : `Auto-detected Project Settings for ${styledFramework(framework.name)}
`
);
settings.framework = framework.slug;
if (!framework.slug) {
for (const setting of settingKeys) {
if (setting === "framework" || setting === "commandForIgnoringBuildStep") {
continue;
}
const defaultSetting = framework.settings[setting];
const override = localConfigurationOverrides?.[setting];
if (!override && defaultSetting) {
output_manager_default.print(
`${import_chalk4.default.dim(
`- ${import_chalk4.default.bold(`${settingMap[setting]}:`)} ${isSettingValue(defaultSetting) ? defaultSetting.value : import_chalk4.default.italic(`${defaultSetting.placeholder}`)}`
)}
`
);
}
}
}
if (autoConfirm || !await client.input.confirm("Want to modify these settings?", false)) {
return settings;
}
const choices = settingKeys.reduce(
(acc, setting) => {
const skip = setting === "framework" || setting === "commandForIgnoringBuildStep" || setting === "installCommand" || localConfigurationOverrides?.[setting];
if (skip)
return acc;
return [...acc, { name: settingMap[setting], value: setting }];
},
[]
);
const settingFields = await client.input.checkbox({
message: "Which settings would you like to overwrite (select multiple)?",
choices
});
for (const setting of settingFields) {
const field = settingMap[setting];
settings[setting] = await client.input.text({
message: `What's your ${import_chalk4.default.bold(field)}?`
});
}
return settings;
}
// src/util/link/setup-and-link.ts
var import_frameworks3 = __toESM(require_frameworks(), 1);
// src/util/input/vercel-auth.ts
var import_chalk5 = __toESM(require_source(), 1);
var DEFAULT_VERCEL_AUTH_SETTING = "standard";
var OPTIONS = {
message: `What setting do you want to use for Vercel Authentication?`,
default: DEFAULT_VERCEL_AUTH_SETTING,
choices: [
{
description: "Standard Protection (recommended)",
name: "standard",
value: "standard"
},
{
description: "No Protection (all deployments will be public)",
name: "none",
value: "none"
}
]
};
async function vercelAuth(client, {
autoConfirm = false
}) {
if (autoConfirm || await client.input.confirm(
`Want to use the default Deployment Protection settings? ${import_chalk5.default.dim(`(Vercel Authentication: Standard Protection)`)}`,
true
)) {
return DEFAULT_VERCEL_AUTH_SETTING;
}
const vercelAuth2 = await client.input.select(OPTIONS);
return vercelAuth2;
}
// src/util/link/setup-and-link.ts
async function setupAndLink(client, path2, {
autoConfirm = false,
forceDelete = false,
link,
successEmoji = "link",
setupMsg = "Set up",
projectName = basename(path2),
nonInteractive = false,
pullEnv = true,
v0
}) {
const { config } = client;
if (!isDirectory(path2)) {
output_manager_default.error(`Expected directory but found file: ${path2}`);
return { status: "error", exitCode: 1, reason: "PATH_IS_FILE" };
}
if (!link) {
link = await getLinkedProject(client, path2);
}
const isTTY = client.stdin.isTTY;
let rootDirectory = null;
let newProjectName;
let org;
if (!forceDelete && link.status === "linked") {
return link;
}
if (forceDelete) {
const vercelDir = getVercelDirectory(path2);
(0, import_fs_extra2.remove)(join(vercelDir, VERCEL_DIR_README));
(0, import_fs_extra2.remove)(join(vercelDir, VERCEL_DIR_PROJECT));
}
if (!isTTY && !autoConfirm && !nonInteractive) {
return { status: "error", exitCode: 1, reason: "HEADLESS" };
}
const shouldStartSetup = autoConfirm || nonInteractive || await client.input.confirm(
`${setupMsg} ${import_chalk6.default.cyan(`\u201C${humanizePath(path2)}\u201D`)}?`,
true
);
if (!shouldStartSetup) {
output_manager_default.print(`Canceled. Project not set up.
`);
return { status: "not_linked", org: null, project: null };
}
try {
org = await selectOrg(
client,
"Which scope should contain your project?",
autoConfirm
);
} catch (err) {
if (isAPIError(err)) {
if (err.code === "NOT_AUTHORIZED") {
output_manager_default.prettyError(err);
return { status: "error", exitCode: 1, reason: "NOT_AUTHORIZED" };
}
if (err.code === "TEAM_DELETED") {
output_manager_default.prettyError(err);
return { status: "error", exitCode: 1, reason: "TEAM_DELETED" };
}
}
throw err;
}
let projectOrNewProjectName;
try {
projectOrNewProjectName = await inputProject(
client,
org,
projectName,
autoConfirm
);
} catch (err) {
if (err instanceof Error && err.code === "HEADLESS") {
return { status: "error", exitCode: 1, reason: "HEADLESS" };
}
throw err;
}
if (typeof projectOrNewProjectName === "string") {
newProjectName = projectOrNewProjectName;
rootDirectory = await inputRootDirectory(client, path2, autoConfirm);
} else {
const project = projectOrNewProjectName;
await linkFolderToProject(
client,
path2,
{
projectId: project.id,
orgId: org.id
},
project.name,
org.slug,
successEmoji,
autoConfirm,
pullEnv
);
return { status: "linked", org, project };
}
if (rootDirectory && !await validateRootDirectory(path2, join(path2, rootDirectory))) {
return { status: "error", exitCode: 1, reason: "INVALID_ROOT_DIRECTORY" };
}
config.currentTeam = org.type === "team" ? org.id : void 0;
const pathWithRootDirectory = rootDirectory ? join(path2, rootDirectory) : path2;
const localConfig = await readConfig(pathWithRootDirectory);
if (localConfig instanceof CantParseJSONFile) {
output_manager_default.prettyError(localConfig);
return { status: "error", exitCode: 1 };
}
const isZeroConfig = !localConfig || !localConfig.builds || localConfig.builds.length === 0;
const servicesResult = await tryDetectServices(pathWithRootDirectory);
try {
let settings = {};
if (servicesResult) {
displayDetectedServices(servicesResult.services);
if (servicesResult.errors.length > 0) {
displayServiceErrors(servicesResult.errors);
}
displayServicesConfigNote();
settings.framework = "services";
} else if (isZeroConfig) {
const localConfigurationOverrides = {
buildCommand: localConfig?.buildCommand,
devCommand: localConfig?.devCommand,
framework: localConfig?.framework,
commandForIgnoringBuildStep: localConfig?.ignoreCommand,
installCommand: localConfig?.installCommand,
outputDirectory: localConfig?.outputDirectory
};
const detectedProjectsForWorkspace = await detectProjects(
pathWithRootDirectory
);
const detectedProjects = detectedProjectsForWorkspace.get("") || [];
const framework = detectedProjects[0] ?? import_frameworks3.frameworkList.find((f) => f.slug === null);
settings = await editProjectSettings(
client,
{},
framework,
autoConfirm,
localConfigurationOverrides
);
}
let changeAdditionalSettings = false;
if (!autoConfirm) {
changeAdditionalSettings = await client.input.confirm(
"Do you want to change additional project settings?",
false
);
}
let vercelAuthSetting = DEFAULT_VERCEL_AUTH_SETTING;
if (changeAdditionalSettings) {
vercelAuthSetting = await vercelAuth(client, {
autoConfirm
});
}
if (rootDirectory) {
settings.rootDirectory = rootDirectory;
}
const project = await createProject(client, {
...settings,
name: newProjectName,
vercelAuth: vercelAuthSetting,
v0
});
await linkFolderToProject(
client,
path2,
{
projectId: project.id,
orgId: org.id
},
project.name,
org.slug,
successEmoji,
autoConfirm,
false
// don't prompt to pull env for newly created projects
);
await connectGitRepository(client, path2, project, autoConfirm, org);
return { status: "linked", org, project };
} catch (err) {
if (isAPIError(err) && err.code === "too_many_projects") {
output_manager_default.prettyError(err);
return { status: "error", exitCode: 1, reason: "TOO_MANY_PROJECTS" };
}
if (err instanceof Error && err.code === "HEADLESS") {
return { status: "error", exitCode: 1, reason: "HEADLESS" };
}
printError(err);
return { status: "error", exitCode: 1 };
}
}
async function connectGitRepository(client, path2, project, autoConfirm, org) {
try {
const gitConfig = await parseGitConfig(join(path2, ".git/config"));
if (!gitConfig) {
return;
}
const remoteUrls = pluckRemoteUrls(gitConfig);
if (!remoteUrls || Object.keys(remoteUrls).length === 0) {
return;
}
const shouldConnect = autoConfirm || await client.input.confirm(
`Detected a repository. Connect it to this project?`,
true
);
if (!shouldConnect) {
return;
}
const repoInfo = await selectAndParseRemoteUrl(client, remoteUrls);
if (!repoInfo) {
return;
}
await checkExistsAndConnect({
client,
confirm: autoConfirm,
gitProviderLink: project.link,
org,
gitOrg: repoInfo.org,
project,
// Type assertion since we only need the id
provider: repoInfo.provider,
repo: repoInfo.repo,
repoPath: `${repoInfo.org}/${repoInfo.repo}`
});
} catch (error) {
output_manager_default.debug(`Failed to connect git repository: ${error}`);
}
}
export {
validateRootDirectory,
validatePaths,
readConfig,
displayDetectedServices,
setupAndLink
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
getLinkedProject
} from "./chunk-QNEHY3TU.js";
import {
getCommandName,
getFlagsSpecification,
parseArguments,
printError
} from "./chunk-ZLCMHY2G.js";
import {
output_manager_default
} from "./chunk-FDJURQMQ.js";
import {
require_source
} from "./chunk-S7KYDPEM.js";
import {
__toESM
} from "./chunk-TZ2YI2VH.js";
// src/util/routes/types.ts
var ROUTE_TYPE_LABELS = {
rewrite: "Rewrite",
redirect: "Redirect",
set_status: "Set Status",
transform: "Transform"
};
function getRouteTypeLabel(rule) {
if (!rule.routeType)
return "-";
return ROUTE_TYPE_LABELS[rule.routeType] ?? "-";
}
var SRC_SYNTAX_LABELS = {
equals: "Exact Match",
"path-to-regexp": "Pattern",
regex: "Regex"
};
function getSrcSyntaxLabel(rule) {
const syntax = rule.srcSyntax ?? "regex";
return SRC_SYNTAX_LABELS[syntax];
}
// src/commands/routes/shared.ts
var import_chalk = __toESM(require_source(), 1);
async function parseSubcommandArgs(argv, command) {
let parsedArgs;
const flagsSpecification = getFlagsSpecification(command.options);
try {
parsedArgs = parseArguments(argv, flagsSpecification);
} catch (err) {
printError(err);
return 1;
}
return parsedArgs;
}
async function ensureProjectLink(client) {
const link = await getLinkedProject(client);
if (link.status === "error") {
return link.exitCode;
} else if (link.status === "not_linked") {
output_manager_default.error(
`Your codebase isn't linked to a project on Vercel. Run ${getCommandName("link")} to begin.`
);
return 1;
}
client.config.currentTeam = link.org.type === "team" ? link.org.id : void 0;
return link;
}
async function confirmAction(client, skipConfirmation, message, details) {
if (skipConfirmation)
return true;
if (details) {
output_manager_default.print(` ${details}
`);
}
return await client.input.confirm(message, false);
}
function validateRequiredArgs(args, required) {
for (let i = 0; i < required.length; i++) {
if (!args[i]) {
return `Missing required argument: ${required[i]}`;
}
}
return null;
}
function formatCondition(condition) {
const parts = [import_chalk.default.gray(`[${condition.type}]`)];
if (condition.key) {
parts.push(import_chalk.default.cyan(condition.key));
}
if (condition.value !== void 0) {
const formatted = typeof condition.value === "string" ? condition.value : JSON.stringify(condition.value);
parts.push(condition.key ? `= ${formatted}` : formatted);
}
return parts.join(" ");
}
var TRANSFORM_TYPE_LABELS = {
"request.headers": "Request Header",
"request.query": "Request Query",
"response.headers": "Response Header"
};
var TRANSFORM_OP_LABELS = {
set: "set",
append: "append",
delete: "delete"
};
function formatTransform(transform, includeType = true) {
const opLabel = TRANSFORM_OP_LABELS[transform.op] ?? transform.op;
const key = typeof transform.target.key === "string" ? transform.target.key : JSON.stringify(transform.target.key);
const parts = [];
if (includeType) {
const typeLabel = TRANSFORM_TYPE_LABELS[transform.type] ?? transform.type;
parts.push(import_chalk.default.gray(`[${typeLabel}]`));
}
parts.push(import_chalk.default.yellow(opLabel), import_chalk.default.cyan(key));
if (transform.args !== void 0 && transform.op !== "delete") {
const argsStr = Array.isArray(transform.args) ? transform.args.join(", ") : transform.args;
parts.push(`= ${argsStr}`);
}
return parts.join(" ");
}
function parsePosition(position) {
if (position === "start") {
return { placement: "start" };
}
if (position === "end") {
return { placement: "end" };
}
if (position.startsWith("after:")) {
const referenceId = position.slice(6);
if (!referenceId) {
throw new Error('Position "after:" requires a route ID');
}
return { placement: "after", referenceId };
}
if (position.startsWith("before:")) {
const referenceId = position.slice(7);
if (!referenceId) {
throw new Error('Position "before:" requires a route ID');
}
return { placement: "before", referenceId };
}
throw new Error(
`Invalid position: "${position}". Use: start, end, after:<id>, or before:<id>`
);
}
async function offerAutoPromote(client, projectId, version, hadExistingStagingVersion, opts) {
const { default: updateRouteVersion } = await import("./update-route-version-E3V47KNI.js");
const { default: stamp } = await import("./stamp-RTPE2EBB.js");
output_manager_default.print(
`
${import_chalk.default.gray(`This change is staged. Run ${import_chalk.default.cyan(getCommandName("routes publish"))} to make it live, or ${import_chalk.default.cyan(getCommandName("routes discard-staging"))} to undo.`)}
`
);
if (!hadExistingStagingVersion && !opts.skipPrompts) {
output_manager_default.print("\n");
const shouldPromote = await client.input.confirm(
"This is the only staged change. Promote to production now?",
false
);
if (shouldPromote) {
const promoteStamp = stamp();
output_manager_default.spinner("Promoting to production");
try {
await updateRouteVersion(client, projectId, version.id, "promote", {
teamId: opts.teamId
});
output_manager_default.log(
`${import_chalk.default.cyan("Promoted")} to production ${import_chalk.default.gray(promoteStamp())}`
);
} catch (e) {
const err = e;
output_manager_default.error(
`Failed to promote to production: ${err.message || "Unknown error"}`
);
}
}
} else if (hadExistingStagingVersion) {
output_manager_default.warn(
`There are other staged changes. Review with ${import_chalk.default.cyan(getCommandName("routes list --diff"))} before promoting.`
);
}
}
function printDiffSummary(routes, maxDisplay = 10) {
const displayRoutes = routes.slice(0, maxDisplay);
for (const route of displayRoutes) {
const symbol = getDiffSymbol(route);
const label = getDiffLabel(route);
const routeType = getRouteTypeLabel(route);
output_manager_default.print(
` ${symbol} ${route.name}${routeType !== "-" ? ` ${import_chalk.default.gray(`(${routeType})`)}` : ""} ${import_chalk.default.gray(`- ${label}`)}
`
);
}
if (routes.length > maxDisplay) {
output_manager_default.print(
import_chalk.default.gray(`
... and ${routes.length - maxDisplay} more changes
`)
);
}
}
function getDiffSymbol(route) {
if (route.action === "+")
return import_chalk.default.green("+");
if (route.action === "-")
return import_chalk.default.red("-");
return import_chalk.default.yellow("~");
}
function getDiffLabel(route) {
if (route.action === "+")
return "Added";
if (route.action === "-")
return "Deleted";
const isReordered = route.previousIndex !== void 0 && route.newIndex !== void 0;
if (isReordered) {
return `Reordered (${route.previousIndex + 1} \u2192 ${route.newIndex + 1})`;
}
if (route.previousEnabled !== void 0) {
return route.enabled === false ? "Disabled" : "Enabled";
}
return "Modified";
}
async function resolveRoute(client, routes, identifier) {
const byId = routes.find((r) => r.id === identifier);
if (byId)
return byId;
const query = identifier.toLowerCase();
const matches = routes.filter(
(r) => r.name.toLowerCase() === query || r.name.toLowerCase().includes(query) || r.id.toLowerCase().includes(query)
);
if (matches.length === 0) {
return null;
}
if (matches.length === 1) {
return matches[0];
}
const selectedId = await client.input.select({
message: `Multiple routes match "${identifier}". Select one:`,
choices: matches.map((route) => ({
value: route.id,
name: `${route.name} ${import_chalk.default.gray(`(${route.route.src})`)}`
}))
});
return matches.find((r) => r.id === selectedId) ?? null;
}
async function resolveRoutes(client, routes, identifiers) {
const resolved = /* @__PURE__ */ new Map();
for (const identifier of identifiers) {
const route = await resolveRoute(client, routes, identifier);
if (!route) {
output_manager_default.error(
`No route found matching "${identifier}". Run ${import_chalk.default.cyan(
getCommandName("routes list")
)} to see all routes.`
);
return null;
}
resolved.set(route.id, route);
}
return Array.from(resolved.values());
}
function findVersionById(versions, identifier) {
const matchingVersions = versions.filter((v) => v.id.startsWith(identifier));
if (matchingVersions.length === 0) {
return {
error: `Version "${identifier}" not found. Run ${import_chalk.default.cyan(
getCommandName("routes list-versions")
)} to see available versions.`
};
}
if (matchingVersions.length > 1) {
return {
error: `Multiple versions match "${identifier}". Please provide a more specific ID:
${matchingVersions.map((v) => ` ${v.id}`).join("\n")}`
};
}
return { version: matchingVersions[0] };
}
// src/util/routes/get-routes.ts
async function getRoutes(client, projectId, options = {}) {
const { teamId, search, filter, versionId, diff } = options;
const query = new URLSearchParams();
if (teamId)
query.set("teamId", teamId);
if (search)
query.set("q", search);
if (filter)
query.set("filter", filter);
if (versionId)
query.set("versionId", versionId);
if (diff)
query.set("diff", "true");
const queryString = query.toString();
const url = `/v1/projects/${projectId}/routes${queryString ? `?${queryString}` : ""}`;
const response = await client.fetch(url);
return response;
}
export {
getRouteTypeLabel,
getSrcSyntaxLabel,
parseSubcommandArgs,
ensureProjectLink,
confirmAction,
validateRequiredArgs,
formatCondition,
TRANSFORM_TYPE_LABELS,
formatTransform,
parsePosition,
offerAutoPromote,
printDiffSummary,
resolveRoute,
resolveRoutes,
findVersionById,
getRoutes
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
getEnvTargetPlaceholder
} from "./chunk-QNEHY3TU.js";
import {
packageName,
yesOption
} from "./chunk-ZLCMHY2G.js";
// src/commands/build/command.ts
var buildCommand = {
name: "build",
aliases: [],
description: "Build the project.",
arguments: [],
options: [
{
name: "prod",
description: "Build a production deployment",
shorthand: null,
type: Boolean,
deprecated: false
},
{
name: "target",
shorthand: null,
type: String,
argument: "TARGET",
deprecated: false,
description: "Specify the target environment"
},
{
name: "output",
description: "Directory where built assets will be written to",
shorthand: null,
argument: "DIR",
type: String,
deprecated: false
},
{
...yesOption,
description: "Skip the confirmation prompt about pulling environment variables and project settings when not found locally"
},
{
name: "standalone",
description: "Create a standalone build with all dependencies inlined into function output folders",
shorthand: null,
type: Boolean,
deprecated: false
}
],
examples: [
{
name: "Build the project",
value: `${packageName} build`
},
{
name: "Build the project in a specific directory",
value: `${packageName} build --cwd ./path-to-project`
}
]
};
// src/commands/pull/command.ts
var pullCommand = {
name: "pull",
aliases: [],
description: "Pull latest environment variables and project settings from Vercel. ",
arguments: [
{
name: "project-path",
required: false
}
],
options: [
{
name: "environment",
description: "Deployment environment [development]",
argument: "TARGET",
shorthand: null,
type: String,
deprecated: false
},
{
name: "git-branch",
description: "Specify the Git branch to pull specific Environment Variables for",
argument: "NAME",
shorthand: null,
type: String,
deprecated: false
},
{
name: "prod",
shorthand: null,
type: Boolean,
deprecated: false
},
{
...yesOption,
description: "Skip questions when setting up new project using default scope and settings"
}
],
examples: [
{
name: "Pull the latest Environment Variables and Project Settings from the cloud",
value: `${packageName} pull`
},
{
name: "Pull the latest Environment Variables and Project Settings from the cloud targeting a directory",
value: `${packageName} pull ./path-to-project`
},
{
name: "Pull for a specific environment",
value: `${packageName} pull --environment=${getEnvTargetPlaceholder()}`
},
{
name: "Pull for a preview feature branch",
value: `${packageName} pull --environment=preview --git-branch=feature-branch`
},
{
name: "If you want to download environment variables to a specific file, use `vercel env pull` instead",
value: `${packageName} env pull`
}
]
};
export {
buildCommand,
pullCommand
};

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
require_once
} from "./chunk-QNEHY3TU.js";
import {
__commonJS
} from "./chunk-TZ2YI2VH.js";
// ../../node_modules/.pnpm/end-of-stream@1.4.1/node_modules/end-of-stream/index.js
var require_end_of_stream = __commonJS({
"../../node_modules/.pnpm/end-of-stream@1.4.1/node_modules/end-of-stream/index.js"(exports, module) {
var once = require_once();
var noop = function() {
};
var isRequest = function(stream) {
return stream.setHeader && typeof stream.abort === "function";
};
var isChildProcess = function(stream) {
return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3;
};
var eos = function(stream, opts, callback) {
if (typeof opts === "function")
return eos(stream, null, opts);
if (!opts)
opts = {};
callback = once(callback || noop);
var ws = stream._writableState;
var rs = stream._readableState;
var readable = opts.readable || opts.readable !== false && stream.readable;
var writable = opts.writable || opts.writable !== false && stream.writable;
var onlegacyfinish = function() {
if (!stream.writable)
onfinish();
};
var onfinish = function() {
writable = false;
if (!readable)
callback.call(stream);
};
var onend = function() {
readable = false;
if (!writable)
callback.call(stream);
};
var onexit = function(exitCode) {
callback.call(stream, exitCode ? new Error("exited with error code: " + exitCode) : null);
};
var onerror = function(err) {
callback.call(stream, err);
};
var onclose = function() {
if (readable && !(rs && rs.ended))
return callback.call(stream, new Error("premature close"));
if (writable && !(ws && ws.ended))
return callback.call(stream, new Error("premature close"));
};
var onrequest = function() {
stream.req.on("finish", onfinish);
};
if (isRequest(stream)) {
stream.on("complete", onfinish);
stream.on("abort", onclose);
if (stream.req)
onrequest();
else
stream.on("request", onrequest);
} else if (writable && !ws) {
stream.on("end", onlegacyfinish);
stream.on("close", onlegacyfinish);
}
if (isChildProcess(stream))
stream.on("exit", onexit);
stream.on("end", onend);
stream.on("finish", onfinish);
if (opts.error !== false)
stream.on("error", onerror);
stream.on("close", onclose);
return function() {
stream.removeListener("complete", onfinish);
stream.removeListener("abort", onclose);
stream.removeListener("request", onrequest);
if (stream.req)
stream.req.removeListener("finish", onfinish);
stream.removeListener("end", onlegacyfinish);
stream.removeListener("close", onlegacyfinish);
stream.removeListener("finish", onfinish);
stream.removeListener("exit", onexit);
stream.removeListener("end", onend);
stream.removeListener("error", onerror);
stream.removeListener("close", onclose);
};
};
module.exports = eos;
}
});
export {
require_end_of_stream
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
getUpdateCommand
} from "./chunk-3BCRZT46.js";
import {
login
} from "./chunk-W3QZF2OP.js";
import {
loginCommand
} from "./chunk-QZ3VE5AG.js";
import {
help
} from "./chunk-DOBFJJLK.js";
import {
TelemetryClient
} from "./chunk-XB2KZC2B.js";
import {
getFlagsSpecification,
parseArguments,
printError,
require_strip_ansi
} from "./chunk-ZLCMHY2G.js";
import {
output_manager_default
} from "./chunk-FDJURQMQ.js";
import {
require_source
} from "./chunk-S7KYDPEM.js";
import {
__commonJS,
__toESM
} from "./chunk-TZ2YI2VH.js";
// ../../node_modules/.pnpm/jaro-winkler@0.2.8/node_modules/jaro-winkler/index.js
var require_jaro_winkler = __commonJS({
"../../node_modules/.pnpm/jaro-winkler@0.2.8/node_modules/jaro-winkler/index.js"(exports, module) {
(function(root) {
"use strict";
function extend(a, b) {
for (var property in b) {
if (b.hasOwnProperty(property)) {
a[property] = b[property];
}
}
return a;
}
function distance2(s1, s2, options) {
var m = 0;
var defaults = { caseSensitive: true };
var settings = extend(defaults, options);
var i;
var j;
if (s1.length === 0 || s2.length === 0) {
return 0;
}
if (!settings.caseSensitive) {
s1 = s1.toUpperCase();
s2 = s2.toUpperCase();
}
if (s1 === s2) {
return 1;
}
var range = Math.floor(Math.max(s1.length, s2.length) / 2) - 1;
var s1Matches = new Array(s1.length);
var s2Matches = new Array(s2.length);
for (i = 0; i < s1.length; i++) {
var low = i >= range ? i - range : 0;
var high = i + range <= s2.length - 1 ? i + range : s2.length - 1;
for (j = low; j <= high; j++) {
if (s1Matches[i] !== true && s2Matches[j] !== true && s1[i] === s2[j]) {
++m;
s1Matches[i] = s2Matches[j] = true;
break;
}
}
}
if (m === 0) {
return 0;
}
var k = 0;
var numTrans = 0;
for (i = 0; i < s1.length; i++) {
if (s1Matches[i] === true) {
for (j = k; j < s2.length; j++) {
if (s2Matches[j] === true) {
k = j + 1;
break;
}
}
if (s1[i] !== s2[j]) {
++numTrans;
}
}
}
var weight = (m / s1.length + m / s2.length + (m - numTrans / 2) / m) / 3;
var l = 0;
var p = 0.1;
if (weight > 0.7) {
while (s1[l] === s2[l] && l < 4) {
++l;
}
weight = weight + l * p * (1 - weight);
}
return weight;
}
if (typeof define === "function" && define.amd) {
define([], function() {
return distance2;
});
} else if (typeof exports === "object") {
module.exports = distance2;
} else {
root.distance = distance2;
}
})(exports);
}
});
// src/util/upgrade.ts
import { spawn } from "child_process";
async function executeUpgrade() {
const updateCommand = await getUpdateCommand();
const [command, ...args] = updateCommand.split(" ");
output_manager_default.log(`Upgrading Vercel CLI...`);
output_manager_default.debug(`Executing: ${updateCommand}`);
return new Promise((resolve) => {
const stdout = [];
const stderr = [];
const upgradeProcess = spawn(command, args, {
stdio: ["inherit", "pipe", "pipe"],
shell: false
});
upgradeProcess.stdout?.on("data", (data) => {
stdout.push(data);
});
upgradeProcess.stderr?.on("data", (data) => {
stderr.push(data);
});
upgradeProcess.on("error", (err) => {
output_manager_default.error(`Failed to execute upgrade command: ${err.message}`);
output_manager_default.log(`You can try running the command manually: ${updateCommand}`);
resolve(1);
});
upgradeProcess.on("close", (code) => {
if (code === 0) {
output_manager_default.success("Vercel CLI has been upgraded successfully!");
} else {
const stdoutStr = Buffer.concat(stdout).toString();
const stderrStr = Buffer.concat(stderr).toString();
if (stdoutStr) {
output_manager_default.print(stdoutStr);
}
if (stderrStr) {
output_manager_default.print(stderrStr);
}
output_manager_default.error(`Upgrade failed with exit code ${code ?? "unknown"}`);
output_manager_default.log(
`You can try running the command manually: ${updateCommand}`
);
}
resolve(code ?? 1);
});
});
}
// src/commands/login/index.ts
var import_chalk = __toESM(require_source(), 1);
// src/util/telemetry/commands/login/index.ts
var LoginTelemetryClient = class extends TelemetryClient {
/**
* Tracks the state of the login process.
* - `started` when the user initiates the login process.
* - `canceled` when the user cancels the login process.
* - `error` when the user encounters an error during the login process.
* - `success` when the user successfully logs in.
*/
trackState(...args) {
this.trackLoginState(...args);
}
};
// src/commands/login/index.ts
async function login2(client, options) {
let parsedArgs = null;
const flagsSpecification = getFlagsSpecification(loginCommand.options);
const telemetry = new LoginTelemetryClient({
opts: {
store: client.telemetryEventStore
}
});
try {
if (options.shouldParseArgs) {
parsedArgs = parseArguments(client.argv.slice(2), flagsSpecification);
}
} catch (error) {
printError(error);
return 1;
}
if (parsedArgs?.flags["--help"]) {
telemetry.trackCliFlagHelp("login");
output_manager_default.print(help(loginCommand, { columns: client.stderr.columns }));
return 0;
}
if (parsedArgs?.flags["--token"]) {
output_manager_default.error('`--token` may not be used with the "login" command');
return 2;
}
if (options.shouldParseArgs && parsedArgs) {
const obsoleteFlags = Object.keys(parsedArgs.flags).filter((flag) => {
const flagKey = flag.replace("--", "");
const option = loginCommand.options.find((o) => o.name === flagKey);
if (!option || typeof option === "number")
return;
return "deprecated" in option && option.deprecated;
});
if (obsoleteFlags.length) {
const flags = obsoleteFlags.map((f) => import_chalk.default.bold(f)).join(", ");
output_manager_default.warn(`The following flags are deprecated: ${flags}`);
}
const obsoleteArguments = parsedArgs.args.slice(1);
if (obsoleteArguments.length) {
const args = obsoleteArguments.map((a) => import_chalk.default.bold(a)).join(", ");
output_manager_default.warn(`The following arguments are deprecated: ${args}`);
}
if (obsoleteArguments.length || obsoleteFlags.length) {
output_manager_default.print(
`Read more in our ${output_manager_default.link("changelog", "https://vercel.com/changelog/new-vercel-cli-login-flow")}.
`
);
}
}
telemetry.trackState("started");
return await login(client, telemetry);
}
// src/util/output/box.ts
var import_chalk2 = __toESM(require_source(), 1);
var import_strip_ansi = __toESM(require_strip_ansi(), 1);
var border = ["\u2500", "\u256D", "\u256E", "\u2502", "\u2502", "\u2570", "\u256F"];
var nothing = ["\u2500", "", "", "", "", "", ""];
function box(message, {
borderColor,
padding = 1,
textAlignment = "center",
terminalColumns: cols = process.stdout.columns || process.env.COLUMNS && parseInt(process.env.COLUMNS, 10) || 80
} = {}) {
const lines = message.split(/\r?\n/).map((line) => [line, (0, import_strip_ansi.default)(line).length]);
const maxLine = lines.reduce((p, [, len]) => Math.max(p, len), 0);
const borderColorFn = borderColor && import_chalk2.default[borderColor] || import_chalk2.default.yellow;
const clampedSidePadding = Math.max(1, padding * 3);
const narrowMode = maxLine + 2 + clampedSidePadding * 2 > cols;
const sidePadding = narrowMode ? 0 : clampedSidePadding;
const innerWidth = Math.min(maxLine + sidePadding * 2, cols);
const [hr, topLeft, topRight, left, right, bottomLeft, bottomRight] = narrowMode ? nothing : border;
const spacerRow = narrowMode ? "\n".repeat(padding) : `${borderColorFn(`${left}${" ".repeat(innerWidth)}${right}`)}
`.repeat(
padding
);
const renderLine = ([line, len]) => {
let leftPadding = 0;
let rightPadding = 0;
if (!narrowMode) {
leftPadding = sidePadding;
rightPadding = sidePadding;
if (textAlignment === "center") {
leftPadding += Math.floor((maxLine - len) / 2);
rightPadding += maxLine - len - leftPadding + sidePadding;
} else if (textAlignment === "right") {
leftPadding += maxLine - len;
} else if (textAlignment === "left") {
rightPadding += maxLine - len;
}
}
return borderColorFn(left) + " ".repeat(leftPadding) + line + " ".repeat(rightPadding) + borderColorFn(right);
};
return borderColorFn(`${topLeft}${hr.repeat(innerWidth)}${topRight}`) + "\n" + spacerRow + lines.map(renderLine).join("\n") + "\n" + spacerRow + borderColorFn(`${bottomLeft}${hr.repeat(innerWidth)}${bottomRight}`);
}
// src/util/did-you-mean.ts
var import_jaro_winkler = __toESM(require_jaro_winkler(), 1);
var did_you_mean_default = didYouMean;
function didYouMean(input, list, threshold = 0.5) {
const rated = list.map((item) => [dashAwareDistance(input, item), item]);
const found = rated.filter((item) => item[0] > threshold);
if (found.length) {
const highestRated = found.reduce((accu, curr) => {
return accu[0] > curr[0] ? accu : curr;
});
return highestRated[1];
}
}
function dashAwareDistance(word, dashWord) {
const fullDistance = (0, import_jaro_winkler.default)(word, dashWord);
const distances = dashWord.split("-").map((w) => (0, import_jaro_winkler.default)(w, word));
const meanDistance = distances.reduce((accu, curr) => accu + curr) / distances.length;
return fullDistance > meanDistance ? fullDistance : meanDistance;
}
export {
did_you_mean_default,
executeUpgrade,
login2 as login,
box
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
DEFAULT_VERCEL_CONFIG_FILENAME,
VERCEL_CONFIG_EXTENSIONS,
compileVercelConfig,
findSourceVercelConfigFile,
getVercelConfigPath,
normalizeConfig
} from "./chunk-6LQRDWWM.js";
import "./chunk-QNEHY3TU.js";
import "./chunk-XB2KZC2B.js";
import "./chunk-SOTR4CXR.js";
import "./chunk-7EHTK7LP.js";
import "./chunk-GGP5R3FU.js";
import "./chunk-ZLCMHY2G.js";
import "./chunk-3XFFP2BA.js";
import "./chunk-FDJURQMQ.js";
import "./chunk-S7KYDPEM.js";
import "./chunk-TZ2YI2VH.js";
export {
DEFAULT_VERCEL_CONFIG_FILENAME,
VERCEL_CONFIG_EXTENSIONS,
compileVercelConfig,
findSourceVercelConfigFile,
getVercelConfigPath,
normalizeConfig
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
getRouteVersions
} from "./chunk-AHU7WNL2.js";
import {
ensureProjectLink,
getRouteTypeLabel,
getRoutes,
offerAutoPromote,
parseSubcommandArgs,
resolveRoutes
} from "./chunk-OJOIUL2M.js";
import {
deleteSubcommand
} from "./chunk-U6XOC6E4.js";
import "./chunk-QNEHY3TU.js";
import "./chunk-XB2KZC2B.js";
import {
stamp_default
} from "./chunk-SOTR4CXR.js";
import "./chunk-7EHTK7LP.js";
import "./chunk-GGP5R3FU.js";
import {
getCommandName
} from "./chunk-ZLCMHY2G.js";
import "./chunk-3XFFP2BA.js";
import {
output_manager_default
} from "./chunk-FDJURQMQ.js";
import {
require_source
} from "./chunk-S7KYDPEM.js";
import {
__toESM
} from "./chunk-TZ2YI2VH.js";
// src/commands/routes/delete.ts
var import_chalk = __toESM(require_source(), 1);
// src/util/routes/delete-routes.ts
async function deleteRoutes(client, projectId, routeIds, options = {}) {
const { teamId } = options;
const query = new URLSearchParams();
if (teamId)
query.set("teamId", teamId);
const queryString = query.toString();
const url = `/v1/projects/${projectId}/routes${queryString ? `?${queryString}` : ""}`;
return await client.fetch(url, {
method: "DELETE",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ routeIds })
});
}
// src/commands/routes/delete.ts
async function deleteRoute(client, argv) {
const parsed = await parseSubcommandArgs(argv, deleteSubcommand);
if (typeof parsed === "number")
return parsed;
const link = await ensureProjectLink(client);
if (typeof link === "number")
return link;
const { project, org } = link;
const teamId = org.type === "team" ? org.id : void 0;
const { args, flags } = parsed;
const skipConfirmation = flags["--yes"];
if (args.length === 0) {
output_manager_default.error(
`At least one route name or ID is required. Usage: ${getCommandName("routes delete <name-or-id> [...]")}`
);
return 1;
}
const { versions } = await getRouteVersions(client, project.id, { teamId });
const existingStagingVersion = versions.find((v) => v.isStaging);
output_manager_default.spinner("Fetching routes");
const { routes } = await getRoutes(client, project.id, { teamId });
output_manager_default.stopSpinner();
if (routes.length === 0) {
output_manager_default.error("No routes found in this project.");
return 1;
}
const resolved = await resolveRoutes(client, routes, args);
if (!resolved)
return 1;
output_manager_default.print("\n");
output_manager_default.log(
`The following ${resolved.length === 1 ? "route" : `${resolved.length} routes`} will be deleted:`
);
for (const route of resolved) {
const typeLabels = getRouteTypeLabel(route);
output_manager_default.print(
` ${import_chalk.default.red("\xD7")} ${route.name} ${import_chalk.default.gray(`(${route.route.src})`)} ${import_chalk.default.gray(`[${typeLabels}]`)}
`
);
}
output_manager_default.print("\n");
if (!skipConfirmation) {
const confirmed = await client.input.confirm(
`Delete ${resolved.length === 1 ? "this route" : `these ${resolved.length} routes`}?`,
false
);
if (!confirmed) {
output_manager_default.log("Aborted.");
return 0;
}
}
const deleteStamp = stamp_default();
output_manager_default.spinner(
`Deleting ${resolved.length === 1 ? "route" : `${resolved.length} routes`}`
);
try {
const { deletedCount, version } = await deleteRoutes(
client,
project.id,
resolved.map((r) => r.id),
{ teamId }
);
output_manager_default.log(
`${import_chalk.default.cyan("Deleted")} ${deletedCount} ${deletedCount === 1 ? "route" : "routes"} ${import_chalk.default.gray(deleteStamp())}`
);
await offerAutoPromote(
client,
project.id,
version,
!!existingStagingVersion,
{ teamId, skipPrompts: skipConfirmation }
);
return 0;
} catch (e) {
const error = e;
output_manager_default.error(error.message || "Failed to delete routes");
return 1;
}
}
export {
deleteRoute as default
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
editRoute
} from "./chunk-P3SKP5WM.js";
import {
getRouteVersions
} from "./chunk-AHU7WNL2.js";
import {
ensureProjectLink,
getRoutes,
offerAutoPromote,
parseSubcommandArgs,
resolveRoute
} from "./chunk-OJOIUL2M.js";
import {
disableSubcommand
} from "./chunk-U6XOC6E4.js";
import "./chunk-QNEHY3TU.js";
import "./chunk-XB2KZC2B.js";
import {
stamp_default
} from "./chunk-SOTR4CXR.js";
import "./chunk-7EHTK7LP.js";
import "./chunk-GGP5R3FU.js";
import {
getCommandName
} from "./chunk-ZLCMHY2G.js";
import "./chunk-3XFFP2BA.js";
import {
output_manager_default
} from "./chunk-FDJURQMQ.js";
import {
require_source
} from "./chunk-S7KYDPEM.js";
import {
__toESM
} from "./chunk-TZ2YI2VH.js";
// src/commands/routes/disable.ts
var import_chalk = __toESM(require_source(), 1);
async function disable(client, argv) {
const parsed = await parseSubcommandArgs(argv, disableSubcommand);
if (typeof parsed === "number")
return parsed;
const link = await ensureProjectLink(client);
if (typeof link === "number")
return link;
const { project, org } = link;
const teamId = org.type === "team" ? org.id : void 0;
const { args } = parsed;
const identifier = args[0];
if (!identifier) {
output_manager_default.error(
`Route name or ID is required. Usage: ${getCommandName("routes disable <name-or-id>")}`
);
return 1;
}
const { versions } = await getRouteVersions(client, project.id, { teamId });
const existingStagingVersion = versions.find((v) => v.isStaging);
output_manager_default.spinner("Fetching routes");
const { routes } = await getRoutes(client, project.id, { teamId });
output_manager_default.stopSpinner();
if (routes.length === 0) {
output_manager_default.error("No routes found in this project.");
return 1;
}
const route = await resolveRoute(client, routes, identifier);
if (!route) {
output_manager_default.error(
`No route found matching "${identifier}". Run ${import_chalk.default.cyan(
getCommandName("routes list")
)} to see all routes.`
);
return 1;
}
if (route.enabled === false) {
output_manager_default.log(`Route "${route.name}" is already disabled.`);
return 0;
}
const disableStamp = stamp_default();
output_manager_default.spinner(`Disabling route "${route.name}"`);
try {
const { version } = await editRoute(
client,
project.id,
route.id,
{
route: {
name: route.name,
description: route.description,
enabled: false,
srcSyntax: route.srcSyntax,
route: route.route
}
},
{ teamId }
);
output_manager_default.log(
`${import_chalk.default.cyan("Disabled")} route "${route.name}" ${import_chalk.default.gray(disableStamp())}`
);
await offerAutoPromote(
client,
project.id,
version,
!!existingStagingVersion,
{ teamId }
);
return 0;
} catch (e) {
const error = e;
output_manager_default.error(error.message || "Failed to disable route");
return 1;
}
}
export {
disable as default
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
updateRouteVersion
} from "./chunk-PMSMUMUO.js";
import {
getRouteVersions
} from "./chunk-AHU7WNL2.js";
import {
confirmAction,
ensureProjectLink,
getRoutes,
parseSubcommandArgs,
printDiffSummary
} from "./chunk-OJOIUL2M.js";
import {
discardSubcommand
} from "./chunk-U6XOC6E4.js";
import "./chunk-QNEHY3TU.js";
import "./chunk-XB2KZC2B.js";
import {
stamp_default
} from "./chunk-SOTR4CXR.js";
import "./chunk-7EHTK7LP.js";
import "./chunk-GGP5R3FU.js";
import {
getCommandName
} from "./chunk-ZLCMHY2G.js";
import "./chunk-3XFFP2BA.js";
import {
output_manager_default
} from "./chunk-FDJURQMQ.js";
import {
require_source
} from "./chunk-S7KYDPEM.js";
import {
__toESM
} from "./chunk-TZ2YI2VH.js";
// src/commands/routes/discard.ts
var import_chalk = __toESM(require_source(), 1);
async function discard(client, argv) {
const parsed = await parseSubcommandArgs(argv, discardSubcommand);
if (typeof parsed === "number")
return parsed;
const link = await ensureProjectLink(client);
if (typeof link === "number")
return link;
const { project, org } = link;
const teamId = org.type === "team" ? org.id : void 0;
output_manager_default.spinner(`Fetching route versions for ${import_chalk.default.bold(project.name)}`);
const { versions } = await getRouteVersions(client, project.id, { teamId });
const stagingVersion = versions.find((v) => v.isStaging);
if (!stagingVersion) {
output_manager_default.warn(
`No staged changes to discard. Make changes first with ${import_chalk.default.cyan(
getCommandName("routes add")
)}.`
);
return 0;
}
output_manager_default.spinner("Fetching staged changes");
const { routes: diffRoutes } = await getRoutes(client, project.id, {
teamId,
versionId: stagingVersion.id,
diff: true
});
const changedRoutes = diffRoutes.filter((r) => r.action !== void 0);
if (changedRoutes.length > 0) {
output_manager_default.print(`
${import_chalk.default.bold("Changes to be discarded:")}
`);
printDiffSummary(changedRoutes);
output_manager_default.print("\n");
} else {
output_manager_default.print(
`
${import_chalk.default.gray("No changes detected in staging version.")}
`
);
}
const confirmed = await confirmAction(
client,
parsed.flags["--yes"],
"Discard all staged changes?",
`This action cannot be undone.`
);
if (!confirmed) {
output_manager_default.log("Canceled");
return 0;
}
const updateStamp = stamp_default();
output_manager_default.spinner("Discarding staged changes");
try {
await updateRouteVersion(client, project.id, stagingVersion.id, "discard", {
teamId
});
output_manager_default.log(
`${import_chalk.default.cyan("Success!")} Staged changes discarded ${import_chalk.default.gray(
updateStamp()
)}`
);
return 0;
} catch (e) {
const error = e;
output_manager_default.error(error.message || "Failed to discard staged changes");
return 1;
}
}
export {
discard as default
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
editRoute
} from "./chunk-P3SKP5WM.js";
import {
applyFlagMutations,
cloneRoute,
convertRouteToCurrentRoute,
generateRoute,
generatedRouteToAddInput,
hasAnyTransformFlags,
populateRouteEnv,
printGeneratedRoutePreview,
printRouteConfig,
routingRuleToCurrentRoute,
runInteractiveEditLoop
} from "./chunk-7C2ITY27.js";
import {
getRouteVersions
} from "./chunk-AHU7WNL2.js";
import {
ensureProjectLink,
getRoutes,
offerAutoPromote,
parseSubcommandArgs,
resolveRoute
} from "./chunk-OJOIUL2M.js";
import {
editSubcommand
} from "./chunk-U6XOC6E4.js";
import "./chunk-QNEHY3TU.js";
import "./chunk-XB2KZC2B.js";
import {
stamp_default
} from "./chunk-SOTR4CXR.js";
import "./chunk-7EHTK7LP.js";
import "./chunk-GGP5R3FU.js";
import {
getCommandName
} from "./chunk-ZLCMHY2G.js";
import "./chunk-3XFFP2BA.js";
import {
output_manager_default
} from "./chunk-FDJURQMQ.js";
import {
require_source
} from "./chunk-S7KYDPEM.js";
import {
__toESM
} from "./chunk-TZ2YI2VH.js";
// src/commands/routes/edit.ts
var import_chalk = __toESM(require_source(), 1);
async function edit(client, argv) {
const parsed = await parseSubcommandArgs(argv, editSubcommand);
if (typeof parsed === "number")
return parsed;
const link = await ensureProjectLink(client);
if (typeof link === "number")
return link;
const { project, org } = link;
const teamId = org.type === "team" ? org.id : void 0;
const { args, flags } = parsed;
const skipConfirmation = flags["--yes"];
const identifier = args[0];
const { RoutesEditTelemetryClient } = await import("./routes-DGDHCTY6.js");
const telemetry = new RoutesEditTelemetryClient({
opts: { store: client.telemetryEventStore }
});
telemetry.trackCliArgumentNameOrId(identifier);
telemetry.trackCliFlagYes(skipConfirmation);
telemetry.trackCliOptionName(flags["--name"]);
telemetry.trackCliOptionDescription(
flags["--description"]
);
telemetry.trackCliOptionSrc(flags["--src"]);
telemetry.trackCliOptionSrcSyntax(
flags["--src-syntax"]
);
telemetry.trackCliOptionAction(flags["--action"]);
telemetry.trackCliOptionDest(flags["--dest"]);
telemetry.trackCliOptionStatus(flags["--status"]);
telemetry.trackCliFlagNoDest(flags["--no-dest"]);
telemetry.trackCliFlagNoStatus(flags["--no-status"]);
telemetry.trackCliFlagClearConditions(
flags["--clear-conditions"]
);
telemetry.trackCliFlagClearHeaders(
flags["--clear-headers"]
);
telemetry.trackCliFlagClearTransforms(
flags["--clear-transforms"]
);
telemetry.trackCliOptionSetResponseHeader(
flags["--set-response-header"]
);
telemetry.trackCliOptionAppendResponseHeader(
flags["--append-response-header"]
);
telemetry.trackCliOptionDeleteResponseHeader(
flags["--delete-response-header"]
);
telemetry.trackCliOptionSetRequestHeader(
flags["--set-request-header"]
);
telemetry.trackCliOptionAppendRequestHeader(
flags["--append-request-header"]
);
telemetry.trackCliOptionDeleteRequestHeader(
flags["--delete-request-header"]
);
telemetry.trackCliOptionSetRequestQuery(
flags["--set-request-query"]
);
telemetry.trackCliOptionAppendRequestQuery(
flags["--append-request-query"]
);
telemetry.trackCliOptionDeleteRequestQuery(
flags["--delete-request-query"]
);
telemetry.trackCliOptionHas(flags["--has"]);
telemetry.trackCliOptionMissing(flags["--missing"]);
telemetry.trackCliOptionAi(flags["--ai"]);
if (!identifier) {
output_manager_default.error(
`Route name or ID is required. Usage: ${getCommandName("routes edit <name-or-id>")}`
);
return 1;
}
const { versions } = await getRouteVersions(client, project.id, { teamId });
const existingStagingVersion = versions.find((v) => v.isStaging);
output_manager_default.spinner("Fetching routes");
const { routes } = await getRoutes(client, project.id, { teamId });
output_manager_default.stopSpinner();
if (routes.length === 0) {
output_manager_default.error("No routes found in this project.");
return 1;
}
const originalRoute = await resolveRoute(client, routes, identifier);
if (!originalRoute) {
output_manager_default.error(
`No route found matching "${identifier}". Run ${import_chalk.default.cyan(
getCommandName("routes list")
)} to see all routes.`
);
return 1;
}
const aiPrompt = flags["--ai"];
if (aiPrompt) {
const conflictingFlags = [
"--name",
"--description",
"--src",
"--src-syntax",
"--action",
"--dest",
"--status",
"--no-dest",
"--no-status",
"--has",
"--missing",
"--set-response-header",
"--append-response-header",
"--delete-response-header",
"--set-request-header",
"--append-request-header",
"--delete-request-header",
"--set-request-query",
"--append-request-query",
"--delete-request-query",
"--clear-conditions",
"--clear-headers",
"--clear-transforms"
];
const usedConflicts = conflictingFlags.filter((f) => flags[f] !== void 0);
if (usedConflicts.length > 0) {
output_manager_default.error(
`Cannot use --ai with ${usedConflicts.join(", ")}. Use --ai alone to describe changes.`
);
return 1;
}
return await handleAIEdit(
client,
project.id,
teamId,
originalRoute,
aiPrompt,
skipConfirmation,
existingStagingVersion
);
}
const route = cloneRoute(originalRoute);
const hasEditFlags = flags["--name"] !== void 0 || flags["--description"] !== void 0 || flags["--src"] !== void 0 || flags["--src-syntax"] !== void 0 || flags["--action"] !== void 0 || flags["--dest"] !== void 0 || flags["--status"] !== void 0 || flags["--no-dest"] !== void 0 || flags["--no-status"] !== void 0 || flags["--has"] !== void 0 || flags["--missing"] !== void 0 || flags["--clear-conditions"] !== void 0 || flags["--clear-headers"] !== void 0 || flags["--clear-transforms"] !== void 0 || hasAnyTransformFlags(flags);
if (hasEditFlags) {
const error = applyFlagMutations(route, flags);
if (error) {
output_manager_default.error(error);
return 1;
}
} else {
if (!client.stdin.isTTY) {
output_manager_default.error(
`No edit flags provided. When running non-interactively, use flags like --name, --dest, --src, etc. Run ${getCommandName("routes edit --help")} for all options.`
);
return 1;
}
output_manager_default.log(`
Editing route "${originalRoute.name}"`);
printRouteConfig(route);
const editMode = await client.input.select({
message: "How would you like to edit this route?",
choices: [
{ name: "Describe changes (AI-powered)", value: "ai" },
{ name: "Edit manually (field by field)", value: "manual" }
]
});
if (editMode === "ai") {
telemetry.trackCliOptionAi("interactive");
return await handleAIEdit(
client,
project.id,
teamId,
originalRoute,
void 0,
skipConfirmation,
existingStagingVersion
);
}
await runInteractiveEditLoop(client, route);
}
populateRouteEnv(route.route);
if (JSON.stringify(route) === JSON.stringify(originalRoute)) {
output_manager_default.log("No changes made.");
return 0;
}
const editStamp = stamp_default();
output_manager_default.spinner(`Updating route "${route.name}"`);
try {
const { version } = await editRoute(
client,
project.id,
originalRoute.id,
{
route: {
name: route.name,
description: route.description,
enabled: route.enabled,
srcSyntax: route.srcSyntax,
route: route.route
}
},
{ teamId }
);
output_manager_default.log(
`${import_chalk.default.cyan("Updated")} route "${route.name}" ${import_chalk.default.gray(editStamp())}`
);
await offerAutoPromote(
client,
project.id,
version,
!!existingStagingVersion,
{ teamId, skipPrompts: skipConfirmation }
);
return 0;
} catch (e) {
const error = e;
output_manager_default.error(error.message || "Failed to update route");
return 1;
}
}
async function handleAIEdit(client, projectId, teamId, originalRoute, aiPrompt, skipConfirmation, existingStagingVersion) {
const currentRoute = routingRuleToCurrentRoute(originalRoute);
let prompt = aiPrompt;
let currentGenerated;
for (; ; ) {
if (!prompt) {
prompt = await client.input.text({
message: "Describe what you'd like to change:",
validate: (val) => {
if (!val)
return "A description is required";
if (val.length > 2e3)
return "Description must be 2000 characters or less";
return true;
}
});
}
output_manager_default.spinner("Generating updated route...");
let errorMessage;
try {
const result = await generateRoute(
client,
projectId,
{ prompt, currentRoute },
{ teamId }
);
if (result.error) {
errorMessage = result.error;
} else if (!result.route) {
errorMessage = "Could not apply changes. Try rephrasing.";
} else {
currentGenerated = result.route;
}
} catch (e) {
const error = e;
errorMessage = error.message || "Failed to generate updated route";
}
if (currentGenerated) {
break;
}
output_manager_default.error(errorMessage);
if (skipConfirmation || !client.stdin.isTTY) {
return 1;
}
const retry = await client.input.select({
message: "What would you like to do?",
choices: [
{ name: "Try again with a different description", value: "retry" },
{ name: "Cancel", value: "cancel" }
]
});
if (retry === "cancel") {
output_manager_default.log("No changes made.");
return 0;
}
prompt = void 0;
}
printGeneratedRoutePreview(currentGenerated);
if (skipConfirmation) {
return await applyAIEdit(
client,
projectId,
teamId,
originalRoute,
currentGenerated,
existingStagingVersion,
skipConfirmation
);
}
if (!client.stdin.isTTY) {
output_manager_default.error(
`Cannot interactively confirm route changes in a non-TTY environment. Use ${getCommandName('routes edit <name-or-id> --ai "..." --yes')} to skip confirmation.`
);
return 1;
}
for (; ; ) {
const choice = await client.input.select({
message: "What would you like to do?",
choices: [
{ name: "Confirm changes", value: "confirm" },
{ name: "Edit again with AI", value: "ai-edit" },
{ name: "Edit manually", value: "manual" },
{ name: "Discard", value: "discard" }
],
pageSize: 4,
loop: false
});
if (choice === "confirm") {
return await applyAIEdit(
client,
projectId,
teamId,
originalRoute,
currentGenerated,
existingStagingVersion,
skipConfirmation
);
}
if (choice === "ai-edit") {
const editPrompt = await client.input.text({
message: "Describe what you'd like to change:",
validate: (val) => {
if (!val)
return "A description is required";
if (val.length > 2e3)
return "Description must be 2000 characters or less";
return true;
}
});
output_manager_default.spinner("Updating route...");
try {
const editResult = await generateRoute(
client,
projectId,
{
prompt: editPrompt,
currentRoute: convertRouteToCurrentRoute(currentGenerated)
},
{ teamId }
);
if (editResult.error) {
output_manager_default.error(editResult.error);
output_manager_default.log("Keeping previous route:");
printGeneratedRoutePreview(currentGenerated);
continue;
}
if (!editResult.route) {
output_manager_default.error("Could not apply changes. Try rephrasing.");
output_manager_default.log("Keeping previous route:");
printGeneratedRoutePreview(currentGenerated);
continue;
}
currentGenerated = editResult.route;
printGeneratedRoutePreview(currentGenerated);
} catch (e) {
const error = e;
output_manager_default.error(error.message || "Failed to update route");
output_manager_default.log("Keeping previous route:");
printGeneratedRoutePreview(currentGenerated);
}
continue;
}
if (choice === "manual") {
const routeInput = generatedRouteToAddInput(currentGenerated);
const manualRoute = cloneRoute(originalRoute);
manualRoute.name = routeInput.name;
manualRoute.description = routeInput.description;
manualRoute.srcSyntax = routeInput.srcSyntax;
manualRoute.route = routeInput.route;
await runInteractiveEditLoop(client, manualRoute);
populateRouteEnv(manualRoute.route);
const editStamp = stamp_default();
output_manager_default.spinner(`Updating route "${manualRoute.name}"`);
try {
const { version } = await editRoute(
client,
projectId,
originalRoute.id,
{
route: {
name: manualRoute.name,
description: manualRoute.description,
enabled: manualRoute.enabled,
srcSyntax: manualRoute.srcSyntax,
route: manualRoute.route
}
},
{ teamId }
);
output_manager_default.log(
`${import_chalk.default.cyan("Updated")} route "${manualRoute.name}" ${import_chalk.default.gray(editStamp())}`
);
await offerAutoPromote(
client,
projectId,
version,
!!existingStagingVersion,
{ teamId, skipPrompts: skipConfirmation }
);
return 0;
} catch (e) {
const error = e;
output_manager_default.error(error.message || "Failed to update route");
return 1;
}
}
output_manager_default.log("No changes made.");
return 0;
}
}
async function applyAIEdit(client, projectId, teamId, originalRoute, generated, existingStagingVersion, skipConfirmation) {
const routeInput = generatedRouteToAddInput(generated);
populateRouteEnv(routeInput.route);
const editStamp = stamp_default();
output_manager_default.spinner(`Updating route "${routeInput.name}"`);
try {
const { version } = await editRoute(
client,
projectId,
originalRoute.id,
{
route: {
name: routeInput.name,
description: routeInput.description,
enabled: originalRoute.enabled,
srcSyntax: routeInput.srcSyntax,
route: routeInput.route
}
},
{ teamId }
);
output_manager_default.log(
`${import_chalk.default.cyan("Updated")} route "${routeInput.name}" ${import_chalk.default.gray(editStamp())}`
);
await offerAutoPromote(
client,
projectId,
version,
!!existingStagingVersion,
{
teamId,
skipPrompts: skipConfirmation
}
);
return 0;
} catch (e) {
const error = e;
output_manager_default.error(error.message || "Failed to update route");
return 1;
}
}
export {
edit as default
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
editRoute
} from "./chunk-P3SKP5WM.js";
import {
getRouteVersions
} from "./chunk-AHU7WNL2.js";
import {
ensureProjectLink,
getRoutes,
offerAutoPromote,
parseSubcommandArgs,
resolveRoute
} from "./chunk-OJOIUL2M.js";
import {
enableSubcommand
} from "./chunk-U6XOC6E4.js";
import "./chunk-QNEHY3TU.js";
import "./chunk-XB2KZC2B.js";
import {
stamp_default
} from "./chunk-SOTR4CXR.js";
import "./chunk-7EHTK7LP.js";
import "./chunk-GGP5R3FU.js";
import {
getCommandName
} from "./chunk-ZLCMHY2G.js";
import "./chunk-3XFFP2BA.js";
import {
output_manager_default
} from "./chunk-FDJURQMQ.js";
import {
require_source
} from "./chunk-S7KYDPEM.js";
import {
__toESM
} from "./chunk-TZ2YI2VH.js";
// src/commands/routes/enable.ts
var import_chalk = __toESM(require_source(), 1);
async function enable(client, argv) {
const parsed = await parseSubcommandArgs(argv, enableSubcommand);
if (typeof parsed === "number")
return parsed;
const link = await ensureProjectLink(client);
if (typeof link === "number")
return link;
const { project, org } = link;
const teamId = org.type === "team" ? org.id : void 0;
const { args } = parsed;
const identifier = args[0];
if (!identifier) {
output_manager_default.error(
`Route name or ID is required. Usage: ${getCommandName("routes enable <name-or-id>")}`
);
return 1;
}
const { versions } = await getRouteVersions(client, project.id, { teamId });
const existingStagingVersion = versions.find((v) => v.isStaging);
output_manager_default.spinner("Fetching routes");
const { routes } = await getRoutes(client, project.id, { teamId });
output_manager_default.stopSpinner();
if (routes.length === 0) {
output_manager_default.error("No routes found in this project.");
return 1;
}
const route = await resolveRoute(client, routes, identifier);
if (!route) {
output_manager_default.error(
`No route found matching "${identifier}". Run ${import_chalk.default.cyan(
getCommandName("routes list")
)} to see all routes.`
);
return 1;
}
if (route.enabled !== false) {
output_manager_default.log(`Route "${route.name}" is already enabled.`);
return 0;
}
const enableStamp = stamp_default();
output_manager_default.spinner(`Enabling route "${route.name}"`);
try {
const { version } = await editRoute(
client,
project.id,
route.id,
{
route: {
name: route.name,
description: route.description,
enabled: true,
srcSyntax: route.srcSyntax,
route: route.route
}
},
{ teamId }
);
output_manager_default.log(
`${import_chalk.default.cyan("Enabled")} route "${route.name}" ${import_chalk.default.gray(enableStamp())}`
);
await offerAutoPromote(
client,
project.id,
version,
!!existingStagingVersion,
{ teamId }
);
return 0;
} catch (e) {
const error = e;
output_manager_default.error(error.message || "Failed to enable route");
return 1;
}
}
export {
enable as default
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
ensureProjectLink,
getRoutes,
parseSubcommandArgs
} from "./chunk-OJOIUL2M.js";
import {
exportSubcommand
} from "./chunk-U6XOC6E4.js";
import "./chunk-QNEHY3TU.js";
import "./chunk-XB2KZC2B.js";
import "./chunk-SOTR4CXR.js";
import "./chunk-7EHTK7LP.js";
import "./chunk-GGP5R3FU.js";
import {
getCommandName
} from "./chunk-ZLCMHY2G.js";
import "./chunk-3XFFP2BA.js";
import {
output_manager_default
} from "./chunk-FDJURQMQ.js";
import "./chunk-S7KYDPEM.js";
import "./chunk-TZ2YI2VH.js";
// src/commands/routes/export.ts
function cleanRoute(route) {
const cleaned = {};
for (const [key, value] of Object.entries(route)) {
if (value === void 0)
continue;
if (key === "middlewarePath" || key === "middlewareRawSrc" || key === "middleware" || key === "check" || key === "important") {
continue;
}
cleaned[key] = value;
}
return cleaned;
}
function routesToVercelJson(rules) {
const enabledRoutes = rules.filter((r) => r.enabled !== false);
const cleaned = enabledRoutes.map((r) => cleanRoute(r.route));
const config = { routes: cleaned };
return JSON.stringify(config, null, 2);
}
function routesToVercelTs(rules) {
const enabledRoutes = rules.filter((r) => r.enabled !== false);
const routeEntries = enabledRoutes.map((r) => {
const cleaned = cleanRoute(r.route);
const routeJson = JSON.stringify(cleaned, null, 2);
const indented = routeJson.split("\n").map((line, i) => i === 0 ? line : ` ${line}`).join("\n");
if (r.description) {
const safeDesc = r.description.replace(/\n/g, " ");
return ` // ${safeDesc}
${indented}`;
}
return ` ${indented}`;
});
const routesContent = routeEntries.length > 0 ? `
${routeEntries.join(",\n")},
` : "";
return `import type { VercelConfig } from '@vercel/config/v1';
export const config: VercelConfig = {
routes: [${routesContent}],
};
`;
}
async function exportRoutes(client, argv) {
const parsed = await parseSubcommandArgs(argv, exportSubcommand);
if (typeof parsed === "number")
return parsed;
const link = await ensureProjectLink(client);
if (typeof link === "number")
return link;
const { project, org } = link;
const teamId = org.type === "team" ? org.id : void 0;
const { args, flags } = parsed;
const format = flags["--format"] || "json";
const nameOrId = args[0];
const validFormats = ["json", "ts"];
if (!validFormats.includes(format)) {
output_manager_default.error(
`Invalid format: "${format}". Valid formats: ${validFormats.join(", ")}. Usage: ${getCommandName("routes export --format json")}`
);
return 1;
}
output_manager_default.spinner("Fetching routes");
try {
const { routes } = await getRoutes(client, project.id, { teamId });
if (routes.length === 0) {
output_manager_default.log(
`No routes found. Create one with ${getCommandName("routes add")}.`
);
return 0;
}
let routesToExport = routes;
if (nameOrId) {
const query = nameOrId.toLowerCase();
routesToExport = routes.filter(
(r) => r.name.toLowerCase() === query || r.name.toLowerCase().includes(query) || r.id === nameOrId
);
if (routesToExport.length === 0) {
output_manager_default.error(
`No route found matching "${nameOrId}". Run ${getCommandName("routes list")} to see all routes.`
);
return 1;
}
}
let result;
switch (format) {
case "ts":
result = routesToVercelTs(routesToExport);
break;
default:
result = routesToVercelJson(routesToExport);
break;
}
output_manager_default.stopSpinner();
client.stdout.write(result.trimEnd() + "\n");
return 0;
} catch (e) {
const error = e;
output_manager_default.error(error.message || "Failed to export routes");
return 1;
}
}
export {
exportRoutes as default
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
handleValidationError,
normalizeRepeatableStringFilters,
outputError,
validateAllProjectMutualExclusivity,
validateIntegerRangeWithDefault,
validateTimeBound,
validateTimeOrder
} from "./chunk-IE7MNZ56.js";
import {
getCommandFlags
} from "./chunk-EOZFDJSY.js";
import {
getScope
} from "./chunk-F7Q6GMBZ.js";
import {
validateJsonOutput
} from "./chunk-XPKWKPWA.js";
import {
activityCommand
} from "./chunk-LW5ZNGW7.js";
import {
getLinkedProject,
getProjectByNameOrId
} from "./chunk-QNEHY3TU.js";
import "./chunk-XB2KZC2B.js";
import "./chunk-SOTR4CXR.js";
import "./chunk-7EHTK7LP.js";
import {
require_ms
} from "./chunk-GGP5R3FU.js";
import {
ProjectNotFound,
getCommandName,
getFlagsSpecification,
isAPIError,
parseArguments,
printError
} from "./chunk-ZLCMHY2G.js";
import "./chunk-3XFFP2BA.js";
import {
output_manager_default
} from "./chunk-FDJURQMQ.js";
import {
require_source
} from "./chunk-S7KYDPEM.js";
import {
__toESM
} from "./chunk-TZ2YI2VH.js";
// src/commands/activity/list.ts
var import_ms = __toESM(require_ms(), 1);
var import_chalk = __toESM(require_source(), 1);
function validateNext(next) {
if (next === void 0) {
return { valid: true, value: void 0 };
}
if (Number.isNaN(next)) {
return {
valid: false,
code: "INVALID_NEXT",
message: "Please provide a number for flag `--next`."
};
}
const date = new Date(next);
if (Number.isNaN(date.getTime())) {
return {
valid: false,
code: "INVALID_NEXT",
message: "Please provide a valid unix timestamp in milliseconds for `--next`."
};
}
return { valid: true, value: date };
}
function handleApiError(err, jsonOutput, client) {
if (err.status === 403) {
return outputError(
client,
jsonOutput,
"FORBIDDEN",
"You do not have permission to list activity events. Required permissions: Event: List or OwnEvent: List."
);
}
return outputError(
client,
jsonOutput,
err.code || "API_ERROR",
err.serverMessage || `API error (${err.status}).`
);
}
function formatActor(event) {
const principal = event.principal;
if (!principal) {
return event.principalId || "-";
}
if (principal.type === "system") {
return "system";
}
if (principal.username) {
return principal.username;
}
if (principal.name) {
return principal.name;
}
if (principal.slug) {
return principal.slug;
}
if (principal.email) {
return principal.email;
}
return event.principalId || "-";
}
function formatAge(createdAt) {
if (!Number.isFinite(createdAt) || createdAt <= 0) {
return "-";
}
const age = Math.max(0, Date.now() - createdAt);
return (0, import_ms.default)(age);
}
function formatEventText(text) {
return text.replace(/\s+/g, " ").trim();
}
function printExpandedEvents(events) {
const lines = [""];
events.forEach((event) => {
lines.push(import_chalk.default.bold(formatEventText(event.text)));
lines.push(` ${import_chalk.default.cyan("Type:")} ${event.type ?? "-"}`);
lines.push(` ${import_chalk.default.cyan("Actor:")} ${formatActor(event)}`);
lines.push(` ${import_chalk.default.cyan("Age:")} ${formatAge(event.createdAt)}`);
lines.push(` ${import_chalk.default.cyan("ID:")} ${event.id}`);
lines.push("");
});
output_manager_default.print(`${lines.join("\n")}
`);
}
function trackTelemetry(flags, types, telemetry) {
telemetry.trackCliOptionType(types.length > 0 ? types : void 0);
telemetry.trackCliOptionSince(flags["--since"]);
telemetry.trackCliOptionUntil(flags["--until"]);
telemetry.trackCliOptionProject(flags["--project"]);
telemetry.trackCliFlagAll(flags["--all"]);
telemetry.trackCliOptionLimit(flags["--limit"]);
telemetry.trackCliOptionNext(flags["--next"]);
telemetry.trackCliOptionFormat(flags["--format"]);
}
function parseFlags(client) {
const flagsSpecification = getFlagsSpecification(activityCommand.options);
try {
const parsedArgs = parseArguments(client.argv.slice(2), flagsSpecification);
return parsedArgs.flags;
} catch (err) {
printError(err);
return 1;
}
}
function resolveValidatedInputs(flags, jsonOutput, client, normalizedTypes) {
const limitResult = validateIntegerRangeWithDefault(flags["--limit"], {
flag: "--limit",
min: 1,
max: 100,
defaultValue: 20
});
if (!limitResult.valid) {
return handleValidationError(limitResult, jsonOutput, client);
}
const mutualResult = validateAllProjectMutualExclusivity(
flags["--all"],
flags["--project"]
);
if (!mutualResult.valid) {
return handleValidationError(mutualResult, jsonOutput, client);
}
const sinceResult = validateTimeBound(flags["--since"]);
if (!sinceResult.valid) {
return handleValidationError(sinceResult, jsonOutput, client);
}
const nextResult = validateNext(flags["--next"]);
if (!nextResult.valid) {
return handleValidationError(nextResult, jsonOutput, client);
}
let until = nextResult.value;
if (!until) {
const untilResult = validateTimeBound(flags["--until"]);
if (!untilResult.valid) {
return handleValidationError(untilResult, jsonOutput, client);
}
until = untilResult.value;
}
const since = sinceResult.value;
const timeOrderResult = validateTimeOrder(since, until);
if (!timeOrderResult.valid) {
return handleValidationError(timeOrderResult, jsonOutput, client);
}
return {
limit: limitResult.value,
types: normalizedTypes,
since,
until
};
}
async function resolveScope(client, opts) {
if (opts.all || opts.project) {
const { team } = await getScope(client);
if (!team) {
return outputError(
client,
opts.jsonOutput,
"NO_TEAM",
"No team context found. Run `vercel switch` to select a team, or use `vercel link` in a project directory."
);
}
if (opts.all) {
return {
teamId: team.id,
teamSlug: team.slug
};
}
let projectResult;
try {
projectResult = await getProjectByNameOrId(
client,
opts.project,
team.id
);
} catch (err) {
if (isAPIError(err)) {
return outputError(
client,
opts.jsonOutput,
err.code || "API_ERROR",
err.serverMessage || (err.status === 403 ? `You do not have permission to access project "${opts.project}" in team "${team.slug}".` : `API error (${err.status}).`)
);
}
throw err;
}
if (projectResult instanceof ProjectNotFound) {
return outputError(
client,
opts.jsonOutput,
"PROJECT_NOT_FOUND",
`Project "${opts.project}" was not found in team "${team.slug}".`
);
}
return {
teamId: team.id,
teamSlug: team.slug,
projectIds: [projectResult.id]
};
}
const linkedProject = await getLinkedProject(client);
if (linkedProject.status === "error") {
return linkedProject.exitCode;
}
if (linkedProject.status === "not_linked") {
return outputError(
client,
opts.jsonOutput,
"NOT_LINKED",
"No linked project found. Run `vercel link` to link a project, or use --project <name> or --all."
);
}
const isTeamProject = linkedProject.org.type === "team";
return {
projectIds: [linkedProject.project.id],
teamId: isTeamProject ? linkedProject.org.id : void 0,
teamSlug: isTeamProject ? linkedProject.org.slug : void 0
};
}
function buildEventsQuery(params) {
const query = new URLSearchParams({
limit: String(params.limit + 1)
});
if (params.types.length > 0) {
query.set("types", params.types.join(","));
}
if (params.since) {
query.set("since", params.since.toISOString());
}
if (params.until) {
query.set("until", params.until.toISOString());
}
if (params.scope.projectIds && params.scope.projectIds.length > 0) {
query.set("projectIds", params.scope.projectIds.join(","));
}
if (params.scope.teamId) {
query.set("teamId", params.scope.teamId);
}
if (params.scope.teamSlug) {
query.set("slug", params.scope.teamSlug);
}
if (params.jsonOutput) {
query.set("withPayload", "true");
}
return query;
}
function paginateEvents(allEvents, limit) {
const events = allEvents.slice(0, limit);
const hasMore = allEvents.length > limit;
const lastVisibleEvent = events[events.length - 1];
const next = hasMore && typeof lastVisibleEvent?.createdAt === "number" ? lastVisibleEvent.createdAt - 1 : null;
return { events, next };
}
function printNextPageHint(flags, next) {
const commandFlags = getCommandFlags(flags, ["--next"]);
output_manager_default.log(
`To display the next page, run ${getCommandName(
`activity${commandFlags} --next ${next}`
)}`
);
}
async function list(client, telemetry) {
const flags = parseFlags(client);
if (typeof flags === "number") {
return flags;
}
const formatResult = validateJsonOutput(flags);
if (!formatResult.valid) {
output_manager_default.error(formatResult.error);
return 1;
}
const jsonOutput = formatResult.jsonOutput;
const normalizedTypes = normalizeRepeatableStringFilters(flags["--type"]);
trackTelemetry(flags, normalizedTypes, telemetry);
const validatedInputs = resolveValidatedInputs(
flags,
jsonOutput,
client,
normalizedTypes
);
if (typeof validatedInputs === "number") {
return validatedInputs;
}
const scope = await resolveScope(client, {
project: flags["--project"],
all: flags["--all"],
jsonOutput
});
if (typeof scope === "number") {
return scope;
}
const query = buildEventsQuery({
limit: validatedInputs.limit,
types: validatedInputs.types,
since: validatedInputs.since,
until: validatedInputs.until,
scope,
jsonOutput
});
output_manager_default.spinner("Fetching activity...");
try {
const response = await client.fetch(
`/v3/events?${query.toString()}`,
{
useCurrentTeam: false
}
);
const allEvents = Array.isArray(response.events) ? response.events : [];
const { events, next } = paginateEvents(allEvents, validatedInputs.limit);
if (jsonOutput) {
client.stdout.write(
`${JSON.stringify({ events, pagination: { next } }, null, 2)}
`
);
return 0;
}
if (events.length === 0) {
output_manager_default.log("No activity events found.");
return 0;
}
printExpandedEvents(events);
if (next !== null) {
printNextPageHint(flags, next);
}
return 0;
} catch (err) {
if (isAPIError(err)) {
return handleApiError(err, jsonOutput, client);
}
throw err;
} finally {
output_manager_default.stopSpinner();
}
}
export {
list as default
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
handleValidationError,
normalizeRepeatableStringFilters,
outputError,
validateAllProjectMutualExclusivity,
validateOptionalIntegerRange,
validateTimeBound,
validateTimeOrder
} from "./chunk-IE7MNZ56.js";
import {
getScope
} from "./chunk-F7Q6GMBZ.js";
import {
validateJsonOutput
} from "./chunk-XPKWKPWA.js";
import {
alertsCommand
} from "./chunk-P5Q6F5IA.js";
import {
getLinkedProject,
getProjectByNameOrId
} from "./chunk-QNEHY3TU.js";
import "./chunk-XB2KZC2B.js";
import "./chunk-SOTR4CXR.js";
import {
table
} from "./chunk-LWBSOTJP.js";
import "./chunk-7EHTK7LP.js";
import {
require_ms
} from "./chunk-GGP5R3FU.js";
import {
ProjectNotFound,
getFlagsSpecification,
isAPIError,
parseArguments,
printError
} from "./chunk-ZLCMHY2G.js";
import "./chunk-3XFFP2BA.js";
import {
output_manager_default
} from "./chunk-FDJURQMQ.js";
import {
require_source
} from "./chunk-S7KYDPEM.js";
import {
__toESM
} from "./chunk-TZ2YI2VH.js";
// src/commands/alerts/list.ts
var import_ms = __toESM(require_ms(), 1);
var import_chalk = __toESM(require_source(), 1);
function handleApiError(err, jsonOutput, client) {
const message = err.status === 401 || err.status === 403 ? "You do not have access to alerts in this scope. Pass --token <TOKEN> and --scope <team-slug> with Alerts read access." : err.status >= 500 ? `The alerts endpoint failed on the server (${err.status}). Re-run with --debug and share the x-vercel-id from the failed request.` : err.serverMessage || `API error (${err.status}).`;
return outputError(client, jsonOutput, err.code || "API_ERROR", message);
}
function getDefaultRange() {
const to = /* @__PURE__ */ new Date();
const from = new Date(to.getTime() - 24 * 60 * 60 * 1e3);
return { from: from.toISOString(), to: to.toISOString() };
}
async function resolveScope(client, opts) {
if (opts.all || opts.project) {
const { team } = await getScope(client);
if (!team) {
return outputError(
client,
opts.jsonOutput,
"NO_TEAM",
"No team context found. Run `vercel switch` to select a team, or use `vercel link` in a project directory."
);
}
if (opts.all) {
return {
teamId: team.id
};
}
let projectResult;
try {
projectResult = await getProjectByNameOrId(
client,
opts.project,
team.id
);
} catch (err) {
if (isAPIError(err)) {
return outputError(
client,
opts.jsonOutput,
err.code || "API_ERROR",
err.serverMessage || (err.status === 403 ? `You do not have permission to access project "${opts.project}" in team "${team.slug}".` : `API error (${err.status}).`)
);
}
throw err;
}
if (projectResult instanceof ProjectNotFound) {
return outputError(
client,
opts.jsonOutput,
"PROJECT_NOT_FOUND",
`Project "${opts.project}" was not found in team "${team.slug}".`
);
}
return {
teamId: team.id,
projectId: projectResult.id
};
}
const linkedProject = await getLinkedProject(client);
if (linkedProject.status === "error") {
return linkedProject.exitCode;
}
if (linkedProject.status === "not_linked") {
return outputError(
client,
opts.jsonOutput,
"NOT_LINKED",
"No linked project found. Run `vercel link` to link a project, or use --project <name> or --all."
);
}
return {
teamId: linkedProject.org.id,
projectId: linkedProject.project.id
};
}
function getGroupTitle(group) {
return group.ai?.title || "Alert group";
}
function parseDateInput(value) {
if (value === void 0) {
return void 0;
}
const epochMs = value < 1e12 ? value * 1e3 : value;
const date = new Date(epochMs);
return Number.isNaN(date.getTime()) ? void 0 : date;
}
function formatDateForDisplay(value) {
const date = parseDateInput(value);
if (!date) {
return "-";
}
return date.toLocaleString("en-US", {
year: "numeric",
month: "short",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
hour12: false,
timeZoneName: "short"
});
}
function getStartedAt(group) {
return formatDateForDisplay(getGroupStartedAt(group)?.getTime());
}
function getGroupStartedAt(group) {
return parseDateInput(group.recordedStartedAt) || parseDateInput(group.alerts?.[0]?.startedAt);
}
function getGroupResolvedAt(group) {
const resolvedTimes = (group.alerts ?? []).map((alert) => parseDateInput(alert.resolvedAt)).filter((d) => Boolean(d)).map((d) => d.getTime());
if (resolvedTimes.length > 0) {
return new Date(Math.max(...resolvedTimes));
}
return getGroupStartedAt(group);
}
function getStatus(group) {
const normalizedStatus = (group.status || "").toLowerCase();
if (normalizedStatus === "active") {
return "active";
}
if (normalizedStatus === "resolved") {
const startedAt = getGroupStartedAt(group);
const resolvedAt = getGroupResolvedAt(group);
if (startedAt && resolvedAt && resolvedAt.getTime() >= startedAt.getTime()) {
return `resolved after ${(0, import_ms.default)(resolvedAt.getTime() - startedAt.getTime())}`;
}
return "resolved";
}
return group.status || "-";
}
function getResolvedAt(group) {
const normalizedStatus = (group.status || "").toLowerCase();
if (normalizedStatus === "active") {
return "active";
}
return formatDateForDisplay(getGroupResolvedAt(group)?.getTime());
}
function getAlertsCount(group) {
return String(group.alerts?.length ?? 0);
}
function printGroups(groups) {
if (groups.length === 0) {
output_manager_default.log("No alerts found.");
return;
}
const headers = ["Title", "Started At", "Type", "Status", "Alerts"].map(
(h) => import_chalk.default.cyan(h)
);
const rows = [
headers,
...groups.map((group) => [
import_chalk.default.bold(getGroupTitle(group)),
getStartedAt(group),
group.type || "-",
getStatus(group),
getAlertsCount(group)
])
];
const tableOutput = table(rows, { hsep: 3 }).split("\n").map((line) => line.trimEnd()).join("\n").replace(/^/gm, " ");
output_manager_default.print(`
${tableOutput}
`);
}
function printAiSections(groups) {
if (groups.length === 0) {
output_manager_default.log("No alerts found.");
return;
}
const rendered = groups.map((group) => {
const title = getGroupTitle(group);
const summary = group.ai?.currentSummary || "N/A";
const findings = group.ai?.keyFindings?.filter(Boolean) ?? [];
const findingsOutput = findings.length > 0 ? findings.map((finding) => ` - ${finding}`).join("\n") : " - N/A";
return [
import_chalk.default.bold(title),
` ${import_chalk.default.cyan("Resolved At:")} ${getResolvedAt(group)}`,
` ${import_chalk.default.cyan("Summary:")} ${summary}`,
` ${import_chalk.default.cyan("Key Findings:")}`,
findingsOutput
].join("\n");
}).join("\n\n");
output_manager_default.print(`
${rendered}
`);
}
function trackTelemetry(flags, types, telemetry) {
telemetry.trackCliOptionType(types.length > 0 ? types : void 0);
telemetry.trackCliOptionSince(flags["--since"]);
telemetry.trackCliOptionUntil(flags["--until"]);
telemetry.trackCliOptionProject(flags["--project"]);
telemetry.trackCliFlagAll(flags["--all"]);
telemetry.trackCliFlagAi(flags["--ai"]);
telemetry.trackCliOptionLimit(flags["--limit"]);
telemetry.trackCliOptionFormat(flags["--format"]);
}
function parseFlags(client) {
const flagsSpecification = getFlagsSpecification(alertsCommand.options);
try {
const parsedArgs = parseArguments(client.argv.slice(2), flagsSpecification);
return parsedArgs.flags;
} catch (err) {
printError(err);
return 1;
}
}
function resolveValidatedInputs(flags, client, jsonOutput) {
const types = normalizeRepeatableStringFilters(flags["--type"]);
const limitResult = validateOptionalIntegerRange(flags["--limit"], {
flag: "--limit",
min: 1,
max: 100
});
if (!limitResult.valid) {
return handleValidationError(limitResult, jsonOutput, client);
}
const mutualResult = validateAllProjectMutualExclusivity(
flags["--all"],
flags["--project"]
);
if (!mutualResult.valid) {
return handleValidationError(mutualResult, jsonOutput, client);
}
const sinceResult = validateTimeBound(flags["--since"]);
if (!sinceResult.valid) {
return handleValidationError(sinceResult, jsonOutput, client);
}
const untilResult = validateTimeBound(flags["--until"]);
if (!untilResult.valid) {
return handleValidationError(untilResult, jsonOutput, client);
}
const timeOrderResult = validateTimeOrder(
sinceResult.value,
untilResult.value
);
if (!timeOrderResult.valid) {
return handleValidationError(timeOrderResult, jsonOutput, client);
}
return {
limit: limitResult.value,
types,
since: sinceResult.value,
until: untilResult.value
};
}
function buildAlertsQuery(scope, inputs) {
const query = new URLSearchParams({
teamId: scope.teamId
});
if (scope.projectId) {
query.set("projectId", scope.projectId);
}
if (inputs.limit) {
query.set("limit", String(inputs.limit));
}
for (const type of inputs.types) {
query.append("types", type);
}
if (inputs.since) {
query.set("from", inputs.since.toISOString());
}
if (inputs.until) {
query.set("to", inputs.until.toISOString());
}
if (!inputs.since && !inputs.until) {
const defaultRange = getDefaultRange();
query.set("from", defaultRange.from);
query.set("to", defaultRange.to);
}
return query;
}
async function list(client, telemetry) {
const flags = parseFlags(client);
if (typeof flags === "number") {
return flags;
}
const formatResult = validateJsonOutput(flags);
if (!formatResult.valid) {
output_manager_default.error(formatResult.error);
return 1;
}
const jsonOutput = formatResult.jsonOutput;
const types = normalizeRepeatableStringFilters(flags["--type"]);
trackTelemetry(flags, types, telemetry);
const validatedInputs = resolveValidatedInputs(flags, client, jsonOutput);
if (typeof validatedInputs === "number") {
return validatedInputs;
}
const scope = await resolveScope(client, {
project: flags["--project"],
all: flags["--all"],
jsonOutput
});
if (typeof scope === "number") {
return scope;
}
const query = buildAlertsQuery(scope, validatedInputs);
const requestPath = `/alerts/v3/groups?${query.toString()}`;
output_manager_default.debug(`Fetching alerts from ${requestPath}`);
output_manager_default.spinner("Fetching alerts...");
try {
const groups = await client.fetch(requestPath);
if (jsonOutput) {
client.stdout.write(`${JSON.stringify({ groups }, null, 2)}
`);
} else {
if (flags["--ai"]) {
printAiSections(groups);
} else {
printGroups(groups);
}
}
return 0;
} catch (err) {
if (isAPIError(err)) {
return handleApiError(err, jsonOutput, client);
}
output_manager_default.debug(err);
const message = `Failed to fetch alerts: ${err.message || String(err)}`;
return outputError(client, jsonOutput, "UNEXPECTED_ERROR", message);
} finally {
output_manager_default.stopSpinner();
}
}
export {
list as default
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
updateRouteVersion
} from "./chunk-PMSMUMUO.js";
import {
getRouteVersions
} from "./chunk-AHU7WNL2.js";
import {
confirmAction,
ensureProjectLink,
getRoutes,
parseSubcommandArgs,
printDiffSummary
} from "./chunk-OJOIUL2M.js";
import {
publishSubcommand
} from "./chunk-U6XOC6E4.js";
import "./chunk-QNEHY3TU.js";
import "./chunk-XB2KZC2B.js";
import {
stamp_default
} from "./chunk-SOTR4CXR.js";
import "./chunk-7EHTK7LP.js";
import "./chunk-GGP5R3FU.js";
import {
getCommandName
} from "./chunk-ZLCMHY2G.js";
import "./chunk-3XFFP2BA.js";
import {
output_manager_default
} from "./chunk-FDJURQMQ.js";
import {
require_source
} from "./chunk-S7KYDPEM.js";
import {
__toESM
} from "./chunk-TZ2YI2VH.js";
// src/commands/routes/publish.ts
var import_chalk = __toESM(require_source(), 1);
async function publish(client, argv) {
const parsed = await parseSubcommandArgs(argv, publishSubcommand);
if (typeof parsed === "number")
return parsed;
const link = await ensureProjectLink(client);
if (typeof link === "number")
return link;
const { project, org } = link;
const teamId = org.type === "team" ? org.id : void 0;
output_manager_default.spinner(`Fetching route versions for ${import_chalk.default.bold(project.name)}`);
const { versions } = await getRouteVersions(client, project.id, { teamId });
const version = versions.find((v) => v.isStaging);
if (!version) {
output_manager_default.warn(
`No staged changes to publish. Make changes first with ${import_chalk.default.cyan(
getCommandName("routes add")
)}.`
);
return 0;
}
output_manager_default.spinner("Fetching changes");
const { routes: diffRoutes } = await getRoutes(client, project.id, {
teamId,
versionId: version.id,
diff: true
});
const changedRoutes = diffRoutes.filter((r) => r.action !== void 0);
if (changedRoutes.length > 0) {
output_manager_default.print(`
${import_chalk.default.bold("Changes to be published:")}
`);
printDiffSummary(changedRoutes);
output_manager_default.print("\n");
} else {
output_manager_default.print(
`
${import_chalk.default.gray("No changes detected from current production version.")}
`
);
}
const confirmed = await confirmAction(
client,
parsed.flags["--yes"],
"Publish these changes to production?",
`This will make them live for ${import_chalk.default.bold(project.name)}.`
);
if (!confirmed) {
output_manager_default.log("Canceled");
return 0;
}
const updateStamp = stamp_default();
output_manager_default.spinner("Publishing to production");
try {
const { version: newVersion } = await updateRouteVersion(
client,
project.id,
version.id,
"promote",
{ teamId }
);
output_manager_default.log(
`${import_chalk.default.cyan("Success!")} Routes published to production ${import_chalk.default.gray(
updateStamp()
)}`
);
if (newVersion.ruleCount !== void 0) {
output_manager_default.print(
` ${import_chalk.default.bold("Active routes:")} ${newVersion.ruleCount}
`
);
}
return 0;
} catch (e) {
const error = e;
output_manager_default.error(error.message || "Failed to publish routes");
return 1;
}
}
export {
publish as default
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
formatErrorJson,
formatQueryJson,
getDefaultAggregation,
getMeasures,
getQueryEngineEventName,
getRollupColumnName,
validateAggregation,
validateEvent,
validateGroupBy,
validateMeasure,
validateMutualExclusivity,
validateRequiredEvent
} from "./chunk-BQ3DXZNT.js";
import {
resolveTimeRange
} from "./chunk-IE7MNZ56.js";
import {
indent_default
} from "./chunk-A3NYPUKZ.js";
import {
getScope
} from "./chunk-F7Q6GMBZ.js";
import {
validateJsonOutput
} from "./chunk-XPKWKPWA.js";
import {
metricsCommand
} from "./chunk-2DLBVZWU.js";
import {
getLinkedProject
} from "./chunk-QNEHY3TU.js";
import "./chunk-XB2KZC2B.js";
import "./chunk-SOTR4CXR.js";
import {
table
} from "./chunk-LWBSOTJP.js";
import "./chunk-7EHTK7LP.js";
import {
require_ms
} from "./chunk-GGP5R3FU.js";
import {
getFlagsSpecification,
isAPIError,
parseArguments,
printError
} from "./chunk-ZLCMHY2G.js";
import "./chunk-3XFFP2BA.js";
import {
output_manager_default
} from "./chunk-FDJURQMQ.js";
import {
require_source
} from "./chunk-S7KYDPEM.js";
import {
__toESM
} from "./chunk-TZ2YI2VH.js";
// src/commands/metrics/text-output.ts
var import_chalk = __toESM(require_source(), 1);
// src/commands/metrics/time-utils.ts
var import_ms = __toESM(require_ms(), 1);
var MINUTE_MS = 60 * 1e3;
var HOUR_MS = 60 * MINUTE_MS;
var DAY_MS = 24 * HOUR_MS;
function toGranularityDuration(input) {
const milliseconds = (0, import_ms.default)(input);
if (milliseconds === void 0) {
throw new Error(
`Invalid granularity format "${input}". Use 1m, 5m, 15m, 1h, 4h, 1d.`
);
}
if (milliseconds >= DAY_MS) {
return { days: milliseconds / DAY_MS };
}
if (milliseconds >= HOUR_MS) {
return { hours: milliseconds / HOUR_MS };
}
return { minutes: milliseconds / MINUTE_MS };
}
function toGranularityMs(input) {
const milliseconds = (0, import_ms.default)(input);
if (milliseconds === void 0) {
throw new Error(`Invalid granularity format "${input}".`);
}
return milliseconds;
}
var GRANULARITY_THRESHOLDS = [
[1 * HOUR_MS, "1m", "1m"],
// ≤1h
[2 * HOUR_MS, "5m", "5m"],
// ≤2h
[12 * HOUR_MS, "15m", "5m"],
// ≤12h
[3 * DAY_MS, "1h", "1h"],
// ≤3d
[30 * DAY_MS, "4h", "4h"]
// ≤30d
];
var FALLBACK_GRANULARITY = "1d";
function getAutoGranularity(rangeMs) {
for (const [maxRange, defaultG] of GRANULARITY_THRESHOLDS) {
if (rangeMs <= maxRange) {
return defaultG;
}
}
return FALLBACK_GRANULARITY;
}
function getMinGranularity(rangeMs) {
for (const [maxRange, , minG] of GRANULARITY_THRESHOLDS) {
if (rangeMs <= maxRange) {
return minG;
}
}
return FALLBACK_GRANULARITY;
}
function computeGranularity(rangeMs, explicit) {
if (!explicit) {
const auto = getAutoGranularity(rangeMs);
return {
duration: toGranularityDuration(auto),
adjusted: false
};
}
const minG = getMinGranularity(rangeMs);
const explicitMs = toGranularityMs(explicit);
const minMs = toGranularityMs(minG);
if (explicitMs < minMs) {
const rangeDays = Math.round(rangeMs / DAY_MS);
const rangeHours = Math.round(rangeMs / HOUR_MS);
const rangeLabel = rangeDays >= 1 ? `${rangeDays}-day` : `${rangeHours}-hour`;
return {
duration: toGranularityDuration(minG),
adjusted: true,
notice: `Granularity adjusted from ${explicit} to ${minG} for a ${rangeLabel} time range.`
};
}
return {
duration: toGranularityDuration(explicit),
adjusted: false
};
}
function roundTimeBoundaries(start, end, granularityMs) {
const flooredStart = new Date(
Math.floor(start.getTime() / granularityMs) * granularityMs
);
const ceiledEnd = new Date(
Math.ceil(end.getTime() / granularityMs) * granularityMs
);
return { start: flooredStart, end: ceiledEnd };
}
function toGranularityMsFromDuration(duration) {
if ("minutes" in duration) {
return duration.minutes * MINUTE_MS;
}
if ("hours" in duration) {
return duration.hours * HOUR_MS;
}
return duration.days * DAY_MS;
}
// src/commands/metrics/text-output.ts
var GROUP_KEY_DELIMITER = "";
var MAX_SPARKLINE_LENGTH = 120;
var COUNT_UNITS = /* @__PURE__ */ new Set(["count", "us dollars", "dollars"]);
var DURATION_UNITS = /* @__PURE__ */ new Set(["milliseconds", "seconds"]);
var BYTES_UNITS = /* @__PURE__ */ new Set([
"bytes",
"megabytes",
"gigabyte hours",
"gigabyte_hours"
]);
var RATIO_UNITS = /* @__PURE__ */ new Set(["ratio", "percent"]);
var BLOCKS = ["\u2581", "\u2582", "\u2583", "\u2584", "\u2585", "\u2586", "\u2587", "\u2588"];
var MISSING_CHAR = "\xB7";
function normalizeUnit(unit) {
return unit.trim().toLowerCase().replace(/[_\s]+/g, " ");
}
function toGroupKey(groupValues) {
if (groupValues.length === 0) {
return "";
}
return groupValues.join(GROUP_KEY_DELIMITER);
}
function pad2(n) {
return String(n).padStart(2, "0");
}
function pad4(n) {
return String(n).padStart(4, "0");
}
function formatHumanMinute(date) {
return `${pad4(date.getUTCFullYear())}-${pad2(date.getUTCMonth() + 1)}-${pad2(date.getUTCDate())} ${pad2(date.getUTCHours())}:${pad2(date.getUTCMinutes())}`;
}
function formatPeriodBound(input) {
const date = new Date(input);
if (isNaN(date.getTime())) {
return input;
}
return formatHumanMinute(date);
}
function formatGranularity(granularity) {
if ("minutes" in granularity) {
return `${granularity.minutes}m`;
}
if ("hours" in granularity) {
return `${granularity.hours}h`;
}
return `${granularity.days}d`;
}
function formatUnitLabel(unit) {
switch (normalizeUnit(unit)) {
case "milliseconds":
return "ms";
case "seconds":
return "s";
case "us dollars":
return "USD";
case "gigabyte hours":
return "GB-h";
default:
return unit;
}
}
function isCountIntegerDisplay(measureType, aggregation) {
return measureType === "count" && aggregation === "sum";
}
function formatNumber(value, measureType, aggregation, opts) {
if (isCountIntegerDisplay(measureType, aggregation)) {
if (opts?.preserveFractionalCountSum && !Number.isInteger(value)) {
return formatDecimal(value);
}
return formatCount(value);
}
return formatDecimal(value);
}
function getStatColumns(measureType) {
if (measureType === "duration" || measureType === "ratio") {
return ["avg", "min", "max"];
}
return ["total", "avg", "min", "max"];
}
function toNumericValue(value) {
if (value === null || value === void 0) {
return null;
}
if (typeof value === "number") {
return Number.isFinite(value) ? value : null;
}
const parsed = Number(value);
return Number.isFinite(parsed) ? parsed : null;
}
function isNonNullNumber(value) {
return value !== null;
}
function isPointWithValue(point) {
return point.value !== null;
}
function getOrCreate(map, key, make) {
const existing = map.get(key);
if (existing !== void 0) {
return existing;
}
const created = make();
map.set(key, created);
return created;
}
function getGroupFieldValue(row, field) {
const value = row[field];
return value == null || value === "" ? "(not set)" : String(value);
}
function normalizeTimestampToIso(timestamp) {
const parsed = Date.parse(timestamp);
if (isNaN(parsed)) {
return null;
}
return new Date(parsed).toISOString();
}
function formatStatCell(column, stats, measureType, aggregation, periodStart, periodEnd) {
switch (column) {
case "total":
return formatNumber(stats.total, measureType, aggregation);
case "avg":
return formatNumber(stats.avg, measureType, aggregation, {
preserveFractionalCountSum: true
});
case "min": {
const ts = formatMinMaxTimestamp(
new Date(stats.min.timestamp),
periodStart,
periodEnd
);
return `${formatNumber(stats.min.value, measureType, aggregation)} at ${ts}`;
}
case "max": {
const ts = formatMinMaxTimestamp(
new Date(stats.max.timestamp),
periodStart,
periodEnd
);
return `${formatNumber(stats.max.value, measureType, aggregation)} at ${ts}`;
}
}
}
function buildExpectedTimestamps(periodStart, periodEnd, granularityMs) {
const start = Date.parse(periodStart);
const end = Date.parse(periodEnd);
if (isNaN(start) || isNaN(end) || granularityMs <= 0 || end <= start) {
return [];
}
const timestamps = [];
for (let current = start; current < end; current += granularityMs) {
timestamps.push(new Date(current).toISOString());
}
return timestamps;
}
function getMeasureType(unit) {
const normalized = normalizeUnit(unit);
if (COUNT_UNITS.has(normalized)) {
return "count";
}
if (DURATION_UNITS.has(normalized)) {
return "duration";
}
if (BYTES_UNITS.has(normalized)) {
return "bytes";
}
if (RATIO_UNITS.has(normalized)) {
return "ratio";
}
return "ratio";
}
function formatCount(n) {
return Math.round(n).toLocaleString("en-US");
}
function formatDecimal(n) {
if (!Number.isFinite(n)) {
return String(n);
}
if (n === 0 || Object.is(n, -0)) {
return "0";
}
const sign = n < 0 ? "-" : "";
const abs = Math.abs(n);
if (abs >= 1) {
return `${sign}${abs.toFixed(1)}`;
}
const exponent = Math.floor(Math.log10(abs));
const decimals = Math.min(20, Math.max(2, -exponent + 1));
const fixed = abs.toFixed(decimals);
const trimmed = fixed.replace(/(\.\d*?[1-9])0+$/, "$1").replace(/\.0+$/, "").replace(/\.$/, "");
return `${sign}${trimmed}`;
}
function formatMinMaxTimestamp(date, periodStart, periodEnd) {
const sameDay = periodStart.getUTCFullYear() === periodEnd.getUTCFullYear() && periodStart.getUTCMonth() === periodEnd.getUTCMonth() && periodStart.getUTCDate() === periodEnd.getUTCDate();
if (sameDay) {
return `${pad2(date.getUTCHours())}:${pad2(date.getUTCMinutes())}`;
}
const sameYear = periodStart.getUTCFullYear() === periodEnd.getUTCFullYear();
if (sameYear) {
return `${pad2(date.getUTCMonth() + 1)}-${pad2(date.getUTCDate())} ${pad2(date.getUTCHours())}:${pad2(date.getUTCMinutes())}`;
}
return `${pad4(date.getUTCFullYear())}-${pad2(date.getUTCMonth() + 1)}-${pad2(date.getUTCDate())} ${pad2(date.getUTCHours())}:${pad2(date.getUTCMinutes())}`;
}
function extractGroupedSeries(data, groupBy, rollupColumn, periodStart, periodEnd, granularityMs) {
const expectedTimestamps = buildExpectedTimestamps(
periodStart,
periodEnd,
granularityMs
);
const groups = [];
const groupValues = /* @__PURE__ */ new Map();
const valueByGroup = /* @__PURE__ */ new Map();
for (const row of data) {
const values = groupBy.map((field) => getGroupFieldValue(row, field));
const key = toGroupKey(values);
if (!groupValues.has(key)) {
groups.push(key);
groupValues.set(key, values);
}
const groupMap = getOrCreate(valueByGroup, key, () => /* @__PURE__ */ new Map());
const rawTimestamp = row.timestamp;
if (rawTimestamp.length === 0) {
continue;
}
const timestamp = normalizeTimestampToIso(rawTimestamp);
if (!timestamp) {
continue;
}
const numeric = toNumericValue(row[rollupColumn]);
groupMap.set(timestamp, numeric);
}
const series = /* @__PURE__ */ new Map();
for (const key of groups) {
const byTimestamp = valueByGroup.get(key);
if (!byTimestamp) {
continue;
}
const points = expectedTimestamps.map((timestamp) => ({
timestamp,
value: byTimestamp.has(timestamp) ? byTimestamp.get(timestamp) ?? null : null
}));
series.set(key, points);
}
return { groups, series, groupValues };
}
function computeGroupStats(points) {
const present = points.filter(isPointWithValue);
if (present.length === 0) {
return {
total: 0,
avg: 0,
min: { value: 0, timestamp: "" },
max: { value: 0, timestamp: "" },
count: 0,
allMissing: true
};
}
let total = 0;
let min = present[0];
let max = present[0];
for (const point of present) {
total += point.value;
if (point.value < min.value) {
min = point;
}
if (point.value > max.value) {
max = point;
}
}
return {
total,
avg: total / present.length,
min: { value: min.value, timestamp: min.timestamp },
max: { value: max.value, timestamp: max.timestamp },
count: present.length,
allMissing: false
};
}
var MAX_GROUP_VALUE_LENGTH = 60;
function ellipsizeMiddle(str, maxLength) {
if (str.length <= maxLength)
return str;
const endLength = Math.floor((maxLength - 1) / 2);
const startLength = maxLength - 1 - endLength;
return `${str.slice(0, startLength)}\u2026${str.slice(str.length - endLength)}`;
}
function downsample(values, maxLen) {
if (maxLen <= 0) {
return [];
}
if (values.length <= maxLen) {
return [...values];
}
const result = [];
for (let i = 0; i < maxLen; i++) {
const start = Math.floor(i * values.length / maxLen);
const end = Math.floor((i + 1) * values.length / maxLen);
const bucket = values.slice(start, Math.max(start + 1, end));
const nullCount = bucket.filter((value) => value === null).length;
if (nullCount === bucket.length || nullCount > bucket.length / 2) {
result.push(null);
continue;
}
const present = bucket.filter(isNonNullNumber);
const avg = present.reduce((sum, value) => sum + value, 0) / present.length;
result.push(avg);
}
return result;
}
function generateSparkline(values) {
const sampled = downsample(values, MAX_SPARKLINE_LENGTH);
if (sampled.length === 0) {
return "";
}
const present = sampled.filter(isNonNullNumber);
if (present.length === 0) {
return sampled.map(() => MISSING_CHAR).join("");
}
const min = Math.min(...present);
const max = Math.max(...present);
if (min === max) {
const block = min === 0 ? BLOCKS[0] : BLOCKS[BLOCKS.length - 1];
return sampled.map((value) => value === null ? MISSING_CHAR : block).join("");
}
const range = max - min;
return sampled.map((value) => {
if (value === null) {
return MISSING_CHAR;
}
const ratio = (value - min) / range;
const index = Math.max(
0,
Math.min(BLOCKS.length - 1, Math.round(ratio * (BLOCKS.length - 1)))
);
return BLOCKS[index];
}).join("");
}
function formatMetadataHeader(opts) {
const rows = [
{
key: "Metric",
value: `${opts.event} / ${opts.measure} ${opts.aggregation}`
},
{
key: "Period",
value: `${formatPeriodBound(opts.periodStart)} to ${formatPeriodBound(opts.periodEnd)}`
},
{
key: "Interval",
value: formatGranularity(opts.granularity)
}
];
if (opts.filter) {
rows.push({ key: "Filter", value: opts.filter });
}
if (opts.scope.type === "project-with-slug") {
rows.push({
key: "Project",
value: `${opts.projectName ?? opts.scope.projectName} (${opts.teamName ?? opts.scope.teamSlug})`
});
} else {
rows.push({
key: "Team",
value: `${opts.teamName ?? opts.scope.teamSlug} (all projects)`
});
}
if (opts.unit && normalizeUnit(opts.unit) !== "count") {
rows.push({ key: "Units", value: formatUnitLabel(opts.unit) });
}
if (typeof opts.groupCount === "number") {
rows.push({ key: "Groups", value: String(opts.groupCount) });
}
return rows.map((row) => `> ${import_chalk.default.gray(`${row.key}:`)} ${row.value}`).join("\n");
}
function formatSummaryTable(opts) {
const statColumns = getStatColumns(opts.measureType);
const header = [...opts.groupByFields, ...statColumns];
const rows = [header.map((name) => import_chalk.default.bold(import_chalk.default.cyan(name)))];
for (const row of opts.rows) {
const nextRow = row.groupValues.map(
(v) => ellipsizeMiddle(v, MAX_GROUP_VALUE_LENGTH)
);
if (row.stats.allMissing) {
nextRow.push(...statColumns.map(() => "--"));
rows.push(nextRow);
continue;
}
nextRow.push(
...statColumns.map(
(column) => formatStatCell(
column,
row.stats,
opts.measureType,
opts.aggregation,
opts.periodStart,
opts.periodEnd
)
)
);
rows.push(nextRow);
}
const centeredColumns = /* @__PURE__ */ new Set(["min", "max"]);
const align = header.map(
(col) => centeredColumns.has(col) ? "c" : "r"
);
return indent_default(
table(rows, {
align,
hsep: 2
}),
2
);
}
function formatSparklineSection(groupRows, sparklines, groupByFields) {
const lines = ["sparklines:"];
if (groupRows.length === 0) {
const sparkline = sparklines[0];
if (sparkline) {
lines.push(indent_default(sparkline, 2));
}
return lines.join("\n");
}
const rowsWithSparklines = groupRows.map((groupValues, index) => ({
groupValues,
sparkline: sparklines[index] ?? ""
}));
const rows = [
[...groupByFields, "sparkline"].map((name) => import_chalk.default.bold(import_chalk.default.cyan(name))),
...rowsWithSparklines.map(({ groupValues, sparkline }) => [
...groupValues.map((v) => ellipsizeMiddle(v, MAX_GROUP_VALUE_LENGTH)),
sparkline
])
];
const align = groupByFields.map(() => "r");
align.push("l");
lines.push(
indent_default(
table(rows, {
align,
hsep: 2
}),
2
)
);
return lines.join("\n");
}
function formatText(response, opts) {
const rollupColumn = getRollupColumnName(opts.measure, opts.aggregation);
const measureSchema = getMeasures(opts.event).find(
(m) => m.name === opts.measure
);
const measureUnit = measureSchema?.unit;
const measureType = getMeasureType(measureUnit ?? "ratio");
const granularityMs = toGranularityMsFromDuration(opts.granularity);
const { groups, series, groupValues } = extractGroupedSeries(
response.data ?? [],
opts.groupBy,
rollupColumn,
opts.periodStart,
opts.periodEnd,
granularityMs
);
const metadata = formatMetadataHeader({
event: opts.event,
measure: opts.measure,
aggregation: opts.aggregation,
periodStart: opts.periodStart,
periodEnd: opts.periodEnd,
granularity: opts.granularity,
filter: opts.filter,
scope: opts.scope,
projectName: opts.projectName,
teamName: opts.teamName,
unit: measureUnit,
groupCount: opts.groupBy.length > 0 ? groups.length : void 0
});
if (groups.length === 0) {
return `${metadata}
No data found for this period.
`;
}
const summaryRows = [];
const groupRows = [];
const sparklineRows = [];
for (const key of groups) {
const points = series.get(key) ?? [];
const values = points.map((point) => point.value);
const currentGroupValues = groupValues.get(key) ?? [];
summaryRows.push({
groupValues: currentGroupValues,
stats: computeGroupStats(points)
});
groupRows.push(currentGroupValues);
sparklineRows.push(generateSparkline(values));
}
const summaryTable = formatSummaryTable({
rows: summaryRows,
groupByFields: opts.groupBy,
measureType,
aggregation: opts.aggregation,
periodStart: new Date(opts.periodStart),
periodEnd: new Date(opts.periodEnd)
});
const groupedOutput = opts.groupBy.length > 0;
const sparklineSection = formatSparklineSection(
groupedOutput ? groupRows : [],
sparklineRows,
opts.groupBy
);
const sections = [metadata, summaryTable, sparklineSection];
return `${sections.join("\n\n")}
`;
}
// src/commands/metrics/query.ts
function handleValidationError(result, jsonOutput, client) {
if (jsonOutput) {
client.stdout.write(
formatErrorJson(result.code, result.message, result.allowedValues)
);
} else {
output_manager_default.error(result.message);
if (result.allowedValues && result.allowedValues.length > 0) {
output_manager_default.print(
`
Available ${result.code === "UNKNOWN_EVENT" ? "events" : result.code === "UNKNOWN_MEASURE" ? "measures" : result.code === "INVALID_AGGREGATION" ? "aggregations" : "dimensions"}: ${result.allowedValues.join(", ")}
`
);
}
}
return 1;
}
function handleApiError(err, jsonOutput, client) {
let code;
let message;
switch (err.status) {
case 402:
code = "PAYMENT_REQUIRED";
message = "This feature requires an Observability Plus subscription. Upgrade at https://vercel.com/dashboard/settings/billing";
break;
case 403:
code = "FORBIDDEN";
message = "You do not have permission to query metrics for this project/team.";
break;
case 500:
code = "INTERNAL_ERROR";
message = "An internal error occurred. Please try again later.";
break;
case 504:
code = "TIMEOUT";
message = "The query timed out. Try a shorter time range or fewer groups.";
break;
default:
code = err.code || "BAD_REQUEST";
message = err.serverMessage || `API error (${err.status})`;
}
if (jsonOutput) {
client.stdout.write(formatErrorJson(code, message));
} else {
output_manager_default.error(message);
}
return 1;
}
async function resolveQueryScope(client, opts) {
if (opts.project || opts.all) {
const { team } = await getScope(client);
if (!team) {
const errMsg = "No team context found. Run `vercel switch` to select a team, or use `vercel link` in a project directory.";
if (opts.jsonOutput) {
client.stdout.write(formatErrorJson("NO_TEAM", errMsg));
} else {
output_manager_default.error(errMsg);
}
return 1;
}
if (opts.all) {
return {
scope: { type: "team-with-slug", teamSlug: team.slug },
accountId: team.id
};
}
return {
scope: {
type: "project-with-slug",
teamSlug: team.slug,
projectName: opts.project
},
accountId: team.id
};
}
const linkedProject = await getLinkedProject(client);
if (linkedProject.status === "error") {
return linkedProject.exitCode;
}
if (linkedProject.status === "not_linked") {
const errMsg = "No linked project found. Run `vercel link` to link a project, or use --project <name> or --all.";
if (opts.jsonOutput) {
client.stdout.write(formatErrorJson("NOT_LINKED", errMsg));
} else {
output_manager_default.error(errMsg);
}
return 1;
}
return {
scope: {
type: "project-with-slug",
teamSlug: linkedProject.org.slug,
projectName: linkedProject.project.name
},
accountId: linkedProject.org.id
};
}
async function query(client, telemetry) {
let parsedArgs;
const flagsSpecification = getFlagsSpecification(metricsCommand.options);
try {
parsedArgs = parseArguments(client.argv.slice(2), flagsSpecification);
} catch (err) {
printError(err);
return 1;
}
const flags = parsedArgs.flags;
const formatResult = validateJsonOutput(flags);
if (!formatResult.valid) {
output_manager_default.error(formatResult.error);
return 1;
}
const jsonOutput = formatResult.jsonOutput;
const eventFlag = flags["--event"];
const measure = flags["--measure"] ?? "count";
const aggregationFlag = flags["--aggregation"];
const groupBy = flags["--group-by"] ?? [];
const limit = flags["--limit"];
const filter = flags["--filter"];
const since = flags["--since"];
const until = flags["--until"];
const granularity = flags["--granularity"];
const project = flags["--project"];
const all = flags["--all"];
telemetry.trackCliOptionEvent(eventFlag);
telemetry.trackCliOptionMeasure(flags["--measure"]);
telemetry.trackCliOptionAggregation(aggregationFlag);
telemetry.trackCliOptionGroupBy(groupBy.length > 0 ? groupBy : void 0);
telemetry.trackCliOptionLimit(limit);
telemetry.trackCliOptionFilter(filter);
telemetry.trackCliOptionSince(since);
telemetry.trackCliOptionUntil(until);
telemetry.trackCliOptionGranularity(granularity);
telemetry.trackCliOptionProject(project);
telemetry.trackCliFlagAll(all);
telemetry.trackCliOptionFormat(flags["--format"]);
const requiredResult = validateRequiredEvent(eventFlag);
if (!requiredResult.valid) {
return handleValidationError(requiredResult, jsonOutput, client);
}
const event = requiredResult.value;
const aggregationInput = aggregationFlag ?? getDefaultAggregation(event, measure);
const eventResult = validateEvent(event);
if (!eventResult.valid) {
return handleValidationError(eventResult, jsonOutput, client);
}
const measureResult = validateMeasure(event, measure);
if (!measureResult.valid) {
return handleValidationError(measureResult, jsonOutput, client);
}
const aggResult = validateAggregation(event, measure, aggregationInput);
if (!aggResult.valid) {
return handleValidationError(aggResult, jsonOutput, client);
}
const aggregation = aggResult.value;
const groupByResult = validateGroupBy(event, groupBy);
if (!groupByResult.valid) {
return handleValidationError(groupByResult, jsonOutput, client);
}
const mutualResult = validateMutualExclusivity(all, project);
if (!mutualResult.valid) {
return handleValidationError(mutualResult, jsonOutput, client);
}
const scopeResult = await resolveQueryScope(client, {
project,
all,
jsonOutput
});
if (typeof scopeResult === "number") {
return scopeResult;
}
const { scope, accountId } = scopeResult;
let startTime;
let endTime;
try {
({ startTime, endTime } = resolveTimeRange(since, until));
} catch (err) {
const errMsg = err instanceof Error ? err.message : String(err);
if (jsonOutput) {
client.stdout.write(formatErrorJson("INVALID_TIME", errMsg));
} else {
output_manager_default.error(errMsg);
}
return 1;
}
const rangeMs = endTime.getTime() - startTime.getTime();
const granResult = computeGranularity(rangeMs, granularity);
if (granResult.adjusted && granResult.notice) {
output_manager_default.log(`Notice: ${granResult.notice}`);
}
const rounded = roundTimeBoundaries(
startTime,
endTime,
toGranularityMsFromDuration(granResult.duration)
);
const rollupColumn = getRollupColumnName(measure, aggregation);
const body = {
reason: "agent",
scope,
event: getQueryEngineEventName(event),
rollups: { [rollupColumn]: { measure, aggregation } },
startTime: rounded.start.toISOString(),
endTime: rounded.end.toISOString(),
granularity: granResult.duration,
...groupBy.length > 0 ? { groupBy } : {},
...filter ? { filter } : {},
limit: limit ?? 10
};
const baseUrl = client.apiUrl === "https://api.vercel.com" ? "https://vercel.com" : client.apiUrl;
const metricsUrl = `${baseUrl}/api/observability/metrics`;
output_manager_default.spinner("Querying metrics...");
let response;
try {
response = await client.fetch(metricsUrl, {
method: "POST",
body: JSON.stringify(body),
headers: { "Content-Type": "application/json" },
accountId
});
} catch (err) {
if (isAPIError(err)) {
return handleApiError(err, jsonOutput, client);
}
const errMsg = err instanceof Error ? err.message : String(err);
if (jsonOutput) {
client.stdout.write(formatErrorJson("NETWORK_ERROR", errMsg));
} else {
output_manager_default.error(errMsg);
}
return 1;
} finally {
output_manager_default.stopSpinner();
}
if (jsonOutput) {
client.stdout.write(
formatQueryJson(
{
event,
measure,
aggregation,
groupBy,
filter,
startTime: rounded.start.toISOString(),
endTime: rounded.end.toISOString(),
granularity: granResult.duration
},
response
)
);
} else {
client.stdout.write(
formatText(response, {
event,
measure,
aggregation,
groupBy,
filter,
scope,
projectName: scope.type === "project-with-slug" ? scope.projectName : void 0,
teamName: scope.teamSlug,
periodStart: rounded.start.toISOString(),
periodEnd: rounded.end.toISOString(),
granularity: granResult.duration
})
);
}
return 0;
}
export {
query as default
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
getRouteVersions
} from "./chunk-AHU7WNL2.js";
import {
ensureProjectLink,
getRoutes,
offerAutoPromote,
parsePosition,
parseSubcommandArgs,
resolveRoute
} from "./chunk-OJOIUL2M.js";
import {
reorderSubcommand
} from "./chunk-U6XOC6E4.js";
import "./chunk-QNEHY3TU.js";
import "./chunk-XB2KZC2B.js";
import {
stamp_default
} from "./chunk-SOTR4CXR.js";
import "./chunk-7EHTK7LP.js";
import "./chunk-GGP5R3FU.js";
import {
getCommandName
} from "./chunk-ZLCMHY2G.js";
import "./chunk-3XFFP2BA.js";
import {
output_manager_default
} from "./chunk-FDJURQMQ.js";
import {
require_source
} from "./chunk-S7KYDPEM.js";
import {
__toESM
} from "./chunk-TZ2YI2VH.js";
// src/commands/routes/reorder.ts
var import_chalk = __toESM(require_source(), 1);
// src/util/routes/stage-routes.ts
async function stageRoutes(client, projectId, routes, overwrite, options = {}) {
const { teamId } = options;
const query = new URLSearchParams();
if (teamId)
query.set("teamId", teamId);
const queryString = query.toString();
const url = `/v1/projects/${projectId}/routes${queryString ? `?${queryString}` : ""}`;
return await client.fetch(url, {
method: "PUT",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ routes, overwrite })
});
}
// src/commands/routes/reorder.ts
async function reorder(client, argv) {
const parsed = await parseSubcommandArgs(argv, reorderSubcommand);
if (typeof parsed === "number")
return parsed;
const link = await ensureProjectLink(client);
if (typeof link === "number")
return link;
const { project, org } = link;
const teamId = org.type === "team" ? org.id : void 0;
const { args, flags } = parsed;
const skipConfirmation = flags["--yes"];
const identifier = args[0];
if (!identifier) {
output_manager_default.error(
`Route name or ID is required. Usage: ${getCommandName("routes reorder <name-or-id> --position <pos>")}`
);
return 1;
}
const { versions } = await getRouteVersions(client, project.id, { teamId });
const existingStagingVersion = versions.find((v) => v.isStaging);
output_manager_default.spinner("Fetching routes");
const { routes } = await getRoutes(client, project.id, { teamId });
output_manager_default.stopSpinner();
if (routes.length === 0) {
output_manager_default.error("No routes found in this project.");
return 1;
}
if (routes.length === 1) {
output_manager_default.error("Cannot reorder when there is only one route.");
return 1;
}
const route = await resolveRoute(client, routes, identifier);
if (!route) {
output_manager_default.error(
`No route found matching "${identifier}". Run ${import_chalk.default.cyan(
getCommandName("routes list")
)} to see all routes.`
);
return 1;
}
const currentIndex = routes.findIndex((r) => r.id === route.id);
const currentPosition = currentIndex + 1;
let targetIndex;
const positionFlag = flags["--position"];
const firstFlag = flags["--first"];
const lastFlag = flags["--last"];
if (firstFlag) {
targetIndex = 0;
} else if (lastFlag) {
targetIndex = routes.length;
} else if (positionFlag) {
if (positionFlag === "first") {
targetIndex = 0;
} else if (positionFlag === "last") {
targetIndex = routes.length;
} else {
const num = parseInt(positionFlag, 10);
if (!isNaN(num) && String(num) === positionFlag) {
if (num < 1) {
output_manager_default.error("Position must be 1 or greater.");
return 1;
}
targetIndex = Math.min(num - 1, routes.length);
} else {
try {
const pos = parsePosition(positionFlag);
if (pos.placement === "start") {
targetIndex = 0;
} else if (pos.placement === "end") {
targetIndex = routes.length;
} else if (pos.placement === "after" && pos.referenceId) {
const refIndex = routes.findIndex((r) => r.id === pos.referenceId);
if (refIndex === -1) {
output_manager_default.error(
`Reference route "${pos.referenceId}" not found. Run ${import_chalk.default.cyan(
getCommandName("routes list")
)} to see route IDs.`
);
return 1;
}
targetIndex = refIndex + 1;
} else if (pos.placement === "before" && pos.referenceId) {
const refIndex = routes.findIndex((r) => r.id === pos.referenceId);
if (refIndex === -1) {
output_manager_default.error(
`Reference route "${pos.referenceId}" not found. Run ${import_chalk.default.cyan(
getCommandName("routes list")
)} to see route IDs.`
);
return 1;
}
targetIndex = refIndex;
} else {
output_manager_default.error("Invalid position specification.");
return 1;
}
} catch (e) {
output_manager_default.error(
`${e instanceof Error ? e.message : "Invalid position"}. Usage: ${getCommandName("routes reorder <name-or-id> --position <pos>")}`
);
return 1;
}
}
}
} else {
output_manager_default.print("\n");
output_manager_default.log("Current route order:");
for (let i = 0; i < routes.length; i++) {
const r = routes[i];
const isCurrent = r.id === route.id;
const prefix = isCurrent ? import_chalk.default.cyan("\u2192") : " ";
const num = import_chalk.default.gray(`${i + 1}.`);
const name = isCurrent ? import_chalk.default.bold(r.name) : r.name;
const src = import_chalk.default.gray(`(${r.route.src})`);
const marker = isCurrent ? import_chalk.default.cyan(" \u2190 current") : "";
output_manager_default.print(` ${prefix} ${num} ${name} ${src}${marker}
`);
}
output_manager_default.print("\n");
const input = await client.input.text({
message: `Move "${route.name}" to position (1-${routes.length}, "first", or "last"):`,
validate: (val) => {
if (!val)
return "Position is required";
if (val === "first" || val === "last")
return true;
const num = parseInt(val, 10);
if (isNaN(num) || num < 1 || num > routes.length) {
return `Enter a number between 1 and ${routes.length}, "first", or "last"`;
}
return true;
}
});
if (input === "first") {
targetIndex = 0;
} else if (input === "last") {
targetIndex = routes.length;
} else {
targetIndex = parseInt(input, 10) - 1;
}
}
const adjustedTarget = currentIndex < targetIndex ? targetIndex - 1 : targetIndex;
const clampedTarget = Math.max(
0,
Math.min(adjustedTarget, routes.length - 1)
);
if (currentIndex === clampedTarget) {
output_manager_default.log(
`Route "${route.name}" is already at position ${currentPosition}.`
);
return 0;
}
const finalPosition = clampedTarget + 1;
if (!skipConfirmation) {
const confirmed = await client.input.confirm(
`Move "${route.name}" from position ${currentPosition} to position ${finalPosition}?`,
true
);
if (!confirmed) {
output_manager_default.log("Aborted.");
return 0;
}
}
const reordered = [...routes];
reordered.splice(currentIndex, 1);
reordered.splice(clampedTarget, 0, route);
const reorderStamp = stamp_default();
output_manager_default.spinner(`Moving route "${route.name}"`);
try {
const { version } = await stageRoutes(
client,
project.id,
reordered,
true,
// overwrite
{ teamId }
);
output_manager_default.log(
`${import_chalk.default.cyan("Moved")} "${route.name}" from position ${currentPosition} to ${finalPosition} ${import_chalk.default.gray(reorderStamp())}`
);
await offerAutoPromote(
client,
project.id,
version,
!!existingStagingVersion,
{ teamId, skipPrompts: skipConfirmation }
);
return 0;
} catch (e) {
const error = e;
output_manager_default.error(error.message || "Failed to reorder route");
return 1;
}
}
export {
reorder as default
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
updateRouteVersion
} from "./chunk-PMSMUMUO.js";
import {
getRouteVersions
} from "./chunk-AHU7WNL2.js";
import {
confirmAction,
ensureProjectLink,
findVersionById,
getRoutes,
parseSubcommandArgs,
printDiffSummary,
validateRequiredArgs
} from "./chunk-OJOIUL2M.js";
import {
restoreSubcommand
} from "./chunk-U6XOC6E4.js";
import "./chunk-QNEHY3TU.js";
import "./chunk-XB2KZC2B.js";
import {
stamp_default
} from "./chunk-SOTR4CXR.js";
import "./chunk-7EHTK7LP.js";
import "./chunk-GGP5R3FU.js";
import {
getCommandName
} from "./chunk-ZLCMHY2G.js";
import "./chunk-3XFFP2BA.js";
import {
output_manager_default
} from "./chunk-FDJURQMQ.js";
import {
require_source
} from "./chunk-S7KYDPEM.js";
import {
__toESM
} from "./chunk-TZ2YI2VH.js";
// src/commands/routes/restore.ts
var import_chalk = __toESM(require_source(), 1);
async function restore(client, argv) {
const parsed = await parseSubcommandArgs(argv, restoreSubcommand);
if (typeof parsed === "number")
return parsed;
const error = validateRequiredArgs(parsed.args, ["version-id"]);
if (error) {
output_manager_default.error(error);
return 1;
}
const link = await ensureProjectLink(client);
if (typeof link === "number")
return link;
const { project, org } = link;
const teamId = org.type === "team" ? org.id : void 0;
const [versionIdentifier] = parsed.args;
output_manager_default.spinner(`Fetching route versions for ${import_chalk.default.bold(project.name)}`);
const { versions } = await getRouteVersions(client, project.id, { teamId });
const result = findVersionById(versions, versionIdentifier);
if (result.error) {
output_manager_default.error(result.error);
return 1;
}
const version = result.version;
if (!version) {
output_manager_default.error("Version not found.");
return 1;
}
if (version.isLive) {
output_manager_default.error(
`Version ${import_chalk.default.bold(
version.id.slice(0, 12)
)} is currently live. You cannot restore the live version.
Run ${import_chalk.default.cyan(
getCommandName("routes list-versions")
)} to see previous versions you can restore.`
);
return 1;
}
if (version.isStaging) {
output_manager_default.error(
`Version ${import_chalk.default.bold(
version.id.slice(0, 12)
)} is staged. Use ${import_chalk.default.cyan(
getCommandName("routes publish")
)} to publish it instead.`
);
return 1;
}
output_manager_default.spinner("Fetching changes");
const { routes: diffRoutes } = await getRoutes(client, project.id, {
teamId,
versionId: version.id,
diff: true
});
const changedRoutes = diffRoutes.filter((r) => r.action !== void 0);
if (changedRoutes.length > 0) {
output_manager_default.print(`
${import_chalk.default.bold("Changes to be restored:")}
`);
printDiffSummary(changedRoutes);
output_manager_default.print("\n");
} else {
output_manager_default.print(
`
${import_chalk.default.gray("No changes detected from current production version.")}
`
);
}
const confirmed = await confirmAction(
client,
parsed.flags["--yes"],
`Restore version ${import_chalk.default.bold(version.id.slice(0, 12))} to production?`,
`This will replace the current live routes for ${import_chalk.default.bold(project.name)}.`
);
if (!confirmed) {
output_manager_default.log("Canceled");
return 0;
}
const updateStamp = stamp_default();
output_manager_default.spinner(`Restoring version ${import_chalk.default.bold(version.id.slice(0, 12))}`);
try {
const { version: newVersion } = await updateRouteVersion(
client,
project.id,
version.id,
"restore",
{ teamId }
);
output_manager_default.log(
`${import_chalk.default.cyan("Success!")} Version ${import_chalk.default.bold(
newVersion.id.slice(0, 12)
)} restored to production ${import_chalk.default.gray(updateStamp())}`
);
if (newVersion.ruleCount !== void 0) {
output_manager_default.print(
` ${import_chalk.default.bold("Active routes:")} ${newVersion.ruleCount}
`
);
}
return 0;
} catch (e) {
const error2 = e;
output_manager_default.error(error2.message || "Failed to restore version");
return 1;
}
}
export {
restore as default
};
+12
-12

@@ -14,3 +14,3 @@ import { createRequire as __createRequire } from 'node:module';

writeBuildResult
} from "../../chunks/chunk-DOFOJNZX.js";
} from "../../chunks/chunk-M5O5PZPC.js";
import {

@@ -21,16 +21,16 @@ require_semver

pullCommandLogic
} from "../../chunks/chunk-SZYO5TXZ.js";
} from "../../chunks/chunk-6DJMYUDD.js";
import {
pickOverrides,
readProjectSettings
} from "../../chunks/chunk-XBSU7P56.js";
} from "../../chunks/chunk-6TUTMN4G.js";
import {
require_dist
} from "../../chunks/chunk-TRF7S7TX.js";
} from "../../chunks/chunk-4X6AR5OT.js";
import "../../chunks/chunk-QXRJ52T4.js";
import "../../chunks/chunk-5GXLSNIT.js";
import "../../chunks/chunk-L7QDUSD6.js";
import "../../chunks/chunk-L4CDAO6F.js";
import "../../chunks/chunk-6CREWAFU.js";
import "../../chunks/chunk-LLUXSKCT.js";
import "../../chunks/chunk-DFZ6DRAH.js";
import "../../chunks/chunk-Y3EHOMJ3.js";
import "../../chunks/chunk-5KMQD57B.js";
import "../../chunks/chunk-MHB67DKL.js";
import "../../chunks/chunk-HP3P6UCH.js";
import {

@@ -41,6 +41,6 @@ DEFAULT_VERCEL_CONFIG_FILENAME,

require_main
} from "../../chunks/chunk-RR4BD6FR.js";
} from "../../chunks/chunk-6LQRDWWM.js";
import {
buildCommand
} from "../../chunks/chunk-RGBET6N6.js";
} from "../../chunks/chunk-QEEF7TLY.js";
import {

@@ -60,3 +60,3 @@ help

resolveProjectCwd
} from "../../chunks/chunk-BMTLRU2D.js";
} from "../../chunks/chunk-QNEHY3TU.js";
import {

@@ -63,0 +63,0 @@ TelemetryClient

@@ -16,6 +16,6 @@ import { createRequire as __createRequire } from 'node:module';

setupDomain
} from "../../chunks/chunk-53HFONUL.js";
} from "../../chunks/chunk-2NPVSUA5.js";
import {
readLocalConfig
} from "../../chunks/chunk-56SHOHOE.js";
} from "../../chunks/chunk-W3QZF2OP.js";
import {

@@ -32,3 +32,3 @@ highlight

} from "../../chunks/chunk-2IQTNMUG.js";
import "../../chunks/chunk-S4G3XJAP.js";
import "../../chunks/chunk-F7Q6GMBZ.js";
import {

@@ -46,3 +46,3 @@ validateJsonOutput

initSubcommand
} from "../../chunks/chunk-W2EUICVJ.js";
} from "../../chunks/chunk-QZ3VE5AG.js";
import "../../chunks/chunk-U6XOC6E4.js";

@@ -56,20 +56,20 @@ import "../../chunks/chunk-O7I4ZOCC.js";

pickOverrides
} from "../../chunks/chunk-XBSU7P56.js";
} from "../../chunks/chunk-6TUTMN4G.js";
import {
require_dist as require_dist2
} from "../../chunks/chunk-TRF7S7TX.js";
} from "../../chunks/chunk-4X6AR5OT.js";
import "../../chunks/chunk-QXRJ52T4.js";
import "../../chunks/chunk-L7QDUSD6.js";
import "../../chunks/chunk-Y3EHOMJ3.js";
import {
ensureLink
} from "../../chunks/chunk-L4CDAO6F.js";
} from "../../chunks/chunk-5KMQD57B.js";
import {
validatePaths,
validateRootDirectory
} from "../../chunks/chunk-6CREWAFU.js";
import "../../chunks/chunk-LLUXSKCT.js";
} from "../../chunks/chunk-MHB67DKL.js";
import "../../chunks/chunk-HP3P6UCH.js";
import {
compileVercelConfig
} from "../../chunks/chunk-RR4BD6FR.js";
import "../../chunks/chunk-RGBET6N6.js";
} from "../../chunks/chunk-6LQRDWWM.js";
import "../../chunks/chunk-QEEF7TLY.js";
import {

@@ -84,3 +84,3 @@ help

require_lib
} from "../../chunks/chunk-BMTLRU2D.js";
} from "../../chunks/chunk-QNEHY3TU.js";
import {

@@ -87,0 +87,0 @@ TelemetryClient

@@ -14,3 +14,3 @@ import { createRequire as __createRequire } from 'node:module';

linkCommand
} from "../../chunks/chunk-W2EUICVJ.js";
} from "../../chunks/chunk-QZ3VE5AG.js";
import "../../chunks/chunk-U6XOC6E4.js";

@@ -24,7 +24,7 @@ import "../../chunks/chunk-O7I4ZOCC.js";

ensureLink
} from "../../chunks/chunk-L4CDAO6F.js";
import "../../chunks/chunk-6CREWAFU.js";
import "../../chunks/chunk-LLUXSKCT.js";
import "../../chunks/chunk-RR4BD6FR.js";
import "../../chunks/chunk-RGBET6N6.js";
} from "../../chunks/chunk-5KMQD57B.js";
import "../../chunks/chunk-MHB67DKL.js";
import "../../chunks/chunk-HP3P6UCH.js";
import "../../chunks/chunk-6LQRDWWM.js";
import "../../chunks/chunk-QEEF7TLY.js";
import {

@@ -37,3 +37,3 @@ help

getTeams
} from "../../chunks/chunk-BMTLRU2D.js";
} from "../../chunks/chunk-QNEHY3TU.js";
import {

@@ -40,0 +40,0 @@ TelemetryClient

@@ -22,7 +22,7 @@ import { createRequire as __createRequire } from 'node:module';

getScope
} from "../../chunks/chunk-S4G3XJAP.js";
} from "../../chunks/chunk-F7Q6GMBZ.js";
import {
formatEnvironment,
validateLsArgs
} from "../../chunks/chunk-HH3MM5AN.js";
} from "../../chunks/chunk-D4EB4RQH.js";
import {

@@ -42,3 +42,3 @@ validateJsonOutput

parseTarget
} from "../../chunks/chunk-BMTLRU2D.js";
} from "../../chunks/chunk-QNEHY3TU.js";
import {

@@ -45,0 +45,0 @@ TelemetryClient

@@ -1,1 +0,1 @@

export const version = "50.31.3";
export const version = "50.32.1";
{
"name": "vercel",
"version": "50.31.3",
"version": "50.32.1",
"type": "module",

@@ -33,22 +33,22 @@ "preferGlobal": true,

"proxy-agent": "6.4.0",
"@vercel/detect-agent": "1.2.1",
"@vercel/build-utils": "13.8.0",
"@vercel/backends": "0.0.45",
"@vercel/elysia": "0.1.48",
"@vercel/build-utils": "13.8.0",
"@vercel/detect-agent": "1.2.1",
"@vercel/express": "0.1.57",
"@vercel/go": "3.4.4",
"@vercel/fastify": "0.1.51",
"@vercel/go": "3.4.4",
"@vercel/h3": "0.1.57",
"@vercel/hono": "0.2.51",
"@vercel/koa": "0.1.31",
"@vercel/hydrogen": "1.3.6",
"@vercel/koa": "0.1.31",
"@vercel/nestjs": "0.2.52",
"@vercel/next": "4.16.1",
"@vercel/node": "5.6.15",
"@vercel/python": "6.22.0",
"@vercel/remix-builder": "5.7.0",
"@vercel/redwood": "2.4.10",
"@vercel/remix-builder": "5.7.0",
"@vercel/ruby": "2.3.2",
"@vercel/rust": "1.0.5",
"@vercel/ruby": "2.3.2",
"@vercel/static-build": "2.9.0"
"@vercel/static-build": "2.9.0",
"@vercel/node": "5.6.15"
},

@@ -181,4 +181,4 @@ "devDependencies": {

"yauzl-promise": "2.1.3",
"@vercel-internals/constants": "1.0.4",
"@vercel-internals/get-package-json": "1.0.0",
"@vercel-internals/constants": "1.0.4",
"@vercel-internals/types": "3.0.6",

@@ -188,3 +188,3 @@ "@vercel/client": "17.2.57",

"@vercel/frameworks": "3.21.0",
"@vercel/fs-detectors": "5.10.1",
"@vercel/fs-detectors": "5.10.2",
"@vercel/routing-utils": "6.0.2"

@@ -191,0 +191,0 @@ },

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
require_end_of_stream
} from "./chunk-L7QDUSD6.js";
import {
require_once
} from "./chunk-BMTLRU2D.js";
import {
require_signal_exit
} from "./chunk-FDJURQMQ.js";
import {
__commonJS,
__require
} from "./chunk-TZ2YI2VH.js";
// ../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/windows.js
var require_windows = __commonJS({
"../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/windows.js"(exports, module) {
module.exports = isexe;
isexe.sync = sync;
var fs = __require("fs");
function checkPathExt(path, options) {
var pathext = options.pathExt !== void 0 ? options.pathExt : process.env.PATHEXT;
if (!pathext) {
return true;
}
pathext = pathext.split(";");
if (pathext.indexOf("") !== -1) {
return true;
}
for (var i = 0; i < pathext.length; i++) {
var p = pathext[i].toLowerCase();
if (p && path.substr(-p.length).toLowerCase() === p) {
return true;
}
}
return false;
}
function checkStat(stat, path, options) {
if (!stat.isSymbolicLink() && !stat.isFile()) {
return false;
}
return checkPathExt(path, options);
}
function isexe(path, options, cb) {
fs.stat(path, function(er, stat) {
cb(er, er ? false : checkStat(stat, path, options));
});
}
function sync(path, options) {
return checkStat(fs.statSync(path), path, options);
}
}
});
// ../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/mode.js
var require_mode = __commonJS({
"../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/mode.js"(exports, module) {
module.exports = isexe;
isexe.sync = sync;
var fs = __require("fs");
function isexe(path, options, cb) {
fs.stat(path, function(er, stat) {
cb(er, er ? false : checkStat(stat, options));
});
}
function sync(path, options) {
return checkStat(fs.statSync(path), options);
}
function checkStat(stat, options) {
return stat.isFile() && checkMode(stat, options);
}
function checkMode(stat, options) {
var mod = stat.mode;
var uid = stat.uid;
var gid = stat.gid;
var myUid = options.uid !== void 0 ? options.uid : process.getuid && process.getuid();
var myGid = options.gid !== void 0 ? options.gid : process.getgid && process.getgid();
var u = parseInt("100", 8);
var g = parseInt("010", 8);
var o = parseInt("001", 8);
var ug = u | g;
var ret = mod & o || mod & g && gid === myGid || mod & u && uid === myUid || mod & ug && myUid === 0;
return ret;
}
}
});
// ../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/index.js
var require_isexe = __commonJS({
"../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/index.js"(exports, module) {
var fs = __require("fs");
var core;
if (process.platform === "win32" || global.TESTING_WINDOWS) {
core = require_windows();
} else {
core = require_mode();
}
module.exports = isexe;
isexe.sync = sync;
function isexe(path, options, cb) {
if (typeof options === "function") {
cb = options;
options = {};
}
if (!cb) {
if (typeof Promise !== "function") {
throw new TypeError("callback not provided");
}
return new Promise(function(resolve, reject) {
isexe(path, options || {}, function(er, is) {
if (er) {
reject(er);
} else {
resolve(is);
}
});
});
}
core(path, options || {}, function(er, is) {
if (er) {
if (er.code === "EACCES" || options && options.ignoreErrors) {
er = null;
is = false;
}
}
cb(er, is);
});
}
function sync(path, options) {
try {
return core.sync(path, options || {});
} catch (er) {
if (options && options.ignoreErrors || er.code === "EACCES") {
return false;
} else {
throw er;
}
}
}
}
});
// ../../node_modules/.pnpm/which@2.0.2/node_modules/which/which.js
var require_which = __commonJS({
"../../node_modules/.pnpm/which@2.0.2/node_modules/which/which.js"(exports, module) {
var isWindows = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys";
var path = __require("path");
var COLON = isWindows ? ";" : ":";
var isexe = require_isexe();
var getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: "ENOENT" });
var getPathInfo = (cmd, opt) => {
const colon = opt.colon || COLON;
const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [""] : [
// windows always checks the cwd first
...isWindows ? [process.cwd()] : [],
...(opt.path || process.env.PATH || /* istanbul ignore next: very unusual */
"").split(colon)
];
const pathExtExe = isWindows ? opt.pathExt || process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM" : "";
const pathExt = isWindows ? pathExtExe.split(colon) : [""];
if (isWindows) {
if (cmd.indexOf(".") !== -1 && pathExt[0] !== "")
pathExt.unshift("");
}
return {
pathEnv,
pathExt,
pathExtExe
};
};
var which = (cmd, opt, cb) => {
if (typeof opt === "function") {
cb = opt;
opt = {};
}
if (!opt)
opt = {};
const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
const found = [];
const step = (i) => new Promise((resolve, reject) => {
if (i === pathEnv.length)
return opt.all && found.length ? resolve(found) : reject(getNotFoundError(cmd));
const ppRaw = pathEnv[i];
const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
const pCmd = path.join(pathPart, cmd);
const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
resolve(subStep(p, i, 0));
});
const subStep = (p, i, ii) => new Promise((resolve, reject) => {
if (ii === pathExt.length)
return resolve(step(i + 1));
const ext = pathExt[ii];
isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {
if (!er && is) {
if (opt.all)
found.push(p + ext);
else
return resolve(p + ext);
}
return resolve(subStep(p, i, ii + 1));
});
});
return cb ? step(0).then((res) => cb(null, res), cb) : step(0);
};
var whichSync = (cmd, opt) => {
opt = opt || {};
const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
const found = [];
for (let i = 0; i < pathEnv.length; i++) {
const ppRaw = pathEnv[i];
const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
const pCmd = path.join(pathPart, cmd);
const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
for (let j = 0; j < pathExt.length; j++) {
const cur = p + pathExt[j];
try {
const is = isexe.sync(cur, { pathExt: pathExtExe });
if (is) {
if (opt.all)
found.push(cur);
else
return cur;
}
} catch (ex) {
}
}
}
if (opt.all && found.length)
return found;
if (opt.nothrow)
return null;
throw getNotFoundError(cmd);
};
module.exports = which;
which.sync = whichSync;
}
});
// ../../node_modules/.pnpm/path-key@3.1.1/node_modules/path-key/index.js
var require_path_key = __commonJS({
"../../node_modules/.pnpm/path-key@3.1.1/node_modules/path-key/index.js"(exports, module) {
"use strict";
var pathKey = (options = {}) => {
const environment = options.env || process.env;
const platform = options.platform || process.platform;
if (platform !== "win32") {
return "PATH";
}
return Object.keys(environment).reverse().find((key) => key.toUpperCase() === "PATH") || "Path";
};
module.exports = pathKey;
module.exports.default = pathKey;
}
});
// ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js
var require_resolveCommand = __commonJS({
"../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js"(exports, module) {
"use strict";
var path = __require("path");
var which = require_which();
var getPathKey = require_path_key();
function resolveCommandAttempt(parsed, withoutPathExt) {
const env = parsed.options.env || process.env;
const cwd = process.cwd();
const hasCustomCwd = parsed.options.cwd != null;
const shouldSwitchCwd = hasCustomCwd && process.chdir !== void 0 && !process.chdir.disabled;
if (shouldSwitchCwd) {
try {
process.chdir(parsed.options.cwd);
} catch (err) {
}
}
let resolved;
try {
resolved = which.sync(parsed.command, {
path: env[getPathKey({ env })],
pathExt: withoutPathExt ? path.delimiter : void 0
});
} catch (e) {
} finally {
if (shouldSwitchCwd) {
process.chdir(cwd);
}
}
if (resolved) {
resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
}
return resolved;
}
function resolveCommand(parsed) {
return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);
}
module.exports = resolveCommand;
}
});
// ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/escape.js
var require_escape = __commonJS({
"../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/escape.js"(exports, module) {
"use strict";
var metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
function escapeCommand(arg) {
arg = arg.replace(metaCharsRegExp, "^$1");
return arg;
}
function escapeArgument(arg, doubleEscapeMetaChars) {
arg = `${arg}`;
arg = arg.replace(/(?=(\\+?)?)\1"/g, '$1$1\\"');
arg = arg.replace(/(?=(\\+?)?)\1$/, "$1$1");
arg = `"${arg}"`;
arg = arg.replace(metaCharsRegExp, "^$1");
if (doubleEscapeMetaChars) {
arg = arg.replace(metaCharsRegExp, "^$1");
}
return arg;
}
module.exports.command = escapeCommand;
module.exports.argument = escapeArgument;
}
});
// ../../node_modules/.pnpm/shebang-regex@3.0.0/node_modules/shebang-regex/index.js
var require_shebang_regex = __commonJS({
"../../node_modules/.pnpm/shebang-regex@3.0.0/node_modules/shebang-regex/index.js"(exports, module) {
"use strict";
module.exports = /^#!(.*)/;
}
});
// ../../node_modules/.pnpm/shebang-command@2.0.0/node_modules/shebang-command/index.js
var require_shebang_command = __commonJS({
"../../node_modules/.pnpm/shebang-command@2.0.0/node_modules/shebang-command/index.js"(exports, module) {
"use strict";
var shebangRegex = require_shebang_regex();
module.exports = (string = "") => {
const match = string.match(shebangRegex);
if (!match) {
return null;
}
const [path, argument] = match[0].replace(/#! ?/, "").split(" ");
const binary = path.split("/").pop();
if (binary === "env") {
return argument;
}
return argument ? `${binary} ${argument}` : binary;
};
}
});
// ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js
var require_readShebang = __commonJS({
"../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js"(exports, module) {
"use strict";
var fs = __require("fs");
var shebangCommand = require_shebang_command();
function readShebang(command) {
const size = 150;
const buffer = Buffer.alloc(size);
let fd;
try {
fd = fs.openSync(command, "r");
fs.readSync(fd, buffer, 0, size, 0);
fs.closeSync(fd);
} catch (e) {
}
return shebangCommand(buffer.toString());
}
module.exports = readShebang;
}
});
// ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js
var require_parse = __commonJS({
"../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js"(exports, module) {
"use strict";
var path = __require("path");
var resolveCommand = require_resolveCommand();
var escape = require_escape();
var readShebang = require_readShebang();
var isWin = process.platform === "win32";
var isExecutableRegExp = /\.(?:com|exe)$/i;
var isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;
function detectShebang(parsed) {
parsed.file = resolveCommand(parsed);
const shebang = parsed.file && readShebang(parsed.file);
if (shebang) {
parsed.args.unshift(parsed.file);
parsed.command = shebang;
return resolveCommand(parsed);
}
return parsed.file;
}
function parseNonShell(parsed) {
if (!isWin) {
return parsed;
}
const commandFile = detectShebang(parsed);
const needsShell = !isExecutableRegExp.test(commandFile);
if (parsed.options.forceShell || needsShell) {
const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
parsed.command = path.normalize(parsed.command);
parsed.command = escape.command(parsed.command);
parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));
const shellCommand = [parsed.command].concat(parsed.args).join(" ");
parsed.args = ["/d", "/s", "/c", `"${shellCommand}"`];
parsed.command = process.env.comspec || "cmd.exe";
parsed.options.windowsVerbatimArguments = true;
}
return parsed;
}
function parse(command, args, options) {
if (args && !Array.isArray(args)) {
options = args;
args = null;
}
args = args ? args.slice(0) : [];
options = Object.assign({}, options);
const parsed = {
command,
args,
options,
file: void 0,
original: {
command,
args
}
};
return options.shell ? parsed : parseNonShell(parsed);
}
module.exports = parse;
}
});
// ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/enoent.js
var require_enoent = __commonJS({
"../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/enoent.js"(exports, module) {
"use strict";
var isWin = process.platform === "win32";
function notFoundError(original, syscall) {
return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), {
code: "ENOENT",
errno: "ENOENT",
syscall: `${syscall} ${original.command}`,
path: original.command,
spawnargs: original.args
});
}
function hookChildProcess(cp, parsed) {
if (!isWin) {
return;
}
const originalEmit = cp.emit;
cp.emit = function(name, arg1) {
if (name === "exit") {
const err = verifyENOENT(arg1, parsed);
if (err) {
return originalEmit.call(cp, "error", err);
}
}
return originalEmit.apply(cp, arguments);
};
}
function verifyENOENT(status, parsed) {
if (isWin && status === 1 && !parsed.file) {
return notFoundError(parsed.original, "spawn");
}
return null;
}
function verifyENOENTSync(status, parsed) {
if (isWin && status === 1 && !parsed.file) {
return notFoundError(parsed.original, "spawnSync");
}
return null;
}
module.exports = {
hookChildProcess,
verifyENOENT,
verifyENOENTSync,
notFoundError
};
}
});
// ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/index.js
var require_cross_spawn = __commonJS({
"../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/index.js"(exports, module) {
"use strict";
var cp = __require("child_process");
var parse = require_parse();
var enoent = require_enoent();
function spawn(command, args, options) {
const parsed = parse(command, args, options);
const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
enoent.hookChildProcess(spawned, parsed);
return spawned;
}
function spawnSync(command, args, options) {
const parsed = parse(command, args, options);
const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);
result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
return result;
}
module.exports = spawn;
module.exports.spawn = spawn;
module.exports.sync = spawnSync;
module.exports._parse = parse;
module.exports._enoent = enoent;
}
});
// ../../node_modules/.pnpm/strip-final-newline@2.0.0/node_modules/strip-final-newline/index.js
var require_strip_final_newline = __commonJS({
"../../node_modules/.pnpm/strip-final-newline@2.0.0/node_modules/strip-final-newline/index.js"(exports, module) {
"use strict";
module.exports = (input) => {
const LF = typeof input === "string" ? "\n" : "\n".charCodeAt();
const CR = typeof input === "string" ? "\r" : "\r".charCodeAt();
if (input[input.length - 1] === LF) {
input = input.slice(0, input.length - 1);
}
if (input[input.length - 1] === CR) {
input = input.slice(0, input.length - 1);
}
return input;
};
}
});
// ../../node_modules/.pnpm/npm-run-path@4.0.1/node_modules/npm-run-path/index.js
var require_npm_run_path = __commonJS({
"../../node_modules/.pnpm/npm-run-path@4.0.1/node_modules/npm-run-path/index.js"(exports, module) {
"use strict";
var path = __require("path");
var pathKey = require_path_key();
var npmRunPath = (options) => {
options = {
cwd: process.cwd(),
path: process.env[pathKey()],
execPath: process.execPath,
...options
};
let previous;
let cwdPath = path.resolve(options.cwd);
const result = [];
while (previous !== cwdPath) {
result.push(path.join(cwdPath, "node_modules/.bin"));
previous = cwdPath;
cwdPath = path.resolve(cwdPath, "..");
}
const execPathDir = path.resolve(options.cwd, options.execPath, "..");
result.push(execPathDir);
return result.concat(options.path).join(path.delimiter);
};
module.exports = npmRunPath;
module.exports.default = npmRunPath;
module.exports.env = (options) => {
options = {
env: process.env,
...options
};
const env = { ...options.env };
const path2 = pathKey({ env });
options.path = env[path2];
env[path2] = module.exports(options);
return env;
};
}
});
// ../../node_modules/.pnpm/mimic-fn@2.1.0/node_modules/mimic-fn/index.js
var require_mimic_fn = __commonJS({
"../../node_modules/.pnpm/mimic-fn@2.1.0/node_modules/mimic-fn/index.js"(exports, module) {
"use strict";
var mimicFn = (to, from) => {
for (const prop of Reflect.ownKeys(from)) {
Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop));
}
return to;
};
module.exports = mimicFn;
module.exports.default = mimicFn;
}
});
// ../../node_modules/.pnpm/onetime@5.1.2/node_modules/onetime/index.js
var require_onetime = __commonJS({
"../../node_modules/.pnpm/onetime@5.1.2/node_modules/onetime/index.js"(exports, module) {
"use strict";
var mimicFn = require_mimic_fn();
var calledFunctions = /* @__PURE__ */ new WeakMap();
var onetime = (function_, options = {}) => {
if (typeof function_ !== "function") {
throw new TypeError("Expected a function");
}
let returnValue;
let callCount = 0;
const functionName = function_.displayName || function_.name || "<anonymous>";
const onetime2 = function(...arguments_) {
calledFunctions.set(onetime2, ++callCount);
if (callCount === 1) {
returnValue = function_.apply(this, arguments_);
function_ = null;
} else if (options.throw === true) {
throw new Error(`Function \`${functionName}\` can only be called once`);
}
return returnValue;
};
mimicFn(onetime2, function_);
calledFunctions.set(onetime2, callCount);
return onetime2;
};
module.exports = onetime;
module.exports.default = onetime;
module.exports.callCount = (function_) => {
if (!calledFunctions.has(function_)) {
throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`);
}
return calledFunctions.get(function_);
};
}
});
// ../../node_modules/.pnpm/human-signals@1.1.1/node_modules/human-signals/build/src/core.js
var require_core = __commonJS({
"../../node_modules/.pnpm/human-signals@1.1.1/node_modules/human-signals/build/src/core.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SIGNALS = void 0;
var SIGNALS = [
{
name: "SIGHUP",
number: 1,
action: "terminate",
description: "Terminal closed",
standard: "posix"
},
{
name: "SIGINT",
number: 2,
action: "terminate",
description: "User interruption with CTRL-C",
standard: "ansi"
},
{
name: "SIGQUIT",
number: 3,
action: "core",
description: "User interruption with CTRL-\\",
standard: "posix"
},
{
name: "SIGILL",
number: 4,
action: "core",
description: "Invalid machine instruction",
standard: "ansi"
},
{
name: "SIGTRAP",
number: 5,
action: "core",
description: "Debugger breakpoint",
standard: "posix"
},
{
name: "SIGABRT",
number: 6,
action: "core",
description: "Aborted",
standard: "ansi"
},
{
name: "SIGIOT",
number: 6,
action: "core",
description: "Aborted",
standard: "bsd"
},
{
name: "SIGBUS",
number: 7,
action: "core",
description: "Bus error due to misaligned, non-existing address or paging error",
standard: "bsd"
},
{
name: "SIGEMT",
number: 7,
action: "terminate",
description: "Command should be emulated but is not implemented",
standard: "other"
},
{
name: "SIGFPE",
number: 8,
action: "core",
description: "Floating point arithmetic error",
standard: "ansi"
},
{
name: "SIGKILL",
number: 9,
action: "terminate",
description: "Forced termination",
standard: "posix",
forced: true
},
{
name: "SIGUSR1",
number: 10,
action: "terminate",
description: "Application-specific signal",
standard: "posix"
},
{
name: "SIGSEGV",
number: 11,
action: "core",
description: "Segmentation fault",
standard: "ansi"
},
{
name: "SIGUSR2",
number: 12,
action: "terminate",
description: "Application-specific signal",
standard: "posix"
},
{
name: "SIGPIPE",
number: 13,
action: "terminate",
description: "Broken pipe or socket",
standard: "posix"
},
{
name: "SIGALRM",
number: 14,
action: "terminate",
description: "Timeout or timer",
standard: "posix"
},
{
name: "SIGTERM",
number: 15,
action: "terminate",
description: "Termination",
standard: "ansi"
},
{
name: "SIGSTKFLT",
number: 16,
action: "terminate",
description: "Stack is empty or overflowed",
standard: "other"
},
{
name: "SIGCHLD",
number: 17,
action: "ignore",
description: "Child process terminated, paused or unpaused",
standard: "posix"
},
{
name: "SIGCLD",
number: 17,
action: "ignore",
description: "Child process terminated, paused or unpaused",
standard: "other"
},
{
name: "SIGCONT",
number: 18,
action: "unpause",
description: "Unpaused",
standard: "posix",
forced: true
},
{
name: "SIGSTOP",
number: 19,
action: "pause",
description: "Paused",
standard: "posix",
forced: true
},
{
name: "SIGTSTP",
number: 20,
action: "pause",
description: 'Paused using CTRL-Z or "suspend"',
standard: "posix"
},
{
name: "SIGTTIN",
number: 21,
action: "pause",
description: "Background process cannot read terminal input",
standard: "posix"
},
{
name: "SIGBREAK",
number: 21,
action: "terminate",
description: "User interruption with CTRL-BREAK",
standard: "other"
},
{
name: "SIGTTOU",
number: 22,
action: "pause",
description: "Background process cannot write to terminal output",
standard: "posix"
},
{
name: "SIGURG",
number: 23,
action: "ignore",
description: "Socket received out-of-band data",
standard: "bsd"
},
{
name: "SIGXCPU",
number: 24,
action: "core",
description: "Process timed out",
standard: "bsd"
},
{
name: "SIGXFSZ",
number: 25,
action: "core",
description: "File too big",
standard: "bsd"
},
{
name: "SIGVTALRM",
number: 26,
action: "terminate",
description: "Timeout or timer",
standard: "bsd"
},
{
name: "SIGPROF",
number: 27,
action: "terminate",
description: "Timeout or timer",
standard: "bsd"
},
{
name: "SIGWINCH",
number: 28,
action: "ignore",
description: "Terminal window size changed",
standard: "bsd"
},
{
name: "SIGIO",
number: 29,
action: "terminate",
description: "I/O is available",
standard: "other"
},
{
name: "SIGPOLL",
number: 29,
action: "terminate",
description: "Watched event",
standard: "other"
},
{
name: "SIGINFO",
number: 29,
action: "ignore",
description: "Request for process information",
standard: "other"
},
{
name: "SIGPWR",
number: 30,
action: "terminate",
description: "Device running out of power",
standard: "systemv"
},
{
name: "SIGSYS",
number: 31,
action: "core",
description: "Invalid system call",
standard: "other"
},
{
name: "SIGUNUSED",
number: 31,
action: "terminate",
description: "Invalid system call",
standard: "other"
}
];
exports.SIGNALS = SIGNALS;
}
});
// ../../node_modules/.pnpm/human-signals@1.1.1/node_modules/human-signals/build/src/realtime.js
var require_realtime = __commonJS({
"../../node_modules/.pnpm/human-signals@1.1.1/node_modules/human-signals/build/src/realtime.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SIGRTMAX = exports.getRealtimeSignals = void 0;
var getRealtimeSignals = function() {
const length = SIGRTMAX - SIGRTMIN + 1;
return Array.from({ length }, getRealtimeSignal);
};
exports.getRealtimeSignals = getRealtimeSignals;
var getRealtimeSignal = function(value, index) {
return {
name: `SIGRT${index + 1}`,
number: SIGRTMIN + index,
action: "terminate",
description: "Application-specific signal (realtime)",
standard: "posix"
};
};
var SIGRTMIN = 34;
var SIGRTMAX = 64;
exports.SIGRTMAX = SIGRTMAX;
}
});
// ../../node_modules/.pnpm/human-signals@1.1.1/node_modules/human-signals/build/src/signals.js
var require_signals = __commonJS({
"../../node_modules/.pnpm/human-signals@1.1.1/node_modules/human-signals/build/src/signals.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getSignals = void 0;
var _os = __require("os");
var _core = require_core();
var _realtime = require_realtime();
var getSignals = function() {
const realtimeSignals = (0, _realtime.getRealtimeSignals)();
const signals = [..._core.SIGNALS, ...realtimeSignals].map(normalizeSignal);
return signals;
};
exports.getSignals = getSignals;
var normalizeSignal = function({
name,
number: defaultNumber,
description,
action,
forced = false,
standard
}) {
const {
signals: { [name]: constantSignal }
} = _os.constants;
const supported = constantSignal !== void 0;
const number = supported ? constantSignal : defaultNumber;
return { name, number, description, supported, action, forced, standard };
};
}
});
// ../../node_modules/.pnpm/human-signals@1.1.1/node_modules/human-signals/build/src/main.js
var require_main = __commonJS({
"../../node_modules/.pnpm/human-signals@1.1.1/node_modules/human-signals/build/src/main.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.signalsByNumber = exports.signalsByName = void 0;
var _os = __require("os");
var _signals = require_signals();
var _realtime = require_realtime();
var getSignalsByName = function() {
const signals = (0, _signals.getSignals)();
return signals.reduce(getSignalByName, {});
};
var getSignalByName = function(signalByNameMemo, { name, number, description, supported, action, forced, standard }) {
return {
...signalByNameMemo,
[name]: { name, number, description, supported, action, forced, standard }
};
};
var signalsByName = getSignalsByName();
exports.signalsByName = signalsByName;
var getSignalsByNumber = function() {
const signals = (0, _signals.getSignals)();
const length = _realtime.SIGRTMAX + 1;
const signalsA = Array.from({ length }, (value, number) => getSignalByNumber(number, signals));
return Object.assign({}, ...signalsA);
};
var getSignalByNumber = function(number, signals) {
const signal = findSignalByNumber(number, signals);
if (signal === void 0) {
return {};
}
const { name, description, supported, action, forced, standard } = signal;
return {
[number]: {
name,
number,
description,
supported,
action,
forced,
standard
}
};
};
var findSignalByNumber = function(number, signals) {
const signal = signals.find(({ name }) => _os.constants.signals[name] === number);
if (signal !== void 0) {
return signal;
}
return signals.find((signalA) => signalA.number === number);
};
var signalsByNumber = getSignalsByNumber();
exports.signalsByNumber = signalsByNumber;
}
});
// ../../node_modules/.pnpm/execa@3.2.0/node_modules/execa/lib/error.js
var require_error = __commonJS({
"../../node_modules/.pnpm/execa@3.2.0/node_modules/execa/lib/error.js"(exports, module) {
"use strict";
var { signalsByName } = require_main();
var getErrorPrefix = ({ timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled }) => {
if (timedOut) {
return `timed out after ${timeout} milliseconds`;
}
if (isCanceled) {
return "was canceled";
}
if (errorCode !== void 0) {
return `failed with ${errorCode}`;
}
if (signal !== void 0) {
return `was killed with ${signal} (${signalDescription})`;
}
if (exitCode !== void 0) {
return `failed with exit code ${exitCode}`;
}
return "failed";
};
var makeError = ({
stdout,
stderr,
all,
error,
signal,
exitCode,
command,
timedOut,
isCanceled,
killed,
parsed: { options: { timeout } }
}) => {
exitCode = exitCode === null ? void 0 : exitCode;
signal = signal === null ? void 0 : signal;
const signalDescription = signal === void 0 ? void 0 : signalsByName[signal].description;
const errorCode = error && error.code;
const prefix = getErrorPrefix({ timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled });
const message = `Command ${prefix}: ${command}`;
if (error instanceof Error) {
error.originalMessage = error.message;
error.message = `${message}
${error.message}`;
} else {
error = new Error(message);
}
error.command = command;
error.exitCode = exitCode;
error.signal = signal;
error.signalDescription = signalDescription;
error.stdout = stdout;
error.stderr = stderr;
if (all !== void 0) {
error.all = all;
}
if ("bufferedData" in error) {
delete error.bufferedData;
}
error.failed = true;
error.timedOut = Boolean(timedOut);
error.isCanceled = isCanceled;
error.killed = killed && !timedOut;
return error;
};
module.exports = makeError;
}
});
// ../../node_modules/.pnpm/execa@3.2.0/node_modules/execa/lib/stdio.js
var require_stdio = __commonJS({
"../../node_modules/.pnpm/execa@3.2.0/node_modules/execa/lib/stdio.js"(exports, module) {
"use strict";
var aliases = ["stdin", "stdout", "stderr"];
var hasAlias = (opts) => aliases.some((alias) => opts[alias] !== void 0);
var normalizeStdio = (opts) => {
if (!opts) {
return;
}
const { stdio } = opts;
if (stdio === void 0) {
return aliases.map((alias) => opts[alias]);
}
if (hasAlias(opts)) {
throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${aliases.map((alias) => `\`${alias}\``).join(", ")}`);
}
if (typeof stdio === "string") {
return stdio;
}
if (!Array.isArray(stdio)) {
throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``);
}
const length = Math.max(stdio.length, aliases.length);
return Array.from({ length }, (value, index) => stdio[index]);
};
module.exports = normalizeStdio;
module.exports.node = (opts) => {
const stdio = normalizeStdio(opts);
if (stdio === "ipc") {
return "ipc";
}
if (stdio === void 0 || typeof stdio === "string") {
return [stdio, stdio, stdio, "ipc"];
}
if (stdio.includes("ipc")) {
return stdio;
}
return [...stdio, "ipc"];
};
}
});
// ../../node_modules/.pnpm/p-finally@2.0.1/node_modules/p-finally/index.js
var require_p_finally = __commonJS({
"../../node_modules/.pnpm/p-finally@2.0.1/node_modules/p-finally/index.js"(exports, module) {
"use strict";
module.exports = async (promise, onFinally = () => {
}) => {
let value;
try {
value = await promise;
} catch (error) {
await onFinally();
throw error;
}
await onFinally();
return value;
};
}
});
// ../../node_modules/.pnpm/execa@3.2.0/node_modules/execa/lib/kill.js
var require_kill = __commonJS({
"../../node_modules/.pnpm/execa@3.2.0/node_modules/execa/lib/kill.js"(exports, module) {
"use strict";
var os = __require("os");
var onExit = require_signal_exit();
var pFinally = require_p_finally();
var DEFAULT_FORCE_KILL_TIMEOUT = 1e3 * 5;
var spawnedKill = (kill, signal = "SIGTERM", options = {}) => {
const killResult = kill(signal);
setKillTimeout(kill, signal, options, killResult);
return killResult;
};
var setKillTimeout = (kill, signal, options, killResult) => {
if (!shouldForceKill(signal, options, killResult)) {
return;
}
const timeout = getForceKillAfterTimeout(options);
setTimeout(() => {
kill("SIGKILL");
}, timeout).unref();
};
var shouldForceKill = (signal, { forceKillAfterTimeout }, killResult) => {
return isSigterm(signal) && forceKillAfterTimeout !== false && killResult;
};
var isSigterm = (signal) => {
return signal === os.constants.signals.SIGTERM || typeof signal === "string" && signal.toUpperCase() === "SIGTERM";
};
var getForceKillAfterTimeout = ({ forceKillAfterTimeout = true }) => {
if (forceKillAfterTimeout === true) {
return DEFAULT_FORCE_KILL_TIMEOUT;
}
if (!Number.isInteger(forceKillAfterTimeout) || forceKillAfterTimeout < 0) {
throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${forceKillAfterTimeout}\` (${typeof forceKillAfterTimeout})`);
}
return forceKillAfterTimeout;
};
var spawnedCancel = (spawned, context) => {
const killResult = spawned.kill();
if (killResult) {
context.isCanceled = true;
}
};
var timeoutKill = (spawned, signal, reject) => {
spawned.kill(signal);
reject(Object.assign(new Error("Timed out"), { timedOut: true, signal }));
};
var setupTimeout = (spawned, { timeout, killSignal = "SIGTERM" }, spawnedPromise) => {
if (timeout === 0 || timeout === void 0) {
return spawnedPromise;
}
if (!Number.isInteger(timeout) || timeout < 0) {
throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`);
}
let timeoutId;
const timeoutPromise = new Promise((resolve, reject) => {
timeoutId = setTimeout(() => {
timeoutKill(spawned, killSignal, reject);
}, timeout);
});
const safeSpawnedPromise = pFinally(spawnedPromise, () => {
clearTimeout(timeoutId);
});
return Promise.race([timeoutPromise, safeSpawnedPromise]);
};
var setExitHandler = (spawned, { cleanup, detached }, timedPromise) => {
if (!cleanup || detached) {
return timedPromise;
}
const removeExitHandler = onExit(() => {
spawned.kill();
});
return pFinally(timedPromise, removeExitHandler);
};
module.exports = {
spawnedKill,
spawnedCancel,
setupTimeout,
setExitHandler
};
}
});
// ../../node_modules/.pnpm/is-stream@2.0.1/node_modules/is-stream/index.js
var require_is_stream = __commonJS({
"../../node_modules/.pnpm/is-stream@2.0.1/node_modules/is-stream/index.js"(exports, module) {
"use strict";
var isStream = (stream) => stream !== null && typeof stream === "object" && typeof stream.pipe === "function";
isStream.writable = (stream) => isStream(stream) && stream.writable !== false && typeof stream._write === "function" && typeof stream._writableState === "object";
isStream.readable = (stream) => isStream(stream) && stream.readable !== false && typeof stream._read === "function" && typeof stream._readableState === "object";
isStream.duplex = (stream) => isStream.writable(stream) && isStream.readable(stream);
isStream.transform = (stream) => isStream.duplex(stream) && typeof stream._transform === "function";
module.exports = isStream;
}
});
// ../../node_modules/.pnpm/pump@3.0.2/node_modules/pump/index.js
var require_pump = __commonJS({
"../../node_modules/.pnpm/pump@3.0.2/node_modules/pump/index.js"(exports, module) {
var once = require_once();
var eos = require_end_of_stream();
var fs;
try {
fs = __require("fs");
} catch (e) {
}
var noop = function() {
};
var ancient = /^v?\.0/.test(process.version);
var isFn = function(fn) {
return typeof fn === "function";
};
var isFS = function(stream) {
if (!ancient)
return false;
if (!fs)
return false;
return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close);
};
var isRequest = function(stream) {
return stream.setHeader && isFn(stream.abort);
};
var destroyer = function(stream, reading, writing, callback) {
callback = once(callback);
var closed = false;
stream.on("close", function() {
closed = true;
});
eos(stream, { readable: reading, writable: writing }, function(err) {
if (err)
return callback(err);
closed = true;
callback();
});
var destroyed = false;
return function(err) {
if (closed)
return;
if (destroyed)
return;
destroyed = true;
if (isFS(stream))
return stream.close(noop);
if (isRequest(stream))
return stream.abort();
if (isFn(stream.destroy))
return stream.destroy();
callback(err || new Error("stream was destroyed"));
};
};
var call = function(fn) {
fn();
};
var pipe = function(from, to) {
return from.pipe(to);
};
var pump = function() {
var streams = Array.prototype.slice.call(arguments);
var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop;
if (Array.isArray(streams[0]))
streams = streams[0];
if (streams.length < 2)
throw new Error("pump requires two streams per minimum");
var error;
var destroys = streams.map(function(stream, i) {
var reading = i < streams.length - 1;
var writing = i > 0;
return destroyer(stream, reading, writing, function(err) {
if (!error)
error = err;
if (err)
destroys.forEach(call);
if (reading)
return;
destroys.forEach(call);
callback(error);
});
});
return streams.reduce(pipe);
};
module.exports = pump;
}
});
// ../../node_modules/.pnpm/get-stream@5.2.0/node_modules/get-stream/buffer-stream.js
var require_buffer_stream = __commonJS({
"../../node_modules/.pnpm/get-stream@5.2.0/node_modules/get-stream/buffer-stream.js"(exports, module) {
"use strict";
var { PassThrough: PassThroughStream } = __require("stream");
module.exports = (options) => {
options = { ...options };
const { array } = options;
let { encoding } = options;
const isBuffer = encoding === "buffer";
let objectMode = false;
if (array) {
objectMode = !(encoding || isBuffer);
} else {
encoding = encoding || "utf8";
}
if (isBuffer) {
encoding = null;
}
const stream = new PassThroughStream({ objectMode });
if (encoding) {
stream.setEncoding(encoding);
}
let length = 0;
const chunks = [];
stream.on("data", (chunk) => {
chunks.push(chunk);
if (objectMode) {
length = chunks.length;
} else {
length += chunk.length;
}
});
stream.getBufferedValue = () => {
if (array) {
return chunks;
}
return isBuffer ? Buffer.concat(chunks, length) : chunks.join("");
};
stream.getBufferedLength = () => length;
return stream;
};
}
});
// ../../node_modules/.pnpm/get-stream@5.2.0/node_modules/get-stream/index.js
var require_get_stream = __commonJS({
"../../node_modules/.pnpm/get-stream@5.2.0/node_modules/get-stream/index.js"(exports, module) {
"use strict";
var { constants: BufferConstants } = __require("buffer");
var pump = require_pump();
var bufferStream = require_buffer_stream();
var MaxBufferError = class extends Error {
constructor() {
super("maxBuffer exceeded");
this.name = "MaxBufferError";
}
};
async function getStream(inputStream, options) {
if (!inputStream) {
return Promise.reject(new Error("Expected a stream"));
}
options = {
maxBuffer: Infinity,
...options
};
const { maxBuffer } = options;
let stream;
await new Promise((resolve, reject) => {
const rejectPromise = (error) => {
if (error && stream.getBufferedLength() <= BufferConstants.MAX_LENGTH) {
error.bufferedData = stream.getBufferedValue();
}
reject(error);
};
stream = pump(inputStream, bufferStream(options), (error) => {
if (error) {
rejectPromise(error);
return;
}
resolve();
});
stream.on("data", () => {
if (stream.getBufferedLength() > maxBuffer) {
rejectPromise(new MaxBufferError());
}
});
});
return stream.getBufferedValue();
}
module.exports = getStream;
module.exports.default = getStream;
module.exports.buffer = (stream, options) => getStream(stream, { ...options, encoding: "buffer" });
module.exports.array = (stream, options) => getStream(stream, { ...options, array: true });
module.exports.MaxBufferError = MaxBufferError;
}
});
// ../../node_modules/.pnpm/merge-stream@2.0.0/node_modules/merge-stream/index.js
var require_merge_stream = __commonJS({
"../../node_modules/.pnpm/merge-stream@2.0.0/node_modules/merge-stream/index.js"(exports, module) {
"use strict";
var { PassThrough } = __require("stream");
module.exports = function() {
var sources = [];
var output = new PassThrough({ objectMode: true });
output.setMaxListeners(0);
output.add = add;
output.isEmpty = isEmpty;
output.on("unpipe", remove);
Array.prototype.slice.call(arguments).forEach(add);
return output;
function add(source) {
if (Array.isArray(source)) {
source.forEach(add);
return this;
}
sources.push(source);
source.once("end", remove.bind(null, source));
source.once("error", output.emit.bind(output, "error"));
source.pipe(output, { end: false });
return this;
}
function isEmpty() {
return sources.length == 0;
}
function remove(source) {
sources = sources.filter(function(it) {
return it !== source;
});
if (!sources.length && output.readable) {
output.end();
}
}
};
}
});
// ../../node_modules/.pnpm/execa@3.2.0/node_modules/execa/lib/stream.js
var require_stream = __commonJS({
"../../node_modules/.pnpm/execa@3.2.0/node_modules/execa/lib/stream.js"(exports, module) {
"use strict";
var isStream = require_is_stream();
var getStream = require_get_stream();
var mergeStream = require_merge_stream();
var handleInput = (spawned, input) => {
if (input === void 0 || spawned.stdin === void 0) {
return;
}
if (isStream(input)) {
input.pipe(spawned.stdin);
} else {
spawned.stdin.end(input);
}
};
var makeAllStream = (spawned, { all }) => {
if (!all || !spawned.stdout && !spawned.stderr) {
return;
}
const mixed = mergeStream();
if (spawned.stdout) {
mixed.add(spawned.stdout);
}
if (spawned.stderr) {
mixed.add(spawned.stderr);
}
return mixed;
};
var getBufferedData = async (stream, streamPromise) => {
if (!stream) {
return;
}
stream.destroy();
try {
return await streamPromise;
} catch (error) {
return error.bufferedData;
}
};
var getStreamPromise = (stream, { encoding, buffer, maxBuffer }) => {
if (!stream || !buffer) {
return;
}
if (encoding) {
return getStream(stream, { encoding, maxBuffer });
}
return getStream.buffer(stream, { maxBuffer });
};
var getSpawnedResult = async ({ stdout, stderr, all }, { encoding, buffer, maxBuffer }, processDone) => {
const stdoutPromise = getStreamPromise(stdout, { encoding, buffer, maxBuffer });
const stderrPromise = getStreamPromise(stderr, { encoding, buffer, maxBuffer });
const allPromise = getStreamPromise(all, { encoding, buffer, maxBuffer: maxBuffer * 2 });
try {
return await Promise.all([processDone, stdoutPromise, stderrPromise, allPromise]);
} catch (error) {
return Promise.all([
{ error, signal: error.signal, timedOut: error.timedOut },
getBufferedData(stdout, stdoutPromise),
getBufferedData(stderr, stderrPromise),
getBufferedData(all, allPromise)
]);
}
};
var validateInputSync = ({ input }) => {
if (isStream(input)) {
throw new TypeError("The `input` option cannot be a stream in sync mode");
}
};
module.exports = {
handleInput,
makeAllStream,
getSpawnedResult,
validateInputSync
};
}
});
// ../../node_modules/.pnpm/execa@3.2.0/node_modules/execa/lib/promise.js
var require_promise = __commonJS({
"../../node_modules/.pnpm/execa@3.2.0/node_modules/execa/lib/promise.js"(exports, module) {
"use strict";
var mergePromiseProperty = (spawned, promise, property) => {
const value = typeof promise === "function" ? (...args) => promise()[property](...args) : promise[property].bind(promise);
Object.defineProperty(spawned, property, {
value,
writable: true,
enumerable: false,
configurable: true
});
};
var mergePromise = (spawned, promise) => {
mergePromiseProperty(spawned, promise, "then");
mergePromiseProperty(spawned, promise, "catch");
if (Promise.prototype.finally) {
mergePromiseProperty(spawned, promise, "finally");
}
return spawned;
};
var getSpawnedPromise = (spawned) => {
return new Promise((resolve, reject) => {
spawned.on("exit", (exitCode, signal) => {
resolve({ exitCode, signal });
});
spawned.on("error", (error) => {
reject(error);
});
if (spawned.stdin) {
spawned.stdin.on("error", (error) => {
reject(error);
});
}
});
};
module.exports = {
mergePromise,
getSpawnedPromise
};
}
});
// ../../node_modules/.pnpm/execa@3.2.0/node_modules/execa/lib/command.js
var require_command = __commonJS({
"../../node_modules/.pnpm/execa@3.2.0/node_modules/execa/lib/command.js"(exports, module) {
"use strict";
var SPACES_REGEXP = / +/g;
var joinCommand = (file, args = []) => {
if (!Array.isArray(args)) {
return file;
}
return [file, ...args].join(" ");
};
var handleEscaping = (tokens, token, index) => {
if (index === 0) {
return [token];
}
const previousToken = tokens[tokens.length - 1];
if (previousToken.endsWith("\\")) {
return [...tokens.slice(0, -1), `${previousToken.slice(0, -1)} ${token}`];
}
return [...tokens, token];
};
var parseCommand = (command) => {
return command.trim().split(SPACES_REGEXP).reduce(handleEscaping, []);
};
module.exports = {
joinCommand,
parseCommand
};
}
});
// ../../node_modules/.pnpm/execa@3.2.0/node_modules/execa/index.js
var require_execa = __commonJS({
"../../node_modules/.pnpm/execa@3.2.0/node_modules/execa/index.js"(exports, module) {
"use strict";
var path = __require("path");
var childProcess = __require("child_process");
var crossSpawn = require_cross_spawn();
var stripFinalNewline = require_strip_final_newline();
var npmRunPath = require_npm_run_path();
var onetime = require_onetime();
var makeError = require_error();
var normalizeStdio = require_stdio();
var { spawnedKill, spawnedCancel, setupTimeout, setExitHandler } = require_kill();
var { handleInput, getSpawnedResult, makeAllStream, validateInputSync } = require_stream();
var { mergePromise, getSpawnedPromise } = require_promise();
var { joinCommand, parseCommand } = require_command();
var DEFAULT_MAX_BUFFER = 1e3 * 1e3 * 100;
var getEnv = ({ env: envOption, extendEnv, preferLocal, localDir, execPath }) => {
const env = extendEnv ? { ...process.env, ...envOption } : envOption;
if (preferLocal) {
return npmRunPath.env({ env, cwd: localDir, execPath });
}
return env;
};
var handleArgs = (file, args, options = {}) => {
const parsed = crossSpawn._parse(file, args, options);
file = parsed.command;
args = parsed.args;
options = parsed.options;
options = {
maxBuffer: DEFAULT_MAX_BUFFER,
buffer: true,
stripFinalNewline: true,
extendEnv: true,
preferLocal: false,
localDir: options.cwd || process.cwd(),
execPath: process.execPath,
encoding: "utf8",
reject: true,
cleanup: true,
all: false,
...options,
windowsHide: true
};
options.env = getEnv(options);
options.stdio = normalizeStdio(options);
if (process.platform === "win32" && path.basename(file, ".exe") === "cmd") {
args.unshift("/q");
}
return { file, args, options, parsed };
};
var handleOutput = (options, value, error) => {
if (typeof value !== "string" && !Buffer.isBuffer(value)) {
return error === void 0 ? void 0 : "";
}
if (options.stripFinalNewline) {
return stripFinalNewline(value);
}
return value;
};
var execa = (file, args, options) => {
const parsed = handleArgs(file, args, options);
const command = joinCommand(file, args);
let spawned;
try {
spawned = childProcess.spawn(parsed.file, parsed.args, parsed.options);
} catch (error) {
const dummySpawned = new childProcess.ChildProcess();
const errorPromise = Promise.reject(makeError({
error,
stdout: "",
stderr: "",
all: "",
command,
parsed,
timedOut: false,
isCanceled: false,
killed: false
}));
return mergePromise(dummySpawned, errorPromise);
}
const spawnedPromise = getSpawnedPromise(spawned);
const timedPromise = setupTimeout(spawned, parsed.options, spawnedPromise);
const processDone = setExitHandler(spawned, parsed.options, timedPromise);
const context = { isCanceled: false };
spawned.kill = spawnedKill.bind(null, spawned.kill.bind(spawned));
spawned.cancel = spawnedCancel.bind(null, spawned, context);
const handlePromise = async () => {
const [{ error, exitCode, signal, timedOut }, stdoutResult, stderrResult, allResult] = await getSpawnedResult(spawned, parsed.options, processDone);
const stdout = handleOutput(parsed.options, stdoutResult);
const stderr = handleOutput(parsed.options, stderrResult);
const all = handleOutput(parsed.options, allResult);
if (error || exitCode !== 0 || signal !== null) {
const returnedError = makeError({
error,
exitCode,
signal,
stdout,
stderr,
all,
command,
parsed,
timedOut,
isCanceled: context.isCanceled,
killed: spawned.killed
});
if (!parsed.options.reject) {
return returnedError;
}
throw returnedError;
}
return {
command,
exitCode: 0,
stdout,
stderr,
all,
failed: false,
timedOut: false,
isCanceled: false,
killed: false
};
};
const handlePromiseOnce = onetime(handlePromise);
crossSpawn._enoent.hookChildProcess(spawned, parsed.parsed);
handleInput(spawned, parsed.options.input);
spawned.all = makeAllStream(spawned, parsed.options);
return mergePromise(spawned, handlePromiseOnce);
};
module.exports = execa;
module.exports.sync = (file, args, options) => {
const parsed = handleArgs(file, args, options);
const command = joinCommand(file, args);
validateInputSync(parsed.options);
let result;
try {
result = childProcess.spawnSync(parsed.file, parsed.args, parsed.options);
} catch (error) {
throw makeError({
error,
stdout: "",
stderr: "",
all: "",
command,
parsed,
timedOut: false,
isCanceled: false,
killed: false
});
}
const stdout = handleOutput(parsed.options, result.stdout, result.error);
const stderr = handleOutput(parsed.options, result.stderr, result.error);
if (result.error || result.status !== 0 || result.signal !== null) {
const error = makeError({
stdout,
stderr,
error: result.error,
signal: result.signal,
exitCode: result.status,
command,
parsed,
timedOut: result.error && result.error.code === "ETIMEDOUT",
isCanceled: false,
killed: result.signal !== null
});
if (!parsed.options.reject) {
return error;
}
throw error;
}
return {
command,
exitCode: 0,
stdout,
stderr,
failed: false,
timedOut: false,
isCanceled: false,
killed: false
};
};
module.exports.command = (command, options) => {
const [file, ...args] = parseCommand(command);
return execa(file, args, options);
};
module.exports.commandSync = (command, options) => {
const [file, ...args] = parseCommand(command);
return execa.sync(file, args, options);
};
module.exports.node = (scriptPath, args, options = {}) => {
if (args && !Array.isArray(args) && typeof args === "object") {
options = args;
args = [];
}
const stdio = normalizeStdio.node(options);
const { nodePath = process.execPath, nodeOptions = process.execArgv } = options;
return execa(
nodePath,
[
...nodeOptions,
scriptPath,
...Array.isArray(args) ? args : []
],
{
...options,
stdin: void 0,
stdout: void 0,
stderr: void 0,
stdio,
shell: false
}
);
};
}
});
export {
require_isexe,
require_execa
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
getLocalPathConfig
} from "./chunk-LLUXSKCT.js";
import {
compileVercelConfig
} from "./chunk-RR4BD6FR.js";
import {
VERCEL_DIR_PROJECT,
VERCEL_DIR_README,
checkExistsAndConnect,
createProject,
detectProjects,
getLinkedProject,
getProjectByNameOrId,
getVercelDirectory,
humanizePath,
isDirectory,
linkFolderToProject,
parseGitConfig,
pluckRemoteUrls,
readJSONFile,
require_frameworks,
require_lib,
require_slugify,
selectAndParseRemoteUrl,
selectOrg,
tryDetectServices
} from "./chunk-BMTLRU2D.js";
import {
table
} from "./chunk-LWBSOTJP.js";
import {
CantParseJSONFile,
ProjectNotFound,
isAPIError,
printError
} from "./chunk-ZLCMHY2G.js";
import {
output_manager_default
} from "./chunk-FDJURQMQ.js";
import {
require_source
} from "./chunk-S7KYDPEM.js";
import {
__toESM
} from "./chunk-TZ2YI2VH.js";
// src/util/validate-paths.ts
var import_fs_extra = __toESM(require_lib(), 1);
var import_chalk = __toESM(require_source(), 1);
import { homedir } from "os";
async function validateRootDirectory(cwd, path2, errorSuffix = "") {
const pathStat = await (0, import_fs_extra.lstat)(path2).catch(() => null);
const suffix = errorSuffix ? ` ${errorSuffix}` : "";
if (!pathStat) {
output_manager_default.error(
`The provided path ${import_chalk.default.cyan(
`\u201C${humanizePath(path2)}\u201D`
)} does not exist.${suffix}`
);
return false;
}
if (!pathStat.isDirectory()) {
output_manager_default.error(
`The provided path ${import_chalk.default.cyan(
`\u201C${humanizePath(path2)}\u201D`
)} is a file, but expected a directory.${suffix}`
);
return false;
}
if (!path2.startsWith(cwd)) {
output_manager_default.error(
`The provided path ${import_chalk.default.cyan(
`\u201C${humanizePath(path2)}\u201D`
)} is outside of the project.${suffix}`
);
return false;
}
return true;
}
async function validatePaths(client, paths) {
if (paths.length > 1) {
output_manager_default.error(`Can't deploy more than one path.`);
return { valid: false, exitCode: 1 };
}
const path2 = paths[0];
const pathStat = await (0, import_fs_extra.lstat)(path2).catch(() => null);
if (!pathStat) {
output_manager_default.error(`Could not find ${import_chalk.default.cyan(`\u201C${humanizePath(path2)}\u201D`)}`);
return { valid: false, exitCode: 1 };
}
if (!pathStat.isDirectory()) {
output_manager_default.prettyError({
message: "Support for single file deployments has been removed.",
link: "https://vercel.link/no-single-file-deployments"
});
return { valid: false, exitCode: 1 };
}
if (path2 === homedir()) {
const shouldDeployHomeDirectory = await client.input.confirm(
`You are deploying your home directory. Do you want to continue?`,
false
);
if (!shouldDeployHomeDirectory) {
output_manager_default.print(`Canceled
`);
return { valid: false, exitCode: 0 };
}
}
return { valid: true, path: path2 };
}
// src/util/config/read-config.ts
async function readConfig(dir) {
let pkgFilePath;
try {
const compileResult = await compileVercelConfig(dir);
pkgFilePath = compileResult.configPath || getLocalPathConfig(dir);
} catch (err) {
if (err instanceof Error) {
return err;
}
throw err;
}
const result = await readJSONFile(pkgFilePath);
if (result instanceof CantParseJSONFile) {
return result;
}
if (result) {
return result;
}
return null;
}
// src/util/input/display-services.ts
var import_frameworks = __toESM(require_frameworks(), 1);
var chalk2 = require_source();
var frameworksBySlug = new Map(import_frameworks.frameworkList.map((f) => [f.slug, f]));
var frameworkColors = {
// JavaScript/TypeScript frameworks
nextjs: chalk2.white,
vite: chalk2.magenta,
nuxtjs: chalk2.green,
remix: chalk2.cyan,
astro: chalk2.magenta,
gatsby: chalk2.magenta,
svelte: chalk2.red,
sveltekit: chalk2.red,
solidstart: chalk2.blue,
angular: chalk2.red,
vue: chalk2.green,
ember: chalk2.red,
preact: chalk2.magenta,
// Python frameworks
fastapi: chalk2.green,
flask: chalk2.cyan,
// Node frameworks
express: chalk2.yellow,
nest: chalk2.red,
hono: chalk2.yellowBright
};
var runtimeColors = {
node: chalk2.green,
python: chalk2.blue,
go: chalk2.cyan,
ruby: chalk2.red,
rust: chalk2.yellowBright
};
function getFrameworkName(slug) {
if (!slug)
return void 0;
return frameworksBySlug.get(slug)?.name;
}
function formatRoutePrefix(routePrefix) {
if (routePrefix === "/") {
return "/";
}
const normalized = routePrefix.startsWith("/") ? routePrefix : `/${routePrefix}`;
return `${normalized}/*`;
}
function getServiceDescriptionInfo(service) {
const frameworkName = getFrameworkName(service.framework);
if (frameworkName && service.framework) {
const colorFn = frameworkColors[service.framework] || chalk2.cyan;
return { label: frameworkName, colorFn };
} else if (service.runtime) {
const normalizedRuntime = service.runtime.toLowerCase().replace(/@.*$/, "");
const colorFn = runtimeColors[normalizedRuntime] || chalk2.yellow;
return { label: service.runtime, colorFn };
} else if (service.builder?.use) {
return { label: service.builder.use, colorFn: chalk2.magenta };
}
return { label: "unknown", colorFn: chalk2.dim };
}
function getServiceTarget(service) {
switch (service.type) {
case "cron":
return `schedule: ${service.schedule ?? "none"}`;
case "worker":
return `topic: ${service.topic ?? "none"}`;
default:
return service.routePrefix ? formatRoutePrefix(service.routePrefix) : "no route";
}
}
function displayDetectedServices(services) {
output_manager_default.print(`Multiple services detected. Project Settings:
`);
const rows = services.map((service) => {
const descInfo = getServiceDescriptionInfo(service);
const target = getServiceTarget(service);
return [
`\u2022 ${service.name}`,
descInfo.colorFn(`[${descInfo.label}]`),
chalk2.dim("\u2192"),
target
];
});
const tableOutput = table(rows, { align: ["l", "l", "l", "l"], hsep: 2 });
output_manager_default.print(`${tableOutput}
`);
}
function displayServicesConfigNote() {
output_manager_default.print(
`
${chalk2.dim("Services (experimental) are configured via vercel.json.")}
`
);
}
function displayServiceErrors(errors) {
for (const error of errors) {
output_manager_default.warn(error.message);
}
}
// src/util/link/setup-and-link.ts
var import_chalk6 = __toESM(require_source(), 1);
var import_fs_extra2 = __toESM(require_lib(), 1);
import { join, basename } from "path";
// src/util/input/input-project.ts
var import_chalk2 = __toESM(require_source(), 1);
var import_slugify = __toESM(require_slugify(), 1);
async function inputProject(client, org, detectedProjectName, autoConfirm = false) {
const slugifiedName = (0, import_slugify.default)(detectedProjectName);
let detectedProject = null;
output_manager_default.spinner("Searching for existing projects\u2026", 1e3);
const [project, slugifiedProject] = await Promise.all([
getProjectByNameOrId(client, detectedProjectName, org.id),
slugifiedName !== detectedProjectName ? getProjectByNameOrId(client, slugifiedName, org.id) : null
]);
detectedProject = !(project instanceof ProjectNotFound) ? project : !(slugifiedProject instanceof ProjectNotFound) ? slugifiedProject : null;
if (detectedProject && !detectedProject.id) {
throw new Error(`Detected linked project does not have "id".`);
}
output_manager_default.stopSpinner();
if (autoConfirm) {
return detectedProject || detectedProjectName;
}
if (client.nonInteractive) {
const err = new Error("Confirmation required");
err.code = "HEADLESS";
throw err;
}
let shouldLinkProject;
if (!detectedProject) {
shouldLinkProject = await client.input.confirm(
`Link to existing project?`,
false
);
} else {
if (await client.input.confirm(
`Found project ${import_chalk2.default.cyan(
`\u201C${org.slug}/${detectedProject.name}\u201D`
)}. Link to it?`,
true
)) {
return detectedProject;
}
shouldLinkProject = await client.input.confirm(
`Link to different existing project?`,
true
);
}
if (shouldLinkProject) {
const firstPage = await client.fetch(`/v9/projects?limit=100`, { accountId: org.id });
const projects = firstPage.projects;
const hasMoreProjects = firstPage.pagination.next !== null;
if (projects.length === 0) {
output_manager_default.log(
`No existing projects found under ${import_chalk2.default.bold(org.slug)}. Creating new project.`
);
} else if (hasMoreProjects) {
let toLink;
await client.input.text({
message: "What's the name of your existing project?",
validate: async (val) => {
if (!val) {
return "Project name cannot be empty";
}
const project2 = await getProjectByNameOrId(client, val, org.id);
if (project2 instanceof ProjectNotFound) {
return "Project not found";
}
toLink = project2;
return true;
}
});
return toLink;
} else {
const choices = projects.sort((a, b) => b.updatedAt - a.updatedAt).map((project2) => ({
name: project2.name,
value: project2
}));
const toLink = await client.input.select({
message: "Which existing project do you want to link?",
choices
});
return toLink;
}
}
return await client.input.text({
message: `What\u2019s your project\u2019s name?`,
default: !detectedProject ? slugifiedName : void 0,
validate: async (val) => {
if (!val) {
return "Project name cannot be empty";
}
const project2 = await getProjectByNameOrId(client, val, org.id);
if (!(project2 instanceof ProjectNotFound)) {
return "Project already exists";
}
return true;
}
});
}
// src/util/input/input-root-directory.ts
var import_chalk3 = __toESM(require_source(), 1);
import path from "path";
async function inputRootDirectory(client, cwd, autoConfirm = false) {
if (autoConfirm) {
return null;
}
while (true) {
const rootDirectory = await client.input.text({
message: `In which directory is your code located?`,
transformer: (input) => {
return `${import_chalk3.default.dim(`./`)}${input}`;
}
});
if (!rootDirectory) {
return null;
}
const normal = path.normalize(rootDirectory);
if (normal === "." || normal === "./") {
return null;
}
const fullPath = path.join(cwd, normal);
if (await validateRootDirectory(
cwd,
fullPath,
"Please choose a different one."
) === false) {
continue;
}
return normal;
}
}
// src/util/input/edit-project-settings.ts
var import_chalk4 = __toESM(require_source(), 1);
var import_frameworks2 = __toESM(require_frameworks(), 1);
// src/util/is-setting-value.ts
function isSettingValue(setting) {
return setting && typeof setting.value === "string";
}
// src/util/input/edit-project-settings.ts
var settingMap = {
buildCommand: "Build Command",
devCommand: "Development Command",
commandForIgnoringBuildStep: "Ignore Command",
installCommand: "Install Command",
outputDirectory: "Output Directory",
framework: "Framework"
};
var settingKeys = Object.keys(settingMap).sort();
async function editProjectSettings(client, projectSettings, framework, autoConfirm, localConfigurationOverrides) {
const settings = Object.assign(
{
buildCommand: null,
devCommand: null,
framework: null,
commandForIgnoringBuildStep: null,
installCommand: null,
outputDirectory: null
},
projectSettings
);
const hasLocalConfigurationOverrides = localConfigurationOverrides && Object.values(localConfigurationOverrides ?? {}).some(Boolean);
if (hasLocalConfigurationOverrides) {
for (const setting of settingKeys) {
const localConfigValue = localConfigurationOverrides[setting];
if (localConfigValue)
settings[setting] = localConfigValue;
}
output_manager_default.print("Local settings detected in vercel.json:\n");
for (const setting of settingKeys) {
const override = localConfigurationOverrides[setting];
if (override) {
output_manager_default.print(
`${import_chalk4.default.dim(
`- ${import_chalk4.default.bold(`${settingMap[setting]}:`)} ${override}`
)}
`
);
}
}
if (localConfigurationOverrides.framework) {
const overrideFramework = import_frameworks2.frameworkList.find(
(f) => f.slug === localConfigurationOverrides.framework
);
if (overrideFramework) {
framework = overrideFramework;
output_manager_default.print(
`Merging default Project Settings for ${framework.name}. Previously listed overrides are prioritized.
`
);
}
}
}
if (!framework) {
settings.framework = null;
return settings;
}
const styledFramework = (frameworkName) => {
const frameworkStyle = {
text: frameworkName,
color: import_chalk4.default.blue
};
if (frameworkName === "Hono") {
frameworkStyle.text = "\u{1F525} Hono";
frameworkStyle.color = import_chalk4.default.hex("#FFA500");
}
return import_chalk4.default.bold(frameworkStyle.color(frameworkStyle.text));
};
output_manager_default.log(
!framework.slug ? `No framework detected. Default Project Settings:
` : `Auto-detected Project Settings for ${styledFramework(framework.name)}
`
);
settings.framework = framework.slug;
if (!framework.slug) {
for (const setting of settingKeys) {
if (setting === "framework" || setting === "commandForIgnoringBuildStep") {
continue;
}
const defaultSetting = framework.settings[setting];
const override = localConfigurationOverrides?.[setting];
if (!override && defaultSetting) {
output_manager_default.print(
`${import_chalk4.default.dim(
`- ${import_chalk4.default.bold(`${settingMap[setting]}:`)} ${isSettingValue(defaultSetting) ? defaultSetting.value : import_chalk4.default.italic(`${defaultSetting.placeholder}`)}`
)}
`
);
}
}
}
if (autoConfirm || !await client.input.confirm("Want to modify these settings?", false)) {
return settings;
}
const choices = settingKeys.reduce(
(acc, setting) => {
const skip = setting === "framework" || setting === "commandForIgnoringBuildStep" || setting === "installCommand" || localConfigurationOverrides?.[setting];
if (skip)
return acc;
return [...acc, { name: settingMap[setting], value: setting }];
},
[]
);
const settingFields = await client.input.checkbox({
message: "Which settings would you like to overwrite (select multiple)?",
choices
});
for (const setting of settingFields) {
const field = settingMap[setting];
settings[setting] = await client.input.text({
message: `What's your ${import_chalk4.default.bold(field)}?`
});
}
return settings;
}
// src/util/link/setup-and-link.ts
var import_frameworks3 = __toESM(require_frameworks(), 1);
// src/util/input/vercel-auth.ts
var import_chalk5 = __toESM(require_source(), 1);
var DEFAULT_VERCEL_AUTH_SETTING = "standard";
var OPTIONS = {
message: `What setting do you want to use for Vercel Authentication?`,
default: DEFAULT_VERCEL_AUTH_SETTING,
choices: [
{
description: "Standard Protection (recommended)",
name: "standard",
value: "standard"
},
{
description: "No Protection (all deployments will be public)",
name: "none",
value: "none"
}
]
};
async function vercelAuth(client, {
autoConfirm = false
}) {
if (autoConfirm || await client.input.confirm(
`Want to use the default Deployment Protection settings? ${import_chalk5.default.dim(`(Vercel Authentication: Standard Protection)`)}`,
true
)) {
return DEFAULT_VERCEL_AUTH_SETTING;
}
const vercelAuth2 = await client.input.select(OPTIONS);
return vercelAuth2;
}
// src/util/link/setup-and-link.ts
async function setupAndLink(client, path2, {
autoConfirm = false,
forceDelete = false,
link,
successEmoji = "link",
setupMsg = "Set up",
projectName = basename(path2),
nonInteractive = false,
pullEnv = true,
v0
}) {
const { config } = client;
if (!isDirectory(path2)) {
output_manager_default.error(`Expected directory but found file: ${path2}`);
return { status: "error", exitCode: 1, reason: "PATH_IS_FILE" };
}
if (!link) {
link = await getLinkedProject(client, path2);
}
const isTTY = client.stdin.isTTY;
let rootDirectory = null;
let newProjectName;
let org;
if (!forceDelete && link.status === "linked") {
return link;
}
if (forceDelete) {
const vercelDir = getVercelDirectory(path2);
(0, import_fs_extra2.remove)(join(vercelDir, VERCEL_DIR_README));
(0, import_fs_extra2.remove)(join(vercelDir, VERCEL_DIR_PROJECT));
}
if (!isTTY && !autoConfirm && !nonInteractive) {
return { status: "error", exitCode: 1, reason: "HEADLESS" };
}
const shouldStartSetup = autoConfirm || nonInteractive || await client.input.confirm(
`${setupMsg} ${import_chalk6.default.cyan(`\u201C${humanizePath(path2)}\u201D`)}?`,
true
);
if (!shouldStartSetup) {
output_manager_default.print(`Canceled. Project not set up.
`);
return { status: "not_linked", org: null, project: null };
}
try {
org = await selectOrg(
client,
"Which scope should contain your project?",
autoConfirm
);
} catch (err) {
if (isAPIError(err)) {
if (err.code === "NOT_AUTHORIZED") {
output_manager_default.prettyError(err);
return { status: "error", exitCode: 1, reason: "NOT_AUTHORIZED" };
}
if (err.code === "TEAM_DELETED") {
output_manager_default.prettyError(err);
return { status: "error", exitCode: 1, reason: "TEAM_DELETED" };
}
}
throw err;
}
let projectOrNewProjectName;
try {
projectOrNewProjectName = await inputProject(
client,
org,
projectName,
autoConfirm
);
} catch (err) {
if (err instanceof Error && err.code === "HEADLESS") {
return { status: "error", exitCode: 1, reason: "HEADLESS" };
}
throw err;
}
if (typeof projectOrNewProjectName === "string") {
newProjectName = projectOrNewProjectName;
rootDirectory = await inputRootDirectory(client, path2, autoConfirm);
} else {
const project = projectOrNewProjectName;
await linkFolderToProject(
client,
path2,
{
projectId: project.id,
orgId: org.id
},
project.name,
org.slug,
successEmoji,
autoConfirm,
pullEnv
);
return { status: "linked", org, project };
}
if (rootDirectory && !await validateRootDirectory(path2, join(path2, rootDirectory))) {
return { status: "error", exitCode: 1, reason: "INVALID_ROOT_DIRECTORY" };
}
config.currentTeam = org.type === "team" ? org.id : void 0;
const pathWithRootDirectory = rootDirectory ? join(path2, rootDirectory) : path2;
const localConfig = await readConfig(pathWithRootDirectory);
if (localConfig instanceof CantParseJSONFile) {
output_manager_default.prettyError(localConfig);
return { status: "error", exitCode: 1 };
}
const isZeroConfig = !localConfig || !localConfig.builds || localConfig.builds.length === 0;
const servicesResult = await tryDetectServices(pathWithRootDirectory);
try {
let settings = {};
if (servicesResult) {
displayDetectedServices(servicesResult.services);
if (servicesResult.errors.length > 0) {
displayServiceErrors(servicesResult.errors);
}
displayServicesConfigNote();
settings.framework = "services";
} else if (isZeroConfig) {
const localConfigurationOverrides = {
buildCommand: localConfig?.buildCommand,
devCommand: localConfig?.devCommand,
framework: localConfig?.framework,
commandForIgnoringBuildStep: localConfig?.ignoreCommand,
installCommand: localConfig?.installCommand,
outputDirectory: localConfig?.outputDirectory
};
const detectedProjectsForWorkspace = await detectProjects(
pathWithRootDirectory
);
const detectedProjects = detectedProjectsForWorkspace.get("") || [];
const framework = detectedProjects[0] ?? import_frameworks3.frameworkList.find((f) => f.slug === null);
settings = await editProjectSettings(
client,
{},
framework,
autoConfirm,
localConfigurationOverrides
);
}
let changeAdditionalSettings = false;
if (!autoConfirm) {
changeAdditionalSettings = await client.input.confirm(
"Do you want to change additional project settings?",
false
);
}
let vercelAuthSetting = DEFAULT_VERCEL_AUTH_SETTING;
if (changeAdditionalSettings) {
vercelAuthSetting = await vercelAuth(client, {
autoConfirm
});
}
if (rootDirectory) {
settings.rootDirectory = rootDirectory;
}
const project = await createProject(client, {
...settings,
name: newProjectName,
vercelAuth: vercelAuthSetting,
v0
});
await linkFolderToProject(
client,
path2,
{
projectId: project.id,
orgId: org.id
},
project.name,
org.slug,
successEmoji,
autoConfirm,
false
// don't prompt to pull env for newly created projects
);
await connectGitRepository(client, path2, project, autoConfirm, org);
return { status: "linked", org, project };
} catch (err) {
if (isAPIError(err) && err.code === "too_many_projects") {
output_manager_default.prettyError(err);
return { status: "error", exitCode: 1, reason: "TOO_MANY_PROJECTS" };
}
if (err instanceof Error && err.code === "HEADLESS") {
return { status: "error", exitCode: 1, reason: "HEADLESS" };
}
printError(err);
return { status: "error", exitCode: 1 };
}
}
async function connectGitRepository(client, path2, project, autoConfirm, org) {
try {
const gitConfig = await parseGitConfig(join(path2, ".git/config"));
if (!gitConfig) {
return;
}
const remoteUrls = pluckRemoteUrls(gitConfig);
if (!remoteUrls || Object.keys(remoteUrls).length === 0) {
return;
}
const shouldConnect = autoConfirm || await client.input.confirm(
`Detected a repository. Connect it to this project?`,
true
);
if (!shouldConnect) {
return;
}
const repoInfo = await selectAndParseRemoteUrl(client, remoteUrls);
if (!repoInfo) {
return;
}
await checkExistsAndConnect({
client,
confirm: autoConfirm,
gitProviderLink: project.link,
org,
gitOrg: repoInfo.org,
project,
// Type assertion since we only need the id
provider: repoInfo.provider,
repo: repoInfo.repo,
repoPath: `${repoInfo.org}/${repoInfo.repo}`
});
} catch (error) {
output_manager_default.debug(`Failed to connect git repository: ${error}`);
}
}
export {
validateRootDirectory,
validatePaths,
readConfig,
displayDetectedServices,
setupAndLink
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
require_lib
} from "./chunk-BMTLRU2D.js";
import {
packageName
} from "./chunk-ZLCMHY2G.js";
import {
__toESM
} from "./chunk-TZ2YI2VH.js";
// src/util/get-update-command.ts
var import_fs_extra = __toESM(require_lib(), 1);
import { sep, dirname, join, resolve } from "path";
import { scanParentDirs } from "@vercel/build-utils";
async function getConfigPrefix() {
const paths = [
process.env.npm_config_userconfig || process.env.NPM_CONFIG_USERCONFIG,
join(process.env.HOME || "/", ".npmrc"),
process.env.npm_config_globalconfig || process.env.NPM_CONFIG_GLOBALCONFIG
].filter(Boolean);
for (const configPath of paths) {
if (!configPath) {
continue;
}
const content = await (0, import_fs_extra.readFile)(configPath).then((buffer) => buffer.toString()).catch(() => null);
if (content) {
const [prefix] = content.split("\n").map((line) => line && line.trim()).filter((line) => line && line.startsWith("prefix")).map((line) => line.slice(line.indexOf("=") + 1).trim());
if (prefix) {
return prefix;
}
}
}
return null;
}
async function isGlobal() {
try {
if (dirname(process.argv[0]) === dirname(process.argv[1])) {
return true;
}
const isWindows = process.platform === "win32";
const defaultPath = isWindows ? process.env.APPDATA : "/usr/local/lib";
const installPath = await (0, import_fs_extra.realpath)(resolve(__dirname));
if (installPath.includes(["", "yarn", "global", "node_modules", ""].join(sep))) {
return true;
}
if (installPath.includes(["", "pnpm", "global", ""].join(sep))) {
return true;
}
if (installPath.includes(["", "fnm", "node-versions", ""].join(sep))) {
return true;
}
const prefixPath = process.env.PREFIX || process.env.npm_config_prefix || process.env.NPM_CONFIG_PREFIX || await getConfigPrefix() || defaultPath;
if (!prefixPath) {
return true;
}
return installPath.startsWith(await (0, import_fs_extra.realpath)(prefixPath));
} catch (_) {
return true;
}
}
async function getUpdateCommand() {
const pkgAndVersion = `${packageName}@latest`;
const entrypoint = await (0, import_fs_extra.realpath)(process.argv[1]);
let { cliType, lockfilePath } = await scanParentDirs(
dirname(dirname(entrypoint))
);
if (!lockfilePath) {
cliType = "npm";
}
const yarn = cliType === "yarn";
let install = yarn ? "add" : "i";
if (await isGlobal()) {
if (yarn) {
install = "global add";
} else {
install = "i -g";
}
}
return `${cliType} ${install} ${pkgAndVersion}`;
}
export {
isGlobal,
getUpdateCommand
};

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
STANDARD_ENVIRONMENTS
} from "./chunk-BMTLRU2D.js";
import {
getCommandName,
require_lib
} from "./chunk-ZLCMHY2G.js";
import {
output_manager_default
} from "./chunk-FDJURQMQ.js";
import {
require_source
} from "./chunk-S7KYDPEM.js";
import {
__toESM
} from "./chunk-TZ2YI2VH.js";
// src/util/target/format-environment.ts
var import_chalk = __toESM(require_source(), 1);
var import_title = __toESM(require_lib(), 1);
function formatEnvironment(orgSlug, projectSlug, environment) {
const projectUrl = `https://vercel.com/${orgSlug}/${projectSlug}`;
const boldName = import_chalk.default.bold(
STANDARD_ENVIRONMENTS.includes(environment.slug) ? (0, import_title.default)(environment.slug) : environment.slug
);
return output_manager_default.link(
boldName,
`${projectUrl}/settings/environments/${environment.slug}`,
{ fallback: () => boldName, color: false }
);
}
// src/util/validate-ls-args.ts
var import_chalk2 = __toESM(require_source(), 1);
function validateLsArgs(options) {
const { commandName, args, maxArgs = 0, exitCode = 1, usageString } = options;
if (args.length > maxArgs) {
const usage = usageString || getCommandName(commandName);
output_manager_default.error(`Invalid number of arguments. Usage: ${import_chalk2.default.cyan(usage)}`);
return exitCode;
}
return 0;
}
export {
formatEnvironment,
validateLsArgs
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
setupAndLink
} from "./chunk-6CREWAFU.js";
import {
buildCommandWithYes,
getLinkedProject,
outputActionRequired,
param,
resolveProjectCwd
} from "./chunk-BMTLRU2D.js";
import {
getCommandName,
getCommandNamePlain
} from "./chunk-ZLCMHY2G.js";
import {
output_manager_default
} from "./chunk-FDJURQMQ.js";
// src/util/link/ensure-link.ts
async function ensureLink(commandName, client, cwd, opts = {}) {
cwd = await resolveProjectCwd(cwd);
let { link } = opts;
const nonInteractive = opts.nonInteractive ?? client.nonInteractive ?? false;
opts.nonInteractive = nonInteractive;
if (!link) {
if (opts.forceDelete) {
link = { status: "not_linked", org: null, project: null };
} else {
link = await getLinkedProject(client, cwd);
}
opts.link = link;
}
if (link.status === "linked" && opts.forceDelete || link.status === "not_linked") {
link = await setupAndLink(client, cwd, opts);
if (link.status === "not_linked") {
return 0;
}
}
if (link.status === "error") {
if (link.reason === "HEADLESS") {
if (nonInteractive) {
outputActionRequired(
client,
{
status: "action_required",
reason: "confirmation_required",
message: `Command ${getCommandNamePlain(commandName)} requires confirmation. Use option --yes to confirm.`,
next: [
{
command: buildCommandWithYes(client.argv),
when: "Confirm and run"
}
]
},
link.exitCode
);
} else {
output_manager_default.error(
`Command ${getCommandName(
commandName
)} requires confirmation. Use option ${param("--yes")} to confirm.`
);
}
}
if (nonInteractive) {
process.exit(link.exitCode);
}
return link.exitCode;
}
return link;
}
export {
ensureLink
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
require_once
} from "./chunk-BMTLRU2D.js";
import {
__commonJS
} from "./chunk-TZ2YI2VH.js";
// ../../node_modules/.pnpm/end-of-stream@1.4.1/node_modules/end-of-stream/index.js
var require_end_of_stream = __commonJS({
"../../node_modules/.pnpm/end-of-stream@1.4.1/node_modules/end-of-stream/index.js"(exports, module) {
var once = require_once();
var noop = function() {
};
var isRequest = function(stream) {
return stream.setHeader && typeof stream.abort === "function";
};
var isChildProcess = function(stream) {
return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3;
};
var eos = function(stream, opts, callback) {
if (typeof opts === "function")
return eos(stream, null, opts);
if (!opts)
opts = {};
callback = once(callback || noop);
var ws = stream._writableState;
var rs = stream._readableState;
var readable = opts.readable || opts.readable !== false && stream.readable;
var writable = opts.writable || opts.writable !== false && stream.writable;
var onlegacyfinish = function() {
if (!stream.writable)
onfinish();
};
var onfinish = function() {
writable = false;
if (!readable)
callback.call(stream);
};
var onend = function() {
readable = false;
if (!writable)
callback.call(stream);
};
var onexit = function(exitCode) {
callback.call(stream, exitCode ? new Error("exited with error code: " + exitCode) : null);
};
var onerror = function(err) {
callback.call(stream, err);
};
var onclose = function() {
if (readable && !(rs && rs.ended))
return callback.call(stream, new Error("premature close"));
if (writable && !(ws && ws.ended))
return callback.call(stream, new Error("premature close"));
};
var onrequest = function() {
stream.req.on("finish", onfinish);
};
if (isRequest(stream)) {
stream.on("complete", onfinish);
stream.on("abort", onclose);
if (stream.req)
onrequest();
else
stream.on("request", onrequest);
} else if (writable && !ws) {
stream.on("end", onlegacyfinish);
stream.on("close", onlegacyfinish);
}
if (isChildProcess(stream))
stream.on("exit", onexit);
stream.on("end", onend);
stream.on("finish", onfinish);
if (opts.error !== false)
stream.on("error", onerror);
stream.on("close", onclose);
return function() {
stream.removeListener("complete", onfinish);
stream.removeListener("abort", onclose);
stream.removeListener("request", onrequest);
if (stream.req)
stream.req.removeListener("finish", onfinish);
stream.removeListener("end", onlegacyfinish);
stream.removeListener("close", onlegacyfinish);
stream.removeListener("finish", onfinish);
stream.removeListener("exit", onexit);
stream.removeListener("end", onend);
stream.removeListener("error", onerror);
stream.removeListener("close", onclose);
};
};
module.exports = eos;
}
});
export {
require_end_of_stream
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
VERCEL_DIR
} from "./chunk-BMTLRU2D.js";
import {
ConflictingConfigFiles,
InvalidLocalConfig,
getArgs
} from "./chunk-ZLCMHY2G.js";
// src/util/config/local-path.ts
import path from "path";
import { existsSync } from "fs";
function getLocalPathConfig(prefix) {
const argv = getArgs(process.argv.slice(2), {}, { permissive: true });
const customPath = argv["--local-config"];
if (customPath) {
if (typeof customPath !== "string") {
throw new InvalidLocalConfig(customPath);
}
return path.resolve(prefix, customPath);
}
const vercelConfigPath = path.join(prefix, "vercel.json");
const nowConfigPath = path.join(prefix, "now.json");
const vercelConfigExists = existsSync(vercelConfigPath);
const nowConfigExists = existsSync(nowConfigPath);
if (nowConfigExists && vercelConfigExists) {
throw new ConflictingConfigFiles([vercelConfigPath, nowConfigPath]);
}
const compiledConfigPath = path.join(prefix, VERCEL_DIR, "vercel.json");
const compiledConfigExists = existsSync(compiledConfigPath);
if (compiledConfigExists) {
return compiledConfigPath;
}
if (nowConfigExists) {
return nowConfigPath;
}
return vercelConfigPath;
}
export {
getLocalPathConfig
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
getUpdateCommand
} from "./chunk-AD357QVF.js";
import {
login
} from "./chunk-56SHOHOE.js";
import {
loginCommand
} from "./chunk-W2EUICVJ.js";
import {
help
} from "./chunk-DOBFJJLK.js";
import {
TelemetryClient
} from "./chunk-XB2KZC2B.js";
import {
getFlagsSpecification,
parseArguments,
printError,
require_strip_ansi
} from "./chunk-ZLCMHY2G.js";
import {
output_manager_default
} from "./chunk-FDJURQMQ.js";
import {
require_source
} from "./chunk-S7KYDPEM.js";
import {
__commonJS,
__toESM
} from "./chunk-TZ2YI2VH.js";
// ../../node_modules/.pnpm/jaro-winkler@0.2.8/node_modules/jaro-winkler/index.js
var require_jaro_winkler = __commonJS({
"../../node_modules/.pnpm/jaro-winkler@0.2.8/node_modules/jaro-winkler/index.js"(exports, module) {
(function(root) {
"use strict";
function extend(a, b) {
for (var property in b) {
if (b.hasOwnProperty(property)) {
a[property] = b[property];
}
}
return a;
}
function distance2(s1, s2, options) {
var m = 0;
var defaults = { caseSensitive: true };
var settings = extend(defaults, options);
var i;
var j;
if (s1.length === 0 || s2.length === 0) {
return 0;
}
if (!settings.caseSensitive) {
s1 = s1.toUpperCase();
s2 = s2.toUpperCase();
}
if (s1 === s2) {
return 1;
}
var range = Math.floor(Math.max(s1.length, s2.length) / 2) - 1;
var s1Matches = new Array(s1.length);
var s2Matches = new Array(s2.length);
for (i = 0; i < s1.length; i++) {
var low = i >= range ? i - range : 0;
var high = i + range <= s2.length - 1 ? i + range : s2.length - 1;
for (j = low; j <= high; j++) {
if (s1Matches[i] !== true && s2Matches[j] !== true && s1[i] === s2[j]) {
++m;
s1Matches[i] = s2Matches[j] = true;
break;
}
}
}
if (m === 0) {
return 0;
}
var k = 0;
var numTrans = 0;
for (i = 0; i < s1.length; i++) {
if (s1Matches[i] === true) {
for (j = k; j < s2.length; j++) {
if (s2Matches[j] === true) {
k = j + 1;
break;
}
}
if (s1[i] !== s2[j]) {
++numTrans;
}
}
}
var weight = (m / s1.length + m / s2.length + (m - numTrans / 2) / m) / 3;
var l = 0;
var p = 0.1;
if (weight > 0.7) {
while (s1[l] === s2[l] && l < 4) {
++l;
}
weight = weight + l * p * (1 - weight);
}
return weight;
}
if (typeof define === "function" && define.amd) {
define([], function() {
return distance2;
});
} else if (typeof exports === "object") {
module.exports = distance2;
} else {
root.distance = distance2;
}
})(exports);
}
});
// src/util/upgrade.ts
import { spawn } from "child_process";
async function executeUpgrade() {
const updateCommand = await getUpdateCommand();
const [command, ...args] = updateCommand.split(" ");
output_manager_default.log(`Upgrading Vercel CLI...`);
output_manager_default.debug(`Executing: ${updateCommand}`);
return new Promise((resolve) => {
const stdout = [];
const stderr = [];
const upgradeProcess = spawn(command, args, {
stdio: ["inherit", "pipe", "pipe"],
shell: false
});
upgradeProcess.stdout?.on("data", (data) => {
stdout.push(data);
});
upgradeProcess.stderr?.on("data", (data) => {
stderr.push(data);
});
upgradeProcess.on("error", (err) => {
output_manager_default.error(`Failed to execute upgrade command: ${err.message}`);
output_manager_default.log(`You can try running the command manually: ${updateCommand}`);
resolve(1);
});
upgradeProcess.on("close", (code) => {
if (code === 0) {
output_manager_default.success("Vercel CLI has been upgraded successfully!");
} else {
const stdoutStr = Buffer.concat(stdout).toString();
const stderrStr = Buffer.concat(stderr).toString();
if (stdoutStr) {
output_manager_default.print(stdoutStr);
}
if (stderrStr) {
output_manager_default.print(stderrStr);
}
output_manager_default.error(`Upgrade failed with exit code ${code ?? "unknown"}`);
output_manager_default.log(
`You can try running the command manually: ${updateCommand}`
);
}
resolve(code ?? 1);
});
});
}
// src/commands/login/index.ts
var import_chalk = __toESM(require_source(), 1);
// src/util/telemetry/commands/login/index.ts
var LoginTelemetryClient = class extends TelemetryClient {
/**
* Tracks the state of the login process.
* - `started` when the user initiates the login process.
* - `canceled` when the user cancels the login process.
* - `error` when the user encounters an error during the login process.
* - `success` when the user successfully logs in.
*/
trackState(...args) {
this.trackLoginState(...args);
}
};
// src/commands/login/index.ts
async function login2(client, options) {
let parsedArgs = null;
const flagsSpecification = getFlagsSpecification(loginCommand.options);
const telemetry = new LoginTelemetryClient({
opts: {
store: client.telemetryEventStore
}
});
try {
if (options.shouldParseArgs) {
parsedArgs = parseArguments(client.argv.slice(2), flagsSpecification);
}
} catch (error) {
printError(error);
return 1;
}
if (parsedArgs?.flags["--help"]) {
telemetry.trackCliFlagHelp("login");
output_manager_default.print(help(loginCommand, { columns: client.stderr.columns }));
return 0;
}
if (parsedArgs?.flags["--token"]) {
output_manager_default.error('`--token` may not be used with the "login" command');
return 2;
}
if (options.shouldParseArgs && parsedArgs) {
const obsoleteFlags = Object.keys(parsedArgs.flags).filter((flag) => {
const flagKey = flag.replace("--", "");
const option = loginCommand.options.find((o) => o.name === flagKey);
if (!option || typeof option === "number")
return;
return "deprecated" in option && option.deprecated;
});
if (obsoleteFlags.length) {
const flags = obsoleteFlags.map((f) => import_chalk.default.bold(f)).join(", ");
output_manager_default.warn(`The following flags are deprecated: ${flags}`);
}
const obsoleteArguments = parsedArgs.args.slice(1);
if (obsoleteArguments.length) {
const args = obsoleteArguments.map((a) => import_chalk.default.bold(a)).join(", ");
output_manager_default.warn(`The following arguments are deprecated: ${args}`);
}
if (obsoleteArguments.length || obsoleteFlags.length) {
output_manager_default.print(
`Read more in our ${output_manager_default.link("changelog", "https://vercel.com/changelog/new-vercel-cli-login-flow")}.
`
);
}
}
telemetry.trackState("started");
return await login(client, telemetry);
}
// src/util/output/box.ts
var import_chalk2 = __toESM(require_source(), 1);
var import_strip_ansi = __toESM(require_strip_ansi(), 1);
var border = ["\u2500", "\u256D", "\u256E", "\u2502", "\u2502", "\u2570", "\u256F"];
var nothing = ["\u2500", "", "", "", "", "", ""];
function box(message, {
borderColor,
padding = 1,
textAlignment = "center",
terminalColumns: cols = process.stdout.columns || process.env.COLUMNS && parseInt(process.env.COLUMNS, 10) || 80
} = {}) {
const lines = message.split(/\r?\n/).map((line) => [line, (0, import_strip_ansi.default)(line).length]);
const maxLine = lines.reduce((p, [, len]) => Math.max(p, len), 0);
const borderColorFn = borderColor && import_chalk2.default[borderColor] || import_chalk2.default.yellow;
const clampedSidePadding = Math.max(1, padding * 3);
const narrowMode = maxLine + 2 + clampedSidePadding * 2 > cols;
const sidePadding = narrowMode ? 0 : clampedSidePadding;
const innerWidth = Math.min(maxLine + sidePadding * 2, cols);
const [hr, topLeft, topRight, left, right, bottomLeft, bottomRight] = narrowMode ? nothing : border;
const spacerRow = narrowMode ? "\n".repeat(padding) : `${borderColorFn(`${left}${" ".repeat(innerWidth)}${right}`)}
`.repeat(
padding
);
const renderLine = ([line, len]) => {
let leftPadding = 0;
let rightPadding = 0;
if (!narrowMode) {
leftPadding = sidePadding;
rightPadding = sidePadding;
if (textAlignment === "center") {
leftPadding += Math.floor((maxLine - len) / 2);
rightPadding += maxLine - len - leftPadding + sidePadding;
} else if (textAlignment === "right") {
leftPadding += maxLine - len;
} else if (textAlignment === "left") {
rightPadding += maxLine - len;
}
}
return borderColorFn(left) + " ".repeat(leftPadding) + line + " ".repeat(rightPadding) + borderColorFn(right);
};
return borderColorFn(`${topLeft}${hr.repeat(innerWidth)}${topRight}`) + "\n" + spacerRow + lines.map(renderLine).join("\n") + "\n" + spacerRow + borderColorFn(`${bottomLeft}${hr.repeat(innerWidth)}${bottomRight}`);
}
// src/util/did-you-mean.ts
var import_jaro_winkler = __toESM(require_jaro_winkler(), 1);
var did_you_mean_default = didYouMean;
function didYouMean(input, list, threshold = 0.5) {
const rated = list.map((item) => [dashAwareDistance(input, item), item]);
const found = rated.filter((item) => item[0] > threshold);
if (found.length) {
const highestRated = found.reduce((accu, curr) => {
return accu[0] > curr[0] ? accu : curr;
});
return highestRated[1];
}
}
function dashAwareDistance(word, dashWord) {
const fullDistance = (0, import_jaro_winkler.default)(word, dashWord);
const distances = dashWord.split("-").map((w) => (0, import_jaro_winkler.default)(w, word));
const meanDistance = distances.reduce((accu, curr) => accu + curr) / distances.length;
return fullDistance > meanDistance ? fullDistance : meanDistance;
}
export {
did_you_mean_default,
executeUpgrade,
login2 as login,
box
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
formatCondition,
formatTransform
} from "./chunk-PAX6W6YL.js";
import {
output_manager_default
} from "./chunk-FDJURQMQ.js";
import {
require_source
} from "./chunk-S7KYDPEM.js";
import {
__toESM
} from "./chunk-TZ2YI2VH.js";
// src/util/routes/env.ts
function extractEnvVarNames(value) {
const names = /* @__PURE__ */ new Set();
for (const m of value.matchAll(/\$\{?([A-Z_][A-Z0-9_]*)\}?/g)) {
names.add(m[1]);
}
return Array.from(names);
}
function populateRouteEnv(route) {
const routeEnv = /* @__PURE__ */ new Set();
if (route.dest) {
for (const name of extractEnvVarNames(route.dest)) {
routeEnv.add(name);
}
}
if (route.headers) {
for (const value of Object.values(route.headers)) {
for (const name of extractEnvVarNames(value)) {
routeEnv.add(name);
}
}
}
route.env = routeEnv.size > 0 ? Array.from(routeEnv) : void 0;
if (route.transforms) {
for (const transform of route.transforms) {
if (transform.args) {
const argsStr = Array.isArray(transform.args) ? transform.args.join(" ") : transform.args;
const names = extractEnvVarNames(argsStr);
transform.env = names.length > 0 ? names : void 0;
}
}
}
}
// src/util/routes/generate-route.ts
async function generateRoute(client, projectId, input, options = {}) {
const { teamId } = options;
const query = new URLSearchParams();
if (teamId)
query.set("teamId", teamId);
const queryString = query.toString();
const url = `/v1/projects/${projectId}/routes/generate${queryString ? `?${queryString}` : ""}`;
return await client.fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(input)
});
}
// src/util/routes/parse-transforms.ts
function parseTransforms(values, type, op) {
return values.map((value) => parseTransform(value, type, op));
}
function parseTransform(input, type, op) {
if (op === "delete") {
const key2 = input.trim();
if (!key2) {
throw new Error("Delete operation requires a key");
}
return {
type,
op,
target: { key: key2 }
};
}
const eqIndex = input.indexOf("=");
if (eqIndex === -1) {
throw new Error(`Invalid format: "${input}". Expected format: key=value`);
}
const key = input.slice(0, eqIndex).trim();
const args = input.slice(eqIndex + 1);
if (!key) {
throw new Error("Transform key cannot be empty");
}
return {
type,
op,
target: { key },
args
};
}
function collectTransforms(flags) {
const transforms = [];
if (flags.setResponseHeader) {
transforms.push(
...parseTransforms(flags.setResponseHeader, "response.headers", "set")
);
}
if (flags.appendResponseHeader) {
transforms.push(
...parseTransforms(
flags.appendResponseHeader,
"response.headers",
"append"
)
);
}
if (flags.deleteResponseHeader) {
transforms.push(
...parseTransforms(
flags.deleteResponseHeader,
"response.headers",
"delete"
)
);
}
if (flags.setRequestHeader) {
transforms.push(
...parseTransforms(flags.setRequestHeader, "request.headers", "set")
);
}
if (flags.appendRequestHeader) {
transforms.push(
...parseTransforms(flags.appendRequestHeader, "request.headers", "append")
);
}
if (flags.deleteRequestHeader) {
transforms.push(
...parseTransforms(flags.deleteRequestHeader, "request.headers", "delete")
);
}
if (flags.setRequestQuery) {
transforms.push(
...parseTransforms(flags.setRequestQuery, "request.query", "set")
);
}
if (flags.appendRequestQuery) {
transforms.push(
...parseTransforms(flags.appendRequestQuery, "request.query", "append")
);
}
if (flags.deleteRequestQuery) {
transforms.push(
...parseTransforms(flags.deleteRequestQuery, "request.query", "delete")
);
}
return transforms;
}
function collectResponseHeaders(setHeaders) {
const headers = {};
for (const input of setHeaders) {
const eqIndex = input.indexOf("=");
if (eqIndex === -1) {
throw new Error(
`Invalid header format: "${input}". Expected format: key=value`
);
}
const key = input.slice(0, eqIndex).trim();
const value = input.slice(eqIndex + 1);
if (!key) {
throw new Error("Header key cannot be empty");
}
headers[key] = value;
}
return headers;
}
// src/util/routes/interactive.ts
var MAX_NAME_LENGTH = 256;
var MAX_DESCRIPTION_LENGTH = 1024;
var MAX_CONDITIONS = 16;
var VALID_SYNTAXES = [
"regex",
"path-to-regexp",
"equals"
];
var REDIRECT_STATUS_CODES = [301, 302, 303, 307, 308];
var VALID_ACTION_TYPES = [
"rewrite",
"redirect",
"set-status"
];
var ALL_ACTION_CHOICES = [
{ name: "Rewrite", value: "rewrite", exclusive: true },
{ name: "Redirect", value: "redirect", exclusive: true },
{ name: "Set Status Code", value: "set-status", exclusive: true },
{ name: "Response Headers", value: "response-headers" },
{ name: "Request Headers", value: "request-headers" },
{ name: "Request Query", value: "request-query" }
];
function stripQuotes(str) {
if (str.startsWith('"') && str.endsWith('"') && str.length >= 2) {
return str.slice(1, -1);
}
if (str.startsWith("'") && str.endsWith("'") && str.length >= 2) {
return str.slice(1, -1);
}
return str;
}
function extractTransformFlags(flags) {
return {
setResponseHeader: flags["--set-response-header"],
appendResponseHeader: flags["--append-response-header"],
deleteResponseHeader: flags["--delete-response-header"],
setRequestHeader: flags["--set-request-header"],
appendRequestHeader: flags["--append-request-header"],
deleteRequestHeader: flags["--delete-request-header"],
setRequestQuery: flags["--set-request-query"],
appendRequestQuery: flags["--append-request-query"],
deleteRequestQuery: flags["--delete-request-query"]
};
}
function collectHeadersAndTransforms(transformFlags) {
const headers = transformFlags.setResponseHeader ? collectResponseHeaders(transformFlags.setResponseHeader) : {};
const transforms = collectTransforms({
...transformFlags,
setResponseHeader: void 0
// Already handled in headers
});
return { headers, transforms };
}
function hasAnyTransformFlags(flags) {
const tf = extractTransformFlags(flags);
return !!(tf.setResponseHeader || tf.appendResponseHeader || tf.deleteResponseHeader || tf.setRequestHeader || tf.appendRequestHeader || tf.deleteRequestHeader || tf.setRequestQuery || tf.appendRequestQuery || tf.deleteRequestQuery);
}
function validateActionFlags(action, dest, status) {
if (!action) {
if (dest || status !== void 0) {
return "--action is required when using --dest or --status. Use --action rewrite, --action redirect, or --action set-status.";
}
return null;
}
if (!VALID_ACTION_TYPES.includes(action)) {
return `Invalid action type: "${action}". Valid types: ${VALID_ACTION_TYPES.join(", ")}`;
}
switch (action) {
case "rewrite":
if (!dest)
return "--action rewrite requires --dest.";
if (status !== void 0)
return "--action rewrite does not accept --status.";
break;
case "redirect":
if (!dest)
return "--action redirect requires --dest.";
if (status === void 0)
return `--action redirect requires --status (${REDIRECT_STATUS_CODES.join(", ")}).`;
if (!REDIRECT_STATUS_CODES.includes(status))
return `Invalid redirect status: ${status}. Must be one of: ${REDIRECT_STATUS_CODES.join(", ")}`;
break;
case "set-status":
if (dest)
return "--action set-status does not accept --dest.";
if (status === void 0)
return "--action set-status requires --status.";
if (status < 100 || status > 599)
return "Status code must be between 100 and 599.";
break;
}
return null;
}
async function collectActionDetails(client, actionType, flags) {
switch (actionType) {
case "rewrite": {
const dest = await client.input.text({
message: "Destination URL:",
validate: (val) => val ? true : "Destination is required"
});
Object.assign(flags, { "--dest": dest });
break;
}
case "redirect": {
const dest = await client.input.text({
message: "Destination URL:",
validate: (val) => val ? true : "Destination is required"
});
const status = await client.input.select({
message: "Status code:",
choices: [
{ name: "307 - Temporary Redirect", value: 307 },
{ name: "308 - Permanent Redirect", value: 308 },
{ name: "301 - Moved Permanently", value: 301 },
{ name: "302 - Found", value: 302 },
{ name: "303 - See Other", value: 303 }
]
});
Object.assign(flags, { "--dest": dest, "--status": status });
break;
}
case "set-status": {
const statusCode = await client.input.text({
message: "HTTP status code:",
validate: (val) => {
const num = parseInt(val, 10);
if (isNaN(num) || num < 100 || num > 599) {
return "Status code must be between 100 and 599";
}
return true;
}
});
Object.assign(flags, { "--status": parseInt(statusCode, 10) });
break;
}
case "response-headers": {
await collectInteractiveHeaders(client, "response", flags);
break;
}
case "request-headers": {
await collectInteractiveHeaders(client, "request-header", flags);
break;
}
case "request-query": {
await collectInteractiveHeaders(client, "request-query", flags);
break;
}
}
}
async function collectInteractiveConditions(client, flags) {
let addMore = true;
while (addMore) {
const currentHas = flags["--has"] || [];
const currentMissing = flags["--missing"] || [];
if (currentHas.length > 0 || currentMissing.length > 0) {
output_manager_default.log("\nCurrent conditions:");
for (const c of currentHas) {
output_manager_default.print(` has: ${c}
`);
}
for (const c of currentMissing) {
output_manager_default.print(` does not have: ${c}
`);
}
output_manager_default.print("\n");
}
const conditionType = await client.input.select({
message: "Condition type:",
choices: [
{ name: "has - Request must have this", value: "has" },
{
name: "does not have - Request must NOT have this",
value: "missing"
}
]
});
const targetType = await client.input.select({
message: "What to check:",
choices: [
{ name: "Header", value: "header" },
{ name: "Cookie", value: "cookie" },
{ name: "Query Parameter", value: "query" },
{ name: "Host", value: "host" }
]
});
let conditionValue;
if (targetType === "host") {
const operator = await client.input.select({
message: "How to match the host:",
choices: [
{ name: "Equals", value: "eq" },
{ name: "Contains", value: "contains" },
{ name: "Matches (regex)", value: "re" }
]
});
const hostInput = await client.input.text({
message: operator === "re" ? "Host pattern (regex):" : "Host value:",
validate: (val) => {
if (!val)
return "Host value is required";
if (operator === "re") {
try {
new RegExp(val);
return true;
} catch {
return "Invalid regex pattern";
}
}
return true;
}
});
conditionValue = `host:${operator}=${hostInput}`;
} else {
const key = await client.input.text({
message: `${targetType.charAt(0).toUpperCase() + targetType.slice(1)} name:`,
validate: (val) => val ? true : `${targetType} name is required`
});
const operator = await client.input.select({
message: "How to match the value:",
choices: [
{ name: "Exists (any value)", value: "exists" },
{ name: "Equals", value: "eq" },
{ name: "Contains", value: "contains" },
{ name: "Matches (regex)", value: "re" }
]
});
if (operator === "exists") {
conditionValue = `${targetType}:${key}:exists`;
} else {
const valueInput = await client.input.text({
message: operator === "re" ? "Value pattern (regex):" : "Value:",
validate: (val) => {
if (!val)
return "Value is required";
if (operator === "re") {
try {
new RegExp(val);
return true;
} catch {
return "Invalid regex pattern";
}
}
return true;
}
});
conditionValue = `${targetType}:${key}:${operator}=${valueInput}`;
}
}
const flagName = conditionType === "has" ? "--has" : "--missing";
const existing = flags[flagName] || [];
flags[flagName] = [...existing, conditionValue];
const totalConditions = (flags["--has"] || []).length + (flags["--missing"] || []).length;
if (totalConditions >= MAX_CONDITIONS) {
output_manager_default.warn(`Maximum ${MAX_CONDITIONS} conditions reached.`);
break;
}
addMore = await client.input.confirm("Add another condition?", false);
}
}
function formatCollectedItems(flags, type) {
const items = [];
const prefix = type === "response" ? "response-header" : type === "request-header" ? "request-header" : "request-query";
const setItems = flags[`--set-${prefix}`] || [];
const appendItems = flags[`--append-${prefix}`] || [];
const deleteItems = flags[`--delete-${prefix}`] || [];
for (const item of setItems) {
items.push(` set: ${item}`);
}
for (const item of appendItems) {
items.push(` append: ${item}`);
}
for (const item of deleteItems) {
items.push(` delete: ${item}`);
}
return items;
}
async function collectInteractiveHeaders(client, type, flags) {
const flagName = type === "response" ? "--set-response-header" : type === "request-header" ? "--set-request-header" : "--set-request-query";
const sectionName = type === "response" ? "Response Headers" : type === "request-header" ? "Request Headers" : "Request Query Parameters";
const itemName = type === "response" ? "response header" : type === "request-header" ? "request header" : "query parameter";
output_manager_default.log(`
--- ${sectionName} ---`);
let addMore = true;
while (addMore) {
const collected = formatCollectedItems(flags, type);
if (collected.length > 0) {
output_manager_default.log(`
Current ${sectionName.toLowerCase()}:`);
for (const item of collected) {
output_manager_default.print(`${item}
`);
}
output_manager_default.print("\n");
}
const op = await client.input.select({
message: `${sectionName} operation:`,
choices: [
{ name: "Set", value: "set" },
{ name: "Append", value: "append" },
{ name: "Delete", value: "delete" }
]
});
const key = await client.input.text({
message: `${itemName.charAt(0).toUpperCase() + itemName.slice(1)} name:`,
validate: (val) => val ? true : `${itemName} name is required`
});
if (op === "delete") {
const opFlagName = flagName.replace("--set-", "--delete-");
const existing = flags[opFlagName] || [];
flags[opFlagName] = [...existing, key];
} else {
const value = await client.input.text({
message: `${itemName.charAt(0).toUpperCase() + itemName.slice(1)} value:`
});
const opFlagName = op === "append" ? flagName.replace("--set-", "--append-") : flagName;
const existing = flags[opFlagName] || [];
flags[opFlagName] = [...existing, `${key}=${value}`];
}
addMore = await client.input.confirm(`Add another ${itemName}?`, false);
}
}
// src/util/routes/ai-transform.ts
var import_chalk = __toESM(require_source(), 1);
// src/util/routes/parse-conditions.ts
var CONDITION_OPERATORS = [
"eq",
"contains",
"re",
"exists"
];
function escapeRegExp(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function buildConditionValue(operator, value) {
if (operator === "exists")
return void 0;
if (operator === "re")
return value;
const escapedValue = escapeRegExp(value);
if (operator === "contains")
return `.*${escapedValue}.*`;
return `^${escapedValue}$`;
}
function validateRegexPattern(pattern, context) {
try {
new RegExp(pattern);
} catch (e) {
throw new Error(
`Invalid regex in ${context}: "${pattern}". ${e instanceof Error ? e.message : ""}`
);
}
}
function parseOperatorValue(valuePart) {
if (valuePart === "exists") {
return { operator: "exists", rawValue: "" };
}
const eqIdx = valuePart.indexOf("=");
if (eqIdx === -1)
return null;
const maybeOp = valuePart.slice(0, eqIdx);
if (CONDITION_OPERATORS.includes(maybeOp)) {
return {
operator: maybeOp,
rawValue: valuePart.slice(eqIdx + 1)
};
}
return null;
}
function parseConditions(conditions) {
return conditions.map(parseCondition);
}
function parseCondition(condition) {
const parts = condition.split(":");
if (parts.length < 2) {
throw new Error(
`Invalid condition format: "${condition}". Expected format: type:key or type:key:value`
);
}
const type = parts[0].toLowerCase();
const validTypes = ["header", "cookie", "query", "host"];
if (!validTypes.includes(type)) {
throw new Error(
`Invalid condition type: "${type}". Valid types: ${validTypes.join(", ")}`
);
}
if (type === "host") {
const rawValue = parts.slice(1).join(":");
if (!rawValue) {
throw new Error("Host condition requires a value");
}
const opResult2 = parseOperatorValue(rawValue);
if (opResult2) {
if (opResult2.operator === "exists") {
throw new Error(
'Host condition does not support "exists" operator (host always has a value)'
);
}
if (opResult2.operator !== "re" && !opResult2.rawValue) {
throw new Error(
`Host condition with "${opResult2.operator}" operator requires a value`
);
}
const compiledValue = buildConditionValue(
opResult2.operator,
opResult2.rawValue
);
if (compiledValue !== void 0) {
validateRegexPattern(compiledValue, "host condition");
}
return { type: "host", value: compiledValue };
}
validateRegexPattern(rawValue, "host condition");
return { type: "host", value: rawValue };
}
const key = parts[1];
if (!key) {
throw new Error(`${type} condition requires a key`);
}
const valuePart = parts.length > 2 ? parts.slice(2).join(":") : void 0;
if (valuePart === void 0) {
return { type, key };
}
const opResult = parseOperatorValue(valuePart);
if (opResult) {
if (opResult.operator === "exists") {
return { type, key };
}
if (opResult.operator !== "re" && !opResult.rawValue) {
throw new Error(
`Condition "${opResult.operator}" operator requires a value after "="`
);
}
const compiledValue = buildConditionValue(
opResult.operator,
opResult.rawValue
);
if (compiledValue !== void 0) {
validateRegexPattern(compiledValue, `${type} condition value`);
}
return {
type,
key,
...compiledValue !== void 0 && { value: compiledValue }
};
}
validateRegexPattern(valuePart, `${type} condition value`);
return {
type,
key,
value: valuePart
};
}
function formatCondition2(field) {
if (field.type === "host") {
return `host:${field.value}`;
}
if (field.value) {
return `${field.type}:${field.key}:${field.value}`;
}
return `${field.type}:${field.key}`;
}
// src/util/routes/ai-transform.ts
function generatedRouteToAddInput(generated) {
const hasConditions = [];
const missingConditions = [];
const headers = {};
const transforms = [];
let dest;
let status;
if (generated.conditions) {
for (const c of generated.conditions) {
const compiledValue = c.value !== void 0 ? buildConditionValue(c.operator, c.value) : void 0;
const field = c.field === "host" ? { type: "host", value: compiledValue ?? c.value ?? "" } : {
type: c.field,
key: c.key ?? "",
...compiledValue !== void 0 && { value: compiledValue }
};
if (c.missing) {
missingConditions.push(field);
} else {
hasConditions.push(field);
}
}
}
for (const action of generated.actions) {
switch (action.type) {
case "rewrite":
dest = action.dest;
break;
case "redirect":
dest = action.dest;
status = action.status;
break;
case "set-status":
status = action.status;
break;
case "modify": {
if (!action.headers)
break;
if (action.subType === "response-headers") {
for (const h of action.headers) {
if (h.op === "set") {
headers[h.key] = h.value ?? "";
} else {
transforms.push({
type: "response.headers",
op: h.op,
target: { key: h.key },
...h.op !== "delete" && h.value && { args: h.value }
});
}
}
} else if (action.subType === "transform-request-header") {
for (const h of action.headers) {
transforms.push({
type: "request.headers",
op: h.op,
target: { key: h.key },
...h.op !== "delete" && h.value && { args: h.value }
});
}
} else if (action.subType === "transform-request-query") {
for (const h of action.headers) {
transforms.push({
type: "request.query",
op: h.op,
target: { key: h.key },
...h.op !== "delete" && h.value && { args: h.value }
});
}
}
break;
}
}
}
return {
name: generated.name,
description: generated.description || void 0,
srcSyntax: generated.pathCondition.syntax,
route: {
src: generated.pathCondition.value,
...dest !== void 0 && { dest },
...status !== void 0 && { status },
...Object.keys(headers).length > 0 && { headers },
...transforms.length > 0 && { transforms },
...hasConditions.length > 0 && { has: hasConditions },
...missingConditions.length > 0 && { missing: missingConditions }
}
};
}
function convertRouteToCurrentRoute(generated) {
return {
name: generated.name,
description: generated.description || void 0,
pathCondition: generated.pathCondition,
conditions: generated.conditions,
actions: generated.actions
};
}
function routingRuleToCurrentRoute(rule) {
const conditions = [];
const actions = [];
if (rule.route.has) {
for (const c of rule.route.has) {
conditions.push({
field: c.type,
operator: c.value !== void 0 ? "re" : "exists",
key: c.key,
value: c.value !== void 0 ? typeof c.value === "string" ? c.value : JSON.stringify(c.value) : void 0,
missing: false
});
}
}
if (rule.route.missing) {
for (const c of rule.route.missing) {
conditions.push({
field: c.type,
operator: c.value !== void 0 ? "re" : "exists",
key: c.key,
value: c.value !== void 0 ? typeof c.value === "string" ? c.value : JSON.stringify(c.value) : void 0,
missing: true
});
}
}
const isRedirect = rule.route.dest && rule.route.status && REDIRECT_STATUS_CODES.includes(rule.route.status);
if (isRedirect) {
actions.push({
type: "redirect",
dest: rule.route.dest,
status: rule.route.status
});
} else if (rule.route.dest) {
actions.push({ type: "rewrite", dest: rule.route.dest });
} else if (rule.route.status) {
actions.push({ type: "set-status", status: rule.route.status });
}
const responseHeaders = rule.route.headers ? Object.entries(rule.route.headers).map(([key, value]) => ({
key,
value,
op: "set"
})) : [];
const allTransforms = rule.route.transforms ?? [];
const responseHeaderTransforms = allTransforms.filter((t) => t.type === "response.headers").map((t) => ({
key: typeof t.target.key === "string" ? t.target.key : String(t.target.key),
value: t.args,
op: t.op
}));
const allResponseHeaders = [...responseHeaders, ...responseHeaderTransforms];
if (allResponseHeaders.length > 0) {
actions.push({
type: "modify",
subType: "response-headers",
headers: allResponseHeaders
});
}
const requestHeaders = allTransforms.filter((t) => t.type === "request.headers").map((t) => ({
key: typeof t.target.key === "string" ? t.target.key : String(t.target.key),
value: t.args,
op: t.op
}));
if (requestHeaders.length > 0) {
actions.push({
type: "modify",
subType: "transform-request-header",
headers: requestHeaders
});
}
const requestQuery = allTransforms.filter((t) => t.type === "request.query").map((t) => ({
key: typeof t.target.key === "string" ? t.target.key : String(t.target.key),
value: t.args,
op: t.op
}));
if (requestQuery.length > 0) {
actions.push({
type: "modify",
subType: "transform-request-query",
headers: requestQuery
});
}
return {
name: rule.name,
description: rule.description,
pathCondition: {
value: rule.route.src,
syntax: rule.srcSyntax ?? "regex"
},
...conditions.length > 0 && { conditions },
actions
};
}
function printGeneratedRoutePreview(generated) {
output_manager_default.print("\n");
output_manager_default.print(` ${import_chalk.default.bold("Generated Route:")}
`);
output_manager_default.print(` ${import_chalk.default.cyan("Name:")} ${generated.name}
`);
if (generated.description) {
output_manager_default.print(` ${import_chalk.default.cyan("Description:")} ${generated.description}
`);
}
output_manager_default.print(
` ${import_chalk.default.cyan("Source:")} ${generated.pathCondition.value}
`
);
if (generated.conditions && generated.conditions.length > 0) {
output_manager_default.print(` ${import_chalk.default.cyan("Conditions:")}
`);
for (const c of generated.conditions) {
const prefix = c.missing ? "does not have" : "has";
const operatorLabel = c.operator === "eq" ? "equal to" : c.operator === "contains" ? "containing" : c.operator === "re" ? "matching" : "";
const key = c.key ? ` ${import_chalk.default.cyan(`"${c.key}"`)}` : "";
const value = c.operator === "exists" || !c.value ? "" : ` ${operatorLabel} ${import_chalk.default.cyan(`"${c.value}"`)}`;
output_manager_default.print(` ${import_chalk.default.gray(prefix)} ${c.field}${key}${value}
`);
}
}
for (const action of generated.actions) {
if (action.type === "rewrite" && action.dest) {
output_manager_default.print(
` ${import_chalk.default.cyan("Action:")} Rewrite \u2192 ${action.dest}
`
);
} else if (action.type === "redirect" && action.dest) {
output_manager_default.print(
` ${import_chalk.default.cyan("Action:")} Redirect \u2192 ${action.dest} (${action.status})
`
);
} else if (action.type === "set-status" && action.status) {
output_manager_default.print(
` ${import_chalk.default.cyan("Action:")} Set Status ${action.status}
`
);
}
}
for (const action of generated.actions) {
if (action.type === "modify" && action.headers) {
const label = action.subType === "response-headers" ? "Response Headers" : action.subType === "transform-request-header" ? "Request Headers" : "Request Query";
output_manager_default.print(` ${import_chalk.default.cyan(`${label}:`)}
`);
for (const h of action.headers) {
if (h.op === "delete") {
output_manager_default.print(` ${import_chalk.default.yellow(h.op)} ${import_chalk.default.cyan(h.key)}
`);
} else {
output_manager_default.print(
` ${import_chalk.default.yellow(h.op)} ${import_chalk.default.cyan(h.key)} = ${h.value}
`
);
}
}
}
}
output_manager_default.print("\n");
}
// src/commands/routes/edit-interactive.ts
var import_chalk2 = __toESM(require_source(), 1);
function getPrimaryActionType(route) {
const { dest, status } = route.route;
if (dest && status && REDIRECT_STATUS_CODES.includes(status)) {
return "redirect";
}
if (dest)
return "rewrite";
if (status)
return "set-status";
return null;
}
function getPrimaryActionLabel(route) {
const actionType = getPrimaryActionType(route);
switch (actionType) {
case "rewrite":
return `Rewrite \u2192 ${route.route.dest}`;
case "redirect":
return `Redirect \u2192 ${route.route.dest} (${route.route.status})`;
case "set-status":
return `Set Status ${route.route.status}`;
default:
return "(none)";
}
}
function getResponseHeaders(route) {
const headers = route.route.headers ?? {};
return Object.entries(headers).map(([key, value]) => ({ key, value }));
}
function getTransformsByType(route, type) {
const transforms = route.route.transforms ?? [];
return transforms.filter((t) => t.type === type);
}
function printRouteConfig(route) {
output_manager_default.print("\n");
output_manager_default.print(` ${import_chalk2.default.cyan("Name:")} ${route.name}
`);
if (route.description) {
output_manager_default.print(` ${import_chalk2.default.cyan("Description:")} ${route.description}
`);
}
output_manager_default.print(
` ${import_chalk2.default.cyan("Source:")} ${route.route.src} ${import_chalk2.default.gray(`(${route.srcSyntax ?? "regex"})`)}
`
);
output_manager_default.print(
` ${import_chalk2.default.cyan("Status:")} ${route.enabled === false ? import_chalk2.default.red("Disabled") : import_chalk2.default.green("Enabled")}
`
);
const actionLabel = getPrimaryActionLabel(route);
output_manager_default.print(` ${import_chalk2.default.cyan("Action:")} ${actionLabel}
`);
const hasConds = route.route.has ?? [];
if (hasConds.length > 0) {
output_manager_default.print(`
${import_chalk2.default.cyan("Has conditions:")}
`);
for (const c of hasConds) {
output_manager_default.print(` ${formatCondition(c)}
`);
}
}
const missingConds = route.route.missing ?? [];
if (missingConds.length > 0) {
output_manager_default.print(`
${import_chalk2.default.cyan("Does not have conditions:")}
`);
for (const c of missingConds) {
output_manager_default.print(` ${formatCondition(c)}
`);
}
}
const responseHeaders = getResponseHeaders(route);
if (responseHeaders.length > 0) {
output_manager_default.print(`
${import_chalk2.default.cyan("Response Headers:")}
`);
for (const h of responseHeaders) {
output_manager_default.print(` ${import_chalk2.default.cyan(h.key)} = ${h.value}
`);
}
}
const requestHeaders = getTransformsByType(route, "request.headers");
if (requestHeaders.length > 0) {
output_manager_default.print(`
${import_chalk2.default.cyan("Request Headers:")}
`);
for (const t of requestHeaders) {
output_manager_default.print(` ${formatTransform(t)}
`);
}
}
const requestQuery = getTransformsByType(route, "request.query");
if (requestQuery.length > 0) {
output_manager_default.print(`
${import_chalk2.default.cyan("Request Query:")}
`);
for (const t of requestQuery) {
output_manager_default.print(` ${formatTransform(t)}
`);
}
}
output_manager_default.print("\n");
}
function cloneRoute(route) {
return JSON.parse(JSON.stringify(route));
}
function applyFlagMutations(route, flags) {
if (flags["--name"] !== void 0) {
const name = flags["--name"];
if (name.length > MAX_NAME_LENGTH) {
return `Name must be ${MAX_NAME_LENGTH} characters or less.`;
}
route.name = name;
}
if (flags["--description"] !== void 0) {
const desc = flags["--description"];
if (desc.length > MAX_DESCRIPTION_LENGTH) {
return `Description must be ${MAX_DESCRIPTION_LENGTH} characters or less.`;
}
route.description = desc || void 0;
}
if (flags["--src"] !== void 0) {
route.route.src = stripQuotes(flags["--src"]);
}
if (flags["--src-syntax"] !== void 0) {
const syntax = flags["--src-syntax"];
if (!VALID_SYNTAXES.includes(syntax)) {
return `Invalid syntax: "${syntax}". Valid options: ${VALID_SYNTAXES.join(", ")}`;
}
route.srcSyntax = syntax;
}
const actionFlag = flags["--action"];
const destFlag = flags["--dest"];
const statusFlag = flags["--status"];
const noDest = flags["--no-dest"];
const noStatus = flags["--no-status"];
if (actionFlag) {
if (!VALID_ACTION_TYPES.includes(actionFlag)) {
return `Invalid action type: "${actionFlag}". Valid types: ${VALID_ACTION_TYPES.join(", ")}`;
}
switch (actionFlag) {
case "rewrite": {
const dest = destFlag ? stripQuotes(destFlag) : void 0;
if (!dest)
return "--action rewrite requires --dest.";
route.route.dest = dest;
delete route.route.status;
break;
}
case "redirect": {
const dest = destFlag ? stripQuotes(destFlag) : void 0;
if (!dest)
return "--action redirect requires --dest.";
if (statusFlag === void 0)
return `--action redirect requires --status (${REDIRECT_STATUS_CODES.join(", ")}).`;
if (!REDIRECT_STATUS_CODES.includes(statusFlag))
return `Invalid redirect status: ${statusFlag}. Must be one of: ${REDIRECT_STATUS_CODES.join(", ")}`;
route.route.dest = dest;
route.route.status = statusFlag;
break;
}
case "set-status": {
if (statusFlag === void 0)
return "--action set-status requires --status.";
if (statusFlag < 100 || statusFlag > 599)
return "Status code must be between 100 and 599.";
delete route.route.dest;
route.route.status = statusFlag;
break;
}
}
} else {
if (destFlag !== void 0) {
route.route.dest = stripQuotes(destFlag);
}
if (statusFlag !== void 0) {
route.route.status = statusFlag;
}
if (noDest) {
delete route.route.dest;
}
if (noStatus) {
delete route.route.status;
}
}
if (flags["--clear-conditions"]) {
route.route.has = [];
route.route.missing = [];
}
if (flags["--clear-headers"]) {
route.route.headers = {};
}
if (flags["--clear-transforms"]) {
route.route.transforms = [];
}
const transformFlags = extractTransformFlags(flags);
try {
const { headers, transforms } = collectHeadersAndTransforms(transformFlags);
if (Object.keys(headers).length > 0) {
route.route.headers = {
...route.route.headers ?? {},
...headers
};
}
if (transforms.length > 0) {
const existing = route.route.transforms ?? [];
route.route.transforms = [...existing, ...transforms];
}
} catch (e) {
return `Invalid transform format. ${e instanceof Error ? e.message : ""}`;
}
const hasFlags = flags["--has"];
const missingFlags = flags["--missing"];
try {
if (hasFlags) {
const newHas = parseConditions(hasFlags);
const existingHas = route.route.has ?? [];
route.route.has = [...existingHas, ...newHas];
}
if (missingFlags) {
const newMissing = parseConditions(missingFlags);
const existingMissing = route.route.missing ?? [];
route.route.missing = [...existingMissing, ...newMissing];
}
} catch (e) {
return e instanceof Error ? e.message : "Invalid condition format";
}
const totalConditions = (route.route.has ?? []).length + (route.route.missing ?? []).length;
if (totalConditions > MAX_CONDITIONS) {
return `Too many conditions: ${totalConditions}. Maximum is ${MAX_CONDITIONS}.`;
}
const hasDest = !!route.route.dest;
const hasStatus = !!route.route.status;
const hasHeaders = Object.keys(route.route.headers ?? {}).length > 0;
const hasTransforms = (route.route.transforms ?? []).length > 0;
if (!hasDest && !hasStatus && !hasHeaders && !hasTransforms) {
return "This edit would leave the route with no action. Add --action, headers, or transforms.";
}
return null;
}
async function runInteractiveEditLoop(client, route) {
for (; ; ) {
const hasConds = (route.route.has ?? []).length;
const missingConds = (route.route.missing ?? []).length;
const responseHeaders = getAllResponseHeaders(route).length;
const requestHeaders = getTransformsByType(route, "request.headers").length;
const requestQuery = getTransformsByType(route, "request.query").length;
const syntaxLabel = route.srcSyntax === "path-to-regexp" ? "Pattern" : route.srcSyntax === "equals" ? "Exact" : "Regex";
const descriptionPreview = route.description ? route.description.length > 40 ? route.description.slice(0, 40) + "..." : route.description : "";
const editChoices = [
{ name: `Name (${route.name})`, value: "name" },
{
name: descriptionPreview ? `Description (${descriptionPreview})` : "Description",
value: "description"
},
{
name: `Source (${syntaxLabel}: ${route.route.src})`,
value: "source"
},
{
name: `Primary action (${getPrimaryActionLabel(route)})`,
value: "action"
},
{
name: `Conditions (${hasConds} has, ${missingConds} missing)`,
value: "conditions"
},
{
name: `Response Headers (${responseHeaders})`,
value: "response-headers"
},
{
name: `Request Headers (${requestHeaders})`,
value: "request-headers"
},
{
name: `Request Query (${requestQuery})`,
value: "request-query"
},
{ name: "Done - save changes", value: "done" }
];
const choice = await client.input.select({
message: "What would you like to edit?",
choices: editChoices,
pageSize: editChoices.length,
loop: false
});
switch (choice) {
case "name":
await editName(client, route);
break;
case "description":
await editDescription(client, route);
break;
case "source":
await editSource(client, route);
break;
case "action":
await editPrimaryAction(client, route);
break;
case "conditions":
await editConditions(client, route);
break;
case "response-headers":
await editResponseHeaders(client, route);
break;
case "request-headers":
await editTransformsByType(
client,
route,
"request.headers",
"request-header"
);
break;
case "request-query":
await editTransformsByType(
client,
route,
"request.query",
"request-query"
);
break;
case "done":
break;
}
if (choice === "done") {
const hasDest = !!route.route.dest;
const hasStatus = !!route.route.status;
const hasHeaders = Object.keys(route.route.headers ?? {}).length > 0;
const hasTransforms = (route.route.transforms ?? []).length > 0;
if (!hasDest && !hasStatus && !hasHeaders && !hasTransforms) {
output_manager_default.warn(
"Route has no action (no destination, status, or headers). Add an action before saving."
);
continue;
}
break;
}
}
}
async function editName(client, route) {
const name = await client.input.text({
message: `Name (current: ${route.name}):`,
validate: (val) => {
if (!val)
return "Route name is required";
if (val.length > MAX_NAME_LENGTH)
return `Name must be ${MAX_NAME_LENGTH} characters or less`;
return true;
}
});
route.name = name;
}
async function editDescription(client, route) {
const desc = await client.input.text({
message: `Description${route.description ? ` (current: ${route.description})` : ""}:`,
validate: (val) => val && val.length > MAX_DESCRIPTION_LENGTH ? `Description must be ${MAX_DESCRIPTION_LENGTH} characters or less` : true
});
route.description = desc || void 0;
}
async function editSource(client, route) {
const syntaxChoice = await client.input.select({
message: `Path syntax (current: ${route.srcSyntax ?? "regex"}):`,
choices: [
{
name: "Path pattern (e.g., /api/:version/users/:id)",
value: "path-to-regexp"
},
{ name: "Exact match (e.g., /about)", value: "equals" },
{ name: "Regular expression (e.g., ^/api/(.*)$)", value: "regex" }
]
});
route.srcSyntax = syntaxChoice;
const src = await client.input.text({
message: `Path pattern (current: ${route.route.src}):`,
validate: (val) => {
if (!val)
return "Path pattern is required";
return true;
}
});
route.route.src = src;
}
async function editPrimaryAction(client, route) {
const currentType = getPrimaryActionType(route);
const choices = [];
if (currentType === "rewrite" || currentType === "redirect") {
choices.push({ name: "Change destination", value: "change-dest" });
}
if (currentType === "redirect" || currentType === "set-status") {
choices.push({ name: "Change status code", value: "change-status" });
}
if (currentType !== "rewrite") {
choices.push({ name: "Switch to Rewrite", value: "switch-rewrite" });
}
if (currentType !== "redirect") {
choices.push({ name: "Switch to Redirect", value: "switch-redirect" });
}
if (currentType !== "set-status") {
choices.push({
name: "Switch to Set Status Code",
value: "switch-set-status"
});
}
if (currentType) {
choices.push({
name: "Remove primary action",
value: "remove"
});
} else {
choices.push({ name: "Add Rewrite", value: "switch-rewrite" });
choices.push({ name: "Add Redirect", value: "switch-redirect" });
choices.push({ name: "Add Set Status Code", value: "switch-set-status" });
}
choices.push({ name: "Back", value: "back" });
const action = await client.input.select({
message: `Primary action (current: ${getPrimaryActionLabel(route)}):`,
choices
});
const flags = {};
switch (action) {
case "change-dest": {
const dest = await client.input.text({
message: `Destination (current: ${route.route.dest}):`,
validate: (val) => val ? true : "Destination is required"
});
route.route.dest = dest;
break;
}
case "change-status": {
if (currentType === "redirect") {
const status = await client.input.select({
message: `Status code (current: ${route.route.status}):`,
choices: [
{ name: "307 - Temporary Redirect", value: 307 },
{ name: "308 - Permanent Redirect", value: 308 },
{ name: "301 - Moved Permanently", value: 301 },
{ name: "302 - Found", value: 302 },
{ name: "303 - See Other", value: 303 }
]
});
route.route.status = status;
} else {
const statusCode = await client.input.text({
message: `Status code (current: ${route.route.status}):`,
validate: (val) => {
const num = parseInt(val, 10);
if (isNaN(num) || num < 100 || num > 599) {
return "Status code must be between 100 and 599";
}
return true;
}
});
route.route.status = parseInt(statusCode, 10);
}
break;
}
case "switch-rewrite": {
await collectActionDetails(client, "rewrite", flags);
route.route.dest = flags["--dest"];
delete route.route.status;
break;
}
case "switch-redirect": {
await collectActionDetails(client, "redirect", flags);
route.route.dest = flags["--dest"];
route.route.status = flags["--status"];
break;
}
case "switch-set-status": {
await collectActionDetails(client, "set-status", flags);
delete route.route.dest;
route.route.status = flags["--status"];
break;
}
case "remove": {
delete route.route.dest;
delete route.route.status;
break;
}
}
}
async function editConditions(client, route) {
for (; ; ) {
const hasConds = route.route.has ?? [];
const missingConds = route.route.missing ?? [];
if (hasConds.length > 0 || missingConds.length > 0) {
output_manager_default.print("\n");
if (hasConds.length > 0) {
output_manager_default.print(` ${import_chalk2.default.cyan("Has conditions:")}
`);
hasConds.forEach((c, i) => {
output_manager_default.print(
` ${import_chalk2.default.gray(`${i + 1}.`)} ${formatCondition(c)}
`
);
});
}
if (missingConds.length > 0) {
output_manager_default.print(` ${import_chalk2.default.cyan("Does not have conditions:")}
`);
missingConds.forEach((c, i) => {
output_manager_default.print(
` ${import_chalk2.default.gray(`${hasConds.length + i + 1}.`)} ${formatCondition(c)}
`
);
});
}
output_manager_default.print("\n");
} else {
output_manager_default.print("\n No conditions set.\n\n");
}
const choices = [];
if (hasConds.length > 0 || missingConds.length > 0) {
choices.push({ name: "Remove a condition", value: "remove" });
}
choices.push({ name: "Add a new condition", value: "add" });
choices.push({ name: "Back", value: "back" });
const action = await client.input.select({
message: "Conditions:",
choices
});
if (action === "back")
break;
if (action === "remove") {
const allConds = [
...hasConds.map((c, i) => ({
label: `[has] ${formatCondition(c)}`,
idx: i,
kind: "has"
})),
...missingConds.map((c, i) => ({
label: `[does not have] ${formatCondition(c)}`,
idx: i,
kind: "missing"
}))
];
const toRemove = await client.input.select({
message: "Select condition to remove:",
choices: [
...allConds.map((c, i) => ({
name: c.label,
value: i
})),
{ name: "Cancel", value: -1 }
]
});
if (toRemove !== -1) {
const selected = allConds[toRemove];
if (selected.kind === "has") {
hasConds.splice(selected.idx, 1);
route.route.has = hasConds;
} else {
missingConds.splice(selected.idx, 1);
route.route.missing = missingConds;
}
}
}
if (action === "add") {
const existingHasStrings = hasConds.map(
(c) => formatCondition2(c)
);
const existingMissingStrings = missingConds.map(
(c) => formatCondition2(c)
);
const tempFlags = {
"--has": existingHasStrings.length > 0 ? existingHasStrings : void 0,
"--missing": existingMissingStrings.length > 0 ? existingMissingStrings : void 0
};
const hasBefore = existingHasStrings.length;
const missingBefore = existingMissingStrings.length;
await collectInteractiveConditions(client, tempFlags);
const allHas = tempFlags["--has"] || [];
const allMissing = tempFlags["--missing"] || [];
const newHas = allHas.slice(hasBefore);
const newMissing = allMissing.slice(missingBefore);
if (newHas.length > 0) {
const parsed = parseConditions(newHas);
const existing = route.route.has ?? [];
route.route.has = [...existing, ...parsed];
}
if (newMissing.length > 0) {
const parsed = parseConditions(newMissing);
const existing = route.route.missing ?? [];
route.route.missing = [...existing, ...parsed];
}
break;
}
}
}
function getAllResponseHeaders(route) {
const items = [];
for (const [key, value] of Object.entries(route.route.headers ?? {})) {
items.push({ op: "set", key, value, source: "headers" });
}
const transforms = route.route.transforms ?? [];
for (const t of transforms) {
if (t.type === "response.headers") {
items.push({
op: t.op,
key: typeof t.target.key === "string" ? t.target.key : JSON.stringify(t.target.key),
value: typeof t.args === "string" ? t.args : void 0,
source: "transform"
});
}
}
return items;
}
function formatResponseHeaderItem(item) {
if (item.op === "delete") {
return `${import_chalk2.default.yellow(item.op)} ${import_chalk2.default.cyan(item.key)}`;
}
return `${import_chalk2.default.yellow(item.op)} ${import_chalk2.default.cyan(item.key)} = ${item.value}`;
}
async function editResponseHeaders(client, route) {
for (; ; ) {
const allHeaders = getAllResponseHeaders(route);
if (allHeaders.length > 0) {
output_manager_default.print("\n");
output_manager_default.print(` ${import_chalk2.default.cyan("Response Headers:")}
`);
allHeaders.forEach((h, i) => {
output_manager_default.print(
` ${import_chalk2.default.gray(`${i + 1}.`)} ${formatResponseHeaderItem(h)}
`
);
});
output_manager_default.print("\n");
} else {
output_manager_default.print("\n No response headers set.\n\n");
}
const choices = [];
if (allHeaders.length > 0) {
choices.push({ name: "Remove a response header", value: "remove" });
}
choices.push({ name: "Add a response header", value: "add" });
choices.push({ name: "Back", value: "back" });
const action = await client.input.select({
message: "Response Headers:",
choices
});
if (action === "back")
break;
if (action === "remove") {
const toRemove = await client.input.select({
message: "Select response header to remove:",
choices: [
...allHeaders.map((h, i) => ({
name: h.op === "delete" ? `${h.op} ${h.key}` : `${h.op} ${h.key} = ${h.value}`,
value: i
})),
{ name: "Cancel", value: -1 }
]
});
if (toRemove !== -1) {
const item = allHeaders[toRemove];
if (item.source === "headers") {
const currentHeaders = { ...route.route.headers ?? {} };
delete currentHeaders[item.key];
route.route.headers = currentHeaders;
} else {
const transforms = route.route.transforms ?? [];
const idx = transforms.findIndex(
(t) => t.type === "response.headers" && t.op === item.op && (typeof t.target.key === "string" ? t.target.key : JSON.stringify(t.target.key)) === item.key
);
if (idx !== -1) {
transforms.splice(idx, 1);
route.route.transforms = transforms;
}
}
}
}
if (action === "add") {
const tempFlags = {};
await collectInteractiveHeaders(client, "response", tempFlags);
const setHeaders = tempFlags["--set-response-header"] || [];
for (const h of setHeaders) {
const eqIdx = h.indexOf("=");
if (eqIdx !== -1) {
const key = h.slice(0, eqIdx).trim();
const value = h.slice(eqIdx + 1);
route.route.headers = {
...route.route.headers ?? {},
[key]: value
};
}
}
const appendHeaders = tempFlags["--append-response-header"] || [];
const deleteHeaders = tempFlags["--delete-response-header"] || [];
const existing = route.route.transforms ?? [];
const newTransforms = [];
for (const h of appendHeaders) {
const eqIdx = h.indexOf("=");
if (eqIdx !== -1) {
newTransforms.push({
type: "response.headers",
op: "append",
target: { key: h.slice(0, eqIdx).trim() },
args: h.slice(eqIdx + 1)
});
}
}
for (const key of deleteHeaders) {
newTransforms.push({
type: "response.headers",
op: "delete",
target: { key: key.trim() }
});
}
if (newTransforms.length > 0) {
route.route.transforms = [...existing, ...newTransforms];
}
break;
}
}
}
async function editTransformsByType(client, route, transformType, headerType) {
const label = transformType === "request.headers" ? "Request Headers" : "Request Query";
const itemName = transformType === "request.headers" ? "request header" : "query parameter";
for (; ; ) {
const allTransforms = route.route.transforms ?? [];
const matching = allTransforms.filter((t) => t.type === transformType);
if (matching.length > 0) {
output_manager_default.print("\n");
output_manager_default.print(` ${import_chalk2.default.cyan(`${label}:`)}
`);
matching.forEach((t, i) => {
output_manager_default.print(
` ${import_chalk2.default.gray(`${i + 1}.`)} ${formatTransform(t)}
`
);
});
output_manager_default.print("\n");
} else {
output_manager_default.print(`
No ${label.toLowerCase()} set.
`);
}
const choices = [];
if (matching.length > 0) {
choices.push({ name: `Remove a ${itemName}`, value: "remove" });
}
choices.push({ name: `Add a ${itemName}`, value: "add" });
choices.push({ name: "Back", value: "back" });
const action = await client.input.select({
message: `${label}:`,
choices
});
if (action === "back")
break;
if (action === "remove") {
const toRemove = await client.input.select({
message: `Select ${itemName} to remove:`,
choices: [
...matching.map((t, i) => ({
name: formatTransform(t),
value: i
})),
{ name: "Cancel", value: -1 }
]
});
if (toRemove !== -1) {
let matchIdx = 0;
const removeIdx = allTransforms.findIndex((t) => {
if (t.type === transformType) {
if (matchIdx === toRemove)
return true;
matchIdx++;
}
return false;
});
if (removeIdx !== -1) {
allTransforms.splice(removeIdx, 1);
route.route.transforms = allTransforms;
}
}
}
if (action === "add") {
const tempFlags = {};
await collectInteractiveHeaders(client, headerType, tempFlags);
const tfFlags = extractTransformFlags(tempFlags);
const { transforms } = collectHeadersAndTransforms(tfFlags);
if (transforms.length > 0) {
route.route.transforms = [...allTransforms, ...transforms];
}
break;
}
}
}
export {
parseConditions,
populateRouteEnv,
generateRoute,
MAX_NAME_LENGTH,
MAX_DESCRIPTION_LENGTH,
MAX_CONDITIONS,
VALID_SYNTAXES,
REDIRECT_STATUS_CODES,
ALL_ACTION_CHOICES,
stripQuotes,
extractTransformFlags,
collectHeadersAndTransforms,
hasAnyTransformFlags,
validateActionFlags,
collectActionDetails,
collectInteractiveConditions,
generatedRouteToAddInput,
convertRouteToCurrentRoute,
routingRuleToCurrentRoute,
printGeneratedRoutePreview,
printRouteConfig,
cloneRoute,
applyFlagMutations,
runInteractiveEditLoop
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
getLinkedProject
} from "./chunk-BMTLRU2D.js";
import {
getCommandName,
getFlagsSpecification,
parseArguments,
printError
} from "./chunk-ZLCMHY2G.js";
import {
output_manager_default
} from "./chunk-FDJURQMQ.js";
import {
require_source
} from "./chunk-S7KYDPEM.js";
import {
__toESM
} from "./chunk-TZ2YI2VH.js";
// src/util/routes/types.ts
var ROUTE_TYPE_LABELS = {
rewrite: "Rewrite",
redirect: "Redirect",
set_status: "Set Status",
transform: "Transform"
};
function getRouteTypeLabel(rule) {
if (!rule.routeType)
return "-";
return ROUTE_TYPE_LABELS[rule.routeType] ?? "-";
}
var SRC_SYNTAX_LABELS = {
equals: "Exact Match",
"path-to-regexp": "Pattern",
regex: "Regex"
};
function getSrcSyntaxLabel(rule) {
const syntax = rule.srcSyntax ?? "regex";
return SRC_SYNTAX_LABELS[syntax];
}
// src/commands/routes/shared.ts
var import_chalk = __toESM(require_source(), 1);
async function parseSubcommandArgs(argv, command) {
let parsedArgs;
const flagsSpecification = getFlagsSpecification(command.options);
try {
parsedArgs = parseArguments(argv, flagsSpecification);
} catch (err) {
printError(err);
return 1;
}
return parsedArgs;
}
async function ensureProjectLink(client) {
const link = await getLinkedProject(client);
if (link.status === "error") {
return link.exitCode;
} else if (link.status === "not_linked") {
output_manager_default.error(
`Your codebase isn't linked to a project on Vercel. Run ${getCommandName("link")} to begin.`
);
return 1;
}
client.config.currentTeam = link.org.type === "team" ? link.org.id : void 0;
return link;
}
async function confirmAction(client, skipConfirmation, message, details) {
if (skipConfirmation)
return true;
if (details) {
output_manager_default.print(` ${details}
`);
}
return await client.input.confirm(message, false);
}
function validateRequiredArgs(args, required) {
for (let i = 0; i < required.length; i++) {
if (!args[i]) {
return `Missing required argument: ${required[i]}`;
}
}
return null;
}
function formatCondition(condition) {
const parts = [import_chalk.default.gray(`[${condition.type}]`)];
if (condition.key) {
parts.push(import_chalk.default.cyan(condition.key));
}
if (condition.value !== void 0) {
const formatted = typeof condition.value === "string" ? condition.value : JSON.stringify(condition.value);
parts.push(condition.key ? `= ${formatted}` : formatted);
}
return parts.join(" ");
}
var TRANSFORM_TYPE_LABELS = {
"request.headers": "Request Header",
"request.query": "Request Query",
"response.headers": "Response Header"
};
var TRANSFORM_OP_LABELS = {
set: "set",
append: "append",
delete: "delete"
};
function formatTransform(transform, includeType = true) {
const opLabel = TRANSFORM_OP_LABELS[transform.op] ?? transform.op;
const key = typeof transform.target.key === "string" ? transform.target.key : JSON.stringify(transform.target.key);
const parts = [];
if (includeType) {
const typeLabel = TRANSFORM_TYPE_LABELS[transform.type] ?? transform.type;
parts.push(import_chalk.default.gray(`[${typeLabel}]`));
}
parts.push(import_chalk.default.yellow(opLabel), import_chalk.default.cyan(key));
if (transform.args !== void 0 && transform.op !== "delete") {
const argsStr = Array.isArray(transform.args) ? transform.args.join(", ") : transform.args;
parts.push(`= ${argsStr}`);
}
return parts.join(" ");
}
function parsePosition(position) {
if (position === "start") {
return { placement: "start" };
}
if (position === "end") {
return { placement: "end" };
}
if (position.startsWith("after:")) {
const referenceId = position.slice(6);
if (!referenceId) {
throw new Error('Position "after:" requires a route ID');
}
return { placement: "after", referenceId };
}
if (position.startsWith("before:")) {
const referenceId = position.slice(7);
if (!referenceId) {
throw new Error('Position "before:" requires a route ID');
}
return { placement: "before", referenceId };
}
throw new Error(
`Invalid position: "${position}". Use: start, end, after:<id>, or before:<id>`
);
}
async function offerAutoPromote(client, projectId, version, hadExistingStagingVersion, opts) {
const { default: updateRouteVersion } = await import("./update-route-version-E3V47KNI.js");
const { default: stamp } = await import("./stamp-RTPE2EBB.js");
output_manager_default.print(
`
${import_chalk.default.gray(`This change is staged. Run ${import_chalk.default.cyan(getCommandName("routes publish"))} to make it live, or ${import_chalk.default.cyan(getCommandName("routes discard-staging"))} to undo.`)}
`
);
if (!hadExistingStagingVersion && !opts.skipPrompts) {
output_manager_default.print("\n");
const shouldPromote = await client.input.confirm(
"This is the only staged change. Promote to production now?",
false
);
if (shouldPromote) {
const promoteStamp = stamp();
output_manager_default.spinner("Promoting to production");
try {
await updateRouteVersion(client, projectId, version.id, "promote", {
teamId: opts.teamId
});
output_manager_default.log(
`${import_chalk.default.cyan("Promoted")} to production ${import_chalk.default.gray(promoteStamp())}`
);
} catch (e) {
const err = e;
output_manager_default.error(
`Failed to promote to production: ${err.message || "Unknown error"}`
);
}
}
} else if (hadExistingStagingVersion) {
output_manager_default.warn(
`There are other staged changes. Review with ${import_chalk.default.cyan(getCommandName("routes list --diff"))} before promoting.`
);
}
}
function printDiffSummary(routes, maxDisplay = 10) {
const displayRoutes = routes.slice(0, maxDisplay);
for (const route of displayRoutes) {
const symbol = getDiffSymbol(route);
const label = getDiffLabel(route);
const routeType = getRouteTypeLabel(route);
output_manager_default.print(
` ${symbol} ${route.name}${routeType !== "-" ? ` ${import_chalk.default.gray(`(${routeType})`)}` : ""} ${import_chalk.default.gray(`- ${label}`)}
`
);
}
if (routes.length > maxDisplay) {
output_manager_default.print(
import_chalk.default.gray(`
... and ${routes.length - maxDisplay} more changes
`)
);
}
}
function getDiffSymbol(route) {
if (route.action === "+")
return import_chalk.default.green("+");
if (route.action === "-")
return import_chalk.default.red("-");
return import_chalk.default.yellow("~");
}
function getDiffLabel(route) {
if (route.action === "+")
return "Added";
if (route.action === "-")
return "Deleted";
const isReordered = route.previousIndex !== void 0 && route.newIndex !== void 0;
if (isReordered) {
return `Reordered (${route.previousIndex + 1} \u2192 ${route.newIndex + 1})`;
}
if (route.previousEnabled !== void 0) {
return route.enabled === false ? "Disabled" : "Enabled";
}
return "Modified";
}
async function resolveRoute(client, routes, identifier) {
const byId = routes.find((r) => r.id === identifier);
if (byId)
return byId;
const query = identifier.toLowerCase();
const matches = routes.filter(
(r) => r.name.toLowerCase() === query || r.name.toLowerCase().includes(query) || r.id.toLowerCase().includes(query)
);
if (matches.length === 0) {
return null;
}
if (matches.length === 1) {
return matches[0];
}
const selectedId = await client.input.select({
message: `Multiple routes match "${identifier}". Select one:`,
choices: matches.map((route) => ({
value: route.id,
name: `${route.name} ${import_chalk.default.gray(`(${route.route.src})`)}`
}))
});
return matches.find((r) => r.id === selectedId) ?? null;
}
async function resolveRoutes(client, routes, identifiers) {
const resolved = /* @__PURE__ */ new Map();
for (const identifier of identifiers) {
const route = await resolveRoute(client, routes, identifier);
if (!route) {
output_manager_default.error(
`No route found matching "${identifier}". Run ${import_chalk.default.cyan(
getCommandName("routes list")
)} to see all routes.`
);
return null;
}
resolved.set(route.id, route);
}
return Array.from(resolved.values());
}
function findVersionById(versions, identifier) {
const matchingVersions = versions.filter((v) => v.id.startsWith(identifier));
if (matchingVersions.length === 0) {
return {
error: `Version "${identifier}" not found. Run ${import_chalk.default.cyan(
getCommandName("routes list-versions")
)} to see available versions.`
};
}
if (matchingVersions.length > 1) {
return {
error: `Multiple versions match "${identifier}". Please provide a more specific ID:
${matchingVersions.map((v) => ` ${v.id}`).join("\n")}`
};
}
return { version: matchingVersions[0] };
}
// src/util/routes/get-routes.ts
async function getRoutes(client, projectId, options = {}) {
const { teamId, search, filter, versionId, diff } = options;
const query = new URLSearchParams();
if (teamId)
query.set("teamId", teamId);
if (search)
query.set("q", search);
if (filter)
query.set("filter", filter);
if (versionId)
query.set("versionId", versionId);
if (diff)
query.set("diff", "true");
const queryString = query.toString();
const url = `/v1/projects/${projectId}/routes${queryString ? `?${queryString}` : ""}`;
const response = await client.fetch(url);
return response;
}
export {
getRouteTypeLabel,
getSrcSyntaxLabel,
parseSubcommandArgs,
ensureProjectLink,
confirmAction,
validateRequiredArgs,
formatCondition,
TRANSFORM_TYPE_LABELS,
formatTransform,
parsePosition,
offerAutoPromote,
printDiffSummary,
resolveRoute,
resolveRoutes,
findVersionById,
getRoutes
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
getEnvTargetPlaceholder
} from "./chunk-BMTLRU2D.js";
import {
packageName,
yesOption
} from "./chunk-ZLCMHY2G.js";
// src/commands/build/command.ts
var buildCommand = {
name: "build",
aliases: [],
description: "Build the project.",
arguments: [],
options: [
{
name: "prod",
description: "Build a production deployment",
shorthand: null,
type: Boolean,
deprecated: false
},
{
name: "target",
shorthand: null,
type: String,
argument: "TARGET",
deprecated: false,
description: "Specify the target environment"
},
{
name: "output",
description: "Directory where built assets will be written to",
shorthand: null,
argument: "DIR",
type: String,
deprecated: false
},
{
...yesOption,
description: "Skip the confirmation prompt about pulling environment variables and project settings when not found locally"
},
{
name: "standalone",
description: "Create a standalone build with all dependencies inlined into function output folders",
shorthand: null,
type: Boolean,
deprecated: false
}
],
examples: [
{
name: "Build the project",
value: `${packageName} build`
},
{
name: "Build the project in a specific directory",
value: `${packageName} build --cwd ./path-to-project`
}
]
};
// src/commands/pull/command.ts
var pullCommand = {
name: "pull",
aliases: [],
description: "Pull latest environment variables and project settings from Vercel. ",
arguments: [
{
name: "project-path",
required: false
}
],
options: [
{
name: "environment",
description: "Deployment environment [development]",
argument: "TARGET",
shorthand: null,
type: String,
deprecated: false
},
{
name: "git-branch",
description: "Specify the Git branch to pull specific Environment Variables for",
argument: "NAME",
shorthand: null,
type: String,
deprecated: false
},
{
name: "prod",
shorthand: null,
type: Boolean,
deprecated: false
},
{
...yesOption,
description: "Skip questions when setting up new project using default scope and settings"
}
],
examples: [
{
name: "Pull the latest Environment Variables and Project Settings from the cloud",
value: `${packageName} pull`
},
{
name: "Pull the latest Environment Variables and Project Settings from the cloud targeting a directory",
value: `${packageName} pull ./path-to-project`
},
{
name: "Pull for a specific environment",
value: `${packageName} pull --environment=${getEnvTargetPlaceholder()}`
},
{
name: "Pull for a preview feature branch",
value: `${packageName} pull --environment=preview --git-branch=feature-branch`
},
{
name: "If you want to download environment variables to a specific file, use `vercel env pull` instead",
value: `${packageName} env pull`
}
]
};
export {
buildCommand,
pullCommand
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
VERCEL_DIR
} from "./chunk-BMTLRU2D.js";
import {
ConflictingConfigFiles
} from "./chunk-ZLCMHY2G.js";
import {
output_manager_default
} from "./chunk-FDJURQMQ.js";
import {
__commonJS,
__require,
__toESM
} from "./chunk-TZ2YI2VH.js";
// ../../node_modules/.pnpm/dotenv@4.0.0/node_modules/dotenv/lib/main.js
var require_main = __commonJS({
"../../node_modules/.pnpm/dotenv@4.0.0/node_modules/dotenv/lib/main.js"(exports, module) {
"use strict";
var fs = __require("fs");
function parse(src) {
var obj = {};
src.toString().split("\n").forEach(function(line) {
var keyValueArr = line.match(/^\s*([\w\.\-]+)\s*=\s*(.*)?\s*$/);
if (keyValueArr != null) {
var key = keyValueArr[1];
var value = keyValueArr[2] ? keyValueArr[2] : "";
var len = value ? value.length : 0;
if (len > 0 && value.charAt(0) === '"' && value.charAt(len - 1) === '"') {
value = value.replace(/\\n/gm, "\n");
}
value = value.replace(/(^['"]|['"]$)/g, "").trim();
obj[key] = value;
}
});
return obj;
}
function config(options) {
var path = ".env";
var encoding = "utf8";
if (options) {
if (options.path) {
path = options.path;
}
if (options.encoding) {
encoding = options.encoding;
}
}
try {
var parsedObj = parse(fs.readFileSync(path, { encoding }));
Object.keys(parsedObj).forEach(function(key) {
process.env[key] = process.env[key] || parsedObj[key];
});
return { parsed: parsedObj };
} catch (e) {
return { error: e };
}
}
module.exports.config = config;
module.exports.load = config;
module.exports.parse = parse;
}
});
// src/util/compile-vercel-config.ts
var import_dotenv = __toESM(require_main(), 1);
import { mkdir, writeFile, unlink, access } from "fs/promises";
import { join, basename } from "path";
import { fork } from "child_process";
import { NowBuildError } from "@vercel/build-utils";
function toRouteFormat(item) {
if ("src" in item)
return item;
const { source, destination, headers, statusCode, permanent, ...rest } = item;
const route = {
src: source,
...rest
};
if (destination)
route.dest = destination;
if (headers)
route.headers = Object.fromEntries(headers.map((h) => [h.key, h.value]));
if (statusCode !== void 0) {
route.status = statusCode;
} else if (permanent !== void 0) {
route.status = permanent ? 308 : 307;
}
return route;
}
function normalizeConfig(config) {
const normalized = { ...config };
const { rewrites, redirects, headers } = normalized;
let allRoutes = normalized.routes || [];
const hasRoutes = allRoutes.length > 0;
const hasRewrites = (rewrites?.length ?? 0) > 0;
const hasRedirects = (redirects?.length ?? 0) > 0;
const hasHeaders = (headers?.length ?? 0) > 0;
function hasRouteFormat(items) {
return items?.some((item) => "src" in item) ?? false;
}
if (hasRoutes && (hasRewrites || hasRedirects || hasHeaders)) {
return normalized;
}
const shouldConvertRewrites = hasRewrites && hasRouteFormat(rewrites);
const shouldConvertRedirects = hasRedirects && hasRouteFormat(redirects);
const shouldConvertHeaders = hasHeaders && hasRouteFormat(headers);
const someWillConvert = shouldConvertRewrites || shouldConvertRedirects || shouldConvertHeaders;
const someWontConvert = hasRewrites && !shouldConvertRewrites || hasRedirects && !shouldConvertRedirects || hasHeaders && !shouldConvertHeaders;
if (someWillConvert && someWontConvert) {
throw new NowBuildError({
code: "INVALID_VERCEL_CONFIG",
message: "Transforms (e.g., requestHeaders) require the `routes` format, which cannot be used alongside `rewrites`, `redirects`, or `headers`. Move everything into the `routes` array instead.",
link: "https://vercel.com/docs/projects/project-configuration#routes"
});
}
if (rewrites && shouldConvertRewrites) {
allRoutes = [...allRoutes, ...rewrites.map(toRouteFormat)];
delete normalized.rewrites;
}
if (redirects && shouldConvertRedirects) {
allRoutes = [...allRoutes, ...redirects.map(toRouteFormat)];
delete normalized.redirects;
}
if (headers && shouldConvertHeaders) {
allRoutes = [...allRoutes, ...headers.map(toRouteFormat)];
delete normalized.headers;
}
if (allRoutes.length > 0) {
normalized.routes = allRoutes.map(toRouteFormat);
}
return normalized;
}
var VERCEL_CONFIG_EXTENSIONS = [
"ts",
"mts",
"js",
"mjs",
"cjs"
];
var DEFAULT_VERCEL_CONFIG_FILENAME = "Vercel config";
async function fileExists(filePath) {
try {
await access(filePath);
return true;
} catch {
return false;
}
}
async function findAllVercelConfigFiles(workPath) {
const foundFiles = [];
for (const ext of VERCEL_CONFIG_EXTENSIONS) {
const configPath = join(workPath, `vercel.${ext}`);
if (await fileExists(configPath)) {
foundFiles.push(configPath);
}
}
return foundFiles;
}
async function findSourceVercelConfigFile(workPath) {
for (const ext of VERCEL_CONFIG_EXTENSIONS) {
const configPath = join(workPath, `vercel.${ext}`);
if (await fileExists(configPath)) {
return basename(configPath);
}
}
return null;
}
async function findVercelConfigFile(workPath) {
const foundFiles = await findAllVercelConfigFiles(workPath);
if (foundFiles.length > 1) {
throw new ConflictingConfigFiles(
foundFiles,
"Multiple vercel config files found. Please use only one configuration file.",
"https://vercel.com/docs/projects/project-configuration"
);
}
return foundFiles[0] || null;
}
function parseConfigLoaderError(stderr) {
if (!stderr.trim()) {
return "";
}
const moduleNotFoundMatch = stderr.match(
/Error \[ERR_MODULE_NOT_FOUND\]: Cannot find package '([^']+)'/
);
if (moduleNotFoundMatch) {
const packageName = moduleNotFoundMatch[1];
return `Cannot find package '${packageName}'. Make sure it's installed in your project dependencies.`;
}
const syntaxErrorMatch = stderr.match(/SyntaxError: (.+?)(?:\n|$)/);
if (syntaxErrorMatch) {
return `Syntax error: ${syntaxErrorMatch[1]}`;
}
const errorMatch = stderr.match(
/^(?:Error|TypeError|ReferenceError): (.+?)(?:\n|$)/m
);
if (errorMatch) {
return errorMatch[1];
}
return stderr.trim();
}
async function compileVercelConfig(workPath) {
const vercelJsonPath = join(workPath, "vercel.json");
const nowJsonPath = join(workPath, "now.json");
const hasVercelJson = await fileExists(vercelJsonPath);
const hasNowJson = await fileExists(nowJsonPath);
if (hasVercelJson && hasNowJson) {
throw new ConflictingConfigFiles([vercelJsonPath, nowJsonPath]);
}
const vercelConfigPath = await findVercelConfigFile(workPath);
const vercelDir = join(workPath, VERCEL_DIR);
const compiledConfigPath = join(vercelDir, "vercel.json");
if (vercelConfigPath && hasNowJson) {
throw new ConflictingConfigFiles(
[vercelConfigPath, nowJsonPath],
`Both ${basename(vercelConfigPath)} and now.json exist in your project. Please use only one configuration method.`,
"https://vercel.com/docs/projects/project-configuration"
);
}
if (vercelConfigPath && hasVercelJson) {
throw new ConflictingConfigFiles(
[vercelConfigPath, vercelJsonPath],
`Both ${basename(vercelConfigPath)} and vercel.json exist in your project. Please use only one configuration method.`,
"https://vercel.com/docs/projects/project-configuration"
);
}
if (!vercelConfigPath) {
if (hasVercelJson) {
return {
configPath: vercelJsonPath,
wasCompiled: false
};
}
if (hasNowJson) {
return {
configPath: nowJsonPath,
wasCompiled: false
};
}
if (await fileExists(compiledConfigPath)) {
return {
configPath: compiledConfigPath,
wasCompiled: true,
sourceFile: await findSourceVercelConfigFile(workPath) ?? void 0
};
}
return {
configPath: null,
wasCompiled: false
};
}
(0, import_dotenv.config)({ path: join(workPath, ".env") });
(0, import_dotenv.config)({ path: join(workPath, ".env.local") });
const tempOutPath = join(vercelDir, "vercel-temp.mjs");
const loaderPath = join(vercelDir, "vercel-loader.mjs");
try {
const { build } = await import("esbuild");
await mkdir(vercelDir, { recursive: true });
await build({
entryPoints: [vercelConfigPath],
bundle: true,
platform: "node",
format: "esm",
outfile: tempOutPath,
packages: "external",
target: "node20",
sourcemap: "inline"
});
const loaderScript = `
import { pathToFileURL } from 'url';
const configModule = await import(pathToFileURL(process.argv[2]).href);
const config = ('default' in configModule) ? configModule.default : ('config' in configModule) ? configModule.config : configModule;
process.send(config);
`;
await writeFile(loaderPath, loaderScript, "utf-8");
const config = await new Promise((resolve, reject) => {
const child = fork(loaderPath, [tempOutPath], {
stdio: ["pipe", "pipe", "pipe", "ipc"]
});
let stderrOutput = "";
let stdoutOutput = "";
if (child.stderr) {
child.stderr.on("data", (data) => {
stderrOutput += data.toString();
});
}
if (child.stdout) {
child.stdout.on("data", (data) => {
stdoutOutput += data.toString();
});
}
const timeout = setTimeout(() => {
child.kill();
reject(new Error("Config loader timed out after 10 seconds"));
}, 1e4);
child.on("message", (message) => {
clearTimeout(timeout);
child.kill();
resolve(message);
});
child.on("error", (err) => {
clearTimeout(timeout);
reject(err);
});
child.on("exit", (code) => {
clearTimeout(timeout);
if (code !== 0) {
if (stderrOutput.trim()) {
output_manager_default.log(stderrOutput);
}
if (stdoutOutput.trim()) {
output_manager_default.log(stdoutOutput);
}
const parsedError = parseConfigLoaderError(stderrOutput);
if (parsedError) {
reject(new Error(parsedError));
} else if (stdoutOutput.trim()) {
reject(new Error(stdoutOutput.trim()));
} else {
reject(new Error(`Config loader exited with code ${code}`));
}
}
});
});
const normalizedConfig = normalizeConfig(config);
await writeFile(
compiledConfigPath,
JSON.stringify(normalizedConfig, null, 2),
"utf-8"
);
output_manager_default.debug(`Compiled ${vercelConfigPath} -> ${compiledConfigPath}`);
return {
configPath: compiledConfigPath,
wasCompiled: true,
sourceFile: await findSourceVercelConfigFile(workPath) ?? void 0
};
} catch (error) {
throw new NowBuildError({
code: error.code ?? "vercel_ts_compilation_failed",
message: `Failed to compile ${basename(vercelConfigPath)}: ${error.message}`,
link: error.link ?? "https://vercel.com/docs/projects/project-configuration"
});
} finally {
await Promise.all([
unlink(tempOutPath).catch((err) => {
if (err.code !== "ENOENT") {
output_manager_default.debug(`Failed to cleanup temp file: ${err}`);
}
}),
unlink(loaderPath).catch((err) => {
if (err.code !== "ENOENT") {
output_manager_default.debug(`Failed to cleanup loader file: ${err}`);
}
})
]);
}
}
async function getVercelConfigPath(workPath) {
const vercelJsonPath = join(workPath, "vercel.json");
const nowJsonPath = join(workPath, "now.json");
const compiledConfigPath = join(workPath, VERCEL_DIR, "vercel.json");
if (await fileExists(vercelJsonPath)) {
return vercelJsonPath;
}
if (await fileExists(nowJsonPath)) {
return nowJsonPath;
}
if (await fileExists(compiledConfigPath)) {
return compiledConfigPath;
}
return nowJsonPath;
}
export {
require_main,
normalizeConfig,
VERCEL_CONFIG_EXTENSIONS,
DEFAULT_VERCEL_CONFIG_FILENAME,
findSourceVercelConfigFile,
compileVercelConfig,
getVercelConfigPath
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
getTeamById,
getUser
} from "./chunk-BMTLRU2D.js";
import {
TeamDeleted
} from "./chunk-ZLCMHY2G.js";
// src/util/get-scope.ts
async function getScope(client, opts = {}) {
const user = await getUser(client);
let contextName = user.username || user.email;
let team = null;
const defaultTeamId = user.version === "northstar" ? user.defaultTeamId : void 0;
const currentTeamOrDefaultTeamId = client.config.currentTeam || defaultTeamId;
if (currentTeamOrDefaultTeamId && opts.getTeam !== false) {
team = await getTeamById(client, currentTeamOrDefaultTeamId);
if (!team) {
throw new TeamDeleted();
}
contextName = team.slug;
}
return { contextName, team, user };
}
export {
getScope
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
writeProjectSettings
} from "./chunk-XBSU7P56.js";
import {
ensureLink
} from "./chunk-L4CDAO6F.js";
import {
pullCommand
} from "./chunk-RGBET6N6.js";
import {
help
} from "./chunk-DOBFJJLK.js";
import {
VERCEL_DIR,
VERCEL_DIR_PROJECT,
envPullCommandLogic,
humanizePath,
parseTarget
} from "./chunk-BMTLRU2D.js";
import {
TelemetryClient
} from "./chunk-XB2KZC2B.js";
import {
stamp_default
} from "./chunk-SOTR4CXR.js";
import {
getFlagsSpecification,
parseArguments,
printError
} from "./chunk-ZLCMHY2G.js";
import {
emoji,
output_manager_default,
prependEmoji
} from "./chunk-FDJURQMQ.js";
import {
require_source
} from "./chunk-S7KYDPEM.js";
import {
__toESM
} from "./chunk-TZ2YI2VH.js";
// src/commands/pull/index.ts
var import_chalk = __toESM(require_source(), 1);
import { join } from "path";
// src/util/telemetry/commands/pull/index.ts
var PullTelemetryClient = class extends TelemetryClient {
trackCliArgumentProjectPath(value) {
if (value) {
this.trackCliArgument({
arg: "projectPath",
value: this.redactedValue
});
}
}
trackCliOptionEnvironment(environment) {
if (environment) {
this.trackCliOption({
option: "environment",
value: this.redactedTargetName(environment)
});
}
}
trackCliOptionGitBranch(gitBranch) {
if (gitBranch) {
this.trackCliOption({
option: "git-branch",
value: this.redactedValue
});
}
}
trackCliFlagProd(isProduction) {
if (isProduction) {
this.trackCliFlag("prod");
}
}
trackCliFlagYes(yes) {
if (yes) {
this.trackCliFlag("yes");
}
}
};
// src/commands/pull/index.ts
async function pullAllEnvFiles(environment, client, link, flags, cwd) {
const environmentFile = `.env.${environment}.local`;
await envPullCommandLogic(
client,
join(".vercel", environmentFile),
!!flags["--yes"],
environment,
link,
flags["--git-branch"],
cwd,
"vercel-cli:pull"
);
return 0;
}
async function main(client) {
let parsedArgs = null;
const flagsSpecification = getFlagsSpecification(pullCommand.options);
try {
parsedArgs = parseArguments(client.argv.slice(2), flagsSpecification);
} catch (error) {
printError(error);
return 1;
}
const telemetryClient = new PullTelemetryClient({
opts: {
store: client.telemetryEventStore
}
});
if (parsedArgs.flags["--help"]) {
telemetryClient.trackCliFlagHelp("pull");
output_manager_default.print(help(pullCommand, { columns: client.stderr.columns }));
return 2;
}
const cwd = parsedArgs.args[1] || client.cwd;
const autoConfirm = Boolean(parsedArgs.flags["--yes"]);
const isProduction = Boolean(parsedArgs.flags["--prod"]);
const environment = parseTarget({
flagName: "environment",
flags: parsedArgs.flags
}) || "development";
telemetryClient.trackCliArgumentProjectPath(parsedArgs.args[1]);
telemetryClient.trackCliFlagYes(autoConfirm);
telemetryClient.trackCliFlagProd(isProduction);
telemetryClient.trackCliOptionGitBranch(parsedArgs.flags["--git-branch"]);
telemetryClient.trackCliOptionEnvironment(parsedArgs.flags["--environment"]);
const returnCode = await pullCommandLogic(
client,
cwd,
autoConfirm,
environment,
parsedArgs.flags
);
return returnCode;
}
async function pullCommandLogic(client, cwd, autoConfirm, environment, flags) {
const link = await ensureLink("pull", client, cwd, {
autoConfirm,
pullEnv: false
});
if (typeof link === "number") {
return link;
}
const { project, org, repoRoot } = link;
let currentDirectory;
if (repoRoot) {
currentDirectory = join(repoRoot, project.rootDirectory || "");
} else {
currentDirectory = cwd;
}
client.config.currentTeam = org.type === "team" ? org.id : void 0;
const pullResultCode = await pullAllEnvFiles(
environment,
client,
link,
flags,
currentDirectory
);
if (pullResultCode !== 0) {
return pullResultCode;
}
output_manager_default.print("\n");
output_manager_default.log("Downloading project settings");
const isRepoLinked = typeof repoRoot === "string";
await writeProjectSettings(currentDirectory, project, org, isRepoLinked);
const settingsStamp = stamp_default();
output_manager_default.print(
`${prependEmoji(
`Downloaded project settings to ${import_chalk.default.bold(
humanizePath(join(currentDirectory, VERCEL_DIR, VERCEL_DIR_PROJECT))
)} ${import_chalk.default.gray(settingsStamp())}`,
emoji("success")
)}
`
);
return 0;
}
export {
main,
pullCommandLogic
};

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
VERCEL_DIR,
VERCEL_DIR_PROJECT,
require_lib
} from "./chunk-BMTLRU2D.js";
import {
require_dist
} from "./chunk-FDJURQMQ.js";
import {
__toESM
} from "./chunk-TZ2YI2VH.js";
// src/util/projects/project-settings.ts
var import_fs_extra = __toESM(require_lib(), 1);
import { join } from "path";
var import_error_utils = __toESM(require_dist(), 1);
async function writeProjectSettings(cwd, project, org, isRepoLinked) {
let analyticsId;
if (project.analytics?.id && (!project.analytics.disabledAt || project.analytics.enabledAt && project.analytics.enabledAt > project.analytics.disabledAt)) {
analyticsId = project.analytics.id;
}
const projectLinkAndSettings = {
projectId: isRepoLinked ? void 0 : project.id,
orgId: isRepoLinked ? void 0 : org.id,
projectName: isRepoLinked ? void 0 : project.name,
settings: {
createdAt: project.createdAt,
framework: project.framework,
devCommand: project.devCommand,
installCommand: project.installCommand,
buildCommand: project.buildCommand,
outputDirectory: project.outputDirectory,
rootDirectory: project.rootDirectory,
directoryListing: project.directoryListing,
nodeVersion: project.nodeVersion,
analyticsId
}
};
const path = join(cwd, VERCEL_DIR, VERCEL_DIR_PROJECT);
return await (0, import_fs_extra.outputJSON)(path, projectLinkAndSettings, {
spaces: 2
});
}
async function readProjectSettings(vercelDir) {
try {
return JSON.parse(
await (0, import_fs_extra.readFile)(join(vercelDir, VERCEL_DIR_PROJECT), "utf8")
);
} catch (err) {
if ((0, import_error_utils.isErrnoException)(err) && err.code && ["ENOENT", "ENOTDIR"].includes(err.code)) {
return null;
}
if ((0, import_error_utils.isError)(err) && err.name === "SyntaxError") {
return null;
}
throw err;
}
}
function pickOverrides(vercelConfig) {
const overrides = {};
for (const prop of [
"buildCommand",
"devCommand",
"framework",
"ignoreCommand",
"installCommand",
"outputDirectory"
]) {
if (typeof vercelConfig[prop] !== "undefined") {
if (prop === "ignoreCommand") {
overrides.commandForIgnoringBuildStep = vercelConfig[prop];
} else {
overrides[prop] = vercelConfig[prop];
}
}
}
return overrides;
}
export {
writeProjectSettings,
readProjectSettings,
pickOverrides
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
DEFAULT_VERCEL_CONFIG_FILENAME,
VERCEL_CONFIG_EXTENSIONS,
compileVercelConfig,
findSourceVercelConfigFile,
getVercelConfigPath,
normalizeConfig
} from "./chunk-RR4BD6FR.js";
import "./chunk-BMTLRU2D.js";
import "./chunk-XB2KZC2B.js";
import "./chunk-SOTR4CXR.js";
import "./chunk-7EHTK7LP.js";
import "./chunk-GGP5R3FU.js";
import "./chunk-ZLCMHY2G.js";
import "./chunk-3XFFP2BA.js";
import "./chunk-FDJURQMQ.js";
import "./chunk-S7KYDPEM.js";
import "./chunk-TZ2YI2VH.js";
export {
DEFAULT_VERCEL_CONFIG_FILENAME,
VERCEL_CONFIG_EXTENSIONS,
compileVercelConfig,
findSourceVercelConfigFile,
getVercelConfigPath,
normalizeConfig
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
getRouteVersions
} from "./chunk-AHU7WNL2.js";
import {
ensureProjectLink,
getRouteTypeLabel,
getRoutes,
offerAutoPromote,
parseSubcommandArgs,
resolveRoutes
} from "./chunk-PAX6W6YL.js";
import {
deleteSubcommand
} from "./chunk-U6XOC6E4.js";
import "./chunk-BMTLRU2D.js";
import "./chunk-XB2KZC2B.js";
import {
stamp_default
} from "./chunk-SOTR4CXR.js";
import "./chunk-7EHTK7LP.js";
import "./chunk-GGP5R3FU.js";
import {
getCommandName
} from "./chunk-ZLCMHY2G.js";
import "./chunk-3XFFP2BA.js";
import {
output_manager_default
} from "./chunk-FDJURQMQ.js";
import {
require_source
} from "./chunk-S7KYDPEM.js";
import {
__toESM
} from "./chunk-TZ2YI2VH.js";
// src/commands/routes/delete.ts
var import_chalk = __toESM(require_source(), 1);
// src/util/routes/delete-routes.ts
async function deleteRoutes(client, projectId, routeIds, options = {}) {
const { teamId } = options;
const query = new URLSearchParams();
if (teamId)
query.set("teamId", teamId);
const queryString = query.toString();
const url = `/v1/projects/${projectId}/routes${queryString ? `?${queryString}` : ""}`;
return await client.fetch(url, {
method: "DELETE",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ routeIds })
});
}
// src/commands/routes/delete.ts
async function deleteRoute(client, argv) {
const parsed = await parseSubcommandArgs(argv, deleteSubcommand);
if (typeof parsed === "number")
return parsed;
const link = await ensureProjectLink(client);
if (typeof link === "number")
return link;
const { project, org } = link;
const teamId = org.type === "team" ? org.id : void 0;
const { args, flags } = parsed;
const skipConfirmation = flags["--yes"];
if (args.length === 0) {
output_manager_default.error(
`At least one route name or ID is required. Usage: ${getCommandName("routes delete <name-or-id> [...]")}`
);
return 1;
}
const { versions } = await getRouteVersions(client, project.id, { teamId });
const existingStagingVersion = versions.find((v) => v.isStaging);
output_manager_default.spinner("Fetching routes");
const { routes } = await getRoutes(client, project.id, { teamId });
output_manager_default.stopSpinner();
if (routes.length === 0) {
output_manager_default.error("No routes found in this project.");
return 1;
}
const resolved = await resolveRoutes(client, routes, args);
if (!resolved)
return 1;
output_manager_default.print("\n");
output_manager_default.log(
`The following ${resolved.length === 1 ? "route" : `${resolved.length} routes`} will be deleted:`
);
for (const route of resolved) {
const typeLabels = getRouteTypeLabel(route);
output_manager_default.print(
` ${import_chalk.default.red("\xD7")} ${route.name} ${import_chalk.default.gray(`(${route.route.src})`)} ${import_chalk.default.gray(`[${typeLabels}]`)}
`
);
}
output_manager_default.print("\n");
if (!skipConfirmation) {
const confirmed = await client.input.confirm(
`Delete ${resolved.length === 1 ? "this route" : `these ${resolved.length} routes`}?`,
false
);
if (!confirmed) {
output_manager_default.log("Aborted.");
return 0;
}
}
const deleteStamp = stamp_default();
output_manager_default.spinner(
`Deleting ${resolved.length === 1 ? "route" : `${resolved.length} routes`}`
);
try {
const { deletedCount, version } = await deleteRoutes(
client,
project.id,
resolved.map((r) => r.id),
{ teamId }
);
output_manager_default.log(
`${import_chalk.default.cyan("Deleted")} ${deletedCount} ${deletedCount === 1 ? "route" : "routes"} ${import_chalk.default.gray(deleteStamp())}`
);
await offerAutoPromote(
client,
project.id,
version,
!!existingStagingVersion,
{ teamId, skipPrompts: skipConfirmation }
);
return 0;
} catch (e) {
const error = e;
output_manager_default.error(error.message || "Failed to delete routes");
return 1;
}
}
export {
deleteRoute as default
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
editRoute
} from "./chunk-P3SKP5WM.js";
import {
getRouteVersions
} from "./chunk-AHU7WNL2.js";
import {
ensureProjectLink,
getRoutes,
offerAutoPromote,
parseSubcommandArgs,
resolveRoute
} from "./chunk-PAX6W6YL.js";
import {
disableSubcommand
} from "./chunk-U6XOC6E4.js";
import "./chunk-BMTLRU2D.js";
import "./chunk-XB2KZC2B.js";
import {
stamp_default
} from "./chunk-SOTR4CXR.js";
import "./chunk-7EHTK7LP.js";
import "./chunk-GGP5R3FU.js";
import {
getCommandName
} from "./chunk-ZLCMHY2G.js";
import "./chunk-3XFFP2BA.js";
import {
output_manager_default
} from "./chunk-FDJURQMQ.js";
import {
require_source
} from "./chunk-S7KYDPEM.js";
import {
__toESM
} from "./chunk-TZ2YI2VH.js";
// src/commands/routes/disable.ts
var import_chalk = __toESM(require_source(), 1);
async function disable(client, argv) {
const parsed = await parseSubcommandArgs(argv, disableSubcommand);
if (typeof parsed === "number")
return parsed;
const link = await ensureProjectLink(client);
if (typeof link === "number")
return link;
const { project, org } = link;
const teamId = org.type === "team" ? org.id : void 0;
const { args } = parsed;
const identifier = args[0];
if (!identifier) {
output_manager_default.error(
`Route name or ID is required. Usage: ${getCommandName("routes disable <name-or-id>")}`
);
return 1;
}
const { versions } = await getRouteVersions(client, project.id, { teamId });
const existingStagingVersion = versions.find((v) => v.isStaging);
output_manager_default.spinner("Fetching routes");
const { routes } = await getRoutes(client, project.id, { teamId });
output_manager_default.stopSpinner();
if (routes.length === 0) {
output_manager_default.error("No routes found in this project.");
return 1;
}
const route = await resolveRoute(client, routes, identifier);
if (!route) {
output_manager_default.error(
`No route found matching "${identifier}". Run ${import_chalk.default.cyan(
getCommandName("routes list")
)} to see all routes.`
);
return 1;
}
if (route.enabled === false) {
output_manager_default.log(`Route "${route.name}" is already disabled.`);
return 0;
}
const disableStamp = stamp_default();
output_manager_default.spinner(`Disabling route "${route.name}"`);
try {
const { version } = await editRoute(
client,
project.id,
route.id,
{
route: {
name: route.name,
description: route.description,
enabled: false,
srcSyntax: route.srcSyntax,
route: route.route
}
},
{ teamId }
);
output_manager_default.log(
`${import_chalk.default.cyan("Disabled")} route "${route.name}" ${import_chalk.default.gray(disableStamp())}`
);
await offerAutoPromote(
client,
project.id,
version,
!!existingStagingVersion,
{ teamId }
);
return 0;
} catch (e) {
const error = e;
output_manager_default.error(error.message || "Failed to disable route");
return 1;
}
}
export {
disable as default
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
updateRouteVersion
} from "./chunk-PMSMUMUO.js";
import {
getRouteVersions
} from "./chunk-AHU7WNL2.js";
import {
confirmAction,
ensureProjectLink,
getRoutes,
parseSubcommandArgs,
printDiffSummary
} from "./chunk-PAX6W6YL.js";
import {
discardSubcommand
} from "./chunk-U6XOC6E4.js";
import "./chunk-BMTLRU2D.js";
import "./chunk-XB2KZC2B.js";
import {
stamp_default
} from "./chunk-SOTR4CXR.js";
import "./chunk-7EHTK7LP.js";
import "./chunk-GGP5R3FU.js";
import {
getCommandName
} from "./chunk-ZLCMHY2G.js";
import "./chunk-3XFFP2BA.js";
import {
output_manager_default
} from "./chunk-FDJURQMQ.js";
import {
require_source
} from "./chunk-S7KYDPEM.js";
import {
__toESM
} from "./chunk-TZ2YI2VH.js";
// src/commands/routes/discard.ts
var import_chalk = __toESM(require_source(), 1);
async function discard(client, argv) {
const parsed = await parseSubcommandArgs(argv, discardSubcommand);
if (typeof parsed === "number")
return parsed;
const link = await ensureProjectLink(client);
if (typeof link === "number")
return link;
const { project, org } = link;
const teamId = org.type === "team" ? org.id : void 0;
output_manager_default.spinner(`Fetching route versions for ${import_chalk.default.bold(project.name)}`);
const { versions } = await getRouteVersions(client, project.id, { teamId });
const stagingVersion = versions.find((v) => v.isStaging);
if (!stagingVersion) {
output_manager_default.warn(
`No staged changes to discard. Make changes first with ${import_chalk.default.cyan(
getCommandName("routes add")
)}.`
);
return 0;
}
output_manager_default.spinner("Fetching staged changes");
const { routes: diffRoutes } = await getRoutes(client, project.id, {
teamId,
versionId: stagingVersion.id,
diff: true
});
const changedRoutes = diffRoutes.filter((r) => r.action !== void 0);
if (changedRoutes.length > 0) {
output_manager_default.print(`
${import_chalk.default.bold("Changes to be discarded:")}
`);
printDiffSummary(changedRoutes);
output_manager_default.print("\n");
} else {
output_manager_default.print(
`
${import_chalk.default.gray("No changes detected in staging version.")}
`
);
}
const confirmed = await confirmAction(
client,
parsed.flags["--yes"],
"Discard all staged changes?",
`This action cannot be undone.`
);
if (!confirmed) {
output_manager_default.log("Canceled");
return 0;
}
const updateStamp = stamp_default();
output_manager_default.spinner("Discarding staged changes");
try {
await updateRouteVersion(client, project.id, stagingVersion.id, "discard", {
teamId
});
output_manager_default.log(
`${import_chalk.default.cyan("Success!")} Staged changes discarded ${import_chalk.default.gray(
updateStamp()
)}`
);
return 0;
} catch (e) {
const error = e;
output_manager_default.error(error.message || "Failed to discard staged changes");
return 1;
}
}
export {
discard as default
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
editRoute
} from "./chunk-P3SKP5WM.js";
import {
applyFlagMutations,
cloneRoute,
convertRouteToCurrentRoute,
generateRoute,
generatedRouteToAddInput,
hasAnyTransformFlags,
populateRouteEnv,
printGeneratedRoutePreview,
printRouteConfig,
routingRuleToCurrentRoute,
runInteractiveEditLoop
} from "./chunk-P67ZYUA2.js";
import {
getRouteVersions
} from "./chunk-AHU7WNL2.js";
import {
ensureProjectLink,
getRoutes,
offerAutoPromote,
parseSubcommandArgs,
resolveRoute
} from "./chunk-PAX6W6YL.js";
import {
editSubcommand
} from "./chunk-U6XOC6E4.js";
import "./chunk-BMTLRU2D.js";
import "./chunk-XB2KZC2B.js";
import {
stamp_default
} from "./chunk-SOTR4CXR.js";
import "./chunk-7EHTK7LP.js";
import "./chunk-GGP5R3FU.js";
import {
getCommandName
} from "./chunk-ZLCMHY2G.js";
import "./chunk-3XFFP2BA.js";
import {
output_manager_default
} from "./chunk-FDJURQMQ.js";
import {
require_source
} from "./chunk-S7KYDPEM.js";
import {
__toESM
} from "./chunk-TZ2YI2VH.js";
// src/commands/routes/edit.ts
var import_chalk = __toESM(require_source(), 1);
async function edit(client, argv) {
const parsed = await parseSubcommandArgs(argv, editSubcommand);
if (typeof parsed === "number")
return parsed;
const link = await ensureProjectLink(client);
if (typeof link === "number")
return link;
const { project, org } = link;
const teamId = org.type === "team" ? org.id : void 0;
const { args, flags } = parsed;
const skipConfirmation = flags["--yes"];
const identifier = args[0];
const { RoutesEditTelemetryClient } = await import("./routes-DGDHCTY6.js");
const telemetry = new RoutesEditTelemetryClient({
opts: { store: client.telemetryEventStore }
});
telemetry.trackCliArgumentNameOrId(identifier);
telemetry.trackCliFlagYes(skipConfirmation);
telemetry.trackCliOptionName(flags["--name"]);
telemetry.trackCliOptionDescription(
flags["--description"]
);
telemetry.trackCliOptionSrc(flags["--src"]);
telemetry.trackCliOptionSrcSyntax(
flags["--src-syntax"]
);
telemetry.trackCliOptionAction(flags["--action"]);
telemetry.trackCliOptionDest(flags["--dest"]);
telemetry.trackCliOptionStatus(flags["--status"]);
telemetry.trackCliFlagNoDest(flags["--no-dest"]);
telemetry.trackCliFlagNoStatus(flags["--no-status"]);
telemetry.trackCliFlagClearConditions(
flags["--clear-conditions"]
);
telemetry.trackCliFlagClearHeaders(
flags["--clear-headers"]
);
telemetry.trackCliFlagClearTransforms(
flags["--clear-transforms"]
);
telemetry.trackCliOptionSetResponseHeader(
flags["--set-response-header"]
);
telemetry.trackCliOptionAppendResponseHeader(
flags["--append-response-header"]
);
telemetry.trackCliOptionDeleteResponseHeader(
flags["--delete-response-header"]
);
telemetry.trackCliOptionSetRequestHeader(
flags["--set-request-header"]
);
telemetry.trackCliOptionAppendRequestHeader(
flags["--append-request-header"]
);
telemetry.trackCliOptionDeleteRequestHeader(
flags["--delete-request-header"]
);
telemetry.trackCliOptionSetRequestQuery(
flags["--set-request-query"]
);
telemetry.trackCliOptionAppendRequestQuery(
flags["--append-request-query"]
);
telemetry.trackCliOptionDeleteRequestQuery(
flags["--delete-request-query"]
);
telemetry.trackCliOptionHas(flags["--has"]);
telemetry.trackCliOptionMissing(flags["--missing"]);
telemetry.trackCliOptionAi(flags["--ai"]);
if (!identifier) {
output_manager_default.error(
`Route name or ID is required. Usage: ${getCommandName("routes edit <name-or-id>")}`
);
return 1;
}
const { versions } = await getRouteVersions(client, project.id, { teamId });
const existingStagingVersion = versions.find((v) => v.isStaging);
output_manager_default.spinner("Fetching routes");
const { routes } = await getRoutes(client, project.id, { teamId });
output_manager_default.stopSpinner();
if (routes.length === 0) {
output_manager_default.error("No routes found in this project.");
return 1;
}
const originalRoute = await resolveRoute(client, routes, identifier);
if (!originalRoute) {
output_manager_default.error(
`No route found matching "${identifier}". Run ${import_chalk.default.cyan(
getCommandName("routes list")
)} to see all routes.`
);
return 1;
}
const aiPrompt = flags["--ai"];
if (aiPrompt) {
const conflictingFlags = [
"--name",
"--description",
"--src",
"--src-syntax",
"--action",
"--dest",
"--status",
"--no-dest",
"--no-status",
"--has",
"--missing",
"--set-response-header",
"--append-response-header",
"--delete-response-header",
"--set-request-header",
"--append-request-header",
"--delete-request-header",
"--set-request-query",
"--append-request-query",
"--delete-request-query",
"--clear-conditions",
"--clear-headers",
"--clear-transforms"
];
const usedConflicts = conflictingFlags.filter((f) => flags[f] !== void 0);
if (usedConflicts.length > 0) {
output_manager_default.error(
`Cannot use --ai with ${usedConflicts.join(", ")}. Use --ai alone to describe changes.`
);
return 1;
}
return await handleAIEdit(
client,
project.id,
teamId,
originalRoute,
aiPrompt,
skipConfirmation,
existingStagingVersion
);
}
const route = cloneRoute(originalRoute);
const hasEditFlags = flags["--name"] !== void 0 || flags["--description"] !== void 0 || flags["--src"] !== void 0 || flags["--src-syntax"] !== void 0 || flags["--action"] !== void 0 || flags["--dest"] !== void 0 || flags["--status"] !== void 0 || flags["--no-dest"] !== void 0 || flags["--no-status"] !== void 0 || flags["--has"] !== void 0 || flags["--missing"] !== void 0 || flags["--clear-conditions"] !== void 0 || flags["--clear-headers"] !== void 0 || flags["--clear-transforms"] !== void 0 || hasAnyTransformFlags(flags);
if (hasEditFlags) {
const error = applyFlagMutations(route, flags);
if (error) {
output_manager_default.error(error);
return 1;
}
} else {
if (!client.stdin.isTTY) {
output_manager_default.error(
`No edit flags provided. When running non-interactively, use flags like --name, --dest, --src, etc. Run ${getCommandName("routes edit --help")} for all options.`
);
return 1;
}
output_manager_default.log(`
Editing route "${originalRoute.name}"`);
printRouteConfig(route);
const editMode = await client.input.select({
message: "How would you like to edit this route?",
choices: [
{ name: "Describe changes (AI-powered)", value: "ai" },
{ name: "Edit manually (field by field)", value: "manual" }
]
});
if (editMode === "ai") {
telemetry.trackCliOptionAi("interactive");
return await handleAIEdit(
client,
project.id,
teamId,
originalRoute,
void 0,
skipConfirmation,
existingStagingVersion
);
}
await runInteractiveEditLoop(client, route);
}
populateRouteEnv(route.route);
if (JSON.stringify(route) === JSON.stringify(originalRoute)) {
output_manager_default.log("No changes made.");
return 0;
}
const editStamp = stamp_default();
output_manager_default.spinner(`Updating route "${route.name}"`);
try {
const { version } = await editRoute(
client,
project.id,
originalRoute.id,
{
route: {
name: route.name,
description: route.description,
enabled: route.enabled,
srcSyntax: route.srcSyntax,
route: route.route
}
},
{ teamId }
);
output_manager_default.log(
`${import_chalk.default.cyan("Updated")} route "${route.name}" ${import_chalk.default.gray(editStamp())}`
);
await offerAutoPromote(
client,
project.id,
version,
!!existingStagingVersion,
{ teamId, skipPrompts: skipConfirmation }
);
return 0;
} catch (e) {
const error = e;
output_manager_default.error(error.message || "Failed to update route");
return 1;
}
}
async function handleAIEdit(client, projectId, teamId, originalRoute, aiPrompt, skipConfirmation, existingStagingVersion) {
const currentRoute = routingRuleToCurrentRoute(originalRoute);
let prompt = aiPrompt;
let currentGenerated;
for (; ; ) {
if (!prompt) {
prompt = await client.input.text({
message: "Describe what you'd like to change:",
validate: (val) => {
if (!val)
return "A description is required";
if (val.length > 2e3)
return "Description must be 2000 characters or less";
return true;
}
});
}
output_manager_default.spinner("Generating updated route...");
let errorMessage;
try {
const result = await generateRoute(
client,
projectId,
{ prompt, currentRoute },
{ teamId }
);
if (result.error) {
errorMessage = result.error;
} else if (!result.route) {
errorMessage = "Could not apply changes. Try rephrasing.";
} else {
currentGenerated = result.route;
}
} catch (e) {
const error = e;
errorMessage = error.message || "Failed to generate updated route";
}
if (currentGenerated) {
break;
}
output_manager_default.error(errorMessage);
if (skipConfirmation || !client.stdin.isTTY) {
return 1;
}
const retry = await client.input.select({
message: "What would you like to do?",
choices: [
{ name: "Try again with a different description", value: "retry" },
{ name: "Cancel", value: "cancel" }
]
});
if (retry === "cancel") {
output_manager_default.log("No changes made.");
return 0;
}
prompt = void 0;
}
printGeneratedRoutePreview(currentGenerated);
if (skipConfirmation) {
return await applyAIEdit(
client,
projectId,
teamId,
originalRoute,
currentGenerated,
existingStagingVersion,
skipConfirmation
);
}
if (!client.stdin.isTTY) {
output_manager_default.error(
`Cannot interactively confirm route changes in a non-TTY environment. Use ${getCommandName('routes edit <name-or-id> --ai "..." --yes')} to skip confirmation.`
);
return 1;
}
for (; ; ) {
const choice = await client.input.select({
message: "What would you like to do?",
choices: [
{ name: "Confirm changes", value: "confirm" },
{ name: "Edit again with AI", value: "ai-edit" },
{ name: "Edit manually", value: "manual" },
{ name: "Discard", value: "discard" }
],
pageSize: 4,
loop: false
});
if (choice === "confirm") {
return await applyAIEdit(
client,
projectId,
teamId,
originalRoute,
currentGenerated,
existingStagingVersion,
skipConfirmation
);
}
if (choice === "ai-edit") {
const editPrompt = await client.input.text({
message: "Describe what you'd like to change:",
validate: (val) => {
if (!val)
return "A description is required";
if (val.length > 2e3)
return "Description must be 2000 characters or less";
return true;
}
});
output_manager_default.spinner("Updating route...");
try {
const editResult = await generateRoute(
client,
projectId,
{
prompt: editPrompt,
currentRoute: convertRouteToCurrentRoute(currentGenerated)
},
{ teamId }
);
if (editResult.error) {
output_manager_default.error(editResult.error);
output_manager_default.log("Keeping previous route:");
printGeneratedRoutePreview(currentGenerated);
continue;
}
if (!editResult.route) {
output_manager_default.error("Could not apply changes. Try rephrasing.");
output_manager_default.log("Keeping previous route:");
printGeneratedRoutePreview(currentGenerated);
continue;
}
currentGenerated = editResult.route;
printGeneratedRoutePreview(currentGenerated);
} catch (e) {
const error = e;
output_manager_default.error(error.message || "Failed to update route");
output_manager_default.log("Keeping previous route:");
printGeneratedRoutePreview(currentGenerated);
}
continue;
}
if (choice === "manual") {
const routeInput = generatedRouteToAddInput(currentGenerated);
const manualRoute = cloneRoute(originalRoute);
manualRoute.name = routeInput.name;
manualRoute.description = routeInput.description;
manualRoute.srcSyntax = routeInput.srcSyntax;
manualRoute.route = routeInput.route;
await runInteractiveEditLoop(client, manualRoute);
populateRouteEnv(manualRoute.route);
const editStamp = stamp_default();
output_manager_default.spinner(`Updating route "${manualRoute.name}"`);
try {
const { version } = await editRoute(
client,
projectId,
originalRoute.id,
{
route: {
name: manualRoute.name,
description: manualRoute.description,
enabled: manualRoute.enabled,
srcSyntax: manualRoute.srcSyntax,
route: manualRoute.route
}
},
{ teamId }
);
output_manager_default.log(
`${import_chalk.default.cyan("Updated")} route "${manualRoute.name}" ${import_chalk.default.gray(editStamp())}`
);
await offerAutoPromote(
client,
projectId,
version,
!!existingStagingVersion,
{ teamId, skipPrompts: skipConfirmation }
);
return 0;
} catch (e) {
const error = e;
output_manager_default.error(error.message || "Failed to update route");
return 1;
}
}
output_manager_default.log("No changes made.");
return 0;
}
}
async function applyAIEdit(client, projectId, teamId, originalRoute, generated, existingStagingVersion, skipConfirmation) {
const routeInput = generatedRouteToAddInput(generated);
populateRouteEnv(routeInput.route);
const editStamp = stamp_default();
output_manager_default.spinner(`Updating route "${routeInput.name}"`);
try {
const { version } = await editRoute(
client,
projectId,
originalRoute.id,
{
route: {
name: routeInput.name,
description: routeInput.description,
enabled: originalRoute.enabled,
srcSyntax: routeInput.srcSyntax,
route: routeInput.route
}
},
{ teamId }
);
output_manager_default.log(
`${import_chalk.default.cyan("Updated")} route "${routeInput.name}" ${import_chalk.default.gray(editStamp())}`
);
await offerAutoPromote(
client,
projectId,
version,
!!existingStagingVersion,
{
teamId,
skipPrompts: skipConfirmation
}
);
return 0;
} catch (e) {
const error = e;
output_manager_default.error(error.message || "Failed to update route");
return 1;
}
}
export {
edit as default
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
editRoute
} from "./chunk-P3SKP5WM.js";
import {
getRouteVersions
} from "./chunk-AHU7WNL2.js";
import {
ensureProjectLink,
getRoutes,
offerAutoPromote,
parseSubcommandArgs,
resolveRoute
} from "./chunk-PAX6W6YL.js";
import {
enableSubcommand
} from "./chunk-U6XOC6E4.js";
import "./chunk-BMTLRU2D.js";
import "./chunk-XB2KZC2B.js";
import {
stamp_default
} from "./chunk-SOTR4CXR.js";
import "./chunk-7EHTK7LP.js";
import "./chunk-GGP5R3FU.js";
import {
getCommandName
} from "./chunk-ZLCMHY2G.js";
import "./chunk-3XFFP2BA.js";
import {
output_manager_default
} from "./chunk-FDJURQMQ.js";
import {
require_source
} from "./chunk-S7KYDPEM.js";
import {
__toESM
} from "./chunk-TZ2YI2VH.js";
// src/commands/routes/enable.ts
var import_chalk = __toESM(require_source(), 1);
async function enable(client, argv) {
const parsed = await parseSubcommandArgs(argv, enableSubcommand);
if (typeof parsed === "number")
return parsed;
const link = await ensureProjectLink(client);
if (typeof link === "number")
return link;
const { project, org } = link;
const teamId = org.type === "team" ? org.id : void 0;
const { args } = parsed;
const identifier = args[0];
if (!identifier) {
output_manager_default.error(
`Route name or ID is required. Usage: ${getCommandName("routes enable <name-or-id>")}`
);
return 1;
}
const { versions } = await getRouteVersions(client, project.id, { teamId });
const existingStagingVersion = versions.find((v) => v.isStaging);
output_manager_default.spinner("Fetching routes");
const { routes } = await getRoutes(client, project.id, { teamId });
output_manager_default.stopSpinner();
if (routes.length === 0) {
output_manager_default.error("No routes found in this project.");
return 1;
}
const route = await resolveRoute(client, routes, identifier);
if (!route) {
output_manager_default.error(
`No route found matching "${identifier}". Run ${import_chalk.default.cyan(
getCommandName("routes list")
)} to see all routes.`
);
return 1;
}
if (route.enabled !== false) {
output_manager_default.log(`Route "${route.name}" is already enabled.`);
return 0;
}
const enableStamp = stamp_default();
output_manager_default.spinner(`Enabling route "${route.name}"`);
try {
const { version } = await editRoute(
client,
project.id,
route.id,
{
route: {
name: route.name,
description: route.description,
enabled: true,
srcSyntax: route.srcSyntax,
route: route.route
}
},
{ teamId }
);
output_manager_default.log(
`${import_chalk.default.cyan("Enabled")} route "${route.name}" ${import_chalk.default.gray(enableStamp())}`
);
await offerAutoPromote(
client,
project.id,
version,
!!existingStagingVersion,
{ teamId }
);
return 0;
} catch (e) {
const error = e;
output_manager_default.error(error.message || "Failed to enable route");
return 1;
}
}
export {
enable as default
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
ensureProjectLink,
getRoutes,
parseSubcommandArgs
} from "./chunk-PAX6W6YL.js";
import {
exportSubcommand
} from "./chunk-U6XOC6E4.js";
import "./chunk-BMTLRU2D.js";
import "./chunk-XB2KZC2B.js";
import "./chunk-SOTR4CXR.js";
import "./chunk-7EHTK7LP.js";
import "./chunk-GGP5R3FU.js";
import {
getCommandName
} from "./chunk-ZLCMHY2G.js";
import "./chunk-3XFFP2BA.js";
import {
output_manager_default
} from "./chunk-FDJURQMQ.js";
import "./chunk-S7KYDPEM.js";
import "./chunk-TZ2YI2VH.js";
// src/commands/routes/export.ts
function cleanRoute(route) {
const cleaned = {};
for (const [key, value] of Object.entries(route)) {
if (value === void 0)
continue;
if (key === "middlewarePath" || key === "middlewareRawSrc" || key === "middleware" || key === "check" || key === "important") {
continue;
}
cleaned[key] = value;
}
return cleaned;
}
function routesToVercelJson(rules) {
const enabledRoutes = rules.filter((r) => r.enabled !== false);
const cleaned = enabledRoutes.map((r) => cleanRoute(r.route));
const config = { routes: cleaned };
return JSON.stringify(config, null, 2);
}
function routesToVercelTs(rules) {
const enabledRoutes = rules.filter((r) => r.enabled !== false);
const routeEntries = enabledRoutes.map((r) => {
const cleaned = cleanRoute(r.route);
const routeJson = JSON.stringify(cleaned, null, 2);
const indented = routeJson.split("\n").map((line, i) => i === 0 ? line : ` ${line}`).join("\n");
if (r.description) {
const safeDesc = r.description.replace(/\n/g, " ");
return ` // ${safeDesc}
${indented}`;
}
return ` ${indented}`;
});
const routesContent = routeEntries.length > 0 ? `
${routeEntries.join(",\n")},
` : "";
return `import type { VercelConfig } from '@vercel/config/v1';
export const config: VercelConfig = {
routes: [${routesContent}],
};
`;
}
async function exportRoutes(client, argv) {
const parsed = await parseSubcommandArgs(argv, exportSubcommand);
if (typeof parsed === "number")
return parsed;
const link = await ensureProjectLink(client);
if (typeof link === "number")
return link;
const { project, org } = link;
const teamId = org.type === "team" ? org.id : void 0;
const { args, flags } = parsed;
const format = flags["--format"] || "json";
const nameOrId = args[0];
const validFormats = ["json", "ts"];
if (!validFormats.includes(format)) {
output_manager_default.error(
`Invalid format: "${format}". Valid formats: ${validFormats.join(", ")}. Usage: ${getCommandName("routes export --format json")}`
);
return 1;
}
output_manager_default.spinner("Fetching routes");
try {
const { routes } = await getRoutes(client, project.id, { teamId });
if (routes.length === 0) {
output_manager_default.log(
`No routes found. Create one with ${getCommandName("routes add")}.`
);
return 0;
}
let routesToExport = routes;
if (nameOrId) {
const query = nameOrId.toLowerCase();
routesToExport = routes.filter(
(r) => r.name.toLowerCase() === query || r.name.toLowerCase().includes(query) || r.id === nameOrId
);
if (routesToExport.length === 0) {
output_manager_default.error(
`No route found matching "${nameOrId}". Run ${getCommandName("routes list")} to see all routes.`
);
return 1;
}
}
let result;
switch (format) {
case "ts":
result = routesToVercelTs(routesToExport);
break;
default:
result = routesToVercelJson(routesToExport);
break;
}
output_manager_default.stopSpinner();
client.stdout.write(result.trimEnd() + "\n");
return 0;
} catch (e) {
const error = e;
output_manager_default.error(error.message || "Failed to export routes");
return 1;
}
}
export {
exportRoutes as default
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
handleValidationError,
normalizeRepeatableStringFilters,
outputError,
validateAllProjectMutualExclusivity,
validateIntegerRangeWithDefault,
validateTimeBound,
validateTimeOrder
} from "./chunk-IE7MNZ56.js";
import {
getCommandFlags
} from "./chunk-EOZFDJSY.js";
import {
getScope
} from "./chunk-S4G3XJAP.js";
import {
validateJsonOutput
} from "./chunk-XPKWKPWA.js";
import {
activityCommand
} from "./chunk-LW5ZNGW7.js";
import {
getLinkedProject,
getProjectByNameOrId
} from "./chunk-BMTLRU2D.js";
import "./chunk-XB2KZC2B.js";
import "./chunk-SOTR4CXR.js";
import "./chunk-7EHTK7LP.js";
import {
require_ms
} from "./chunk-GGP5R3FU.js";
import {
ProjectNotFound,
getCommandName,
getFlagsSpecification,
isAPIError,
parseArguments,
printError
} from "./chunk-ZLCMHY2G.js";
import "./chunk-3XFFP2BA.js";
import {
output_manager_default
} from "./chunk-FDJURQMQ.js";
import {
require_source
} from "./chunk-S7KYDPEM.js";
import {
__toESM
} from "./chunk-TZ2YI2VH.js";
// src/commands/activity/list.ts
var import_ms = __toESM(require_ms(), 1);
var import_chalk = __toESM(require_source(), 1);
function validateNext(next) {
if (next === void 0) {
return { valid: true, value: void 0 };
}
if (Number.isNaN(next)) {
return {
valid: false,
code: "INVALID_NEXT",
message: "Please provide a number for flag `--next`."
};
}
const date = new Date(next);
if (Number.isNaN(date.getTime())) {
return {
valid: false,
code: "INVALID_NEXT",
message: "Please provide a valid unix timestamp in milliseconds for `--next`."
};
}
return { valid: true, value: date };
}
function handleApiError(err, jsonOutput, client) {
if (err.status === 403) {
return outputError(
client,
jsonOutput,
"FORBIDDEN",
"You do not have permission to list activity events. Required permissions: Event: List or OwnEvent: List."
);
}
return outputError(
client,
jsonOutput,
err.code || "API_ERROR",
err.serverMessage || `API error (${err.status}).`
);
}
function formatActor(event) {
const principal = event.principal;
if (!principal) {
return event.principalId || "-";
}
if (principal.type === "system") {
return "system";
}
if (principal.username) {
return principal.username;
}
if (principal.name) {
return principal.name;
}
if (principal.slug) {
return principal.slug;
}
if (principal.email) {
return principal.email;
}
return event.principalId || "-";
}
function formatAge(createdAt) {
if (!Number.isFinite(createdAt) || createdAt <= 0) {
return "-";
}
const age = Math.max(0, Date.now() - createdAt);
return (0, import_ms.default)(age);
}
function formatEventText(text) {
return text.replace(/\s+/g, " ").trim();
}
function printExpandedEvents(events) {
const lines = [""];
events.forEach((event) => {
lines.push(import_chalk.default.bold(formatEventText(event.text)));
lines.push(` ${import_chalk.default.cyan("Type:")} ${event.type ?? "-"}`);
lines.push(` ${import_chalk.default.cyan("Actor:")} ${formatActor(event)}`);
lines.push(` ${import_chalk.default.cyan("Age:")} ${formatAge(event.createdAt)}`);
lines.push(` ${import_chalk.default.cyan("ID:")} ${event.id}`);
lines.push("");
});
output_manager_default.print(`${lines.join("\n")}
`);
}
function trackTelemetry(flags, types, telemetry) {
telemetry.trackCliOptionType(types.length > 0 ? types : void 0);
telemetry.trackCliOptionSince(flags["--since"]);
telemetry.trackCliOptionUntil(flags["--until"]);
telemetry.trackCliOptionProject(flags["--project"]);
telemetry.trackCliFlagAll(flags["--all"]);
telemetry.trackCliOptionLimit(flags["--limit"]);
telemetry.trackCliOptionNext(flags["--next"]);
telemetry.trackCliOptionFormat(flags["--format"]);
}
function parseFlags(client) {
const flagsSpecification = getFlagsSpecification(activityCommand.options);
try {
const parsedArgs = parseArguments(client.argv.slice(2), flagsSpecification);
return parsedArgs.flags;
} catch (err) {
printError(err);
return 1;
}
}
function resolveValidatedInputs(flags, jsonOutput, client, normalizedTypes) {
const limitResult = validateIntegerRangeWithDefault(flags["--limit"], {
flag: "--limit",
min: 1,
max: 100,
defaultValue: 20
});
if (!limitResult.valid) {
return handleValidationError(limitResult, jsonOutput, client);
}
const mutualResult = validateAllProjectMutualExclusivity(
flags["--all"],
flags["--project"]
);
if (!mutualResult.valid) {
return handleValidationError(mutualResult, jsonOutput, client);
}
const sinceResult = validateTimeBound(flags["--since"]);
if (!sinceResult.valid) {
return handleValidationError(sinceResult, jsonOutput, client);
}
const nextResult = validateNext(flags["--next"]);
if (!nextResult.valid) {
return handleValidationError(nextResult, jsonOutput, client);
}
let until = nextResult.value;
if (!until) {
const untilResult = validateTimeBound(flags["--until"]);
if (!untilResult.valid) {
return handleValidationError(untilResult, jsonOutput, client);
}
until = untilResult.value;
}
const since = sinceResult.value;
const timeOrderResult = validateTimeOrder(since, until);
if (!timeOrderResult.valid) {
return handleValidationError(timeOrderResult, jsonOutput, client);
}
return {
limit: limitResult.value,
types: normalizedTypes,
since,
until
};
}
async function resolveScope(client, opts) {
if (opts.all || opts.project) {
const { team } = await getScope(client);
if (!team) {
return outputError(
client,
opts.jsonOutput,
"NO_TEAM",
"No team context found. Run `vercel switch` to select a team, or use `vercel link` in a project directory."
);
}
if (opts.all) {
return {
teamId: team.id,
teamSlug: team.slug
};
}
let projectResult;
try {
projectResult = await getProjectByNameOrId(
client,
opts.project,
team.id
);
} catch (err) {
if (isAPIError(err)) {
return outputError(
client,
opts.jsonOutput,
err.code || "API_ERROR",
err.serverMessage || (err.status === 403 ? `You do not have permission to access project "${opts.project}" in team "${team.slug}".` : `API error (${err.status}).`)
);
}
throw err;
}
if (projectResult instanceof ProjectNotFound) {
return outputError(
client,
opts.jsonOutput,
"PROJECT_NOT_FOUND",
`Project "${opts.project}" was not found in team "${team.slug}".`
);
}
return {
teamId: team.id,
teamSlug: team.slug,
projectIds: [projectResult.id]
};
}
const linkedProject = await getLinkedProject(client);
if (linkedProject.status === "error") {
return linkedProject.exitCode;
}
if (linkedProject.status === "not_linked") {
return outputError(
client,
opts.jsonOutput,
"NOT_LINKED",
"No linked project found. Run `vercel link` to link a project, or use --project <name> or --all."
);
}
const isTeamProject = linkedProject.org.type === "team";
return {
projectIds: [linkedProject.project.id],
teamId: isTeamProject ? linkedProject.org.id : void 0,
teamSlug: isTeamProject ? linkedProject.org.slug : void 0
};
}
function buildEventsQuery(params) {
const query = new URLSearchParams({
limit: String(params.limit + 1)
});
if (params.types.length > 0) {
query.set("types", params.types.join(","));
}
if (params.since) {
query.set("since", params.since.toISOString());
}
if (params.until) {
query.set("until", params.until.toISOString());
}
if (params.scope.projectIds && params.scope.projectIds.length > 0) {
query.set("projectIds", params.scope.projectIds.join(","));
}
if (params.scope.teamId) {
query.set("teamId", params.scope.teamId);
}
if (params.scope.teamSlug) {
query.set("slug", params.scope.teamSlug);
}
if (params.jsonOutput) {
query.set("withPayload", "true");
}
return query;
}
function paginateEvents(allEvents, limit) {
const events = allEvents.slice(0, limit);
const hasMore = allEvents.length > limit;
const lastVisibleEvent = events[events.length - 1];
const next = hasMore && typeof lastVisibleEvent?.createdAt === "number" ? lastVisibleEvent.createdAt - 1 : null;
return { events, next };
}
function printNextPageHint(flags, next) {
const commandFlags = getCommandFlags(flags, ["--next"]);
output_manager_default.log(
`To display the next page, run ${getCommandName(
`activity${commandFlags} --next ${next}`
)}`
);
}
async function list(client, telemetry) {
const flags = parseFlags(client);
if (typeof flags === "number") {
return flags;
}
const formatResult = validateJsonOutput(flags);
if (!formatResult.valid) {
output_manager_default.error(formatResult.error);
return 1;
}
const jsonOutput = formatResult.jsonOutput;
const normalizedTypes = normalizeRepeatableStringFilters(flags["--type"]);
trackTelemetry(flags, normalizedTypes, telemetry);
const validatedInputs = resolveValidatedInputs(
flags,
jsonOutput,
client,
normalizedTypes
);
if (typeof validatedInputs === "number") {
return validatedInputs;
}
const scope = await resolveScope(client, {
project: flags["--project"],
all: flags["--all"],
jsonOutput
});
if (typeof scope === "number") {
return scope;
}
const query = buildEventsQuery({
limit: validatedInputs.limit,
types: validatedInputs.types,
since: validatedInputs.since,
until: validatedInputs.until,
scope,
jsonOutput
});
output_manager_default.spinner("Fetching activity...");
try {
const response = await client.fetch(
`/v3/events?${query.toString()}`,
{
useCurrentTeam: false
}
);
const allEvents = Array.isArray(response.events) ? response.events : [];
const { events, next } = paginateEvents(allEvents, validatedInputs.limit);
if (jsonOutput) {
client.stdout.write(
`${JSON.stringify({ events, pagination: { next } }, null, 2)}
`
);
return 0;
}
if (events.length === 0) {
output_manager_default.log("No activity events found.");
return 0;
}
printExpandedEvents(events);
if (next !== null) {
printNextPageHint(flags, next);
}
return 0;
} catch (err) {
if (isAPIError(err)) {
return handleApiError(err, jsonOutput, client);
}
throw err;
} finally {
output_manager_default.stopSpinner();
}
}
export {
list as default
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
handleValidationError,
normalizeRepeatableStringFilters,
outputError,
validateAllProjectMutualExclusivity,
validateOptionalIntegerRange,
validateTimeBound,
validateTimeOrder
} from "./chunk-IE7MNZ56.js";
import {
getScope
} from "./chunk-S4G3XJAP.js";
import {
validateJsonOutput
} from "./chunk-XPKWKPWA.js";
import {
alertsCommand
} from "./chunk-P5Q6F5IA.js";
import {
getLinkedProject,
getProjectByNameOrId
} from "./chunk-BMTLRU2D.js";
import "./chunk-XB2KZC2B.js";
import "./chunk-SOTR4CXR.js";
import {
table
} from "./chunk-LWBSOTJP.js";
import "./chunk-7EHTK7LP.js";
import {
require_ms
} from "./chunk-GGP5R3FU.js";
import {
ProjectNotFound,
getFlagsSpecification,
isAPIError,
parseArguments,
printError
} from "./chunk-ZLCMHY2G.js";
import "./chunk-3XFFP2BA.js";
import {
output_manager_default
} from "./chunk-FDJURQMQ.js";
import {
require_source
} from "./chunk-S7KYDPEM.js";
import {
__toESM
} from "./chunk-TZ2YI2VH.js";
// src/commands/alerts/list.ts
var import_ms = __toESM(require_ms(), 1);
var import_chalk = __toESM(require_source(), 1);
function handleApiError(err, jsonOutput, client) {
const message = err.status === 401 || err.status === 403 ? "You do not have access to alerts in this scope. Pass --token <TOKEN> and --scope <team-slug> with Alerts read access." : err.status >= 500 ? `The alerts endpoint failed on the server (${err.status}). Re-run with --debug and share the x-vercel-id from the failed request.` : err.serverMessage || `API error (${err.status}).`;
return outputError(client, jsonOutput, err.code || "API_ERROR", message);
}
function getDefaultRange() {
const to = /* @__PURE__ */ new Date();
const from = new Date(to.getTime() - 24 * 60 * 60 * 1e3);
return { from: from.toISOString(), to: to.toISOString() };
}
async function resolveScope(client, opts) {
if (opts.all || opts.project) {
const { team } = await getScope(client);
if (!team) {
return outputError(
client,
opts.jsonOutput,
"NO_TEAM",
"No team context found. Run `vercel switch` to select a team, or use `vercel link` in a project directory."
);
}
if (opts.all) {
return {
teamId: team.id
};
}
let projectResult;
try {
projectResult = await getProjectByNameOrId(
client,
opts.project,
team.id
);
} catch (err) {
if (isAPIError(err)) {
return outputError(
client,
opts.jsonOutput,
err.code || "API_ERROR",
err.serverMessage || (err.status === 403 ? `You do not have permission to access project "${opts.project}" in team "${team.slug}".` : `API error (${err.status}).`)
);
}
throw err;
}
if (projectResult instanceof ProjectNotFound) {
return outputError(
client,
opts.jsonOutput,
"PROJECT_NOT_FOUND",
`Project "${opts.project}" was not found in team "${team.slug}".`
);
}
return {
teamId: team.id,
projectId: projectResult.id
};
}
const linkedProject = await getLinkedProject(client);
if (linkedProject.status === "error") {
return linkedProject.exitCode;
}
if (linkedProject.status === "not_linked") {
return outputError(
client,
opts.jsonOutput,
"NOT_LINKED",
"No linked project found. Run `vercel link` to link a project, or use --project <name> or --all."
);
}
return {
teamId: linkedProject.org.id,
projectId: linkedProject.project.id
};
}
function getGroupTitle(group) {
return group.ai?.title || "Alert group";
}
function parseDateInput(value) {
if (value === void 0) {
return void 0;
}
const epochMs = value < 1e12 ? value * 1e3 : value;
const date = new Date(epochMs);
return Number.isNaN(date.getTime()) ? void 0 : date;
}
function formatDateForDisplay(value) {
const date = parseDateInput(value);
if (!date) {
return "-";
}
return date.toLocaleString("en-US", {
year: "numeric",
month: "short",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
hour12: false,
timeZoneName: "short"
});
}
function getStartedAt(group) {
return formatDateForDisplay(getGroupStartedAt(group)?.getTime());
}
function getGroupStartedAt(group) {
return parseDateInput(group.recordedStartedAt) || parseDateInput(group.alerts?.[0]?.startedAt);
}
function getGroupResolvedAt(group) {
const resolvedTimes = (group.alerts ?? []).map((alert) => parseDateInput(alert.resolvedAt)).filter((d) => Boolean(d)).map((d) => d.getTime());
if (resolvedTimes.length > 0) {
return new Date(Math.max(...resolvedTimes));
}
return getGroupStartedAt(group);
}
function getStatus(group) {
const normalizedStatus = (group.status || "").toLowerCase();
if (normalizedStatus === "active") {
return "active";
}
if (normalizedStatus === "resolved") {
const startedAt = getGroupStartedAt(group);
const resolvedAt = getGroupResolvedAt(group);
if (startedAt && resolvedAt && resolvedAt.getTime() >= startedAt.getTime()) {
return `resolved after ${(0, import_ms.default)(resolvedAt.getTime() - startedAt.getTime())}`;
}
return "resolved";
}
return group.status || "-";
}
function getResolvedAt(group) {
const normalizedStatus = (group.status || "").toLowerCase();
if (normalizedStatus === "active") {
return "active";
}
return formatDateForDisplay(getGroupResolvedAt(group)?.getTime());
}
function getAlertsCount(group) {
return String(group.alerts?.length ?? 0);
}
function printGroups(groups) {
if (groups.length === 0) {
output_manager_default.log("No alerts found.");
return;
}
const headers = ["Title", "Started At", "Type", "Status", "Alerts"].map(
(h) => import_chalk.default.cyan(h)
);
const rows = [
headers,
...groups.map((group) => [
import_chalk.default.bold(getGroupTitle(group)),
getStartedAt(group),
group.type || "-",
getStatus(group),
getAlertsCount(group)
])
];
const tableOutput = table(rows, { hsep: 3 }).split("\n").map((line) => line.trimEnd()).join("\n").replace(/^/gm, " ");
output_manager_default.print(`
${tableOutput}
`);
}
function printAiSections(groups) {
if (groups.length === 0) {
output_manager_default.log("No alerts found.");
return;
}
const rendered = groups.map((group) => {
const title = getGroupTitle(group);
const summary = group.ai?.currentSummary || "N/A";
const findings = group.ai?.keyFindings?.filter(Boolean) ?? [];
const findingsOutput = findings.length > 0 ? findings.map((finding) => ` - ${finding}`).join("\n") : " - N/A";
return [
import_chalk.default.bold(title),
` ${import_chalk.default.cyan("Resolved At:")} ${getResolvedAt(group)}`,
` ${import_chalk.default.cyan("Summary:")} ${summary}`,
` ${import_chalk.default.cyan("Key Findings:")}`,
findingsOutput
].join("\n");
}).join("\n\n");
output_manager_default.print(`
${rendered}
`);
}
function trackTelemetry(flags, types, telemetry) {
telemetry.trackCliOptionType(types.length > 0 ? types : void 0);
telemetry.trackCliOptionSince(flags["--since"]);
telemetry.trackCliOptionUntil(flags["--until"]);
telemetry.trackCliOptionProject(flags["--project"]);
telemetry.trackCliFlagAll(flags["--all"]);
telemetry.trackCliFlagAi(flags["--ai"]);
telemetry.trackCliOptionLimit(flags["--limit"]);
telemetry.trackCliOptionFormat(flags["--format"]);
}
function parseFlags(client) {
const flagsSpecification = getFlagsSpecification(alertsCommand.options);
try {
const parsedArgs = parseArguments(client.argv.slice(2), flagsSpecification);
return parsedArgs.flags;
} catch (err) {
printError(err);
return 1;
}
}
function resolveValidatedInputs(flags, client, jsonOutput) {
const types = normalizeRepeatableStringFilters(flags["--type"]);
const limitResult = validateOptionalIntegerRange(flags["--limit"], {
flag: "--limit",
min: 1,
max: 100
});
if (!limitResult.valid) {
return handleValidationError(limitResult, jsonOutput, client);
}
const mutualResult = validateAllProjectMutualExclusivity(
flags["--all"],
flags["--project"]
);
if (!mutualResult.valid) {
return handleValidationError(mutualResult, jsonOutput, client);
}
const sinceResult = validateTimeBound(flags["--since"]);
if (!sinceResult.valid) {
return handleValidationError(sinceResult, jsonOutput, client);
}
const untilResult = validateTimeBound(flags["--until"]);
if (!untilResult.valid) {
return handleValidationError(untilResult, jsonOutput, client);
}
const timeOrderResult = validateTimeOrder(
sinceResult.value,
untilResult.value
);
if (!timeOrderResult.valid) {
return handleValidationError(timeOrderResult, jsonOutput, client);
}
return {
limit: limitResult.value,
types,
since: sinceResult.value,
until: untilResult.value
};
}
function buildAlertsQuery(scope, inputs) {
const query = new URLSearchParams({
teamId: scope.teamId
});
if (scope.projectId) {
query.set("projectId", scope.projectId);
}
if (inputs.limit) {
query.set("limit", String(inputs.limit));
}
for (const type of inputs.types) {
query.append("types", type);
}
if (inputs.since) {
query.set("from", inputs.since.toISOString());
}
if (inputs.until) {
query.set("to", inputs.until.toISOString());
}
if (!inputs.since && !inputs.until) {
const defaultRange = getDefaultRange();
query.set("from", defaultRange.from);
query.set("to", defaultRange.to);
}
return query;
}
async function list(client, telemetry) {
const flags = parseFlags(client);
if (typeof flags === "number") {
return flags;
}
const formatResult = validateJsonOutput(flags);
if (!formatResult.valid) {
output_manager_default.error(formatResult.error);
return 1;
}
const jsonOutput = formatResult.jsonOutput;
const types = normalizeRepeatableStringFilters(flags["--type"]);
trackTelemetry(flags, types, telemetry);
const validatedInputs = resolveValidatedInputs(flags, client, jsonOutput);
if (typeof validatedInputs === "number") {
return validatedInputs;
}
const scope = await resolveScope(client, {
project: flags["--project"],
all: flags["--all"],
jsonOutput
});
if (typeof scope === "number") {
return scope;
}
const query = buildAlertsQuery(scope, validatedInputs);
const requestPath = `/alerts/v3/groups?${query.toString()}`;
output_manager_default.debug(`Fetching alerts from ${requestPath}`);
output_manager_default.spinner("Fetching alerts...");
try {
const groups = await client.fetch(requestPath);
if (jsonOutput) {
client.stdout.write(`${JSON.stringify({ groups }, null, 2)}
`);
} else {
if (flags["--ai"]) {
printAiSections(groups);
} else {
printGroups(groups);
}
}
return 0;
} catch (err) {
if (isAPIError(err)) {
return handleApiError(err, jsonOutput, client);
}
output_manager_default.debug(err);
const message = `Failed to fetch alerts: ${err.message || String(err)}`;
return outputError(client, jsonOutput, "UNEXPECTED_ERROR", message);
} finally {
output_manager_default.stopSpinner();
}
}
export {
list as default
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
updateRouteVersion
} from "./chunk-PMSMUMUO.js";
import {
getRouteVersions
} from "./chunk-AHU7WNL2.js";
import {
confirmAction,
ensureProjectLink,
getRoutes,
parseSubcommandArgs,
printDiffSummary
} from "./chunk-PAX6W6YL.js";
import {
publishSubcommand
} from "./chunk-U6XOC6E4.js";
import "./chunk-BMTLRU2D.js";
import "./chunk-XB2KZC2B.js";
import {
stamp_default
} from "./chunk-SOTR4CXR.js";
import "./chunk-7EHTK7LP.js";
import "./chunk-GGP5R3FU.js";
import {
getCommandName
} from "./chunk-ZLCMHY2G.js";
import "./chunk-3XFFP2BA.js";
import {
output_manager_default
} from "./chunk-FDJURQMQ.js";
import {
require_source
} from "./chunk-S7KYDPEM.js";
import {
__toESM
} from "./chunk-TZ2YI2VH.js";
// src/commands/routes/publish.ts
var import_chalk = __toESM(require_source(), 1);
async function publish(client, argv) {
const parsed = await parseSubcommandArgs(argv, publishSubcommand);
if (typeof parsed === "number")
return parsed;
const link = await ensureProjectLink(client);
if (typeof link === "number")
return link;
const { project, org } = link;
const teamId = org.type === "team" ? org.id : void 0;
output_manager_default.spinner(`Fetching route versions for ${import_chalk.default.bold(project.name)}`);
const { versions } = await getRouteVersions(client, project.id, { teamId });
const version = versions.find((v) => v.isStaging);
if (!version) {
output_manager_default.warn(
`No staged changes to publish. Make changes first with ${import_chalk.default.cyan(
getCommandName("routes add")
)}.`
);
return 0;
}
output_manager_default.spinner("Fetching changes");
const { routes: diffRoutes } = await getRoutes(client, project.id, {
teamId,
versionId: version.id,
diff: true
});
const changedRoutes = diffRoutes.filter((r) => r.action !== void 0);
if (changedRoutes.length > 0) {
output_manager_default.print(`
${import_chalk.default.bold("Changes to be published:")}
`);
printDiffSummary(changedRoutes);
output_manager_default.print("\n");
} else {
output_manager_default.print(
`
${import_chalk.default.gray("No changes detected from current production version.")}
`
);
}
const confirmed = await confirmAction(
client,
parsed.flags["--yes"],
"Publish these changes to production?",
`This will make them live for ${import_chalk.default.bold(project.name)}.`
);
if (!confirmed) {
output_manager_default.log("Canceled");
return 0;
}
const updateStamp = stamp_default();
output_manager_default.spinner("Publishing to production");
try {
const { version: newVersion } = await updateRouteVersion(
client,
project.id,
version.id,
"promote",
{ teamId }
);
output_manager_default.log(
`${import_chalk.default.cyan("Success!")} Routes published to production ${import_chalk.default.gray(
updateStamp()
)}`
);
if (newVersion.ruleCount !== void 0) {
output_manager_default.print(
` ${import_chalk.default.bold("Active routes:")} ${newVersion.ruleCount}
`
);
}
return 0;
} catch (e) {
const error = e;
output_manager_default.error(error.message || "Failed to publish routes");
return 1;
}
}
export {
publish as default
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
formatErrorJson,
formatQueryJson,
getDefaultAggregation,
getMeasures,
getQueryEngineEventName,
getRollupColumnName,
validateAggregation,
validateEvent,
validateGroupBy,
validateMeasure,
validateMutualExclusivity,
validateRequiredEvent
} from "./chunk-BQ3DXZNT.js";
import {
resolveTimeRange
} from "./chunk-IE7MNZ56.js";
import {
indent_default
} from "./chunk-A3NYPUKZ.js";
import {
getScope
} from "./chunk-S4G3XJAP.js";
import {
validateJsonOutput
} from "./chunk-XPKWKPWA.js";
import {
metricsCommand
} from "./chunk-2DLBVZWU.js";
import {
getLinkedProject
} from "./chunk-BMTLRU2D.js";
import "./chunk-XB2KZC2B.js";
import "./chunk-SOTR4CXR.js";
import {
table
} from "./chunk-LWBSOTJP.js";
import "./chunk-7EHTK7LP.js";
import {
require_ms
} from "./chunk-GGP5R3FU.js";
import {
getFlagsSpecification,
isAPIError,
parseArguments,
printError
} from "./chunk-ZLCMHY2G.js";
import "./chunk-3XFFP2BA.js";
import {
output_manager_default
} from "./chunk-FDJURQMQ.js";
import {
require_source
} from "./chunk-S7KYDPEM.js";
import {
__toESM
} from "./chunk-TZ2YI2VH.js";
// src/commands/metrics/text-output.ts
var import_chalk = __toESM(require_source(), 1);
// src/commands/metrics/time-utils.ts
var import_ms = __toESM(require_ms(), 1);
var MINUTE_MS = 60 * 1e3;
var HOUR_MS = 60 * MINUTE_MS;
var DAY_MS = 24 * HOUR_MS;
function toGranularityDuration(input) {
const milliseconds = (0, import_ms.default)(input);
if (milliseconds === void 0) {
throw new Error(
`Invalid granularity format "${input}". Use 1m, 5m, 15m, 1h, 4h, 1d.`
);
}
if (milliseconds >= DAY_MS) {
return { days: milliseconds / DAY_MS };
}
if (milliseconds >= HOUR_MS) {
return { hours: milliseconds / HOUR_MS };
}
return { minutes: milliseconds / MINUTE_MS };
}
function toGranularityMs(input) {
const milliseconds = (0, import_ms.default)(input);
if (milliseconds === void 0) {
throw new Error(`Invalid granularity format "${input}".`);
}
return milliseconds;
}
var GRANULARITY_THRESHOLDS = [
[1 * HOUR_MS, "1m", "1m"],
// ≤1h
[2 * HOUR_MS, "5m", "5m"],
// ≤2h
[12 * HOUR_MS, "15m", "5m"],
// ≤12h
[3 * DAY_MS, "1h", "1h"],
// ≤3d
[30 * DAY_MS, "4h", "4h"]
// ≤30d
];
var FALLBACK_GRANULARITY = "1d";
function getAutoGranularity(rangeMs) {
for (const [maxRange, defaultG] of GRANULARITY_THRESHOLDS) {
if (rangeMs <= maxRange) {
return defaultG;
}
}
return FALLBACK_GRANULARITY;
}
function getMinGranularity(rangeMs) {
for (const [maxRange, , minG] of GRANULARITY_THRESHOLDS) {
if (rangeMs <= maxRange) {
return minG;
}
}
return FALLBACK_GRANULARITY;
}
function computeGranularity(rangeMs, explicit) {
if (!explicit) {
const auto = getAutoGranularity(rangeMs);
return {
duration: toGranularityDuration(auto),
adjusted: false
};
}
const minG = getMinGranularity(rangeMs);
const explicitMs = toGranularityMs(explicit);
const minMs = toGranularityMs(minG);
if (explicitMs < minMs) {
const rangeDays = Math.round(rangeMs / DAY_MS);
const rangeHours = Math.round(rangeMs / HOUR_MS);
const rangeLabel = rangeDays >= 1 ? `${rangeDays}-day` : `${rangeHours}-hour`;
return {
duration: toGranularityDuration(minG),
adjusted: true,
notice: `Granularity adjusted from ${explicit} to ${minG} for a ${rangeLabel} time range.`
};
}
return {
duration: toGranularityDuration(explicit),
adjusted: false
};
}
function roundTimeBoundaries(start, end, granularityMs) {
const flooredStart = new Date(
Math.floor(start.getTime() / granularityMs) * granularityMs
);
const ceiledEnd = new Date(
Math.ceil(end.getTime() / granularityMs) * granularityMs
);
return { start: flooredStart, end: ceiledEnd };
}
function toGranularityMsFromDuration(duration) {
if ("minutes" in duration) {
return duration.minutes * MINUTE_MS;
}
if ("hours" in duration) {
return duration.hours * HOUR_MS;
}
return duration.days * DAY_MS;
}
// src/commands/metrics/text-output.ts
var GROUP_KEY_DELIMITER = "";
var MAX_SPARKLINE_LENGTH = 120;
var COUNT_UNITS = /* @__PURE__ */ new Set(["count", "us dollars", "dollars"]);
var DURATION_UNITS = /* @__PURE__ */ new Set(["milliseconds", "seconds"]);
var BYTES_UNITS = /* @__PURE__ */ new Set([
"bytes",
"megabytes",
"gigabyte hours",
"gigabyte_hours"
]);
var RATIO_UNITS = /* @__PURE__ */ new Set(["ratio", "percent"]);
var BLOCKS = ["\u2581", "\u2582", "\u2583", "\u2584", "\u2585", "\u2586", "\u2587", "\u2588"];
var MISSING_CHAR = "\xB7";
function normalizeUnit(unit) {
return unit.trim().toLowerCase().replace(/[_\s]+/g, " ");
}
function toGroupKey(groupValues) {
if (groupValues.length === 0) {
return "";
}
return groupValues.join(GROUP_KEY_DELIMITER);
}
function pad2(n) {
return String(n).padStart(2, "0");
}
function pad4(n) {
return String(n).padStart(4, "0");
}
function formatHumanMinute(date) {
return `${pad4(date.getUTCFullYear())}-${pad2(date.getUTCMonth() + 1)}-${pad2(date.getUTCDate())} ${pad2(date.getUTCHours())}:${pad2(date.getUTCMinutes())}`;
}
function formatPeriodBound(input) {
const date = new Date(input);
if (isNaN(date.getTime())) {
return input;
}
return formatHumanMinute(date);
}
function formatGranularity(granularity) {
if ("minutes" in granularity) {
return `${granularity.minutes}m`;
}
if ("hours" in granularity) {
return `${granularity.hours}h`;
}
return `${granularity.days}d`;
}
function formatUnitLabel(unit) {
switch (normalizeUnit(unit)) {
case "milliseconds":
return "ms";
case "seconds":
return "s";
case "us dollars":
return "USD";
case "gigabyte hours":
return "GB-h";
default:
return unit;
}
}
function isCountIntegerDisplay(measureType, aggregation) {
return measureType === "count" && aggregation === "sum";
}
function formatNumber(value, measureType, aggregation, opts) {
if (isCountIntegerDisplay(measureType, aggregation)) {
if (opts?.preserveFractionalCountSum && !Number.isInteger(value)) {
return formatDecimal(value);
}
return formatCount(value);
}
return formatDecimal(value);
}
function getStatColumns(measureType) {
if (measureType === "duration" || measureType === "ratio") {
return ["avg", "min", "max"];
}
return ["total", "avg", "min", "max"];
}
function toNumericValue(value) {
if (value === null || value === void 0) {
return null;
}
if (typeof value === "number") {
return Number.isFinite(value) ? value : null;
}
const parsed = Number(value);
return Number.isFinite(parsed) ? parsed : null;
}
function isNonNullNumber(value) {
return value !== null;
}
function isPointWithValue(point) {
return point.value !== null;
}
function getOrCreate(map, key, make) {
const existing = map.get(key);
if (existing !== void 0) {
return existing;
}
const created = make();
map.set(key, created);
return created;
}
function getGroupFieldValue(row, field) {
const value = row[field];
return value == null || value === "" ? "(not set)" : String(value);
}
function normalizeTimestampToIso(timestamp) {
const parsed = Date.parse(timestamp);
if (isNaN(parsed)) {
return null;
}
return new Date(parsed).toISOString();
}
function formatStatCell(column, stats, measureType, aggregation, periodStart, periodEnd) {
switch (column) {
case "total":
return formatNumber(stats.total, measureType, aggregation);
case "avg":
return formatNumber(stats.avg, measureType, aggregation, {
preserveFractionalCountSum: true
});
case "min": {
const ts = formatMinMaxTimestamp(
new Date(stats.min.timestamp),
periodStart,
periodEnd
);
return `${formatNumber(stats.min.value, measureType, aggregation)} at ${ts}`;
}
case "max": {
const ts = formatMinMaxTimestamp(
new Date(stats.max.timestamp),
periodStart,
periodEnd
);
return `${formatNumber(stats.max.value, measureType, aggregation)} at ${ts}`;
}
}
}
function buildExpectedTimestamps(periodStart, periodEnd, granularityMs) {
const start = Date.parse(periodStart);
const end = Date.parse(periodEnd);
if (isNaN(start) || isNaN(end) || granularityMs <= 0 || end <= start) {
return [];
}
const timestamps = [];
for (let current = start; current < end; current += granularityMs) {
timestamps.push(new Date(current).toISOString());
}
return timestamps;
}
function getMeasureType(unit) {
const normalized = normalizeUnit(unit);
if (COUNT_UNITS.has(normalized)) {
return "count";
}
if (DURATION_UNITS.has(normalized)) {
return "duration";
}
if (BYTES_UNITS.has(normalized)) {
return "bytes";
}
if (RATIO_UNITS.has(normalized)) {
return "ratio";
}
return "ratio";
}
function formatCount(n) {
return Math.round(n).toLocaleString("en-US");
}
function formatDecimal(n) {
if (!Number.isFinite(n)) {
return String(n);
}
if (n === 0 || Object.is(n, -0)) {
return "0";
}
const sign = n < 0 ? "-" : "";
const abs = Math.abs(n);
if (abs >= 1) {
return `${sign}${abs.toFixed(1)}`;
}
const exponent = Math.floor(Math.log10(abs));
const decimals = Math.min(20, Math.max(2, -exponent + 1));
const fixed = abs.toFixed(decimals);
const trimmed = fixed.replace(/(\.\d*?[1-9])0+$/, "$1").replace(/\.0+$/, "").replace(/\.$/, "");
return `${sign}${trimmed}`;
}
function formatMinMaxTimestamp(date, periodStart, periodEnd) {
const sameDay = periodStart.getUTCFullYear() === periodEnd.getUTCFullYear() && periodStart.getUTCMonth() === periodEnd.getUTCMonth() && periodStart.getUTCDate() === periodEnd.getUTCDate();
if (sameDay) {
return `${pad2(date.getUTCHours())}:${pad2(date.getUTCMinutes())}`;
}
const sameYear = periodStart.getUTCFullYear() === periodEnd.getUTCFullYear();
if (sameYear) {
return `${pad2(date.getUTCMonth() + 1)}-${pad2(date.getUTCDate())} ${pad2(date.getUTCHours())}:${pad2(date.getUTCMinutes())}`;
}
return `${pad4(date.getUTCFullYear())}-${pad2(date.getUTCMonth() + 1)}-${pad2(date.getUTCDate())} ${pad2(date.getUTCHours())}:${pad2(date.getUTCMinutes())}`;
}
function extractGroupedSeries(data, groupBy, rollupColumn, periodStart, periodEnd, granularityMs) {
const expectedTimestamps = buildExpectedTimestamps(
periodStart,
periodEnd,
granularityMs
);
const groups = [];
const groupValues = /* @__PURE__ */ new Map();
const valueByGroup = /* @__PURE__ */ new Map();
for (const row of data) {
const values = groupBy.map((field) => getGroupFieldValue(row, field));
const key = toGroupKey(values);
if (!groupValues.has(key)) {
groups.push(key);
groupValues.set(key, values);
}
const groupMap = getOrCreate(valueByGroup, key, () => /* @__PURE__ */ new Map());
const rawTimestamp = row.timestamp;
if (rawTimestamp.length === 0) {
continue;
}
const timestamp = normalizeTimestampToIso(rawTimestamp);
if (!timestamp) {
continue;
}
const numeric = toNumericValue(row[rollupColumn]);
groupMap.set(timestamp, numeric);
}
const series = /* @__PURE__ */ new Map();
for (const key of groups) {
const byTimestamp = valueByGroup.get(key);
if (!byTimestamp) {
continue;
}
const points = expectedTimestamps.map((timestamp) => ({
timestamp,
value: byTimestamp.has(timestamp) ? byTimestamp.get(timestamp) ?? null : null
}));
series.set(key, points);
}
return { groups, series, groupValues };
}
function computeGroupStats(points) {
const present = points.filter(isPointWithValue);
if (present.length === 0) {
return {
total: 0,
avg: 0,
min: { value: 0, timestamp: "" },
max: { value: 0, timestamp: "" },
count: 0,
allMissing: true
};
}
let total = 0;
let min = present[0];
let max = present[0];
for (const point of present) {
total += point.value;
if (point.value < min.value) {
min = point;
}
if (point.value > max.value) {
max = point;
}
}
return {
total,
avg: total / present.length,
min: { value: min.value, timestamp: min.timestamp },
max: { value: max.value, timestamp: max.timestamp },
count: present.length,
allMissing: false
};
}
var MAX_GROUP_VALUE_LENGTH = 60;
function ellipsizeMiddle(str, maxLength) {
if (str.length <= maxLength)
return str;
const endLength = Math.floor((maxLength - 1) / 2);
const startLength = maxLength - 1 - endLength;
return `${str.slice(0, startLength)}\u2026${str.slice(str.length - endLength)}`;
}
function downsample(values, maxLen) {
if (maxLen <= 0) {
return [];
}
if (values.length <= maxLen) {
return [...values];
}
const result = [];
for (let i = 0; i < maxLen; i++) {
const start = Math.floor(i * values.length / maxLen);
const end = Math.floor((i + 1) * values.length / maxLen);
const bucket = values.slice(start, Math.max(start + 1, end));
const nullCount = bucket.filter((value) => value === null).length;
if (nullCount === bucket.length || nullCount > bucket.length / 2) {
result.push(null);
continue;
}
const present = bucket.filter(isNonNullNumber);
const avg = present.reduce((sum, value) => sum + value, 0) / present.length;
result.push(avg);
}
return result;
}
function generateSparkline(values) {
const sampled = downsample(values, MAX_SPARKLINE_LENGTH);
if (sampled.length === 0) {
return "";
}
const present = sampled.filter(isNonNullNumber);
if (present.length === 0) {
return sampled.map(() => MISSING_CHAR).join("");
}
const min = Math.min(...present);
const max = Math.max(...present);
if (min === max) {
const block = min === 0 ? BLOCKS[0] : BLOCKS[BLOCKS.length - 1];
return sampled.map((value) => value === null ? MISSING_CHAR : block).join("");
}
const range = max - min;
return sampled.map((value) => {
if (value === null) {
return MISSING_CHAR;
}
const ratio = (value - min) / range;
const index = Math.max(
0,
Math.min(BLOCKS.length - 1, Math.round(ratio * (BLOCKS.length - 1)))
);
return BLOCKS[index];
}).join("");
}
function formatMetadataHeader(opts) {
const rows = [
{
key: "Metric",
value: `${opts.event} / ${opts.measure} ${opts.aggregation}`
},
{
key: "Period",
value: `${formatPeriodBound(opts.periodStart)} to ${formatPeriodBound(opts.periodEnd)}`
},
{
key: "Interval",
value: formatGranularity(opts.granularity)
}
];
if (opts.filter) {
rows.push({ key: "Filter", value: opts.filter });
}
if (opts.scope.type === "project-with-slug") {
rows.push({
key: "Project",
value: `${opts.projectName ?? opts.scope.projectName} (${opts.teamName ?? opts.scope.teamSlug})`
});
} else {
rows.push({
key: "Team",
value: `${opts.teamName ?? opts.scope.teamSlug} (all projects)`
});
}
if (opts.unit && normalizeUnit(opts.unit) !== "count") {
rows.push({ key: "Units", value: formatUnitLabel(opts.unit) });
}
if (typeof opts.groupCount === "number") {
rows.push({ key: "Groups", value: String(opts.groupCount) });
}
return rows.map((row) => `> ${import_chalk.default.gray(`${row.key}:`)} ${row.value}`).join("\n");
}
function formatSummaryTable(opts) {
const statColumns = getStatColumns(opts.measureType);
const header = [...opts.groupByFields, ...statColumns];
const rows = [header.map((name) => import_chalk.default.bold(import_chalk.default.cyan(name)))];
for (const row of opts.rows) {
const nextRow = row.groupValues.map(
(v) => ellipsizeMiddle(v, MAX_GROUP_VALUE_LENGTH)
);
if (row.stats.allMissing) {
nextRow.push(...statColumns.map(() => "--"));
rows.push(nextRow);
continue;
}
nextRow.push(
...statColumns.map(
(column) => formatStatCell(
column,
row.stats,
opts.measureType,
opts.aggregation,
opts.periodStart,
opts.periodEnd
)
)
);
rows.push(nextRow);
}
const centeredColumns = /* @__PURE__ */ new Set(["min", "max"]);
const align = header.map(
(col) => centeredColumns.has(col) ? "c" : "r"
);
return indent_default(
table(rows, {
align,
hsep: 2
}),
2
);
}
function formatSparklineSection(groupRows, sparklines, groupByFields) {
const lines = ["sparklines:"];
if (groupRows.length === 0) {
const sparkline = sparklines[0];
if (sparkline) {
lines.push(indent_default(sparkline, 2));
}
return lines.join("\n");
}
const rowsWithSparklines = groupRows.map((groupValues, index) => ({
groupValues,
sparkline: sparklines[index] ?? ""
}));
const rows = [
[...groupByFields, "sparkline"].map((name) => import_chalk.default.bold(import_chalk.default.cyan(name))),
...rowsWithSparklines.map(({ groupValues, sparkline }) => [
...groupValues.map((v) => ellipsizeMiddle(v, MAX_GROUP_VALUE_LENGTH)),
sparkline
])
];
const align = groupByFields.map(() => "r");
align.push("l");
lines.push(
indent_default(
table(rows, {
align,
hsep: 2
}),
2
)
);
return lines.join("\n");
}
function formatText(response, opts) {
const rollupColumn = getRollupColumnName(opts.measure, opts.aggregation);
const measureSchema = getMeasures(opts.event).find(
(m) => m.name === opts.measure
);
const measureUnit = measureSchema?.unit;
const measureType = getMeasureType(measureUnit ?? "ratio");
const granularityMs = toGranularityMsFromDuration(opts.granularity);
const { groups, series, groupValues } = extractGroupedSeries(
response.data ?? [],
opts.groupBy,
rollupColumn,
opts.periodStart,
opts.periodEnd,
granularityMs
);
const metadata = formatMetadataHeader({
event: opts.event,
measure: opts.measure,
aggregation: opts.aggregation,
periodStart: opts.periodStart,
periodEnd: opts.periodEnd,
granularity: opts.granularity,
filter: opts.filter,
scope: opts.scope,
projectName: opts.projectName,
teamName: opts.teamName,
unit: measureUnit,
groupCount: opts.groupBy.length > 0 ? groups.length : void 0
});
if (groups.length === 0) {
return `${metadata}
No data found for this period.
`;
}
const summaryRows = [];
const groupRows = [];
const sparklineRows = [];
for (const key of groups) {
const points = series.get(key) ?? [];
const values = points.map((point) => point.value);
const currentGroupValues = groupValues.get(key) ?? [];
summaryRows.push({
groupValues: currentGroupValues,
stats: computeGroupStats(points)
});
groupRows.push(currentGroupValues);
sparklineRows.push(generateSparkline(values));
}
const summaryTable = formatSummaryTable({
rows: summaryRows,
groupByFields: opts.groupBy,
measureType,
aggregation: opts.aggregation,
periodStart: new Date(opts.periodStart),
periodEnd: new Date(opts.periodEnd)
});
const groupedOutput = opts.groupBy.length > 0;
const sparklineSection = formatSparklineSection(
groupedOutput ? groupRows : [],
sparklineRows,
opts.groupBy
);
const sections = [metadata, summaryTable, sparklineSection];
return `${sections.join("\n\n")}
`;
}
// src/commands/metrics/query.ts
function handleValidationError(result, jsonOutput, client) {
if (jsonOutput) {
client.stdout.write(
formatErrorJson(result.code, result.message, result.allowedValues)
);
} else {
output_manager_default.error(result.message);
if (result.allowedValues && result.allowedValues.length > 0) {
output_manager_default.print(
`
Available ${result.code === "UNKNOWN_EVENT" ? "events" : result.code === "UNKNOWN_MEASURE" ? "measures" : result.code === "INVALID_AGGREGATION" ? "aggregations" : "dimensions"}: ${result.allowedValues.join(", ")}
`
);
}
}
return 1;
}
function handleApiError(err, jsonOutput, client) {
let code;
let message;
switch (err.status) {
case 402:
code = "PAYMENT_REQUIRED";
message = "This feature requires an Observability Plus subscription. Upgrade at https://vercel.com/dashboard/settings/billing";
break;
case 403:
code = "FORBIDDEN";
message = "You do not have permission to query metrics for this project/team.";
break;
case 500:
code = "INTERNAL_ERROR";
message = "An internal error occurred. Please try again later.";
break;
case 504:
code = "TIMEOUT";
message = "The query timed out. Try a shorter time range or fewer groups.";
break;
default:
code = err.code || "BAD_REQUEST";
message = err.serverMessage || `API error (${err.status})`;
}
if (jsonOutput) {
client.stdout.write(formatErrorJson(code, message));
} else {
output_manager_default.error(message);
}
return 1;
}
async function resolveQueryScope(client, opts) {
if (opts.project || opts.all) {
const { team } = await getScope(client);
if (!team) {
const errMsg = "No team context found. Run `vercel switch` to select a team, or use `vercel link` in a project directory.";
if (opts.jsonOutput) {
client.stdout.write(formatErrorJson("NO_TEAM", errMsg));
} else {
output_manager_default.error(errMsg);
}
return 1;
}
if (opts.all) {
return {
scope: { type: "team-with-slug", teamSlug: team.slug },
accountId: team.id
};
}
return {
scope: {
type: "project-with-slug",
teamSlug: team.slug,
projectName: opts.project
},
accountId: team.id
};
}
const linkedProject = await getLinkedProject(client);
if (linkedProject.status === "error") {
return linkedProject.exitCode;
}
if (linkedProject.status === "not_linked") {
const errMsg = "No linked project found. Run `vercel link` to link a project, or use --project <name> or --all.";
if (opts.jsonOutput) {
client.stdout.write(formatErrorJson("NOT_LINKED", errMsg));
} else {
output_manager_default.error(errMsg);
}
return 1;
}
return {
scope: {
type: "project-with-slug",
teamSlug: linkedProject.org.slug,
projectName: linkedProject.project.name
},
accountId: linkedProject.org.id
};
}
async function query(client, telemetry) {
let parsedArgs;
const flagsSpecification = getFlagsSpecification(metricsCommand.options);
try {
parsedArgs = parseArguments(client.argv.slice(2), flagsSpecification);
} catch (err) {
printError(err);
return 1;
}
const flags = parsedArgs.flags;
const formatResult = validateJsonOutput(flags);
if (!formatResult.valid) {
output_manager_default.error(formatResult.error);
return 1;
}
const jsonOutput = formatResult.jsonOutput;
const eventFlag = flags["--event"];
const measure = flags["--measure"] ?? "count";
const aggregationFlag = flags["--aggregation"];
const groupBy = flags["--group-by"] ?? [];
const limit = flags["--limit"];
const filter = flags["--filter"];
const since = flags["--since"];
const until = flags["--until"];
const granularity = flags["--granularity"];
const project = flags["--project"];
const all = flags["--all"];
telemetry.trackCliOptionEvent(eventFlag);
telemetry.trackCliOptionMeasure(flags["--measure"]);
telemetry.trackCliOptionAggregation(aggregationFlag);
telemetry.trackCliOptionGroupBy(groupBy.length > 0 ? groupBy : void 0);
telemetry.trackCliOptionLimit(limit);
telemetry.trackCliOptionFilter(filter);
telemetry.trackCliOptionSince(since);
telemetry.trackCliOptionUntil(until);
telemetry.trackCliOptionGranularity(granularity);
telemetry.trackCliOptionProject(project);
telemetry.trackCliFlagAll(all);
telemetry.trackCliOptionFormat(flags["--format"]);
const requiredResult = validateRequiredEvent(eventFlag);
if (!requiredResult.valid) {
return handleValidationError(requiredResult, jsonOutput, client);
}
const event = requiredResult.value;
const aggregationInput = aggregationFlag ?? getDefaultAggregation(event, measure);
const eventResult = validateEvent(event);
if (!eventResult.valid) {
return handleValidationError(eventResult, jsonOutput, client);
}
const measureResult = validateMeasure(event, measure);
if (!measureResult.valid) {
return handleValidationError(measureResult, jsonOutput, client);
}
const aggResult = validateAggregation(event, measure, aggregationInput);
if (!aggResult.valid) {
return handleValidationError(aggResult, jsonOutput, client);
}
const aggregation = aggResult.value;
const groupByResult = validateGroupBy(event, groupBy);
if (!groupByResult.valid) {
return handleValidationError(groupByResult, jsonOutput, client);
}
const mutualResult = validateMutualExclusivity(all, project);
if (!mutualResult.valid) {
return handleValidationError(mutualResult, jsonOutput, client);
}
const scopeResult = await resolveQueryScope(client, {
project,
all,
jsonOutput
});
if (typeof scopeResult === "number") {
return scopeResult;
}
const { scope, accountId } = scopeResult;
let startTime;
let endTime;
try {
({ startTime, endTime } = resolveTimeRange(since, until));
} catch (err) {
const errMsg = err instanceof Error ? err.message : String(err);
if (jsonOutput) {
client.stdout.write(formatErrorJson("INVALID_TIME", errMsg));
} else {
output_manager_default.error(errMsg);
}
return 1;
}
const rangeMs = endTime.getTime() - startTime.getTime();
const granResult = computeGranularity(rangeMs, granularity);
if (granResult.adjusted && granResult.notice) {
output_manager_default.log(`Notice: ${granResult.notice}`);
}
const rounded = roundTimeBoundaries(
startTime,
endTime,
toGranularityMsFromDuration(granResult.duration)
);
const rollupColumn = getRollupColumnName(measure, aggregation);
const body = {
reason: "agent",
scope,
event: getQueryEngineEventName(event),
rollups: { [rollupColumn]: { measure, aggregation } },
startTime: rounded.start.toISOString(),
endTime: rounded.end.toISOString(),
granularity: granResult.duration,
...groupBy.length > 0 ? { groupBy } : {},
...filter ? { filter } : {},
limit: limit ?? 10
};
const baseUrl = client.apiUrl === "https://api.vercel.com" ? "https://vercel.com" : client.apiUrl;
const metricsUrl = `${baseUrl}/api/observability/metrics`;
output_manager_default.spinner("Querying metrics...");
let response;
try {
response = await client.fetch(metricsUrl, {
method: "POST",
body: JSON.stringify(body),
headers: { "Content-Type": "application/json" },
accountId
});
} catch (err) {
if (isAPIError(err)) {
return handleApiError(err, jsonOutput, client);
}
const errMsg = err instanceof Error ? err.message : String(err);
if (jsonOutput) {
client.stdout.write(formatErrorJson("NETWORK_ERROR", errMsg));
} else {
output_manager_default.error(errMsg);
}
return 1;
} finally {
output_manager_default.stopSpinner();
}
if (jsonOutput) {
client.stdout.write(
formatQueryJson(
{
event,
measure,
aggregation,
groupBy,
filter,
startTime: rounded.start.toISOString(),
endTime: rounded.end.toISOString(),
granularity: granResult.duration
},
response
)
);
} else {
client.stdout.write(
formatText(response, {
event,
measure,
aggregation,
groupBy,
filter,
scope,
projectName: scope.type === "project-with-slug" ? scope.projectName : void 0,
teamName: scope.teamSlug,
periodStart: rounded.start.toISOString(),
periodEnd: rounded.end.toISOString(),
granularity: granResult.duration
})
);
}
return 0;
}
export {
query as default
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
getRouteVersions
} from "./chunk-AHU7WNL2.js";
import {
ensureProjectLink,
getRoutes,
offerAutoPromote,
parsePosition,
parseSubcommandArgs,
resolveRoute
} from "./chunk-PAX6W6YL.js";
import {
reorderSubcommand
} from "./chunk-U6XOC6E4.js";
import "./chunk-BMTLRU2D.js";
import "./chunk-XB2KZC2B.js";
import {
stamp_default
} from "./chunk-SOTR4CXR.js";
import "./chunk-7EHTK7LP.js";
import "./chunk-GGP5R3FU.js";
import {
getCommandName
} from "./chunk-ZLCMHY2G.js";
import "./chunk-3XFFP2BA.js";
import {
output_manager_default
} from "./chunk-FDJURQMQ.js";
import {
require_source
} from "./chunk-S7KYDPEM.js";
import {
__toESM
} from "./chunk-TZ2YI2VH.js";
// src/commands/routes/reorder.ts
var import_chalk = __toESM(require_source(), 1);
// src/util/routes/stage-routes.ts
async function stageRoutes(client, projectId, routes, overwrite, options = {}) {
const { teamId } = options;
const query = new URLSearchParams();
if (teamId)
query.set("teamId", teamId);
const queryString = query.toString();
const url = `/v1/projects/${projectId}/routes${queryString ? `?${queryString}` : ""}`;
return await client.fetch(url, {
method: "PUT",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ routes, overwrite })
});
}
// src/commands/routes/reorder.ts
async function reorder(client, argv) {
const parsed = await parseSubcommandArgs(argv, reorderSubcommand);
if (typeof parsed === "number")
return parsed;
const link = await ensureProjectLink(client);
if (typeof link === "number")
return link;
const { project, org } = link;
const teamId = org.type === "team" ? org.id : void 0;
const { args, flags } = parsed;
const skipConfirmation = flags["--yes"];
const identifier = args[0];
if (!identifier) {
output_manager_default.error(
`Route name or ID is required. Usage: ${getCommandName("routes reorder <name-or-id> --position <pos>")}`
);
return 1;
}
const { versions } = await getRouteVersions(client, project.id, { teamId });
const existingStagingVersion = versions.find((v) => v.isStaging);
output_manager_default.spinner("Fetching routes");
const { routes } = await getRoutes(client, project.id, { teamId });
output_manager_default.stopSpinner();
if (routes.length === 0) {
output_manager_default.error("No routes found in this project.");
return 1;
}
if (routes.length === 1) {
output_manager_default.error("Cannot reorder when there is only one route.");
return 1;
}
const route = await resolveRoute(client, routes, identifier);
if (!route) {
output_manager_default.error(
`No route found matching "${identifier}". Run ${import_chalk.default.cyan(
getCommandName("routes list")
)} to see all routes.`
);
return 1;
}
const currentIndex = routes.findIndex((r) => r.id === route.id);
const currentPosition = currentIndex + 1;
let targetIndex;
const positionFlag = flags["--position"];
const firstFlag = flags["--first"];
const lastFlag = flags["--last"];
if (firstFlag) {
targetIndex = 0;
} else if (lastFlag) {
targetIndex = routes.length;
} else if (positionFlag) {
if (positionFlag === "first") {
targetIndex = 0;
} else if (positionFlag === "last") {
targetIndex = routes.length;
} else {
const num = parseInt(positionFlag, 10);
if (!isNaN(num) && String(num) === positionFlag) {
if (num < 1) {
output_manager_default.error("Position must be 1 or greater.");
return 1;
}
targetIndex = Math.min(num - 1, routes.length);
} else {
try {
const pos = parsePosition(positionFlag);
if (pos.placement === "start") {
targetIndex = 0;
} else if (pos.placement === "end") {
targetIndex = routes.length;
} else if (pos.placement === "after" && pos.referenceId) {
const refIndex = routes.findIndex((r) => r.id === pos.referenceId);
if (refIndex === -1) {
output_manager_default.error(
`Reference route "${pos.referenceId}" not found. Run ${import_chalk.default.cyan(
getCommandName("routes list")
)} to see route IDs.`
);
return 1;
}
targetIndex = refIndex + 1;
} else if (pos.placement === "before" && pos.referenceId) {
const refIndex = routes.findIndex((r) => r.id === pos.referenceId);
if (refIndex === -1) {
output_manager_default.error(
`Reference route "${pos.referenceId}" not found. Run ${import_chalk.default.cyan(
getCommandName("routes list")
)} to see route IDs.`
);
return 1;
}
targetIndex = refIndex;
} else {
output_manager_default.error("Invalid position specification.");
return 1;
}
} catch (e) {
output_manager_default.error(
`${e instanceof Error ? e.message : "Invalid position"}. Usage: ${getCommandName("routes reorder <name-or-id> --position <pos>")}`
);
return 1;
}
}
}
} else {
output_manager_default.print("\n");
output_manager_default.log("Current route order:");
for (let i = 0; i < routes.length; i++) {
const r = routes[i];
const isCurrent = r.id === route.id;
const prefix = isCurrent ? import_chalk.default.cyan("\u2192") : " ";
const num = import_chalk.default.gray(`${i + 1}.`);
const name = isCurrent ? import_chalk.default.bold(r.name) : r.name;
const src = import_chalk.default.gray(`(${r.route.src})`);
const marker = isCurrent ? import_chalk.default.cyan(" \u2190 current") : "";
output_manager_default.print(` ${prefix} ${num} ${name} ${src}${marker}
`);
}
output_manager_default.print("\n");
const input = await client.input.text({
message: `Move "${route.name}" to position (1-${routes.length}, "first", or "last"):`,
validate: (val) => {
if (!val)
return "Position is required";
if (val === "first" || val === "last")
return true;
const num = parseInt(val, 10);
if (isNaN(num) || num < 1 || num > routes.length) {
return `Enter a number between 1 and ${routes.length}, "first", or "last"`;
}
return true;
}
});
if (input === "first") {
targetIndex = 0;
} else if (input === "last") {
targetIndex = routes.length;
} else {
targetIndex = parseInt(input, 10) - 1;
}
}
const adjustedTarget = currentIndex < targetIndex ? targetIndex - 1 : targetIndex;
const clampedTarget = Math.max(
0,
Math.min(adjustedTarget, routes.length - 1)
);
if (currentIndex === clampedTarget) {
output_manager_default.log(
`Route "${route.name}" is already at position ${currentPosition}.`
);
return 0;
}
const finalPosition = clampedTarget + 1;
if (!skipConfirmation) {
const confirmed = await client.input.confirm(
`Move "${route.name}" from position ${currentPosition} to position ${finalPosition}?`,
true
);
if (!confirmed) {
output_manager_default.log("Aborted.");
return 0;
}
}
const reordered = [...routes];
reordered.splice(currentIndex, 1);
reordered.splice(clampedTarget, 0, route);
const reorderStamp = stamp_default();
output_manager_default.spinner(`Moving route "${route.name}"`);
try {
const { version } = await stageRoutes(
client,
project.id,
reordered,
true,
// overwrite
{ teamId }
);
output_manager_default.log(
`${import_chalk.default.cyan("Moved")} "${route.name}" from position ${currentPosition} to ${finalPosition} ${import_chalk.default.gray(reorderStamp())}`
);
await offerAutoPromote(
client,
project.id,
version,
!!existingStagingVersion,
{ teamId, skipPrompts: skipConfirmation }
);
return 0;
} catch (e) {
const error = e;
output_manager_default.error(error.message || "Failed to reorder route");
return 1;
}
}
export {
reorder as default
};
import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath as __fileURLToPath } from 'node:url';
import { dirname as __dirname_ } from 'node:path';
const require = __createRequire(import.meta.url);
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __dirname_(__filename);
import {
updateRouteVersion
} from "./chunk-PMSMUMUO.js";
import {
getRouteVersions
} from "./chunk-AHU7WNL2.js";
import {
confirmAction,
ensureProjectLink,
findVersionById,
getRoutes,
parseSubcommandArgs,
printDiffSummary,
validateRequiredArgs
} from "./chunk-PAX6W6YL.js";
import {
restoreSubcommand
} from "./chunk-U6XOC6E4.js";
import "./chunk-BMTLRU2D.js";
import "./chunk-XB2KZC2B.js";
import {
stamp_default
} from "./chunk-SOTR4CXR.js";
import "./chunk-7EHTK7LP.js";
import "./chunk-GGP5R3FU.js";
import {
getCommandName
} from "./chunk-ZLCMHY2G.js";
import "./chunk-3XFFP2BA.js";
import {
output_manager_default
} from "./chunk-FDJURQMQ.js";
import {
require_source
} from "./chunk-S7KYDPEM.js";
import {
__toESM
} from "./chunk-TZ2YI2VH.js";
// src/commands/routes/restore.ts
var import_chalk = __toESM(require_source(), 1);
async function restore(client, argv) {
const parsed = await parseSubcommandArgs(argv, restoreSubcommand);
if (typeof parsed === "number")
return parsed;
const error = validateRequiredArgs(parsed.args, ["version-id"]);
if (error) {
output_manager_default.error(error);
return 1;
}
const link = await ensureProjectLink(client);
if (typeof link === "number")
return link;
const { project, org } = link;
const teamId = org.type === "team" ? org.id : void 0;
const [versionIdentifier] = parsed.args;
output_manager_default.spinner(`Fetching route versions for ${import_chalk.default.bold(project.name)}`);
const { versions } = await getRouteVersions(client, project.id, { teamId });
const result = findVersionById(versions, versionIdentifier);
if (result.error) {
output_manager_default.error(result.error);
return 1;
}
const version = result.version;
if (!version) {
output_manager_default.error("Version not found.");
return 1;
}
if (version.isLive) {
output_manager_default.error(
`Version ${import_chalk.default.bold(
version.id.slice(0, 12)
)} is currently live. You cannot restore the live version.
Run ${import_chalk.default.cyan(
getCommandName("routes list-versions")
)} to see previous versions you can restore.`
);
return 1;
}
if (version.isStaging) {
output_manager_default.error(
`Version ${import_chalk.default.bold(
version.id.slice(0, 12)
)} is staged. Use ${import_chalk.default.cyan(
getCommandName("routes publish")
)} to publish it instead.`
);
return 1;
}
output_manager_default.spinner("Fetching changes");
const { routes: diffRoutes } = await getRoutes(client, project.id, {
teamId,
versionId: version.id,
diff: true
});
const changedRoutes = diffRoutes.filter((r) => r.action !== void 0);
if (changedRoutes.length > 0) {
output_manager_default.print(`
${import_chalk.default.bold("Changes to be restored:")}
`);
printDiffSummary(changedRoutes);
output_manager_default.print("\n");
} else {
output_manager_default.print(
`
${import_chalk.default.gray("No changes detected from current production version.")}
`
);
}
const confirmed = await confirmAction(
client,
parsed.flags["--yes"],
`Restore version ${import_chalk.default.bold(version.id.slice(0, 12))} to production?`,
`This will replace the current live routes for ${import_chalk.default.bold(project.name)}.`
);
if (!confirmed) {
output_manager_default.log("Canceled");
return 0;
}
const updateStamp = stamp_default();
output_manager_default.spinner(`Restoring version ${import_chalk.default.bold(version.id.slice(0, 12))}`);
try {
const { version: newVersion } = await updateRouteVersion(
client,
project.id,
version.id,
"restore",
{ teamId }
);
output_manager_default.log(
`${import_chalk.default.cyan("Success!")} Version ${import_chalk.default.bold(
newVersion.id.slice(0, 12)
)} restored to production ${import_chalk.default.gray(updateStamp())}`
);
if (newVersion.ruleCount !== void 0) {
output_manager_default.print(
` ${import_chalk.default.bold("Active routes:")} ${newVersion.ruleCount}
`
);
}
return 0;
} catch (e) {
const error2 = e;
output_manager_default.error(error2.message || "Failed to restore version");
return 1;
}
}
export {
restore as default
};

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display