UNPKG

vercel

Version:

The command-line interface for Vercel

1,552 lines (1,518 loc) • 91.4 kB
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 { highlight } from "./chunk-V5P25P7F.js"; import { ua_default } from "./chunk-76ZNZKIN.js"; import { getLocalPathConfig } from "./chunk-4VPRHRPA.js"; import { autoInstallVercelPlugin } from "./chunk-ZKKIBUCU.js"; import { DEFAULT_VERCEL_CONFIG_FILENAME, VERCEL_CONFIG_EXTENSIONS, VERCEL_DIR, createPrompt, esm_default, esm_default2, esm_default3, getUser, humanizePath, isBackspaceKey, isEnterKey, isVercelTomlEnabled, makeTheme, onExit, require_cli_width, require_dist as require_dist2, require_lib2 as require_lib, require_source as require_source2, require_wrap_ansi, useKeypress, usePrefix, useState } from "./chunk-X775BOSL.js"; import { require_load_json_file } from "./chunk-4OEA5ILS.js"; import { require_lib as require_lib2 } from "./chunk-N2T234LO.js"; import { parseArguments, printError, require_strip_ansi } from "./chunk-4GQQJY5Y.js"; import { APIError, NowError, getCommandName } from "./chunk-UGXBNJMO.js"; import { emoji, link_default, output_manager_default, prependEmoji, require_ansi_escapes, require_dist } from "./chunk-ZQKJVHXY.js"; import { require_source } from "./chunk-S7KYDPEM.js"; import { __commonJS, __publicField, __require, __toESM } from "./chunk-TZ2YI2VH.js"; // ../../node_modules/.pnpm/yoctocolors-cjs@2.1.3/node_modules/yoctocolors-cjs/index.js var require_yoctocolors_cjs = __commonJS({ "../../node_modules/.pnpm/yoctocolors-cjs@2.1.3/node_modules/yoctocolors-cjs/index.js"(exports, module) { var tty = __require("tty"); var hasColors = tty?.WriteStream?.prototype?.hasColors?.() ?? false; var format = (open2, close) => { if (!hasColors) { return (input) => input; } const openCode = `\x1B[${open2}m`; const closeCode = `\x1B[${close}m`; return (input) => { const string = input + ""; let index = string.indexOf(closeCode); if (index === -1) { return openCode + string + closeCode; } let result = openCode; let lastIndex = 0; const reopenOnNestedClose = close === 22; const replaceCode = (reopenOnNestedClose ? closeCode : "") + openCode; while (index !== -1) { result += string.slice(lastIndex, index) + replaceCode; lastIndex = index + closeCode.length; index = string.indexOf(closeCode, lastIndex); } result += string.slice(lastIndex) + closeCode; return result; }; }; var colors4 = {}; colors4.reset = format(0, 0); colors4.bold = format(1, 22); colors4.dim = format(2, 22); colors4.italic = format(3, 23); colors4.underline = format(4, 24); colors4.overline = format(53, 55); colors4.inverse = format(7, 27); colors4.hidden = format(8, 28); colors4.strikethrough = format(9, 29); colors4.black = format(30, 39); colors4.red = format(31, 39); colors4.green = format(32, 39); colors4.yellow = format(33, 39); colors4.blue = format(34, 39); colors4.magenta = format(35, 39); colors4.cyan = format(36, 39); colors4.white = format(37, 39); colors4.gray = format(90, 39); colors4.bgBlack = format(40, 49); colors4.bgRed = format(41, 49); colors4.bgGreen = format(42, 49); colors4.bgYellow = format(43, 49); colors4.bgBlue = format(44, 49); colors4.bgMagenta = format(45, 49); colors4.bgCyan = format(46, 49); colors4.bgWhite = format(47, 49); colors4.bgGray = format(100, 49); colors4.redBright = format(91, 39); colors4.greenBright = format(92, 39); colors4.yellowBright = format(93, 39); colors4.blueBright = format(94, 39); colors4.magentaBright = format(95, 39); colors4.cyanBright = format(96, 39); colors4.whiteBright = format(97, 39); colors4.bgRedBright = format(101, 49); colors4.bgGreenBright = format(102, 49); colors4.bgYellowBright = format(103, 49); colors4.bgBlueBright = format(104, 49); colors4.bgMagentaBright = format(105, 49); colors4.bgCyanBright = format(106, 49); colors4.bgWhiteBright = format(107, 49); module.exports = colors4; } }); // ../../node_modules/.pnpm/retry@0.10.1/node_modules/retry/lib/retry_operation.js var require_retry_operation = __commonJS({ "../../node_modules/.pnpm/retry@0.10.1/node_modules/retry/lib/retry_operation.js"(exports, module) { function RetryOperation(timeouts, options) { if (typeof options === "boolean") { options = { forever: options }; } this._timeouts = timeouts; this._options = options || {}; this._fn = null; this._errors = []; this._attempts = 1; this._operationTimeout = null; this._operationTimeoutCb = null; this._timeout = null; if (this._options.forever) { this._cachedTimeouts = this._timeouts.slice(0); } } module.exports = RetryOperation; RetryOperation.prototype.stop = function() { if (this._timeout) { clearTimeout(this._timeout); } this._timeouts = []; this._cachedTimeouts = null; }; RetryOperation.prototype.retry = function(err) { if (this._timeout) { clearTimeout(this._timeout); } if (!err) { return false; } this._errors.push(err); var timeout = this._timeouts.shift(); if (timeout === void 0) { if (this._cachedTimeouts) { this._errors.splice(this._errors.length - 1, this._errors.length); this._timeouts = this._cachedTimeouts.slice(0); timeout = this._timeouts.shift(); } else { return false; } } var self = this; var timer = setTimeout(function() { self._attempts++; if (self._operationTimeoutCb) { self._timeout = setTimeout(function() { self._operationTimeoutCb(self._attempts); }, self._operationTimeout); if (this._options.unref) { self._timeout.unref(); } } self._fn(self._attempts); }, timeout); if (this._options.unref) { timer.unref(); } return true; }; RetryOperation.prototype.attempt = function(fn, timeoutOps) { this._fn = fn; if (timeoutOps) { if (timeoutOps.timeout) { this._operationTimeout = timeoutOps.timeout; } if (timeoutOps.cb) { this._operationTimeoutCb = timeoutOps.cb; } } var self = this; if (this._operationTimeoutCb) { this._timeout = setTimeout(function() { self._operationTimeoutCb(); }, self._operationTimeout); } this._fn(this._attempts); }; RetryOperation.prototype.try = function(fn) { console.log("Using RetryOperation.try() is deprecated"); this.attempt(fn); }; RetryOperation.prototype.start = function(fn) { console.log("Using RetryOperation.start() is deprecated"); this.attempt(fn); }; RetryOperation.prototype.start = RetryOperation.prototype.try; RetryOperation.prototype.errors = function() { return this._errors; }; RetryOperation.prototype.attempts = function() { return this._attempts; }; RetryOperation.prototype.mainError = function() { if (this._errors.length === 0) { return null; } var counts = {}; var mainError = null; var mainErrorCount = 0; for (var i = 0; i < this._errors.length; i++) { var error = this._errors[i]; var message = error.message; var count = (counts[message] || 0) + 1; counts[message] = count; if (count >= mainErrorCount) { mainError = error; mainErrorCount = count; } } return mainError; }; } }); // ../../node_modules/.pnpm/retry@0.10.1/node_modules/retry/lib/retry.js var require_retry = __commonJS({ "../../node_modules/.pnpm/retry@0.10.1/node_modules/retry/lib/retry.js"(exports) { var RetryOperation = require_retry_operation(); exports.operation = function(options) { var timeouts = exports.timeouts(options); return new RetryOperation(timeouts, { forever: options && options.forever, unref: options && options.unref }); }; exports.timeouts = function(options) { if (options instanceof Array) { return [].concat(options); } var opts = { retries: 10, factor: 2, minTimeout: 1 * 1e3, maxTimeout: Infinity, randomize: false }; for (var key in options) { opts[key] = options[key]; } if (opts.minTimeout > opts.maxTimeout) { throw new Error("minTimeout is greater than maxTimeout"); } var timeouts = []; for (var i = 0; i < opts.retries; i++) { timeouts.push(this.createTimeout(i, opts)); } if (options && options.forever && !timeouts.length) { timeouts.push(this.createTimeout(i, opts)); } timeouts.sort(function(a, b) { return a - b; }); return timeouts; }; exports.createTimeout = function(attempt, opts) { var random = opts.randomize ? Math.random() + 1 : 1; var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt)); timeout = Math.min(timeout, opts.maxTimeout); return timeout; }; exports.wrap = function(obj, options, methods) { if (options instanceof Array) { methods = options; options = null; } if (!methods) { methods = []; for (var key in obj) { if (typeof obj[key] === "function") { methods.push(key); } } } for (var i = 0; i < methods.length; i++) { var method = methods[i]; var original = obj[method]; obj[method] = function retryWrapper() { var op = exports.operation(options); var args = Array.prototype.slice.call(arguments); var callback = args.pop(); args.push(function(err) { if (op.retry(err)) { return; } if (err) { arguments[0] = op.mainError(); } callback.apply(this, arguments); }); op.attempt(function() { original.apply(obj, args); }); }; obj[method].options = options; } }; } }); // ../../node_modules/.pnpm/retry@0.10.1/node_modules/retry/index.js var require_retry2 = __commonJS({ "../../node_modules/.pnpm/retry@0.10.1/node_modules/retry/index.js"(exports, module) { module.exports = require_retry(); } }); // ../../node_modules/.pnpm/async-retry@1.1.3/node_modules/async-retry/dist/index.js var require_dist3 = __commonJS({ "../../node_modules/.pnpm/async-retry@1.1.3/node_modules/async-retry/dist/index.js"(exports, module) { "use strict"; var retrier = require_retry2(); module.exports = function(fn, opts) { opts = opts || {}; return new Promise(function(resolve2, reject) { var op = retrier.operation(opts); var bail = function bail2(err) { return reject(err || new Error("Aborted")); }; var onError = function onError2(err) { if (err.bail) { return bail(err); } if (!op.retry(err)) { reject(op.mainError()); } else if (opts.onRetry) { opts.onRetry(err); } }; op.attempt(function(num) { var val = void 0; try { val = fn(bail, num); } catch (err) { return onError(err); } Promise.resolve(val).then(resolve2, onError); }); }); }; } }); // ../../node_modules/.pnpm/is-docker@2.2.1/node_modules/is-docker/index.js var require_is_docker = __commonJS({ "../../node_modules/.pnpm/is-docker@2.2.1/node_modules/is-docker/index.js"(exports, module) { "use strict"; var fs = __require("fs"); var isDocker; function hasDockerEnv() { try { fs.statSync("/.dockerenv"); return true; } catch (_) { return false; } } function hasDockerCGroup() { try { return fs.readFileSync("/proc/self/cgroup", "utf8").includes("docker"); } catch (_) { return false; } } module.exports = () => { if (isDocker === void 0) { isDocker = hasDockerEnv() || hasDockerCGroup(); } return isDocker; }; } }); // ../../node_modules/.pnpm/is-wsl@2.2.0/node_modules/is-wsl/index.js var require_is_wsl = __commonJS({ "../../node_modules/.pnpm/is-wsl@2.2.0/node_modules/is-wsl/index.js"(exports, module) { "use strict"; var os = __require("os"); var fs = __require("fs"); var isDocker = require_is_docker(); var isWsl = () => { if (process.platform !== "linux") { return false; } if (os.release().toLowerCase().includes("microsoft")) { if (isDocker()) { return false; } return true; } try { return fs.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft") ? !isDocker() : false; } catch (_) { return false; } }; if (process.env.__IS_WSL_TEST__) { module.exports = isWsl; } else { module.exports = isWsl(); } } }); // ../../node_modules/.pnpm/define-lazy-prop@2.0.0/node_modules/define-lazy-prop/index.js var require_define_lazy_prop = __commonJS({ "../../node_modules/.pnpm/define-lazy-prop@2.0.0/node_modules/define-lazy-prop/index.js"(exports, module) { "use strict"; module.exports = (object, propertyName, fn) => { const define = (value) => Object.defineProperty(object, propertyName, { value, enumerable: true, writable: true }); Object.defineProperty(object, propertyName, { configurable: true, enumerable: true, get() { const result = fn(); define(result); return result; }, set(value) { define(value); } }); return object; }; } }); // ../../node_modules/.pnpm/open@8.4.0/node_modules/open/index.js var require_open = __commonJS({ "../../node_modules/.pnpm/open@8.4.0/node_modules/open/index.js"(exports, module) { var path2 = __require("path"); var childProcess = __require("child_process"); var { promises: fs, constants: fsConstants } = __require("fs"); var isWsl = require_is_wsl(); var isDocker = require_is_docker(); var defineLazyProperty = require_define_lazy_prop(); var localXdgOpenPath = path2.join(__dirname, "xdg-open"); var { platform, arch } = process; var getWslDrivesMountPoint = (() => { const defaultMountPoint = "/mnt/"; let mountPoint; return async function() { if (mountPoint) { return mountPoint; } const configFilePath = "/etc/wsl.conf"; let isConfigFileExists = false; try { await fs.access(configFilePath, fsConstants.F_OK); isConfigFileExists = true; } catch { } if (!isConfigFileExists) { return defaultMountPoint; } const configContent = await fs.readFile(configFilePath, { encoding: "utf8" }); const configMountPoint = /(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(configContent); if (!configMountPoint) { return defaultMountPoint; } mountPoint = configMountPoint.groups.mountPoint.trim(); mountPoint = mountPoint.endsWith("/") ? mountPoint : `${mountPoint}/`; return mountPoint; }; })(); var pTryEach = async (array, mapper) => { let latestError; for (const item of array) { try { return await mapper(item); } catch (error) { latestError = error; } } throw latestError; }; var baseOpen = async (options) => { options = { wait: false, background: false, newInstance: false, allowNonzeroExitCode: false, ...options }; if (Array.isArray(options.app)) { return pTryEach(options.app, (singleApp) => baseOpen({ ...options, app: singleApp })); } let { name: app, arguments: appArguments = [] } = options.app || {}; appArguments = [...appArguments]; if (Array.isArray(app)) { return pTryEach(app, (appName) => baseOpen({ ...options, app: { name: appName, arguments: appArguments } })); } let command; const cliArguments = []; const childProcessOptions = {}; if (platform === "darwin") { command = "open"; if (options.wait) { cliArguments.push("--wait-apps"); } if (options.background) { cliArguments.push("--background"); } if (options.newInstance) { cliArguments.push("--new"); } if (app) { cliArguments.push("-a", app); } } else if (platform === "win32" || isWsl && !isDocker()) { const mountPoint = await getWslDrivesMountPoint(); command = isWsl ? `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe` : `${process.env.SYSTEMROOT}\\System32\\WindowsPowerShell\\v1.0\\powershell`; cliArguments.push( "-NoProfile", "-NonInteractive", "\u2013ExecutionPolicy", "Bypass", "-EncodedCommand" ); if (!isWsl) { childProcessOptions.windowsVerbatimArguments = true; } const encodedArguments = ["Start"]; if (options.wait) { encodedArguments.push("-Wait"); } if (app) { encodedArguments.push(`"\`"${app}\`""`, "-ArgumentList"); if (options.target) { appArguments.unshift(options.target); } } else if (options.target) { encodedArguments.push(`"${options.target}"`); } if (appArguments.length > 0) { appArguments = appArguments.map((arg) => `"\`"${arg}\`""`); encodedArguments.push(appArguments.join(",")); } options.target = Buffer.from(encodedArguments.join(" "), "utf16le").toString("base64"); } else { if (app) { command = app; } else { const isBundled = !__dirname || __dirname === "/"; let exeLocalXdgOpen = false; try { await fs.access(localXdgOpenPath, fsConstants.X_OK); exeLocalXdgOpen = true; } catch { } const useSystemXdgOpen = process.versions.electron || platform === "android" || isBundled || !exeLocalXdgOpen; command = useSystemXdgOpen ? "xdg-open" : localXdgOpenPath; } if (appArguments.length > 0) { cliArguments.push(...appArguments); } if (!options.wait) { childProcessOptions.stdio = "ignore"; childProcessOptions.detached = true; } } if (options.target) { cliArguments.push(options.target); } if (platform === "darwin" && appArguments.length > 0) { cliArguments.push("--args", ...appArguments); } const subprocess = childProcess.spawn(command, cliArguments, childProcessOptions); if (options.wait) { return new Promise((resolve2, reject) => { subprocess.once("error", reject); subprocess.once("close", (exitCode) => { if (options.allowNonzeroExitCode && exitCode > 0) { reject(new Error(`Exited with code ${exitCode}`)); return; } resolve2(subprocess); }); }); } subprocess.unref(); return subprocess; }; var open2 = (target, options) => { if (typeof target !== "string") { throw new TypeError("Expected a `target`"); } return baseOpen({ ...options, target }); }; var openApp = (name, options) => { if (typeof name !== "string") { throw new TypeError("Expected a `name`"); } const { arguments: appArguments = [] } = options || {}; if (appArguments !== void 0 && appArguments !== null && !Array.isArray(appArguments)) { throw new TypeError("Expected `appArguments` as Array type"); } return baseOpen({ ...options, app: { name, arguments: appArguments } }); }; function detectArchBinary(binary) { if (typeof binary === "string" || Array.isArray(binary)) { return binary; } const { [arch]: archBinary } = binary; if (!archBinary) { throw new Error(`${arch} is not supported`); } return archBinary; } function detectPlatformBinary({ [platform]: platformBinary }, { wsl }) { if (wsl && isWsl) { return detectArchBinary(wsl); } if (!platformBinary) { throw new Error(`${platform} is not supported`); } return detectArchBinary(platformBinary); } var apps = {}; defineLazyProperty(apps, "chrome", () => detectPlatformBinary({ darwin: "google chrome", win32: "chrome", linux: ["google-chrome", "google-chrome-stable", "chromium"] }, { wsl: { ia32: "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe", x64: ["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe", "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"] } })); defineLazyProperty(apps, "firefox", () => detectPlatformBinary({ darwin: "firefox", win32: "C:\\Program Files\\Mozilla Firefox\\firefox.exe", linux: "firefox" }, { wsl: "/mnt/c/Program Files/Mozilla Firefox/firefox.exe" })); defineLazyProperty(apps, "edge", () => detectPlatformBinary({ darwin: "microsoft edge", win32: "msedge", linux: ["microsoft-edge", "microsoft-edge-dev"] }, { wsl: "/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe" })); open2.apps = apps; open2.openApp = openApp; module.exports = open2; } }); // src/util/config/global-path.ts import path from "path"; import * as config from "@vercel/cli-config"; function getGlobalPathConfig2(argvSlice = process.argv.slice(2), cwd = process.cwd()) { const args = parseArguments(argvSlice, {}, { permissive: true }); const confFlag = args.flags["--global-config"]; if (confFlag) { return path.resolve(cwd, confFlag); } else { return config.getGlobalPathConfig(); } } // src/util/config/files.ts var import_load_json_file = __toESM(require_load_json_file(), 1); var import_client = __toESM(require_dist2(), 1); import { join, basename, dirname } from "path"; import { accessSync, constants } from "fs"; import * as config2 from "@vercel/cli-config"; var import_error_utils = __toESM(require_dist(), 1); var VERCEL_DIR2 = getGlobalPathConfig2(); var CONFIG_FILE_PATH = config2.getConfigFilePath(VERCEL_DIR2); var AUTH_CONFIG_FILE_PATH = config2.getAuthConfigFilePath(VERCEL_DIR2); var readConfigFile = () => { return config2.readGlobalConfigFile(CONFIG_FILE_PATH); }; var writeToConfigFile = (stuff) => { try { config2.writeGlobalConfigFile(CONFIG_FILE_PATH, stuff); } catch (err) { if ((0, import_error_utils.isErrnoException)(err)) { if ((0, import_error_utils.isErrnoException)(err) && err.code === "EPERM") { output_manager_default.error( `Not able to create ${highlight( CONFIG_FILE_PATH )} (operation not permitted).` ); process.exit(1); } else if (err.code === "EBADF") { output_manager_default.error( `Not able to create ${highlight( CONFIG_FILE_PATH )} (bad file descriptor).` ); process.exit(1); } } throw err; } }; var readAuthConfigFile2 = () => { return config2.readAuthConfigFile(AUTH_CONFIG_FILE_PATH); }; var writeToAuthConfigFile = (authConfig) => { try { return config2.writeAuthConfigFile(AUTH_CONFIG_FILE_PATH, authConfig); } catch (err) { if ((0, import_error_utils.isErrnoException)(err)) { if (err.code === "EPERM") { output_manager_default.error( `Not able to create ${highlight( AUTH_CONFIG_FILE_PATH )} (operation not permitted).` ); process.exit(1); } else if (err.code === "EBADF") { output_manager_default.error( `Not able to create ${highlight( AUTH_CONFIG_FILE_PATH )} (bad file descriptor).` ); process.exit(1); } } throw err; } }; function getConfigFilePath2() { return CONFIG_FILE_PATH; } function getAuthConfigFilePath2() { return AUTH_CONFIG_FILE_PATH; } function readLocalConfig(prefix = process.cwd()) { let config3 = void 0; let target = ""; try { target = getLocalPathConfig(prefix); } catch (err) { if (err instanceof NowError) { output_manager_default.error(err.message); process.exit(1); } else { throw err; } } if (!target) { return; } try { accessSync(target, constants.F_OK); config3 = import_load_json_file.default.sync(target); } catch (err) { if ((0, import_error_utils.isErrnoException)(err) && err.code === "ENOENT") { } else if ((0, import_error_utils.isError)(err) && err.name === "JSONError") { output_manager_default.error(err.message); process.exit(1); } else if ((0, import_error_utils.isErrnoException)(err)) { const code = err.code ? ` (${err.code})` : ""; output_manager_default.error(`Failed to read config file: ${target}${code}`); process.exit(1); } else { output_manager_default.prettyError(err); process.exit(1); } } if (!config3) { return; } const isCompiledConfig = basename(target) === "vercel.json" && basename(dirname(target)) === VERCEL_DIR; if (isCompiledConfig) { const workPath = dirname(dirname(target)); let sourceFile = null; for (const ext of VERCEL_CONFIG_EXTENSIONS) { const configPath = join(workPath, `vercel.${ext}`); try { accessSync(configPath, constants.F_OK); sourceFile = basename(configPath); break; } catch { } } if (!sourceFile && isVercelTomlEnabled()) { const tomlPath = join(workPath, "vercel.toml"); try { accessSync(tomlPath, constants.F_OK); sourceFile = "vercel.toml"; } catch { } } config3[import_client.fileNameSymbol] = sourceFile || DEFAULT_VERCEL_CONFIG_FILENAME; } else { config3[import_client.fileNameSymbol] = basename(target); } return config3; } // src/util/client.ts var import_chalk5 = __toESM(require_source(), 1); // ../../node_modules/.pnpm/@inquirer+confirm@3.1.2/node_modules/@inquirer/confirm/dist/esm/index.mjs var esm_default4 = createPrompt((config3, done) => { const { transformer = (answer) => answer ? "yes" : "no" } = config3; const [status, setStatus] = useState("pending"); const [value, setValue] = useState(""); const theme = makeTheme(config3.theme); const prefix = usePrefix({ theme }); useKeypress((key, rl) => { if (isEnterKey(key)) { let answer = config3.default !== false; if (/^(y|yes)/i.test(value)) answer = true; else if (/^(n|no)/i.test(value)) answer = false; setValue(transformer(answer)); setStatus("done"); done(answer); } else { setValue(rl.line); } }); let formattedValue = value; let defaultValue = ""; if (status === "done") { formattedValue = theme.style.answer(value); } else { defaultValue = ` ${theme.style.defaultAnswer(config3.default === false ? "y/N" : "Y/n")}`; } const message = theme.style.message(config3.message); return `${prefix} ${message}${defaultValue} ${formattedValue}`; }); // ../../node_modules/.pnpm/@inquirer+expand@2.1.2/node_modules/@inquirer/expand/dist/esm/index.mjs var import_chalk = __toESM(require_source2(), 1); var helpChoice = { key: "h", name: "Help, list all options", value: void 0 }; function getChoiceKey(choice, key) { if (key === "name") { if ("name" in choice) return choice.name; return choice.value; } if ("value" in choice) return choice.value; return choice.name; } var esm_default5 = createPrompt((config3, done) => { const { choices, default: defaultKey = "h", expanded: defaultExpandState = false } = config3; const [status, setStatus] = useState("pending"); const [value, setValue] = useState(""); const [expanded, setExpanded] = useState(defaultExpandState); const [errorMsg, setError] = useState(void 0); const theme = makeTheme(config3.theme); const prefix = usePrefix({ theme }); useKeypress((event, rl) => { if (isEnterKey(event)) { const answer = (value || defaultKey).toLowerCase(); if (answer === "h" && !expanded) { setExpanded(true); } else { const selectedChoice = choices.find(({ key }) => key === answer); if (selectedChoice) { const finalValue = getChoiceKey(selectedChoice, "value"); setValue(finalValue); setStatus("done"); done(finalValue); } else if (value === "") { setError("Please input a value"); } else { setError(`"${import_chalk.default.red(value)}" isn't an available option`); } } } else { setValue(rl.line); setError(void 0); } }); const message = theme.style.message(config3.message); if (status === "done") { return `${prefix} ${message} ${theme.style.answer(value)}`; } const allChoices = expanded ? choices : [...choices, helpChoice]; let longChoices = ""; let shortChoices = allChoices.map((choice) => { if (choice.key === defaultKey) { return choice.key.toUpperCase(); } return choice.key; }).join(""); shortChoices = ` ${theme.style.defaultAnswer(shortChoices)}`; if (expanded) { shortChoices = ""; longChoices = allChoices.map((choice) => { const line = ` ${choice.key}) ${getChoiceKey(choice, "name")}`; if (choice.key === value.toLowerCase()) { return theme.style.highlight(line); } return line; }).join("\n"); } let helpTip = ""; const currentOption = allChoices.find(({ key }) => key === value.toLowerCase()); if (currentOption) { helpTip = `${import_chalk.default.cyan(">>")} ${getChoiceKey(currentOption, "name")}`; } let error = ""; if (errorMsg) { error = theme.style.error(errorMsg); } return [ `${prefix} ${message}${shortChoices} ${value}`, [longChoices, helpTip, error].filter(Boolean).join("\n") ]; }); // ../../node_modules/.pnpm/@inquirer+input@2.1.2/node_modules/@inquirer/input/dist/esm/index.mjs var esm_default6 = createPrompt((config3, done) => { const { validate = () => true } = config3; const theme = makeTheme(config3.theme); const [status, setStatus] = useState("pending"); const [defaultValue = "", setDefaultValue] = useState(config3.default); const [errorMsg, setError] = useState(void 0); const [value, setValue] = useState(""); const isLoading = status === "loading"; const prefix = usePrefix({ isLoading, theme }); useKeypress(async (key, rl) => { if (status !== "pending") { return; } if (isEnterKey(key)) { const answer = value || defaultValue; setStatus("loading"); const isValid = await validate(answer); if (isValid === true) { setValue(answer); setStatus("done"); done(answer); } else { rl.write(value); setError(isValid || "You must provide a valid value"); setStatus("pending"); } } else if (isBackspaceKey(key) && !value) { setDefaultValue(void 0); } else if (key.name === "tab" && !value) { setDefaultValue(void 0); rl.clearLine(0); rl.write(defaultValue); setValue(defaultValue); } else { setValue(rl.line); setError(void 0); } }); const message = theme.style.message(config3.message); let formattedValue = value; if (typeof config3.transformer === "function") { formattedValue = config3.transformer(value, { isFinal: status === "done" }); } else if (status === "done") { formattedValue = theme.style.answer(value); } let defaultStr; if (defaultValue && status !== "done" && !value) { defaultStr = theme.style.defaultAnswer(defaultValue); } let error = ""; if (errorMsg) { error = theme.style.error(errorMsg); } return [ [prefix, message, defaultStr, formattedValue].filter((v) => v !== void 0).join(" "), error ]; }); // ../../node_modules/.pnpm/@inquirer+password@2.1.2/node_modules/@inquirer/password/dist/esm/index.mjs var import_ansi_escapes = __toESM(require_ansi_escapes(), 1); var esm_default7 = createPrompt((config3, done) => { const { validate = () => true } = config3; const theme = makeTheme(config3.theme); const [status, setStatus] = useState("pending"); const [errorMsg, setError] = useState(void 0); const [value, setValue] = useState(""); const isLoading = status === "loading"; const prefix = usePrefix({ isLoading, theme }); useKeypress(async (key, rl) => { if (status !== "pending") { return; } if (isEnterKey(key)) { const answer = value; setStatus("loading"); const isValid = await validate(answer); if (isValid === true) { setValue(answer); setStatus("done"); done(answer); } else { rl.write(value); setError(isValid || "You must provide a valid value"); setStatus("pending"); } } else { setValue(rl.line); setError(void 0); } }); const message = theme.style.message(config3.message); let formattedValue = ""; let helpTip; if (config3.mask) { const maskChar = typeof config3.mask === "string" ? config3.mask : "*"; formattedValue = maskChar.repeat(value.length); } else if (status !== "done") { helpTip = `${theme.style.help("[input is masked]")}${import_ansi_escapes.default.cursorHide}`; } if (status === "done") { formattedValue = theme.style.answer(formattedValue); } let error = ""; if (errorMsg) { error = theme.style.error(errorMsg); } return [[prefix, message, formattedValue, helpTip].filter(Boolean).join(" "), error]; }); // ../../node_modules/.pnpm/@inquirer+core@9.2.1/node_modules/@inquirer/core/dist/esm/lib/key.mjs var isEnterKey2 = (key) => key.name === "enter" || key.name === "return"; // ../../node_modules/.pnpm/@inquirer+core@9.2.1/node_modules/@inquirer/core/dist/esm/lib/errors.mjs var AbortPromptError = class extends Error { constructor(options) { super(); __publicField(this, "name", "AbortPromptError"); __publicField(this, "message", "Prompt was aborted"); this.cause = options?.cause; } }; var CancelPromptError = class extends Error { constructor() { super(...arguments); __publicField(this, "name", "CancelPromptError"); __publicField(this, "message", "Prompt was canceled"); } }; var ExitPromptError = class extends Error { constructor() { super(...arguments); __publicField(this, "name", "ExitPromptError"); } }; var HookError = class extends Error { constructor() { super(...arguments); __publicField(this, "name", "HookError"); } }; var ValidationError = class extends Error { constructor() { super(...arguments); __publicField(this, "name", "ValidationError"); } }; // ../../node_modules/.pnpm/@inquirer+core@9.2.1/node_modules/@inquirer/core/dist/esm/lib/use-prefix.mjs import { AsyncResource as AsyncResource2 } from "async_hooks"; // ../../node_modules/.pnpm/@inquirer+core@9.2.1/node_modules/@inquirer/core/dist/esm/lib/hook-engine.mjs import { AsyncLocalStorage, AsyncResource } from "async_hooks"; var hookStorage = new AsyncLocalStorage(); function createStore(rl) { const store = { rl, hooks: [], hooksCleanup: [], hooksEffect: [], index: 0, handleChange() { } }; return store; } function withHooks(rl, cb) { const store = createStore(rl); return hookStorage.run(store, () => { function cycle(render) { store.handleChange = () => { store.index = 0; render(); }; store.handleChange(); } return cb(cycle); }); } function getStore() { const store = hookStorage.getStore(); if (!store) { throw new HookError("[Inquirer] Hook functions can only be called from within a prompt"); } return store; } function readline() { return getStore().rl; } function withUpdates(fn) { const wrapped = (...args) => { const store = getStore(); let shouldUpdate = false; const oldHandleChange = store.handleChange; store.handleChange = () => { shouldUpdate = true; }; const returnValue = fn(...args); if (shouldUpdate) { oldHandleChange(); } store.handleChange = oldHandleChange; return returnValue; }; return AsyncResource.bind(wrapped); } function withPointer(cb) { const store = getStore(); const { index } = store; const pointer = { get() { return store.hooks[index]; }, set(value) { store.hooks[index] = value; }, initialized: index in store.hooks }; const returnValue = cb(pointer); store.index++; return returnValue; } function handleChange() { getStore().handleChange(); } var effectScheduler = { queue(cb) { const store = getStore(); const { index } = store; store.hooksEffect.push(() => { store.hooksCleanup[index]?.(); const cleanFn = cb(readline()); if (cleanFn != null && typeof cleanFn !== "function") { throw new ValidationError("useEffect return value must be a cleanup function or nothing."); } store.hooksCleanup[index] = cleanFn; }); }, run() { const store = getStore(); withUpdates(() => { store.hooksEffect.forEach((effect) => { effect(); }); store.hooksEffect.length = 0; })(); }, clearAll() { const store = getStore(); store.hooksCleanup.forEach((cleanFn) => { cleanFn?.(); }); store.hooksEffect.length = 0; store.hooksCleanup.length = 0; } }; // ../../node_modules/.pnpm/@inquirer+core@9.2.1/node_modules/@inquirer/core/dist/esm/lib/use-state.mjs function useState2(defaultValue) { return withPointer((pointer) => { const setFn = (newValue) => { if (pointer.get() !== newValue) { pointer.set(newValue); handleChange(); } }; if (pointer.initialized) { return [pointer.get(), setFn]; } const value = typeof defaultValue === "function" ? defaultValue() : defaultValue; pointer.set(value); return [value, setFn]; }); } // ../../node_modules/.pnpm/@inquirer+core@9.2.1/node_modules/@inquirer/core/dist/esm/lib/use-effect.mjs function useEffect(cb, depArray) { withPointer((pointer) => { const oldDeps = pointer.get(); const hasChanged = !Array.isArray(oldDeps) || depArray.some((dep, i) => !Object.is(dep, oldDeps[i])); if (hasChanged) { effectScheduler.queue(cb); } pointer.set(depArray); }); } // ../../node_modules/.pnpm/@inquirer+core@9.2.1/node_modules/@inquirer/core/dist/esm/lib/theme.mjs var import_yoctocolors_cjs = __toESM(require_yoctocolors_cjs(), 1); var defaultTheme = { prefix: { idle: import_yoctocolors_cjs.default.blue("?"), // TODO: use figure done: import_yoctocolors_cjs.default.green(esm_default.tick) }, spinner: { interval: 80, frames: ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"].map((frame) => import_yoctocolors_cjs.default.yellow(frame)) }, style: { answer: import_yoctocolors_cjs.default.cyan, message: import_yoctocolors_cjs.default.bold, error: (text) => import_yoctocolors_cjs.default.red(`> ${text}`), defaultAnswer: (text) => import_yoctocolors_cjs.default.dim(`(${text})`), help: import_yoctocolors_cjs.default.dim, highlight: import_yoctocolors_cjs.default.cyan, key: (text) => import_yoctocolors_cjs.default.cyan(import_yoctocolors_cjs.default.bold(`<${text}>`)) } }; // ../../node_modules/.pnpm/@inquirer+core@9.2.1/node_modules/@inquirer/core/dist/esm/lib/make-theme.mjs function isPlainObject(value) { if (typeof value !== "object" || value === null) return false; let proto = value; while (Object.getPrototypeOf(proto) !== null) { proto = Object.getPrototypeOf(proto); } return Object.getPrototypeOf(value) === proto; } function deepMerge(...objects) { const output = {}; for (const obj of objects) { for (const [key, value] of Object.entries(obj)) { const prevValue = output[key]; output[key] = isPlainObject(prevValue) && isPlainObject(value) ? deepMerge(prevValue, value) : value; } } return output; } function makeTheme2(...themes) { const themesToMerge = [ defaultTheme, ...themes.filter((theme) => theme != null) ]; return deepMerge(...themesToMerge); } // ../../node_modules/.pnpm/@inquirer+core@9.2.1/node_modules/@inquirer/core/dist/esm/lib/use-prefix.mjs function usePrefix2({ status = "idle", theme }) { const [showLoader, setShowLoader] = useState2(false); const [tick, setTick] = useState2(0); const { prefix, spinner } = makeTheme2(theme); useEffect(() => { if (status === "loading") { let tickInterval; let inc = -1; const delayTimeout = setTimeout(AsyncResource2.bind(() => { setShowLoader(true); tickInterval = setInterval(AsyncResource2.bind(() => { inc = inc + 1; setTick(inc % spinner.frames.length); }), spinner.interval); }), 300); return () => { clearTimeout(delayTimeout); clearInterval(tickInterval); }; } else { setShowLoader(false); } }, [status]); if (showLoader) { return spinner.frames[tick]; } const iconName = status === "loading" ? "idle" : status; return typeof prefix === "string" ? prefix : prefix[iconName]; } // ../../node_modules/.pnpm/@inquirer+core@9.2.1/node_modules/@inquirer/core/dist/esm/lib/use-memo.mjs function useMemo(fn, dependencies) { return withPointer((pointer) => { const prev = pointer.get(); if (!prev || prev.dependencies.length !== dependencies.length || prev.dependencies.some((dep, i) => dep !== dependencies[i])) { const value = fn(); pointer.set({ value, dependencies }); return value; } return prev.value; }); } // ../../node_modules/.pnpm/@inquirer+core@9.2.1/node_modules/@inquirer/core/dist/esm/lib/use-ref.mjs function useRef(val) { return useState2({ current: val })[0]; } // ../../node_modules/.pnpm/@inquirer+core@9.2.1/node_modules/@inquirer/core/dist/esm/lib/use-keypress.mjs function useKeypress2(userHandler) { const signal = useRef(userHandler); signal.current = userHandler; useEffect((rl) => { let ignore = false; const handler = withUpdates((_input, event) => { if (ignore) return; void signal.current(event, rl); }); rl.input.on("keypress", handler); return () => { ignore = true; rl.input.removeListener("keypress", handler); }; }, []); } // ../../node_modules/.pnpm/@inquirer+core@9.2.1/node_modules/@inquirer/core/dist/esm/lib/utils.mjs var import_cli_width = __toESM(require_cli_width(), 1); var import_wrap_ansi = __toESM(require_wrap_ansi(), 1); function breakLines(content, width) { return content.split("\n").flatMap((line) => (0, import_wrap_ansi.default)(line, width, { trim: false, hard: true }).split("\n").map((str) => str.trimEnd())).join("\n"); } function readlineWidth() { return (0, import_cli_width.default)({ defaultWidth: 80, output: readline().output }); } // ../../node_modules/.pnpm/@inquirer+core@9.2.1/node_modules/@inquirer/core/dist/esm/lib/pagination/lines.mjs function split(content, width) { return breakLines(content, width).split("\n"); } function rotate(count, items) { const max = items.length; const offset = (count % max + max) % max; return [...items.slice(offset), ...items.slice(0, offset)]; } function lines({ items, width, renderItem, active, position: requested, pageSize }) { const layouts = items.map((item, index) => ({ item, index, isActive: index === active })); const layoutsInPage = rotate(active - requested, layouts).slice(0, pageSize); const renderItemAt = (index) => layoutsInPage[index] == null ? [] : split(renderItem(layoutsInPage[index]), width); const pageBuffer = Array.from({ length: pageSize }); const activeItem = renderItemAt(requested).slice(0, pageSize); const position = requested + activeItem.length <= pageSize ? requested : pageSize - activeItem.length; pageBuffer.splice(position, activeItem.length, ...activeItem); let bufferPointer = position + activeItem.length; let layoutPointer = requested + 1; while (bufferPointer < pageSize && layoutPointer < layoutsInPage.length) { for (const line of renderItemAt(layoutPointer)) { pageBuffer[bufferPointer++] = line; if (bufferPointer >= pageSize) break; } layoutPointer++; } bufferPointer = position - 1; layoutPointer = requested - 1; while (bufferPointer >= 0 && layoutPointer >= 0) { for (const line of renderItemAt(layoutPointer).reverse()) { pageBuffer[bufferPointer--] = line; if (bufferPointer < 0) break; } layoutPointer--; } return pageBuffer.filter((line) => typeof line === "string"); } // ../../node_modules/.pnpm/@inquirer+core@9.2.1/node_modules/@inquirer/core/dist/esm/lib/pagination/position.mjs function finite({ active, pageSize, total }) { const middle = Math.floor(pageSize / 2); if (total <= pageSize || active < middle) return active; if (active >= total - middle) return active + pageSize - total; return middle; } function infinite({ active, lastActive, total, pageSize, pointer }) { if (total <= pageSize) return active; if (lastActive < active && active - lastActive < pageSize) { return Math.min(Math.floor(pageSize / 2), pointer + active - lastActive); } return pointer; } // ../../node_modules/.pnpm/@inquirer+core@9.2.1/node_modules/@inquirer/core/dist/esm/lib/pagination/use-pagination.mjs function usePagination({ items, active, renderItem, pageSize, loop = true }) { const state = useRef({ position: 0, lastActive: 0 }); const position = loop ? infinite({ active, lastActive: state.current.lastActive, total: items.length, pageSize, pointer: state.current.position }) : finite({ active, total: items.length, pageSize }); state.current.position = position; state.current.lastActive = active; return lines({ items, width: readlineWidth(), renderItem, active, position, pageSize }).join("\n"); } // ../../node_modules/.pnpm/@inquirer+core@9.2.1/node_modules/@inquirer/core/dist/esm/lib/create-prompt.mjs var import_mute_stream = __toESM(require_lib(), 1); import * as readline2 from "readline"; import { AsyncResource as AsyncResource3 } from "async_hooks"; // ../../node_modules/.pnpm/@inquirer+core@9.2.1/node_modules/@inquirer/core/dist/esm/lib/screen-manager.mjs var import_strip_ansi = __toESM(require_strip_ansi(), 1); var import_ansi_escapes2 = __toESM(require_ansi_escapes(), 1); var height = (content) => content.split("\n").length; var lastLine = (content) => content.split("\n").pop() ?? ""; function cursorDown(n) { return n > 0 ? import_ansi_escapes2.default.cursorDown(n) : ""; } var ScreenManager = class { constructor(rl) { __publicField(this, "rl"); // These variables are keeping information to allow correct prompt re-rendering __publicField(this, "height", 0); __publicField(this, "extraLinesUnderPrompt", 0); __publicField(this, "cursorPos"); this.rl = rl; this.rl = rl; this.cursorPos = rl.getCursorPos(); } write(content) { this.rl.output.unmute(); this.rl.output.write(content); this.rl.output.mute(); } render(content, bottomContent = "") { const promptLine = lastLine(content); const rawPromptLine = (0, import_strip_ansi.default)(promptLine); let prompt = rawPromptLine; if (this.rl.line.length > 0) { prompt = prompt.slice(0, -this.rl.line.length); } this.rl.setPrompt(prompt); this.cursorPos = this.rl.getCursorPos(); const width = readlineWidth(); content = breakLines(content, width); bottomContent = breakLines(bottomContent, width); if (rawPromptLine.length % width === 0) { content += "\n"; } let output = content + (bottomContent ? "\n" + bottomContent : ""); const promptLineUpDiff = Math.floor(rawPromptLine.length / width) - this.cursorPos.rows; const bottomContentHeight = promptLineUpDiff + (bottomContent ? height(bottomContent) : 0); if (bottomContentHeight > 0) output += import_ansi_escapes2.default.cursorUp(bottomContentHeight); output += import_ansi_escapes2.default.cursorTo(this.cursorPos.cols); this.write(cursorDown(this.extraLinesUnderPrompt) + import_ansi_escapes2.default.eraseLines(this.height) + output); this.extraLinesUnderPrompt = bottomContentHeight; this.height = height(output); } checkCursorPos() { const cursorPos = this.rl.getCursorPos(); if (cu