upgrade-rspeedy
Version:
Upgrade Rspeedy-related packages
1,000 lines (999 loc) • 119 kB
JavaScript
#!/usr/bin/env node
import external_process_default from "process";
import external_os_default from "os";
import external_tty_default from "tty";
import { EOL } from "node:os";
import { createRequire } from "node:module";
import * as __WEBPACK_EXTERNAL_MODULE_node_child_process_27f17141__ from "node:child_process";
import * as __WEBPACK_EXTERNAL_MODULE_node_events_0a6aefe7__ from "node:events";
import * as __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__ from "node:fs";
import * as __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__ from "node:path";
import * as __WEBPACK_EXTERNAL_MODULE_node_process_786449bf__ from "node:process";
var __webpack_modules__ = {
"../../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js": function(module) {
let p = process || {}, argv = p.argv || [], env = p.env || {};
let isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || "win32" === p.platform || (p.stdout || {}).isTTY && "dumb" !== env.TERM || !!env.CI);
let formatter = (open, close, replace = open)=>(input)=>{
let string = "" + input, index = string.indexOf(close, open.length);
return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
};
let replaceClose = (string, close, replace, index)=>{
let result = "", cursor = 0;
do {
result += string.substring(cursor, index) + replace;
cursor = index + close.length;
index = string.indexOf(close, cursor);
}while (~index);
return result + string.substring(cursor);
};
let createColors = (enabled = isColorSupported)=>{
let f = enabled ? formatter : ()=>String;
return {
isColorSupported: enabled,
reset: f("\x1b[0m", "\x1b[0m"),
bold: f("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m"),
dim: f("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m"),
italic: f("\x1b[3m", "\x1b[23m"),
underline: f("\x1b[4m", "\x1b[24m"),
inverse: f("\x1b[7m", "\x1b[27m"),
hidden: f("\x1b[8m", "\x1b[28m"),
strikethrough: f("\x1b[9m", "\x1b[29m"),
black: f("\x1b[30m", "\x1b[39m"),
red: f("\x1b[31m", "\x1b[39m"),
green: f("\x1b[32m", "\x1b[39m"),
yellow: f("\x1b[33m", "\x1b[39m"),
blue: f("\x1b[34m", "\x1b[39m"),
magenta: f("\x1b[35m", "\x1b[39m"),
cyan: f("\x1b[36m", "\x1b[39m"),
white: f("\x1b[37m", "\x1b[39m"),
gray: f("\x1b[90m", "\x1b[39m"),
bgBlack: f("\x1b[40m", "\x1b[49m"),
bgRed: f("\x1b[41m", "\x1b[49m"),
bgGreen: f("\x1b[42m", "\x1b[49m"),
bgYellow: f("\x1b[43m", "\x1b[49m"),
bgBlue: f("\x1b[44m", "\x1b[49m"),
bgMagenta: f("\x1b[45m", "\x1b[49m"),
bgCyan: f("\x1b[46m", "\x1b[49m"),
bgWhite: f("\x1b[47m", "\x1b[49m"),
blackBright: f("\x1b[90m", "\x1b[39m"),
redBright: f("\x1b[91m", "\x1b[39m"),
greenBright: f("\x1b[92m", "\x1b[39m"),
yellowBright: f("\x1b[93m", "\x1b[39m"),
blueBright: f("\x1b[94m", "\x1b[39m"),
magentaBright: f("\x1b[95m", "\x1b[39m"),
cyanBright: f("\x1b[96m", "\x1b[39m"),
whiteBright: f("\x1b[97m", "\x1b[39m"),
bgBlackBright: f("\x1b[100m", "\x1b[49m"),
bgRedBright: f("\x1b[101m", "\x1b[49m"),
bgGreenBright: f("\x1b[102m", "\x1b[49m"),
bgYellowBright: f("\x1b[103m", "\x1b[49m"),
bgBlueBright: f("\x1b[104m", "\x1b[49m"),
bgMagentaBright: f("\x1b[105m", "\x1b[49m"),
bgCyanBright: f("\x1b[106m", "\x1b[49m"),
bgWhiteBright: f("\x1b[107m", "\x1b[49m")
};
};
module.exports = createColors();
module.exports.createColors = createColors;
},
"./src/main.ts": function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
__webpack_require__.d(__webpack_exports__, {
D: ()=>main
});
var commander = __webpack_require__("../../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/index.js");
const { program: esm_program, createCommand, createArgument, createOption, CommanderError, InvalidArgumentError, InvalidOptionArgumentError, Command, Argument, Option, Help } = commander;
function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : external_process_default.argv) {
const prefix = flag.startsWith("-") ? "" : 1 === flag.length ? "-" : "--";
const position = argv.indexOf(prefix + flag);
const terminatorPosition = argv.indexOf("--");
return -1 !== position && (-1 === terminatorPosition || position < terminatorPosition);
}
var { env } = external_process_default;
var flagForceColor;
if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) flagForceColor = 0;
else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) flagForceColor = 1;
function envForceColor() {
if ("FORCE_COLOR" in env) {
if ("true" === env.FORCE_COLOR) return 1;
if ("false" === env.FORCE_COLOR) return 0;
return 0 === env.FORCE_COLOR.length ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
}
}
function translateLevel(level) {
if (0 === level) return false;
return {
level,
hasBasic: true,
has256: level >= 2,
has16m: level >= 3
};
}
function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
const noFlagForceColor = envForceColor();
if (void 0 !== noFlagForceColor) flagForceColor = noFlagForceColor;
const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
if (0 === forceColor) return 0;
if (sniffFlags) {
if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) return 3;
if (hasFlag("color=256")) return 2;
}
if ("TF_BUILD" in env && "AGENT_NAME" in env) return 1;
if (haveStream && !streamIsTTY && void 0 === forceColor) return 0;
const min = forceColor || 0;
if ("dumb" === env.TERM) return min;
if ("win32" === external_process_default.platform) {
const osRelease = external_os_default.release().split(".");
if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) return Number(osRelease[2]) >= 14931 ? 3 : 2;
return 1;
}
if ("CI" in env) {
if ("GITHUB_ACTIONS" in env || "GITEA_ACTIONS" in env) return 3;
if ([
"TRAVIS",
"CIRCLECI",
"APPVEYOR",
"GITLAB_CI",
"BUILDKITE",
"DRONE"
].some((sign)=>sign in env) || "codeship" === env.CI_NAME) return 1;
return min;
}
if ("TEAMCITY_VERSION" in env) return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
if ("truecolor" === env.COLORTERM) return 3;
if ("xterm-kitty" === env.TERM) return 3;
if ("TERM_PROGRAM" in env) {
const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
switch(env.TERM_PROGRAM){
case "iTerm.app":
return version >= 3 ? 3 : 2;
case "Apple_Terminal":
return 2;
}
}
if (/-256(color)?$/i.test(env.TERM)) return 2;
if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) return 1;
if ("COLORTERM" in env) return 1;
return min;
}
function createSupportsColor(stream, options = {}) {
const level = _supportsColor(stream, {
streamIsTTY: stream && stream.isTTY,
...options
});
return translateLevel(level);
}
var supportsColor = {
stdout: createSupportsColor({
isTTY: external_tty_default.isatty(1)
}),
stderr: createSupportsColor({
isTTY: external_tty_default.isatty(2)
})
};
var supports_color_default = supportsColor;
var colorLevel = supports_color_default.stdout ? supports_color_default.stdout.level : 0;
var errorStackRegExp = /at\s.*:\d+:\d+[\s\)]*$/;
var anonymousErrorStackRegExp = /at\s.*\(<anonymous>\)$/;
var isErrorStackMessage = (message)=>errorStackRegExp.test(message) || anonymousErrorStackRegExp.test(message);
var formatter = (open, close, replace = open)=>colorLevel >= 2 ? (input)=>{
let string = "" + input;
let index = string.indexOf(close, open.length);
return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
} : String;
var replaceClose = (string, close, replace, index)=>{
let start = string.substring(0, index) + replace;
let end = string.substring(index + close.length);
let nextIndex = end.indexOf(close);
return ~nextIndex ? start + replaceClose(end, close, replace, nextIndex) : start + end;
};
var bold = formatter("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m");
var red = formatter("\x1B[31m", "\x1B[39m");
var green = formatter("\x1B[32m", "\x1B[39m");
var yellow = formatter("\x1B[33m", "\x1B[39m");
var magenta = formatter("\x1B[35m", "\x1B[39m");
var cyan = formatter("\x1B[36m", "\x1B[39m");
var gray = formatter("\x1B[90m", "\x1B[39m");
var startColor = [
189,
255,
243
];
var endColor = [
74,
194,
154
];
var isWord = (char)=>!/[\s\n]/.test(char);
var gradient = (message)=>{
if (colorLevel < 3) return 2 === colorLevel ? bold(cyan(message)) : message;
let chars = [
...message
];
let steps = chars.filter(isWord).length;
let r = startColor[0];
let g = startColor[1];
let b = startColor[2];
let rStep = (endColor[0] - r) / steps;
let gStep = (endColor[1] - g) / steps;
let bStep = (endColor[2] - b) / steps;
let output = "";
for (let char of chars){
if (isWord(char)) {
r += rStep;
g += gStep;
b += bStep;
}
output += `\x1B[38;2;${Math.round(r)};${Math.round(g)};${Math.round(b)}m${char}\x1B[39m`;
}
return bold(output);
};
var LOG_LEVEL = {
error: 0,
warn: 1,
info: 2,
log: 3,
verbose: 4
};
var LOG_TYPES = {
error: {
label: "error",
level: "error",
color: red
},
warn: {
label: "warn",
level: "warn",
color: yellow
},
info: {
label: "info",
level: "info",
color: cyan
},
start: {
label: "start",
level: "info",
color: cyan
},
ready: {
label: "ready",
level: "info",
color: green
},
success: {
label: "success",
level: "info",
color: green
},
log: {
level: "log"
},
debug: {
label: "debug",
level: "verbose",
color: magenta
}
};
var createLogger = (options = {})=>{
let maxLevel = options.level || "log";
let log = (type, message, ...args)=>{
if (LOG_LEVEL[LOG_TYPES[type].level] > LOG_LEVEL[maxLevel]) return;
if (null == message) return console.log();
let logType = LOG_TYPES[type];
let label = "";
let text = "";
if ("label" in logType) {
label = (logType.label || "").padEnd(7);
label = bold(logType.color ? logType.color(label) : label);
}
if (message instanceof Error) if (message.stack) {
let [name, ...rest] = message.stack.split("\n");
if (name.startsWith("Error: ")) name = name.slice(7);
text = `${name}
${gray(rest.join("\n"))}`;
} else text = message.message;
else if ("error" === logType.level && "string" == typeof message) {
let lines = message.split("\n");
text = lines.map((line)=>isErrorStackMessage(line) ? gray(line) : line).join("\n");
} else text = `${message}`;
console.log(label.length ? `${label} ${text}` : text, ...args);
};
let logger2 = {
greet: (message)=>log("log", gradient(message))
};
Object.keys(LOG_TYPES).forEach((key)=>{
logger2[key] = (...args)=>log(key, ...args);
});
Object.defineProperty(logger2, "level", {
get: ()=>maxLevel,
set (val) {
maxLevel = val;
}
});
logger2.override = (customLogger)=>{
Object.assign(logger2, customLogger);
};
return logger2;
};
var logger = createLogger();
var external_node_fs_ = __webpack_require__("node:fs");
var external_node_path_ = __webpack_require__("node:path");
const INDENT_REGEX = /^(?:( )+|\t+)/;
const INDENT_TYPE_SPACE = 'space';
const INDENT_TYPE_TAB = 'tab';
function makeIndentsMap(string, ignoreSingleSpaces) {
const indents = new Map();
let previousSize = 0;
let previousIndentType;
let key;
for (const line of string.split(/\n/g)){
if (!line) continue;
let indent;
let indentType;
let use;
let weight;
let entry;
const matches = line.match(INDENT_REGEX);
if (null === matches) {
previousSize = 0;
previousIndentType = '';
} else {
indent = matches[0].length;
indentType = matches[1] ? INDENT_TYPE_SPACE : INDENT_TYPE_TAB;
if (ignoreSingleSpaces && indentType === INDENT_TYPE_SPACE && 1 === indent) continue;
if (indentType !== previousIndentType) previousSize = 0;
previousIndentType = indentType;
use = 1;
weight = 0;
const indentDifference = indent - previousSize;
previousSize = indent;
if (0 === indentDifference) {
use = 0;
weight = 1;
} else {
const absoluteIndentDifference = indentDifference > 0 ? indentDifference : -indentDifference;
key = encodeIndentsKey(indentType, absoluteIndentDifference);
}
entry = indents.get(key);
entry = void 0 === entry ? [
1,
0
] : [
entry[0] + use,
entry[1] + weight
];
indents.set(key, entry);
}
}
return indents;
}
function encodeIndentsKey(indentType, indentAmount) {
const typeCharacter = indentType === INDENT_TYPE_SPACE ? 's' : 't';
return typeCharacter + String(indentAmount);
}
function decodeIndentsKey(indentsKey) {
const keyHasTypeSpace = 's' === indentsKey[0];
const type = keyHasTypeSpace ? INDENT_TYPE_SPACE : INDENT_TYPE_TAB;
const amount = Number(indentsKey.slice(1));
return {
type,
amount
};
}
function getMostUsedKey(indents) {
let result;
let maxUsed = 0;
let maxWeight = 0;
for (const [key, [usedCount, weight]] of indents)if (usedCount > maxUsed || usedCount === maxUsed && weight > maxWeight) {
maxUsed = usedCount;
maxWeight = weight;
result = key;
}
return result;
}
function makeIndentString(type, amount) {
const indentCharacter = type === INDENT_TYPE_SPACE ? ' ' : '\t';
return indentCharacter.repeat(amount);
}
function detectIndent(string) {
if ('string' != typeof string) throw new TypeError('Expected a string');
let indents = makeIndentsMap(string, true);
if (0 === indents.size) indents = makeIndentsMap(string, false);
const keyOfMostUsedIndent = getMostUsedKey(indents);
let type;
let amount = 0;
let indent = '';
if (void 0 !== keyOfMostUsedIndent) {
({ type, amount } = decodeIndentsKey(keyOfMostUsedIndent));
indent = makeIndentString(type, amount);
}
return {
amount,
type,
indent
};
}
var picocolors = __webpack_require__("../../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js");
var picocolors_default = /*#__PURE__*/ __webpack_require__.n(picocolors);
const version_require = createRequire(import.meta.url);
const version_pkg = version_require('../package.json');
const version_version = version_pkg.version;
const devDependencies = version_pkg.devDependencies;
const LYNX_RSPEEDY = '@lynx-js/rspeedy';
async function install(cwd) {
const packageJSONPath = external_node_path_["default"].resolve(cwd, 'package.json');
if (!external_node_fs_["default"].existsSync(packageJSONPath)) {
const message = `${picocolors_default().underline(picocolors_default().yellow(packageJSONPath))} not found. Please run ${picocolors_default().bold('upgrade-rspeedy')} in your Rspeedy project.`;
logger.error(message);
throw new Error(message);
}
try {
const content = await external_node_fs_["default"].promises.readFile(packageJSONPath, 'utf-8');
const pkg = JSON.parse(content);
if (pkg.dependencies?.[LYNX_RSPEEDY] === void 0 && pkg.devDependencies?.[LYNX_RSPEEDY] === void 0) throw new Error(`No ${picocolors_default().yellow(LYNX_RSPEEDY)} found in ${packageJSONPath}.
Please run ${picocolors_default().bold('upgrade-rspeedy')} in your Rspeedy project.`);
const { indent } = detectIndent(content);
console.info();
const dependenciesUpdated = updateDependencies(pkg, packageJSONPath, 'dependencies');
console.info();
const devDependenciesUpdated = updateDependencies(pkg, packageJSONPath, 'devDependencies');
console.info();
if (dependenciesUpdated || devDependenciesUpdated) {
await external_node_fs_["default"].promises.writeFile(packageJSONPath, JSON.stringify(pkg, null, indent) + EOL, 'utf-8');
logger.success(`${picocolors_default().yellow(packageJSONPath)} has been updated.`);
logger.success("Please install the dependencies with your package manager.");
}
} catch (error) {
logger.error(error);
throw error;
}
}
function updateDependencies(pkg, packageJSONPath, name) {
const dependencies = pkg[name];
if (!dependencies) {
logger.info(`No ${picocolors_default().yellow(name)} is found in ${picocolors_default().underline(packageJSONPath)}`);
return false;
}
const updatedDependencies = findDependencies(dependencies).filter(([, { original, target }])=>original !== target);
if (0 === updatedDependencies.length) {
logger.info(`No ${picocolors_default().yellow(name)} need to be updated in ${picocolors_default().underline(packageJSONPath)}`);
return false;
}
{
const sep = '\n - ';
logger.info(`Updated ${picocolors_default().yellow(name)}:\n${sep}${updatedDependencies.map(([name, { original, target }])=>`${picocolors_default().cyan(name)}: ${picocolors_default().dim(original)} -> ${picocolors_default().green(target)}`).join(sep)}`);
}
updatedDependencies.forEach(([dependency, { target }])=>{
dependencies[dependency] = target;
});
return true;
}
const targetDependencies = new Map(Object.entries(devDependencies ?? {}));
function findDependencies(dependencies) {
return Object.entries(dependencies).map(([name, original])=>{
if (targetDependencies.has(name) && (name.startsWith('@lynx-js/') || name.includes('rsbuild'))) return [
name,
{
original,
target: targetDependencies.get(name)
}
];
return null;
}).filter((i)=>null !== i);
}
async function main(cwd, argv) {
const program = new Command('upgrade-rspeedy');
const { npm_execpath } = process.env;
if (!npm_execpath || npm_execpath.includes('npm-cli.js') || npm_execpath.includes('npx-cli.js')) console.info();
logger.greet(`Upgrade Rspeedy v${version_version}\n`);
program.helpCommand(false).description('Upgrade the Rspeedy-related packages').action(()=>install(cwd ?? process.cwd()));
await program.parseAsync(argv);
}
},
"./src/upgrade-rspeedy.ts": function(module, __webpack_exports__, __webpack_require__) {
__webpack_require__.a(module, async function(__webpack_handle_async_dependencies__, __webpack_async_result__) {
try {
__webpack_require__.r(__webpack_exports__);
var _main_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("./src/main.ts");
await (0, _main_js__WEBPACK_IMPORTED_MODULE_0__.D)();
__webpack_async_result__();
} catch (e) {
__webpack_async_result__(e);
}
}, 1);
},
"node:child_process": function(module) {
module.exports = __WEBPACK_EXTERNAL_MODULE_node_child_process_27f17141__;
},
"node:events": function(module) {
module.exports = __WEBPACK_EXTERNAL_MODULE_node_events_0a6aefe7__;
},
"node:fs": function(module) {
module.exports = __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__;
},
"node:path": function(module) {
module.exports = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__;
},
"node:process": function(module) {
module.exports = __WEBPACK_EXTERNAL_MODULE_node_process_786449bf__;
},
"../../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/index.js": function(__unused_webpack_module, exports, __webpack_require__) {
const { Argument } = __webpack_require__("../../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/argument.js");
const { Command } = __webpack_require__("../../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/command.js");
const { CommanderError, InvalidArgumentError } = __webpack_require__("../../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/error.js");
const { Help } = __webpack_require__("../../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/help.js");
const { Option } = __webpack_require__("../../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/option.js");
exports.program = new Command();
exports.createCommand = (name)=>new Command(name);
exports.createOption = (flags, description)=>new Option(flags, description);
exports.createArgument = (name, description)=>new Argument(name, description);
exports.Command = Command;
exports.Option = Option;
exports.Argument = Argument;
exports.Help = Help;
exports.CommanderError = CommanderError;
exports.InvalidArgumentError = InvalidArgumentError;
exports.InvalidOptionArgumentError = InvalidArgumentError;
},
"../../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/argument.js": function(__unused_webpack_module, exports, __webpack_require__) {
const { InvalidArgumentError } = __webpack_require__("../../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/error.js");
class Argument {
constructor(name, description){
this.description = description || '';
this.variadic = false;
this.parseArg = void 0;
this.defaultValue = void 0;
this.defaultValueDescription = void 0;
this.argChoices = void 0;
switch(name[0]){
case '<':
this.required = true;
this._name = name.slice(1, -1);
break;
case '[':
this.required = false;
this._name = name.slice(1, -1);
break;
default:
this.required = true;
this._name = name;
break;
}
if (this._name.length > 3 && '...' === this._name.slice(-3)) {
this.variadic = true;
this._name = this._name.slice(0, -3);
}
}
name() {
return this._name;
}
_concatValue(value, previous) {
if (previous === this.defaultValue || !Array.isArray(previous)) return [
value
];
return previous.concat(value);
}
default(value, description) {
this.defaultValue = value;
this.defaultValueDescription = description;
return this;
}
argParser(fn) {
this.parseArg = fn;
return this;
}
choices(values) {
this.argChoices = values.slice();
this.parseArg = (arg, previous)=>{
if (!this.argChoices.includes(arg)) throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(', ')}.`);
if (this.variadic) return this._concatValue(arg, previous);
return arg;
};
return this;
}
argRequired() {
this.required = true;
return this;
}
argOptional() {
this.required = false;
return this;
}
}
function humanReadableArgName(arg) {
const nameOutput = arg.name() + (true === arg.variadic ? '...' : '');
return arg.required ? '<' + nameOutput + '>' : '[' + nameOutput + ']';
}
exports.Argument = Argument;
exports.humanReadableArgName = humanReadableArgName;
},
"../../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/command.js": function(__unused_webpack_module, exports, __webpack_require__) {
const EventEmitter = __webpack_require__("node:events").EventEmitter;
const childProcess = __webpack_require__("node:child_process");
const path = __webpack_require__("node:path");
const fs = __webpack_require__("node:fs");
const process1 = __webpack_require__("node:process");
const { Argument, humanReadableArgName } = __webpack_require__("../../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/argument.js");
const { CommanderError } = __webpack_require__("../../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/error.js");
const { Help, stripColor } = __webpack_require__("../../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/help.js");
const { Option, DualOptions } = __webpack_require__("../../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/option.js");
const { suggestSimilar } = __webpack_require__("../../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/suggestSimilar.js");
class Command extends EventEmitter {
constructor(name){
super();
this.commands = [];
this.options = [];
this.parent = null;
this._allowUnknownOption = false;
this._allowExcessArguments = false;
this.registeredArguments = [];
this._args = this.registeredArguments;
this.args = [];
this.rawArgs = [];
this.processedArgs = [];
this._scriptPath = null;
this._name = name || '';
this._optionValues = {};
this._optionValueSources = {};
this._storeOptionsAsProperties = false;
this._actionHandler = null;
this._executableHandler = false;
this._executableFile = null;
this._executableDir = null;
this._defaultCommandName = null;
this._exitCallback = null;
this._aliases = [];
this._combineFlagAndOptionalValue = true;
this._description = '';
this._summary = '';
this._argsDescription = void 0;
this._enablePositionalOptions = false;
this._passThroughOptions = false;
this._lifeCycleHooks = {};
this._showHelpAfterError = false;
this._showSuggestionAfterError = true;
this._savedState = null;
this._outputConfiguration = {
writeOut: (str)=>process1.stdout.write(str),
writeErr: (str)=>process1.stderr.write(str),
outputError: (str, write)=>write(str),
getOutHelpWidth: ()=>process1.stdout.isTTY ? process1.stdout.columns : void 0,
getErrHelpWidth: ()=>process1.stderr.isTTY ? process1.stderr.columns : void 0,
getOutHasColors: ()=>useColor() ?? (process1.stdout.isTTY && process1.stdout.hasColors?.()),
getErrHasColors: ()=>useColor() ?? (process1.stderr.isTTY && process1.stderr.hasColors?.()),
stripColor: (str)=>stripColor(str)
};
this._hidden = false;
this._helpOption = void 0;
this._addImplicitHelpCommand = void 0;
this._helpCommand = void 0;
this._helpConfiguration = {};
}
copyInheritedSettings(sourceCommand) {
this._outputConfiguration = sourceCommand._outputConfiguration;
this._helpOption = sourceCommand._helpOption;
this._helpCommand = sourceCommand._helpCommand;
this._helpConfiguration = sourceCommand._helpConfiguration;
this._exitCallback = sourceCommand._exitCallback;
this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
this._allowExcessArguments = sourceCommand._allowExcessArguments;
this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
this._showHelpAfterError = sourceCommand._showHelpAfterError;
this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
return this;
}
_getCommandAndAncestors() {
const result = [];
for(let command = this; command; command = command.parent)result.push(command);
return result;
}
command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
let desc = actionOptsOrExecDesc;
let opts = execOpts;
if ('object' == typeof desc && null !== desc) {
opts = desc;
desc = null;
}
opts = opts || {};
const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
const cmd = this.createCommand(name);
if (desc) {
cmd.description(desc);
cmd._executableHandler = true;
}
if (opts.isDefault) this._defaultCommandName = cmd._name;
cmd._hidden = !!(opts.noHelp || opts.hidden);
cmd._executableFile = opts.executableFile || null;
if (args) cmd.arguments(args);
this._registerCommand(cmd);
cmd.parent = this;
cmd.copyInheritedSettings(this);
if (desc) return this;
return cmd;
}
createCommand(name) {
return new Command(name);
}
createHelp() {
return Object.assign(new Help(), this.configureHelp());
}
configureHelp(configuration) {
if (void 0 === configuration) return this._helpConfiguration;
this._helpConfiguration = configuration;
return this;
}
configureOutput(configuration) {
if (void 0 === configuration) return this._outputConfiguration;
Object.assign(this._outputConfiguration, configuration);
return this;
}
showHelpAfterError(displayHelp = true) {
if ('string' != typeof displayHelp) displayHelp = !!displayHelp;
this._showHelpAfterError = displayHelp;
return this;
}
showSuggestionAfterError(displaySuggestion = true) {
this._showSuggestionAfterError = !!displaySuggestion;
return this;
}
addCommand(cmd, opts) {
if (!cmd._name) throw new Error(`Command passed to .addCommand() must have a name
- specify the name in Command constructor or using .name()`);
opts = opts || {};
if (opts.isDefault) this._defaultCommandName = cmd._name;
if (opts.noHelp || opts.hidden) cmd._hidden = true;
this._registerCommand(cmd);
cmd.parent = this;
cmd._checkForBrokenPassThrough();
return this;
}
createArgument(name, description) {
return new Argument(name, description);
}
argument(name, description, fn, defaultValue) {
const argument = this.createArgument(name, description);
if ('function' == typeof fn) argument.default(defaultValue).argParser(fn);
else argument.default(fn);
this.addArgument(argument);
return this;
}
arguments(names) {
names.trim().split(/ +/).forEach((detail)=>{
this.argument(detail);
});
return this;
}
addArgument(argument) {
const previousArgument = this.registeredArguments.slice(-1)[0];
if (previousArgument && previousArgument.variadic) throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
if (argument.required && void 0 !== argument.defaultValue && void 0 === argument.parseArg) throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
this.registeredArguments.push(argument);
return this;
}
helpCommand(enableOrNameAndArgs, description) {
if ('boolean' == typeof enableOrNameAndArgs) {
this._addImplicitHelpCommand = enableOrNameAndArgs;
return this;
}
enableOrNameAndArgs = enableOrNameAndArgs ?? 'help [command]';
const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);
const helpDescription = description ?? 'display help for command';
const helpCommand = this.createCommand(helpName);
helpCommand.helpOption(false);
if (helpArgs) helpCommand.arguments(helpArgs);
if (helpDescription) helpCommand.description(helpDescription);
this._addImplicitHelpCommand = true;
this._helpCommand = helpCommand;
return this;
}
addHelpCommand(helpCommand, deprecatedDescription) {
if ('object' != typeof helpCommand) {
this.helpCommand(helpCommand, deprecatedDescription);
return this;
}
this._addImplicitHelpCommand = true;
this._helpCommand = helpCommand;
return this;
}
_getHelpCommand() {
const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand('help'));
if (hasImplicitHelpCommand) {
if (void 0 === this._helpCommand) this.helpCommand(void 0, void 0);
return this._helpCommand;
}
return null;
}
hook(event, listener) {
const allowedValues = [
'preSubcommand',
'preAction',
'postAction'
];
if (!allowedValues.includes(event)) throw new Error(`Unexpected value for event passed to hook : '${event}'.
Expecting one of '${allowedValues.join("', '")}'`);
if (this._lifeCycleHooks[event]) this._lifeCycleHooks[event].push(listener);
else this._lifeCycleHooks[event] = [
listener
];
return this;
}
exitOverride(fn) {
if (fn) this._exitCallback = fn;
else this._exitCallback = (err)=>{
if ('commander.executeSubCommandAsync' !== err.code) throw err;
};
return this;
}
_exit(exitCode, code, message) {
if (this._exitCallback) this._exitCallback(new CommanderError(exitCode, code, message));
process1.exit(exitCode);
}
action(fn) {
const listener = (args)=>{
const expectedArgsCount = this.registeredArguments.length;
const actionArgs = args.slice(0, expectedArgsCount);
if (this._storeOptionsAsProperties) actionArgs[expectedArgsCount] = this;
else actionArgs[expectedArgsCount] = this.opts();
actionArgs.push(this);
return fn.apply(this, actionArgs);
};
this._actionHandler = listener;
return this;
}
createOption(flags, description) {
return new Option(flags, description);
}
_callParseArg(target, value, previous, invalidArgumentMessage) {
try {
return target.parseArg(value, previous);
} catch (err) {
if ('commander.invalidArgument' === err.code) {
const message = `${invalidArgumentMessage} ${err.message}`;
this.error(message, {
exitCode: err.exitCode,
code: err.code
});
}
throw err;
}
}
_registerOption(option) {
const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
if (matchingOption) {
const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
- already used by option '${matchingOption.flags}'`);
}
this.options.push(option);
}
_registerCommand(command) {
const knownBy = (cmd)=>[
cmd.name()
].concat(cmd.aliases());
const alreadyUsed = knownBy(command).find((name)=>this._findCommand(name));
if (alreadyUsed) {
const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');
const newCmd = knownBy(command).join('|');
throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
}
this.commands.push(command);
}
addOption(option) {
this._registerOption(option);
const oname = option.name();
const name = option.attributeName();
if (option.negate) {
const positiveLongFlag = option.long.replace(/^--no-/, '--');
if (!this._findOption(positiveLongFlag)) this.setOptionValueWithSource(name, void 0 === option.defaultValue ? true : option.defaultValue, 'default');
} else if (void 0 !== option.defaultValue) this.setOptionValueWithSource(name, option.defaultValue, 'default');
const handleOptionValue = (val, invalidValueMessage, valueSource)=>{
if (null == val && void 0 !== option.presetArg) val = option.presetArg;
const oldValue = this.getOptionValue(name);
if (null !== val && option.parseArg) val = this._callParseArg(option, val, oldValue, invalidValueMessage);
else if (null !== val && option.variadic) val = option._concatValue(val, oldValue);
if (null == val) val = option.negate ? false : option.isBoolean() || option.optional ? true : '';
this.setOptionValueWithSource(name, val, valueSource);
};
this.on('option:' + oname, (val)=>{
const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
handleOptionValue(val, invalidValueMessage, 'cli');
});
if (option.envVar) this.on('optionEnv:' + oname, (val)=>{
const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
handleOptionValue(val, invalidValueMessage, 'env');
});
return this;
}
_optionEx(config, flags, description, fn, defaultValue) {
if ('object' == typeof flags && flags instanceof Option) throw new Error('To add an Option object use addOption() instead of option() or requiredOption()');
const option = this.createOption(flags, description);
option.makeOptionMandatory(!!config.mandatory);
if ('function' == typeof fn) option.default(defaultValue).argParser(fn);
else if (fn instanceof RegExp) {
const regex = fn;
fn = (val, def)=>{
const m = regex.exec(val);
return m ? m[0] : def;
};
option.default(defaultValue).argParser(fn);
} else option.default(fn);
return this.addOption(option);
}
option(flags, description, parseArg, defaultValue) {
return this._optionEx({}, flags, description, parseArg, defaultValue);
}
requiredOption(flags, description, parseArg, defaultValue) {
return this._optionEx({
mandatory: true
}, flags, description, parseArg, defaultValue);
}
combineFlagAndOptionalValue(combine = true) {
this._combineFlagAndOptionalValue = !!combine;
return this;
}
allowUnknownOption(allowUnknown = true) {
this._allowUnknownOption = !!allowUnknown;
return this;
}
allowExcessArguments(allowExcess = true) {
this._allowExcessArguments = !!allowExcess;
return this;
}
enablePositionalOptions(positional = true) {
this._enablePositionalOptions = !!positional;
return this;
}
passThroughOptions(passThrough = true) {
this._passThroughOptions = !!passThrough;
this._checkForBrokenPassThrough();
return this;
}
_checkForBrokenPassThrough() {
if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
}
storeOptionsAsProperties(storeAsProperties = true) {
if (this.options.length) throw new Error('call .storeOptionsAsProperties() before adding options');
if (Object.keys(this._optionValues).length) throw new Error('call .storeOptionsAsProperties() before setting option values');
this._storeOptionsAsProperties = !!storeAsProperties;
return this;
}
getOptionValue(key) {
if (this._storeOptionsAsProperties) return this[key];
return this._optionValues[key];
}
setOptionValue(key, value) {
return this.setOptionValueWithSource(key, value, void 0);
}
setOptionValueWithSource(key, value, source) {
if (this._storeOptionsAsProperties) this[key] = value;
else this._optionValues[key] = value;
this._optionValueSources[key] = source;
return this;
}
getOptionValueSource(key) {
return this._optionValueSources[key];
}
getOptionValueSourceWithGlobals(key) {
let source;
this._getCommandAndAncestors().forEach((cmd)=>{
if (void 0 !== cmd.getOptionValueSource(key)) source = cmd.getOptionValueSource(key);
});
return source;
}
_prepareUserArgs(argv, parseOptions) {
if (void 0 !== argv && !Array.isArray(argv)) throw new Error('first parameter to parse must be array or undefined');
parseOptions = parseOptions || {};
if (void 0 === argv && void 0 === parseOptions.from) {
if (process1.versions?.electron) parseOptions.from = 'electron';
const execArgv = process1.execArgv ?? [];
if (execArgv.includes('-e') || execArgv.includes('--eval') || execArgv.includes('-p') || execArgv.includes('--print')) parseOptions.from = 'eval';
}
if (void 0 === argv) argv = process1.argv;
this.rawArgs = argv.slice();
let userArgs;
switch(parseOptions.from){
case void 0:
case 'node':
this._scriptPath = argv[1];
userArgs = argv.slice(2)