@storybook/core
Version:
Storybook framework-agnostic API
1,393 lines (1,387 loc) • 96.8 kB
JavaScript
import ESM_COMPAT_Module from "node:module";
import { fileURLToPath as ESM_COMPAT_fileURLToPath } from 'node:url';
import { dirname as ESM_COMPAT_dirname } from 'node:path';
const __filename = ESM_COMPAT_fileURLToPath(import.meta.url);
const __dirname = ESM_COMPAT_dirname(__filename);
const require = ESM_COMPAT_Module.createRequire(import.meta.url);
var $e = Object.create;
var N = Object.defineProperty;
var Ve = Object.getOwnPropertyDescriptor;
var He = Object.getOwnPropertyNames;
var qe = Object.getPrototypeOf, Pe = Object.prototype.hasOwnProperty;
var c = (n, e) => N(n, "name", { value: e, configurable: !0 }), x = /* @__PURE__ */ ((n) => typeof require < "u" ? require : typeof Proxy < "\
u" ? new Proxy(n, {
get: (e, t) => (typeof require < "u" ? require : e)[t]
}) : n)(function(n) {
if (typeof require < "u") return require.apply(this, arguments);
throw Error('Dynamic require of "' + n + '" is not supported');
});
var b = (n, e) => () => (e || n((e = { exports: {} }).exports, e), e.exports);
var De = (n, e, t, i) => {
if (e && typeof e == "object" || typeof e == "function")
for (let s of He(e))
!Pe.call(n, s) && s !== t && N(n, s, { get: () => e[s], enumerable: !(i = Ve(e, s)) || i.enumerable });
return n;
};
var S = (n, e, t) => (t = n != null ? $e(qe(n)) : {}, De(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
e || !n || !n.__esModule ? N(t, "default", { value: n, enumerable: !0 }) : t,
n
));
// ../node_modules/commander/lib/error.js
var A = b((I) => {
var j = class extends Error {
static {
c(this, "CommanderError");
}
/**
* Constructs the CommanderError class
* @param {number} exitCode suggested exit code which could be used with process.exit
* @param {string} code an id string representing the error
* @param {string} message human-readable description of the error
*/
constructor(e, t, i) {
super(i), Error.captureStackTrace(this, this.constructor), this.name = this.constructor.name, this.code = t, this.exitCode = e, this.nestedError =
void 0;
}
}, T = class extends j {
static {
c(this, "InvalidArgumentError");
}
/**
* Constructs the InvalidArgumentError class
* @param {string} [message] explanation of why argument is invalid
*/
constructor(e) {
super(1, "commander.invalidArgument", e), Error.captureStackTrace(this, this.constructor), this.name = this.constructor.name;
}
};
I.CommanderError = j;
I.InvalidArgumentError = T;
});
// ../node_modules/commander/lib/argument.js
var $ = b((B) => {
var { InvalidArgumentError: Ne } = A(), F = class {
static {
c(this, "Argument");
}
/**
* Initialize a new command argument with the given name and description.
* The default is that the argument is required, and you can explicitly
* indicate this with <> around the name. Put [] around the name for an optional argument.
*
* @param {string} name
* @param {string} [description]
*/
constructor(e, t) {
switch (this.description = t || "", this.variadic = !1, this.parseArg = void 0, this.defaultValue = void 0, this.defaultValueDescription =
void 0, this.argChoices = void 0, e[0]) {
case "<":
this.required = !0, this._name = e.slice(1, -1);
break;
case "[":
this.required = !1, this._name = e.slice(1, -1);
break;
default:
this.required = !0, this._name = e;
break;
}
this._name.length > 3 && this._name.slice(-3) === "..." && (this.variadic = !0, this._name = this._name.slice(0, -3));
}
/**
* Return argument name.
*
* @return {string}
*/
name() {
return this._name;
}
/**
* @package
*/
_concatValue(e, t) {
return t === this.defaultValue || !Array.isArray(t) ? [e] : t.concat(e);
}
/**
* Set the default value, and optionally supply the description to be displayed in the help.
*
* @param {*} value
* @param {string} [description]
* @return {Argument}
*/
default(e, t) {
return this.defaultValue = e, this.defaultValueDescription = t, this;
}
/**
* Set the custom handler for processing CLI command arguments into argument values.
*
* @param {Function} [fn]
* @return {Argument}
*/
argParser(e) {
return this.parseArg = e, this;
}
/**
* Only allow argument value to be one of choices.
*
* @param {string[]} values
* @return {Argument}
*/
choices(e) {
return this.argChoices = e.slice(), this.parseArg = (t, i) => {
if (!this.argChoices.includes(t))
throw new Ne(
`Allowed choices are ${this.argChoices.join(", ")}.`
);
return this.variadic ? this._concatValue(t, i) : t;
}, this;
}
/**
* Make argument required.
*
* @returns {Argument}
*/
argRequired() {
return this.required = !0, this;
}
/**
* Make argument optional.
*
* @returns {Argument}
*/
argOptional() {
return this.required = !1, this;
}
};
function Te(n) {
let e = n.name() + (n.variadic === !0 ? "..." : "");
return n.required ? "<" + e + ">" : "[" + e + "]";
}
c(Te, "humanReadableArgName");
B.Argument = F;
B.humanReadableArgName = Te;
});
// ../node_modules/commander/lib/help.js
var W = b((se) => {
var { humanReadableArgName: Ie } = $(), M = class {
static {
c(this, "Help");
}
constructor() {
this.helpWidth = void 0, this.sortSubcommands = !1, this.sortOptions = !1, this.showGlobalOptions = !1;
}
/**
* Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
*
* @param {Command} cmd
* @returns {Command[]}
*/
visibleCommands(e) {
let t = e.commands.filter((s) => !s._hidden), i = e._getHelpCommand();
return i && !i._hidden && t.push(i), this.sortSubcommands && t.sort((s, r) => s.name().localeCompare(r.name())), t;
}
/**
* Compare options for sort.
*
* @param {Option} a
* @param {Option} b
* @returns {number}
*/
compareOptions(e, t) {
let i = /* @__PURE__ */ c((s) => s.short ? s.short.replace(/^-/, "") : s.long.replace(/^--/, ""), "getSortKey");
return i(e).localeCompare(i(t));
}
/**
* Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
*
* @param {Command} cmd
* @returns {Option[]}
*/
visibleOptions(e) {
let t = e.options.filter((s) => !s.hidden), i = e._getHelpOption();
if (i && !i.hidden) {
let s = i.short && e._findOption(i.short), r = i.long && e._findOption(i.long);
!s && !r ? t.push(i) : i.long && !r ? t.push(
e.createOption(i.long, i.description)
) : i.short && !s && t.push(
e.createOption(i.short, i.description)
);
}
return this.sortOptions && t.sort(this.compareOptions), t;
}
/**
* Get an array of the visible global options. (Not including help.)
*
* @param {Command} cmd
* @returns {Option[]}
*/
visibleGlobalOptions(e) {
if (!this.showGlobalOptions) return [];
let t = [];
for (let i = e.parent; i; i = i.parent) {
let s = i.options.filter(
(r) => !r.hidden
);
t.push(...s);
}
return this.sortOptions && t.sort(this.compareOptions), t;
}
/**
* Get an array of the arguments if any have a description.
*
* @param {Command} cmd
* @returns {Argument[]}
*/
visibleArguments(e) {
return e._argsDescription && e.registeredArguments.forEach((t) => {
t.description = t.description || e._argsDescription[t.name()] || "";
}), e.registeredArguments.find((t) => t.description) ? e.registeredArguments : [];
}
/**
* Get the command term to show in the list of subcommands.
*
* @param {Command} cmd
* @returns {string}
*/
subcommandTerm(e) {
let t = e.registeredArguments.map((i) => Ie(i)).join(" ");
return e._name + (e._aliases[0] ? "|" + e._aliases[0] : "") + (e.options.length ? " [options]" : "") + // simplistic check for non-help option
(t ? " " + t : "");
}
/**
* Get the option term to show in the list of options.
*
* @param {Option} option
* @returns {string}
*/
optionTerm(e) {
return e.flags;
}
/**
* Get the argument term to show in the list of arguments.
*
* @param {Argument} argument
* @returns {string}
*/
argumentTerm(e) {
return e.name();
}
/**
* Get the longest command term length.
*
* @param {Command} cmd
* @param {Help} helper
* @returns {number}
*/
longestSubcommandTermLength(e, t) {
return t.visibleCommands(e).reduce((i, s) => Math.max(i, t.subcommandTerm(s).length), 0);
}
/**
* Get the longest option term length.
*
* @param {Command} cmd
* @param {Help} helper
* @returns {number}
*/
longestOptionTermLength(e, t) {
return t.visibleOptions(e).reduce((i, s) => Math.max(i, t.optionTerm(s).length), 0);
}
/**
* Get the longest global option term length.
*
* @param {Command} cmd
* @param {Help} helper
* @returns {number}
*/
longestGlobalOptionTermLength(e, t) {
return t.visibleGlobalOptions(e).reduce((i, s) => Math.max(i, t.optionTerm(s).length), 0);
}
/**
* Get the longest argument term length.
*
* @param {Command} cmd
* @param {Help} helper
* @returns {number}
*/
longestArgumentTermLength(e, t) {
return t.visibleArguments(e).reduce((i, s) => Math.max(i, t.argumentTerm(s).length), 0);
}
/**
* Get the command usage to be displayed at the top of the built-in help.
*
* @param {Command} cmd
* @returns {string}
*/
commandUsage(e) {
let t = e._name;
e._aliases[0] && (t = t + "|" + e._aliases[0]);
let i = "";
for (let s = e.parent; s; s = s.parent)
i = s.name() + " " + i;
return i + t + " " + e.usage();
}
/**
* Get the description for the command.
*
* @param {Command} cmd
* @returns {string}
*/
commandDescription(e) {
return e.description();
}
/**
* Get the subcommand summary to show in the list of subcommands.
* (Fallback to description for backwards compatibility.)
*
* @param {Command} cmd
* @returns {string}
*/
subcommandDescription(e) {
return e.summary() || e.description();
}
/**
* Get the option description to show in the list of options.
*
* @param {Option} option
* @return {string}
*/
optionDescription(e) {
let t = [];
return e.argChoices && t.push(
// use stringify to match the display of the default value
`choices: ${e.argChoices.map((i) => JSON.stringify(i)).join(", ")}`
), e.defaultValue !== void 0 && (e.required || e.optional || e.isBoolean() && typeof e.defaultValue == "boolean") && t.push(
`default: ${e.defaultValueDescription || JSON.stringify(e.defaultValue)}`
), e.presetArg !== void 0 && e.optional && t.push(`preset: ${JSON.stringify(e.presetArg)}`), e.envVar !== void 0 && t.push(`env: ${e.envVar}`),
t.length > 0 ? `${e.description} (${t.join(", ")})` : e.description;
}
/**
* Get the argument description to show in the list of arguments.
*
* @param {Argument} argument
* @return {string}
*/
argumentDescription(e) {
let t = [];
if (e.argChoices && t.push(
// use stringify to match the display of the default value
`choices: ${e.argChoices.map((i) => JSON.stringify(i)).join(", ")}`
), e.defaultValue !== void 0 && t.push(
`default: ${e.defaultValueDescription || JSON.stringify(e.defaultValue)}`
), t.length > 0) {
let i = `(${t.join(", ")})`;
return e.description ? `${e.description} ${i}` : i;
}
return e.description;
}
/**
* Generate the built-in help text.
*
* @param {Command} cmd
* @param {Help} helper
* @returns {string}
*/
formatHelp(e, t) {
let i = t.padWidth(e, t), s = t.helpWidth || 80, r = 2, o = 2;
function l(f, v) {
if (v) {
let D = `${f.padEnd(i + o)}${v}`;
return t.wrap(
D,
s - r,
i + o
);
}
return f;
}
c(l, "formatItem");
function a(f) {
return f.join(`
`).replace(/^/gm, " ".repeat(r));
}
c(a, "formatList");
let u = [`Usage: ${t.commandUsage(e)}`, ""], d = t.commandDescription(e);
d.length > 0 && (u = u.concat([
t.wrap(d, s, 0),
""
]));
let h = t.visibleArguments(e).map((f) => l(
t.argumentTerm(f),
t.argumentDescription(f)
));
h.length > 0 && (u = u.concat(["Arguments:", a(h), ""]));
let m = t.visibleOptions(e).map((f) => l(
t.optionTerm(f),
t.optionDescription(f)
));
if (m.length > 0 && (u = u.concat(["Options:", a(m), ""])), this.showGlobalOptions) {
let f = t.visibleGlobalOptions(e).map((v) => l(
t.optionTerm(v),
t.optionDescription(v)
));
f.length > 0 && (u = u.concat([
"Global Options:",
a(f),
""
]));
}
let _ = t.visibleCommands(e).map((f) => l(
t.subcommandTerm(f),
t.subcommandDescription(f)
));
return _.length > 0 && (u = u.concat(["Commands:", a(_), ""])), u.join(`
`);
}
/**
* Calculate the pad width from the maximum term length.
*
* @param {Command} cmd
* @param {Help} helper
* @returns {number}
*/
padWidth(e, t) {
return Math.max(
t.longestOptionTermLength(e, t),
t.longestGlobalOptionTermLength(e, t),
t.longestSubcommandTermLength(e, t),
t.longestArgumentTermLength(e, t)
);
}
/**
* Wrap the given string to width characters per line, with lines after the first indented.
* Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.
*
* @param {string} str
* @param {number} width
* @param {number} indent
* @param {number} [minColumnWidth=40]
* @return {string}
*
*/
wrap(e, t, i, s = 40) {
let r = " \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF", o = new RegExp(`[\\n][${r}]+`);
if (e.match(o)) return e;
let l = t - i;
if (l < s) return e;
let a = e.slice(0, i), u = e.slice(i).replace(`\r
`, `
`), d = " ".repeat(i), m = "\\s\u200B", _ = new RegExp(
`
|.{1,${l - 1}}([${m}]|$)|[^${m}]+?([${m}]|$)`,
"g"
), f = u.match(_) || [];
return a + f.map((v, D) => v === `
` ? "" : (D > 0 ? d : "") + v.trimEnd()).join(`
`);
}
};
se.Help = M;
});
// ../node_modules/commander/lib/option.js
var U = b((G) => {
var { InvalidArgumentError: Fe } = A(), L = class {
static {
c(this, "Option");
}
/**
* Initialize a new `Option` with the given `flags` and `description`.
*
* @param {string} flags
* @param {string} [description]
*/
constructor(e, t) {
this.flags = e, this.description = t || "", this.required = e.includes("<"), this.optional = e.includes("["), this.variadic = /\w\.\.\.[>\]]$/.
test(e), this.mandatory = !1;
let i = Me(e);
this.short = i.shortFlag, this.long = i.longFlag, this.negate = !1, this.long && (this.negate = this.long.startsWith("--no-")), this.defaultValue =
void 0, this.defaultValueDescription = void 0, this.presetArg = void 0, this.envVar = void 0, this.parseArg = void 0, this.hidden = !1,
this.argChoices = void 0, this.conflictsWith = [], this.implied = void 0;
}
/**
* Set the default value, and optionally supply the description to be displayed in the help.
*
* @param {*} value
* @param {string} [description]
* @return {Option}
*/
default(e, t) {
return this.defaultValue = e, this.defaultValueDescription = t, this;
}
/**
* Preset to use when option used without option-argument, especially optional but also boolean and negated.
* The custom processing (parseArg) is called.
*
* @example
* new Option('--color').default('GREYSCALE').preset('RGB');
* new Option('--donate [amount]').preset('20').argParser(parseFloat);
*
* @param {*} arg
* @return {Option}
*/
preset(e) {
return this.presetArg = e, this;
}
/**
* Add option name(s) that conflict with this option.
* An error will be displayed if conflicting options are found during parsing.
*
* @example
* new Option('--rgb').conflicts('cmyk');
* new Option('--js').conflicts(['ts', 'jsx']);
*
* @param {(string | string[])} names
* @return {Option}
*/
conflicts(e) {
return this.conflictsWith = this.conflictsWith.concat(e), this;
}
/**
* Specify implied option values for when this option is set and the implied options are not.
*
* The custom processing (parseArg) is not called on the implied values.
*
* @example
* program
* .addOption(new Option('--log', 'write logging information to file'))
* .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
*
* @param {object} impliedOptionValues
* @return {Option}
*/
implies(e) {
let t = e;
return typeof e == "string" && (t = { [e]: !0 }), this.implied = Object.assign(this.implied || {}, t), this;
}
/**
* Set environment variable to check for option value.
*
* An environment variable is only used if when processed the current option value is
* undefined, or the source of the current value is 'default' or 'config' or 'env'.
*
* @param {string} name
* @return {Option}
*/
env(e) {
return this.envVar = e, this;
}
/**
* Set the custom handler for processing CLI option arguments into option values.
*
* @param {Function} [fn]
* @return {Option}
*/
argParser(e) {
return this.parseArg = e, this;
}
/**
* Whether the option is mandatory and must have a value after parsing.
*
* @param {boolean} [mandatory=true]
* @return {Option}
*/
makeOptionMandatory(e = !0) {
return this.mandatory = !!e, this;
}
/**
* Hide option in help.
*
* @param {boolean} [hide=true]
* @return {Option}
*/
hideHelp(e = !0) {
return this.hidden = !!e, this;
}
/**
* @package
*/
_concatValue(e, t) {
return t === this.defaultValue || !Array.isArray(t) ? [e] : t.concat(e);
}
/**
* Only allow option value to be one of choices.
*
* @param {string[]} values
* @return {Option}
*/
choices(e) {
return this.argChoices = e.slice(), this.parseArg = (t, i) => {
if (!this.argChoices.includes(t))
throw new Fe(
`Allowed choices are ${this.argChoices.join(", ")}.`
);
return this.variadic ? this._concatValue(t, i) : t;
}, this;
}
/**
* Return option name.
*
* @return {string}
*/
name() {
return this.long ? this.long.replace(/^--/, "") : this.short.replace(/^-/, "");
}
/**
* Return option name, in a camelcase format that can be used
* as a object attribute key.
*
* @return {string}
*/
attributeName() {
return Be(this.name().replace(/^no-/, ""));
}
/**
* Check if `arg` matches the short or long flag.
*
* @param {string} arg
* @return {boolean}
* @package
*/
is(e) {
return this.short === e || this.long === e;
}
/**
* Return whether a boolean option.
*
* Options are one of boolean, negated, required argument, or optional argument.
*
* @return {boolean}
* @package
*/
isBoolean() {
return !this.required && !this.optional && !this.negate;
}
}, R = class {
static {
c(this, "DualOptions");
}
/**
* @param {Option[]} options
*/
constructor(e) {
this.positiveOptions = /* @__PURE__ */ new Map(), this.negativeOptions = /* @__PURE__ */ new Map(), this.dualOptions = /* @__PURE__ */ new Set(),
e.forEach((t) => {
t.negate ? this.negativeOptions.set(t.attributeName(), t) : this.positiveOptions.set(t.attributeName(), t);
}), this.negativeOptions.forEach((t, i) => {
this.positiveOptions.has(i) && this.dualOptions.add(i);
});
}
/**
* Did the value come from the option, and not from possible matching dual option?
*
* @param {*} value
* @param {Option} option
* @returns {boolean}
*/
valueFromOption(e, t) {
let i = t.attributeName();
if (!this.dualOptions.has(i)) return !0;
let s = this.negativeOptions.get(i).presetArg, r = s !== void 0 ? s : !1;
return t.negate === (r === e);
}
};
function Be(n) {
return n.split("-").reduce((e, t) => e + t[0].toUpperCase() + t.slice(1));
}
c(Be, "camelcase");
function Me(n) {
let e, t, i = n.split(/[ |,]+/);
return i.length > 1 && !/^[[<]/.test(i[1]) && (e = i.shift()), t = i.shift(), !e && /^-[^-]$/.test(t) && (e = t, t = void 0), { shortFlag: e,
longFlag: t };
}
c(Me, "splitOptionFlags");
G.Option = L;
G.DualOptions = R;
});
// ../node_modules/commander/lib/suggestSimilar.js
var ne = b((re) => {
function We(n, e) {
if (Math.abs(n.length - e.length) > 3)
return Math.max(n.length, e.length);
let t = [];
for (let i = 0; i <= n.length; i++)
t[i] = [i];
for (let i = 0; i <= e.length; i++)
t[0][i] = i;
for (let i = 1; i <= e.length; i++)
for (let s = 1; s <= n.length; s++) {
let r = 1;
n[s - 1] === e[i - 1] ? r = 0 : r = 1, t[s][i] = Math.min(
t[s - 1][i] + 1,
// deletion
t[s][i - 1] + 1,
// insertion
t[s - 1][i - 1] + r
// substitution
), s > 1 && i > 1 && n[s - 1] === e[i - 2] && n[s - 2] === e[i - 1] && (t[s][i] = Math.min(t[s][i], t[s - 2][i - 2] + 1));
}
return t[n.length][e.length];
}
c(We, "editDistance");
function Le(n, e) {
if (!e || e.length === 0) return "";
e = Array.from(new Set(e));
let t = n.startsWith("--");
t && (n = n.slice(2), e = e.map((o) => o.slice(2)));
let i = [], s = 3, r = 0.4;
return e.forEach((o) => {
if (o.length <= 1) return;
let l = We(n, o), a = Math.max(n.length, o.length);
(a - l) / a > r && (l < s ? (s = l, i = [o]) : l === s && i.push(o));
}), i.sort((o, l) => o.localeCompare(l)), t && (i = i.map((o) => `--${o}`)), i.length > 1 ? `
(Did you mean one of ${i.join(", ")}?)` : i.length === 1 ? `
(Did you mean ${i[0]}?)` : "";
}
c(Le, "suggestSimilar");
re.suggestSimilar = Le;
});
// ../node_modules/commander/lib/command.js
var ue = b((ce) => {
var Re = x("node:events").EventEmitter, J = x("node:child_process"), y = x("node:path"), Y = x("node:fs"), p = x("node:process"), { Argument: Ge,
humanReadableArgName: Ue } = $(), { CommanderError: z } = A(), { Help: Je } = W(), { Option: oe, DualOptions: Ye } = U(), { suggestSimilar: ae } = ne(),
K = class n extends Re {
static {
c(this, "Command");
}
/**
* Initialize a new `Command`.
*
* @param {string} [name]
*/
constructor(e) {
super(), this.commands = [], this.options = [], this.parent = null, this._allowUnknownOption = !1, this._allowExcessArguments = !0, this.
registeredArguments = [], this._args = this.registeredArguments, this.args = [], this.rawArgs = [], this.processedArgs = [], this._scriptPath =
null, this._name = e || "", this._optionValues = {}, this._optionValueSources = {}, this._storeOptionsAsProperties = !1, this._actionHandler =
null, this._executableHandler = !1, this._executableFile = null, this._executableDir = null, this._defaultCommandName = null, this._exitCallback =
null, this._aliases = [], this._combineFlagAndOptionalValue = !0, this._description = "", this._summary = "", this._argsDescription = void 0,
this._enablePositionalOptions = !1, this._passThroughOptions = !1, this._lifeCycleHooks = {}, this._showHelpAfterError = !1, this._showSuggestionAfterError =
!0, this._outputConfiguration = {
writeOut: /* @__PURE__ */ c((t) => p.stdout.write(t), "writeOut"),
writeErr: /* @__PURE__ */ c((t) => p.stderr.write(t), "writeErr"),
getOutHelpWidth: /* @__PURE__ */ c(() => p.stdout.isTTY ? p.stdout.columns : void 0, "getOutHelpWidth"),
getErrHelpWidth: /* @__PURE__ */ c(() => p.stderr.isTTY ? p.stderr.columns : void 0, "getErrHelpWidth"),
outputError: /* @__PURE__ */ c((t, i) => i(t), "outputError")
}, this._hidden = !1, this._helpOption = void 0, this._addImplicitHelpCommand = void 0, this._helpCommand = void 0, this._helpConfiguration =
{};
}
/**
* Copy settings that are useful to have in common across root command and subcommands.
*
* (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
*
* @param {Command} sourceCommand
* @return {Command} `this` command for chaining
*/
copyInheritedSettings(e) {
return this._outputConfiguration = e._outputConfiguration, this._helpOption = e._helpOption, this._helpCommand = e._helpCommand, this.
_helpConfiguration = e._helpConfiguration, this._exitCallback = e._exitCallback, this._storeOptionsAsProperties = e._storeOptionsAsProperties,
this._combineFlagAndOptionalValue = e._combineFlagAndOptionalValue, this._allowExcessArguments = e._allowExcessArguments, this._enablePositionalOptions =
e._enablePositionalOptions, this._showHelpAfterError = e._showHelpAfterError, this._showSuggestionAfterError = e._showSuggestionAfterError,
this;
}
/**
* @returns {Command[]}
* @private
*/
_getCommandAndAncestors() {
let e = [];
for (let t = this; t; t = t.parent)
e.push(t);
return e;
}
/**
* Define a command.
*
* There are two styles of command: pay attention to where to put the description.
*
* @example
* // Command implemented using action handler (description is supplied separately to `.command`)
* program
* .command('clone <source> [destination]')
* .description('clone a repository into a newly created directory')
* .action((source, destination) => {
* console.log('clone command called');
* });
*
* // Command implemented using separate executable file (description is second parameter to `.command`)
* program
* .command('start <service>', 'start named service')
* .command('stop [service]', 'stop named service, or all if no name supplied');
*
* @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
* @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
* @param {object} [execOpts] - configuration options (for executable)
* @return {Command} returns new command for action handler, or `this` for executable command
*/
command(e, t, i) {
let s = t, r = i;
typeof s == "object" && s !== null && (r = s, s = null), r = r || {};
let [, o, l] = e.match(/([^ ]+) *(.*)/), a = this.createCommand(o);
return s && (a.description(s), a._executableHandler = !0), r.isDefault && (this._defaultCommandName = a._name), a._hidden = !!(r.noHelp ||
r.hidden), a._executableFile = r.executableFile || null, l && a.arguments(l), this._registerCommand(a), a.parent = this, a.copyInheritedSettings(
this), s ? this : a;
}
/**
* Factory routine to create a new unattached command.
*
* See .command() for creating an attached subcommand, which uses this routine to
* create the command. You can override createCommand to customise subcommands.
*
* @param {string} [name]
* @return {Command} new command
*/
createCommand(e) {
return new n(e);
}
/**
* You can customise the help with a subclass of Help by overriding createHelp,
* or by overriding Help properties using configureHelp().
*
* @return {Help}
*/
createHelp() {
return Object.assign(new Je(), this.configureHelp());
}
/**
* You can customise the help by overriding Help properties using configureHelp(),
* or with a subclass of Help by overriding createHelp().
*
* @param {object} [configuration] - configuration options
* @return {(Command | object)} `this` command for chaining, or stored configuration
*/
configureHelp(e) {
return e === void 0 ? this._helpConfiguration : (this._helpConfiguration = e, this);
}
/**
* The default output goes to stdout and stderr. You can customise this for special
* applications. You can also customise the display of errors by overriding outputError.
*
* The configuration properties are all functions:
*
* // functions to change where being written, stdout and stderr
* writeOut(str)
* writeErr(str)
* // matching functions to specify width for wrapping help
* getOutHelpWidth()
* getErrHelpWidth()
* // functions based on what is being written out
* outputError(str, write) // used for displaying errors, and not used for displaying help
*
* @param {object} [configuration] - configuration options
* @return {(Command | object)} `this` command for chaining, or stored configuration
*/
configureOutput(e) {
return e === void 0 ? this._outputConfiguration : (Object.assign(this._outputConfiguration, e), this);
}
/**
* Display the help or a custom message after an error occurs.
*
* @param {(boolean|string)} [displayHelp]
* @return {Command} `this` command for chaining
*/
showHelpAfterError(e = !0) {
return typeof e != "string" && (e = !!e), this._showHelpAfterError = e, this;
}
/**
* Display suggestion of similar commands for unknown commands, or options for unknown options.
*
* @param {boolean} [displaySuggestion]
* @return {Command} `this` command for chaining
*/
showSuggestionAfterError(e = !0) {
return this._showSuggestionAfterError = !!e, this;
}
/**
* Add a prepared subcommand.
*
* See .command() for creating an attached subcommand which inherits settings from its parent.
*
* @param {Command} cmd - new subcommand
* @param {object} [opts] - configuration options
* @return {Command} `this` command for chaining
*/
addCommand(e, t) {
if (!e._name)
throw new Error(`Command passed to .addCommand() must have a name
- specify the name in Command constructor or using .name()`);
return t = t || {}, t.isDefault && (this._defaultCommandName = e._name), (t.noHelp || t.hidden) && (e._hidden = !0), this._registerCommand(
e), e.parent = this, e._checkForBrokenPassThrough(), this;
}
/**
* Factory routine to create a new unattached argument.
*
* See .argument() for creating an attached argument, which uses this routine to
* create the argument. You can override createArgument to return a custom argument.
*
* @param {string} name
* @param {string} [description]
* @return {Argument} new argument
*/
createArgument(e, t) {
return new Ge(e, t);
}
/**
* Define argument syntax for command.
*
* The default is that the argument is required, and you can explicitly
* indicate this with <> around the name. Put [] around the name for an optional argument.
*
* @example
* program.argument('<input-file>');
* program.argument('[output-file]');
*
* @param {string} name
* @param {string} [description]
* @param {(Function|*)} [fn] - custom argument processing function
* @param {*} [defaultValue]
* @return {Command} `this` command for chaining
*/
argument(e, t, i, s) {
let r = this.createArgument(e, t);
return typeof i == "function" ? r.default(s).argParser(i) : r.default(i), this.addArgument(r), this;
}
/**
* Define argument syntax for command, adding multiple at once (without descriptions).
*
* See also .argument().
*
* @example
* program.arguments('<cmd> [env]');
*
* @param {string} names
* @return {Command} `this` command for chaining
*/
arguments(e) {
return e.trim().split(/ +/).forEach((t) => {
this.argument(t);
}), this;
}
/**
* Define argument syntax for command, adding a prepared argument.
*
* @param {Argument} argument
* @return {Command} `this` command for chaining
*/
addArgument(e) {
let t = this.registeredArguments.slice(-1)[0];
if (t && t.variadic)
throw new Error(
`only the last argument can be variadic '${t.name()}'`
);
if (e.required && e.defaultValue !== void 0 && e.parseArg === void 0)
throw new Error(
`a default value for a required argument is never used: '${e.name()}'`
);
return this.registeredArguments.push(e), this;
}
/**
* Customise or override default help command. By default a help command is automatically added if your command has subcommands.
*
* @example
* program.helpCommand('help [cmd]');
* program.helpCommand('help [cmd]', 'show help');
* program.helpCommand(false); // suppress default help command
* program.helpCommand(true); // add help command even if no subcommands
*
* @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
* @param {string} [description] - custom description
* @return {Command} `this` command for chaining
*/
helpCommand(e, t) {
if (typeof e == "boolean")
return this._addImplicitHelpCommand = e, this;
e = e ?? "help [command]";
let [, i, s] = e.match(/([^ ]+) *(.*)/), r = t ?? "display help for command", o = this.createCommand(i);
return o.helpOption(!1), s && o.arguments(s), r && o.description(r), this._addImplicitHelpCommand = !0, this._helpCommand = o, this;
}
/**
* Add prepared custom help command.
*
* @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
* @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
* @return {Command} `this` command for chaining
*/
addHelpCommand(e, t) {
return typeof e != "object" ? (this.helpCommand(e, t), this) : (this._addImplicitHelpCommand = !0, this._helpCommand = e, this);
}
/**
* Lazy create help command.
*
* @return {(Command|null)}
* @package
*/
_getHelpCommand() {
return this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help")) ? (this._helpCommand ===
void 0 && this.helpCommand(void 0, void 0), this._helpCommand) : null;
}
/**
* Add hook for life cycle event.
*
* @param {string} event
* @param {Function} listener
* @return {Command} `this` command for chaining
*/
hook(e, t) {
let i = ["preSubcommand", "preAction", "postAction"];
if (!i.includes(e))
throw new Error(`Unexpected value for event passed to hook : '${e}'.
Expecting one of '${i.join("', '")}'`);
return this._lifeCycleHooks[e] ? this._lifeCycleHooks[e].push(t) : this._lifeCycleHooks[e] = [t], this;
}
/**
* Register callback to use as replacement for calling process.exit.
*
* @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
* @return {Command} `this` command for chaining
*/
exitOverride(e) {
return e ? this._exitCallback = e : this._exitCallback = (t) => {
if (t.code !== "commander.executeSubCommandAsync")
throw t;
}, this;
}
/**
* Call process.exit, and _exitCallback if defined.
*
* @param {number} exitCode exit code for using with process.exit
* @param {string} code an id string representing the error
* @param {string} message human-readable description of the error
* @return never
* @private
*/
_exit(e, t, i) {
this._exitCallback && this._exitCallback(new z(e, t, i)), p.exit(e);
}
/**
* Register callback `fn` for the command.
*
* @example
* program
* .command('serve')
* .description('start service')
* .action(function() {
* // do work here
* });
*
* @param {Function} fn
* @return {Command} `this` command for chaining
*/
action(e) {
let t = /* @__PURE__ */ c((i) => {
let s = this.registeredArguments.length, r = i.slice(0, s);
return this._storeOptionsAsProperties ? r[s] = this : r[s] = this.opts(), r.push(this), e.apply(this, r);
}, "listener");
return this._actionHandler = t, this;
}
/**
* Factory routine to create a new unattached option.
*
* See .option() for creating an attached option, which uses this routine to
* create the option. You can override createOption to return a custom option.
*
* @param {string} flags
* @param {string} [description]
* @return {Option} new option
*/
createOption(e, t) {
return new oe(e, t);
}
/**
* Wrap parseArgs to catch 'commander.invalidArgument'.
*
* @param {(Option | Argument)} target
* @param {string} value
* @param {*} previous
* @param {string} invalidArgumentMessage
* @private
*/
_callParseArg(e, t, i, s) {
try {
return e.parseArg(t, i);
} catch (r) {
if (r.code === "commander.invalidArgument") {
let o = `${s} ${r.message}`;
this.error(o, { exitCode: r.exitCode, code: r.code });
}
throw r;
}
}
/**
* Check for option flag conflicts.
* Register option if no conflicts found, or throw on conflict.
*
* @param {Option} option
* @private
*/
_registerOption(e) {
let t = e.short && this._findOption(e.short) || e.long && this._findOption(e.long);
if (t) {
let i = e.long && this._findOption(e.long) ? e.long : e.short;
throw new Error(`Cannot add option '${e.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${i}'
- already used by option '${t.flags}'`);
}
this.options.push(e);
}
/**
* Check for command name and alias conflicts with existing commands.
* Register command if no conflicts found, or throw on conflict.
*
* @param {Command} command
* @private
*/
_registerCommand(e) {
let t = /* @__PURE__ */ c((s) => [s.name()].concat(s.aliases()), "knownBy"), i = t(e).find(
(s) => this._findCommand(s)
);
if (i) {
let s = t(this._findCommand(i)).join("|"), r = t(e).join("|");
throw new Error(
`cannot add command '${r}' as already have command '${s}'`
);
}
this.commands.push(e);
}
/**
* Add an option.
*
* @param {Option} option
* @return {Command} `this` command for chaining
*/
addOption(e) {
this._registerOption(e);
let t = e.name(), i = e.attributeName();
if (e.negate) {
let r = e.long.replace(/^--no-/, "--");
this._findOption(r) || this.setOptionValueWithSource(
i,
e.defaultValue === void 0 ? !0 : e.defaultValue,
"default"
);
} else e.defaultValue !== void 0 && this.setOptionValueWithSource(i, e.defaultValue, "default");
let s = /* @__PURE__ */ c((r, o, l) => {
r == null && e.presetArg !== void 0 && (r = e.presetArg);
let a = this.getOptionValue(i);
r !== null && e.parseArg ? r = this._callParseArg(e, r, a, o) : r !== null && e.variadic && (r = e._concatValue(r, a)), r == null &&
(e.negate ? r = !1 : e.isBoolean() || e.optional ? r = !0 : r = ""), this.setOptionValueWithSource(i, r, l);
}, "handleOptionValue");
return this.on("option:" + t, (r) => {
let o = `error: option '${e.flags}' argument '${r}' is invalid.`;
s(r, o, "cli");
}), e.envVar && this.on("optionEnv:" + t, (r) => {
let o = `error: option '${e.flags}' value '${r}' from env '${e.envVar}' is invalid.`;
s(r, o, "env");
}), this;
}
/**
* Internal implementation shared by .option() and .requiredOption()
*
* @return {Command} `this` command for chaining
* @private
*/
_optionEx(e, t, i, s, r) {
if (typeof t == "object" && t instanceof oe)
throw new Error(
"To add an Option object use addOption() instead of option() or requiredOption()"
);
let o = this.createOption(t, i);
if (o.makeOptionMandatory(!!e.mandatory), typeof s == "function")
o.default(r).argParser(s);
else if (s instanceof RegExp) {
let l = s;
s = /* @__PURE__ */ c((a, u) => {
let d = l.exec(a);
return d ? d[0] : u;
}, "fn"), o.default(r).argParser(s);
} else
o.default(s);
return this.addOption(o);
}
/**
* Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
*
* The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
* option-argument is indicated by `<>` and an optional option-argument by `[]`.
*
* See the README for more details, and see also addOption() and requiredOption().
*
* @example
* program
* .option('-p, --pepper', 'add pepper')
* .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument
* .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
* .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
*
* @param {string} flags
* @param {string} [description]
* @param {(Function|*)} [parseArg] - custom option processing function or default value
* @param {*} [defaultValue]
* @return {Command} `this` command for chaining
*/
option(e, t, i, s) {
return this._optionEx({}, e, t, i, s);
}
/**
* Add a required option which must have a value after parsing. This usually means
* the option must be specified on the command line. (Otherwise the same as .option().)
*
* The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
*
* @param {string} flags
* @param {string} [description]
* @param {(Function|*)} [parseArg] - custom option processing function or default value
* @param {*} [defaultValue]
* @return {Command} `this` command for chaining
*/
requiredOption(e, t, i, s) {
return this._optionEx(
{ mandatory: !0 },
e,
t,
i,
s
);
}
/**
* Alter parsing of short flags with optional values.
*
* @example
* // for `.option('-f,--flag [value]'):
* program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
* program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
*
* @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
* @return {Command} `this` command for chaining
*/
combineFlagAndOptionalValue(e = !0) {
return this._combineFlagAndOptionalValue = !!e, this;
}
/**
* Allow unknown options on the command line.
*
* @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
* @return {Command} `this` command for chaining
*/
allowUnknownOption(e = !0) {
return this._allowUnknownOption = !!e, this;
}
/**
* Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
*
* @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
* @return {Command} `this` command for chaining
*/
allowExcessArguments(e = !0) {
return this._allowExcessArguments = !!e, this;
}
/**
* Enable positional options. Positional means global options are specified before subcommands which lets
* subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
* The default behaviour is non-positional and global options may appear anywhere on the command line.
*
* @param {boolean} [positional]
* @return {Command} `this` command for chaining
*/
enablePositionalOptions(e = !0) {
return this._enablePositionalOptions = !!e, this;
}
/**
* Pass through options that come after command-arguments rather than treat them as command-options,
* so actual command-options come before command-arguments. Turning this on for a subcommand requires
* positional options to have been enabled on the program (parent commands).
* The default behaviour is non-positional and options may appear before or after command-arguments.
*
* @param {boolean} [passThrough] for unknown options.
* @return {Command} `this` command for chaining
*/
passThroughOptions(e = !0) {
return this._passThroughOptions = !!e, this._checkForBrokenPassThrough(), this;
}
/**
* @private
*/
_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)`
);
}
/**
* Whether to store option values as properties on command object,
* or store separately (specify false). In both cases the option values can be accessed using .opts().
*
* @param {boolean} [storeAsProperties=true]
* @return {Command} `this` command for chaining
*/
storeOptionsAsProperties(e = !0) {
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"
);
return this._storeOptionsAsProperties = !!e, this;
}
/**
* Retrieve option value.
*
* @param {string} key
* @return {object} value
*/
getOptionValue(e) {
return this._storeOptionsAsProperties ? this[e] : this._optionValues[e];
}
/**
* Store option value.
*
* @param {string} key
* @param {object} value
* @return {Command} `this` command for chaining
*/
setOptionValue(e, t) {
return this.setOptionValueWithSource(e, t, void 0);
}
/**
* Store option value and where the value came from.
*
* @param {string} key
* @param {object} value
* @param {string} source - expected values are default/config/env/cli/implied
* @return {Command} `this` command for chaining
*/
setOptionValueWithSource(e, t, i) {
return this._storeOptionsAsProperties ? this[e] = t : this._optionValues[e] = t, this._optionValueSources[e] = i, this;
}
/**
* Get source of option value.
* Expected values are default | config | env | cli | implied
*
* @param {string} key
* @return {string}
*/
getOptionValueSource(e) {
return this._optionValueSources[e];
}
/**
* Get source of option value. See also .optsWithGlobals().
* Expected values are default | config | env | cli | implied
*
* @param {string} key
* @return {string}
*/
getOptionValueSourceWithGlobals(e) {
let t;
return this._getCommandAndAncestors().forEach((i) => {
i.getOptionValueSource(e) !== void 0 && (t = i.getOptionValueSource(e));
}), t;
}
/**
* Get user arguments from implied or explicit arguments.
* Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
*
* @private
*/
_prepareUserArgs(e, t) {
if (e !== void 0 && !Array.isArray(e))
throw new Error("first parameter to parse must be arr