lifetracker/apps/cli/bin/index.js

4433 lines
135 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import process$1 from "node:process";
import os from "node:os";
import tty from "node:tty";
import require$$0 from "node:events";
import require$$1 from "node:child_process";
import require$$2 from "node:path";
import require$$3 from "node:fs";
const ANSI_BACKGROUND_OFFSET = 10;
const wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`;
const wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`;
const wrapAnsi16m = (offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`;
const styles$1 = {
modifier: {
reset: [0, 0],
// 21 isn't widely supported and 22 does the same thing
bold: [1, 22],
dim: [2, 22],
italic: [3, 23],
underline: [4, 24],
overline: [53, 55],
inverse: [7, 27],
hidden: [8, 28],
strikethrough: [9, 29]
},
color: {
black: [30, 39],
red: [31, 39],
green: [32, 39],
yellow: [33, 39],
blue: [34, 39],
magenta: [35, 39],
cyan: [36, 39],
white: [37, 39],
// Bright color
blackBright: [90, 39],
gray: [90, 39],
// Alias of `blackBright`
grey: [90, 39],
// Alias of `blackBright`
redBright: [91, 39],
greenBright: [92, 39],
yellowBright: [93, 39],
blueBright: [94, 39],
magentaBright: [95, 39],
cyanBright: [96, 39],
whiteBright: [97, 39]
},
bgColor: {
bgBlack: [40, 49],
bgRed: [41, 49],
bgGreen: [42, 49],
bgYellow: [43, 49],
bgBlue: [44, 49],
bgMagenta: [45, 49],
bgCyan: [46, 49],
bgWhite: [47, 49],
// Bright color
bgBlackBright: [100, 49],
bgGray: [100, 49],
// Alias of `bgBlackBright`
bgGrey: [100, 49],
// Alias of `bgBlackBright`
bgRedBright: [101, 49],
bgGreenBright: [102, 49],
bgYellowBright: [103, 49],
bgBlueBright: [104, 49],
bgMagentaBright: [105, 49],
bgCyanBright: [106, 49],
bgWhiteBright: [107, 49]
}
};
Object.keys(styles$1.modifier);
const foregroundColorNames = Object.keys(styles$1.color);
const backgroundColorNames = Object.keys(styles$1.bgColor);
[...foregroundColorNames, ...backgroundColorNames];
function assembleStyles() {
const codes = /* @__PURE__ */ new Map();
for (const [groupName, group] of Object.entries(styles$1)) {
for (const [styleName, style] of Object.entries(group)) {
styles$1[styleName] = {
open: `\x1B[${style[0]}m`,
close: `\x1B[${style[1]}m`
};
group[styleName] = styles$1[styleName];
codes.set(style[0], style[1]);
}
Object.defineProperty(styles$1, groupName, {
value: group,
enumerable: false
});
}
Object.defineProperty(styles$1, "codes", {
value: codes,
enumerable: false
});
styles$1.color.close = "\x1B[39m";
styles$1.bgColor.close = "\x1B[49m";
styles$1.color.ansi = wrapAnsi16();
styles$1.color.ansi256 = wrapAnsi256();
styles$1.color.ansi16m = wrapAnsi16m();
styles$1.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
styles$1.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
styles$1.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
Object.defineProperties(styles$1, {
rgbToAnsi256: {
value(red, green, blue) {
if (red === green && green === blue) {
if (red < 8) {
return 16;
}
if (red > 248) {
return 231;
}
return Math.round((red - 8) / 247 * 24) + 232;
}
return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
},
enumerable: false
},
hexToRgb: {
value(hex) {
const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
if (!matches) {
return [0, 0, 0];
}
let [colorString] = matches;
if (colorString.length === 3) {
colorString = [...colorString].map((character) => character + character).join("");
}
const integer = Number.parseInt(colorString, 16);
return [
/* eslint-disable no-bitwise */
integer >> 16 & 255,
integer >> 8 & 255,
integer & 255
/* eslint-enable no-bitwise */
];
},
enumerable: false
},
hexToAnsi256: {
value: (hex) => styles$1.rgbToAnsi256(...styles$1.hexToRgb(hex)),
enumerable: false
},
ansi256ToAnsi: {
value(code) {
if (code < 8) {
return 30 + code;
}
if (code < 16) {
return 90 + (code - 8);
}
let red;
let green;
let blue;
if (code >= 232) {
red = ((code - 232) * 10 + 8) / 255;
green = red;
blue = red;
} else {
code -= 16;
const remainder = code % 36;
red = Math.floor(code / 36) / 5;
green = Math.floor(remainder / 6) / 5;
blue = remainder % 6 / 5;
}
const value = Math.max(red, green, blue) * 2;
if (value === 0) {
return 30;
}
let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
if (value === 2) {
result += 60;
}
return result;
},
enumerable: false
},
rgbToAnsi: {
value: (red, green, blue) => styles$1.ansi256ToAnsi(styles$1.rgbToAnsi256(red, green, blue)),
enumerable: false
},
hexToAnsi: {
value: (hex) => styles$1.ansi256ToAnsi(styles$1.hexToAnsi256(hex)),
enumerable: false
}
});
return styles$1;
}
const ansiStyles = assembleStyles();
function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process$1.argv) {
const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
const position = argv.indexOf(prefix + flag);
const terminatorPosition = argv.indexOf("--");
return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
}
const { env } = process$1;
let 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 (env.FORCE_COLOR === "true") {
return 1;
}
if (env.FORCE_COLOR === "false") {
return 0;
}
return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
}
}
function translateLevel(level) {
if (level === 0) {
return false;
}
return {
level,
hasBasic: true,
has256: level >= 2,
has16m: level >= 3
};
}
function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
const noFlagForceColor = envForceColor();
if (noFlagForceColor !== void 0) {
flagForceColor = noFlagForceColor;
}
const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
if (forceColor === 0) {
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 && forceColor === void 0) {
return 0;
}
const min = forceColor || 0;
if (env.TERM === "dumb") {
return min;
}
if (process$1.platform === "win32") {
const osRelease = os.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) || env.CI_NAME === "codeship") {
return 1;
}
return min;
}
if ("TEAMCITY_VERSION" in env) {
return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
}
if (env.COLORTERM === "truecolor") {
return 3;
}
if (env.TERM === "xterm-kitty") {
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);
}
const supportsColor = {
stdout: createSupportsColor({ isTTY: tty.isatty(1) }),
stderr: createSupportsColor({ isTTY: tty.isatty(2) })
};
function stringReplaceAll(string, substring, replacer) {
let index = string.indexOf(substring);
if (index === -1) {
return string;
}
const substringLength = substring.length;
let endIndex = 0;
let returnValue = "";
do {
returnValue += string.slice(endIndex, index) + substring + replacer;
endIndex = index + substringLength;
index = string.indexOf(substring, endIndex);
} while (index !== -1);
returnValue += string.slice(endIndex);
return returnValue;
}
function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
let endIndex = 0;
let returnValue = "";
do {
const gotCR = string[index - 1] === "\r";
returnValue += string.slice(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? "\r\n" : "\n") + postfix;
endIndex = index + 1;
index = string.indexOf("\n", endIndex);
} while (index !== -1);
returnValue += string.slice(endIndex);
return returnValue;
}
const { stdout: stdoutColor, stderr: stderrColor } = supportsColor;
const GENERATOR = Symbol("GENERATOR");
const STYLER = Symbol("STYLER");
const IS_EMPTY = Symbol("IS_EMPTY");
const levelMapping = [
"ansi",
"ansi",
"ansi256",
"ansi16m"
];
const styles = /* @__PURE__ */ Object.create(null);
const applyOptions = (object, options = {}) => {
if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
throw new Error("The `level` option should be an integer from 0 to 3");
}
const colorLevel = stdoutColor ? stdoutColor.level : 0;
object.level = options.level === void 0 ? colorLevel : options.level;
};
const chalkFactory = (options) => {
const chalk2 = (...strings) => strings.join(" ");
applyOptions(chalk2, options);
Object.setPrototypeOf(chalk2, createChalk.prototype);
return chalk2;
};
function createChalk(options) {
return chalkFactory(options);
}
Object.setPrototypeOf(createChalk.prototype, Function.prototype);
for (const [styleName, style] of Object.entries(ansiStyles)) {
styles[styleName] = {
get() {
const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
Object.defineProperty(this, styleName, { value: builder });
return builder;
}
};
}
styles.visible = {
get() {
const builder = createBuilder(this, this[STYLER], true);
Object.defineProperty(this, "visible", { value: builder });
return builder;
}
};
const getModelAnsi = (model, level, type, ...arguments_) => {
if (model === "rgb") {
if (level === "ansi16m") {
return ansiStyles[type].ansi16m(...arguments_);
}
if (level === "ansi256") {
return ansiStyles[type].ansi256(ansiStyles.rgbToAnsi256(...arguments_));
}
return ansiStyles[type].ansi(ansiStyles.rgbToAnsi(...arguments_));
}
if (model === "hex") {
return getModelAnsi("rgb", level, type, ...ansiStyles.hexToRgb(...arguments_));
}
return ansiStyles[type][model](...arguments_);
};
const usedModels = ["rgb", "hex", "ansi256"];
for (const model of usedModels) {
styles[model] = {
get() {
const { level } = this;
return function(...arguments_) {
const styler = createStyler(getModelAnsi(model, levelMapping[level], "color", ...arguments_), ansiStyles.color.close, this[STYLER]);
return createBuilder(this, styler, this[IS_EMPTY]);
};
}
};
const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
styles[bgModel] = {
get() {
const { level } = this;
return function(...arguments_) {
const styler = createStyler(getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_), ansiStyles.bgColor.close, this[STYLER]);
return createBuilder(this, styler, this[IS_EMPTY]);
};
}
};
}
const proto = Object.defineProperties(() => {
}, {
...styles,
level: {
enumerable: true,
get() {
return this[GENERATOR].level;
},
set(level) {
this[GENERATOR].level = level;
}
}
});
const createStyler = (open, close, parent) => {
let openAll;
let closeAll;
if (parent === void 0) {
openAll = open;
closeAll = close;
} else {
openAll = parent.openAll + open;
closeAll = close + parent.closeAll;
}
return {
open,
close,
openAll,
closeAll,
parent
};
};
const createBuilder = (self, _styler, _isEmpty) => {
const builder = (...arguments_) => applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" "));
Object.setPrototypeOf(builder, proto);
builder[GENERATOR] = self;
builder[STYLER] = _styler;
builder[IS_EMPTY] = _isEmpty;
return builder;
};
const applyStyle = (self, string) => {
if (self.level <= 0 || !string) {
return self[IS_EMPTY] ? "" : string;
}
let styler = self[STYLER];
if (styler === void 0) {
return string;
}
const { openAll, closeAll } = styler;
if (string.includes("\x1B")) {
while (styler !== void 0) {
string = stringReplaceAll(string, styler.close, styler.open);
styler = styler.parent;
}
}
const lfIndex = string.indexOf("\n");
if (lfIndex !== -1) {
string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
}
return openAll + string + closeAll;
};
Object.defineProperties(createChalk.prototype, styles);
const chalk = createChalk();
createChalk({ level: stderrColor ? stderrColor.level : 0 });
let globalOpts = void 0;
function setGlobalOptions(opts) {
globalOpts = opts;
}
function getGlobalOptions() {
if (!globalOpts) {
throw new Error("Global options are not initalized yet");
}
return globalOpts;
}
function printStatusMessage(success, message) {
const status = "Error";
const colorFunction = chalk.red;
console.error(colorFunction(`${status}: ${message}`));
}
function printErrorMessageWithReason(message, error2) {
const errorMessage = "message" in error2 ? error2.message : error2;
printStatusMessage(false, `${message}. Reason: ${errorMessage}`);
}
function identity(x) {
return x;
}
function pipeFromArray(fns) {
if (fns.length === 0) {
return identity;
}
if (fns.length === 1) {
return fns[0];
}
return function piped(input) {
return fns.reduce((prev, fn) => fn(prev), input);
};
}
function observable(subscribe) {
const self = {
subscribe(observer) {
let teardownRef = null;
let isDone = false;
let unsubscribed = false;
let teardownImmediately = false;
function unsubscribe() {
if (teardownRef === null) {
teardownImmediately = true;
return;
}
if (unsubscribed) {
return;
}
unsubscribed = true;
if (typeof teardownRef === "function") {
teardownRef();
} else if (teardownRef) {
teardownRef.unsubscribe();
}
}
teardownRef = subscribe({
next(value) {
var _a;
if (isDone) {
return;
}
(_a = observer.next) == null ? void 0 : _a.call(observer, value);
},
error(err) {
var _a;
if (isDone) {
return;
}
isDone = true;
(_a = observer.error) == null ? void 0 : _a.call(observer, err);
unsubscribe();
},
complete() {
var _a;
if (isDone) {
return;
}
isDone = true;
(_a = observer.complete) == null ? void 0 : _a.call(observer);
unsubscribe();
}
});
if (teardownImmediately) {
unsubscribe();
}
return {
unsubscribe
};
},
pipe(...operations) {
return pipeFromArray(operations)(self);
}
};
return self;
}
function share(_opts) {
return (originalObserver) => {
let refCount = 0;
let subscription = null;
const observers = [];
function startIfNeeded() {
if (subscription) {
return;
}
subscription = originalObserver.subscribe({
next(value) {
var _a;
for (const observer of observers) {
(_a = observer.next) == null ? void 0 : _a.call(observer, value);
}
},
error(error2) {
var _a;
for (const observer of observers) {
(_a = observer.error) == null ? void 0 : _a.call(observer, error2);
}
},
complete() {
var _a;
for (const observer of observers) {
(_a = observer.complete) == null ? void 0 : _a.call(observer);
}
}
});
}
function resetIfNeeded() {
if (refCount === 0 && subscription) {
const _sub = subscription;
subscription = null;
_sub.unsubscribe();
}
}
return {
subscribe(observer) {
refCount++;
observers.push(observer);
startIfNeeded();
return {
unsubscribe() {
refCount--;
resetIfNeeded();
const index = observers.findIndex((v) => v === observer);
if (index > -1) {
observers.splice(index, 1);
}
}
};
}
};
};
}
class ObservableAbortError extends Error {
constructor(message) {
super(message);
this.name = "ObservableAbortError";
Object.setPrototypeOf(this, ObservableAbortError.prototype);
}
}
function observableToPromise(observable2) {
let abort;
const promise = new Promise((resolve, reject) => {
let isDone = false;
function onDone() {
if (isDone) {
return;
}
isDone = true;
reject(new ObservableAbortError("This operation was aborted."));
obs$.unsubscribe();
}
const obs$ = observable2.subscribe({
next(data) {
isDone = true;
resolve(data);
onDone();
},
error(data) {
isDone = true;
reject(data);
onDone();
},
complete() {
isDone = true;
onDone();
}
});
abort = onDone;
});
return {
promise,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
abort
};
}
function createChain(opts) {
return observable((observer) => {
function execute(index = 0, op = opts.op) {
const next = opts.links[index];
if (!next) {
throw new Error("No more links to execute - did you forget to add an ending link?");
}
const subscription = next({
op,
next(nextOp) {
const nextObserver = execute(index + 1, nextOp);
return nextObserver;
}
});
return subscription;
}
const obs$ = execute();
return obs$.subscribe(observer);
});
}
function invert(obj) {
const newObj = /* @__PURE__ */ Object.create(null);
for (const key in obj) {
const v = obj[key];
newObj[v] = key;
}
return newObj;
}
const TRPC_ERROR_CODES_BY_KEY = {
/**
* Invalid JSON was received by the server.
* An error occurred on the server while parsing the JSON text.
*/
PARSE_ERROR: -32700,
/**
* The JSON sent is not a valid Request object.
*/
BAD_REQUEST: -32600,
// Internal JSON-RPC error
INTERNAL_SERVER_ERROR: -32603,
NOT_IMPLEMENTED: -32603,
// Implementation specific errors
UNAUTHORIZED: -32001,
FORBIDDEN: -32003,
NOT_FOUND: -32004,
METHOD_NOT_SUPPORTED: -32005,
TIMEOUT: -32008,
CONFLICT: -32009,
PRECONDITION_FAILED: -32012,
PAYLOAD_TOO_LARGE: -32013,
UNPROCESSABLE_CONTENT: -32022,
TOO_MANY_REQUESTS: -32029,
CLIENT_CLOSED_REQUEST: -32099
};
invert(TRPC_ERROR_CODES_BY_KEY);
invert(TRPC_ERROR_CODES_BY_KEY);
const noop = () => {
};
function createInnerProxy(callback, path2) {
const proxy = new Proxy(noop, {
get(_obj, key) {
if (typeof key !== "string" || key === "then") {
return void 0;
}
return createInnerProxy(callback, [
...path2,
key
]);
},
apply(_1, _2, args) {
const isApply = path2[path2.length - 1] === "apply";
return callback({
args: isApply ? args.length >= 2 ? args[1] : [] : args,
path: isApply ? path2.slice(0, -1) : path2
});
}
});
return proxy;
}
const createRecursiveProxy = (callback) => createInnerProxy(callback, []);
const createFlatProxy = (callback) => {
return new Proxy(noop, {
get(_obj, name) {
if (typeof name !== "string" || name === "then") {
return void 0;
}
return callback(name);
}
});
};
function isObject$1(value) {
return !!value && !Array.isArray(value) && typeof value === "object";
}
class UnknownCauseError extends Error {
}
function getCauseFromUnknown(cause) {
if (cause instanceof Error) {
return cause;
}
const type = typeof cause;
if (type === "undefined" || type === "function" || cause === null) {
return void 0;
}
if (type !== "object") {
return new Error(String(cause));
}
if (isObject$1(cause)) {
const err = new UnknownCauseError();
for (const key in cause) {
err[key] = cause[key];
}
return err;
}
return void 0;
}
function isObject(value) {
return !!value && !Array.isArray(value) && typeof value === "object";
}
function transformResultInner(response, runtime) {
if ("error" in response) {
const error2 = runtime.transformer.deserialize(response.error);
return {
ok: false,
error: {
...response,
error: error2
}
};
}
const result = {
...response.result,
...(!response.result.type || response.result.type === "data") && {
type: "data",
data: runtime.transformer.deserialize(response.result.data)
}
};
return {
ok: true,
result
};
}
class TransformResultError extends Error {
constructor() {
super("Unable to transform response from server");
}
}
function transformResult(response, runtime) {
let result;
try {
result = transformResultInner(response, runtime);
} catch (err) {
throw new TransformResultError();
}
if (!result.ok && (!isObject(result.error.error) || typeof result.error.error.code !== "number")) {
throw new TransformResultError();
}
if (result.ok && !isObject(result.result)) {
throw new TransformResultError();
}
return result;
}
function isTRPCClientError(cause) {
return cause instanceof TRPCClientError || /**
* @deprecated
* Delete in next major
*/
cause instanceof Error && cause.name === "TRPCClientError";
}
function isTRPCErrorResponse(obj) {
return isObject(obj) && isObject(obj.error) && typeof obj.error.code === "number" && typeof obj.error.message === "string";
}
class TRPCClientError extends Error {
static from(_cause, opts = {}) {
const cause = _cause;
if (isTRPCClientError(cause)) {
if (opts.meta) {
cause.meta = {
...cause.meta,
...opts.meta
};
}
return cause;
}
if (isTRPCErrorResponse(cause)) {
return new TRPCClientError(cause.error.message, {
...opts,
result: cause
});
}
if (!(cause instanceof Error)) {
return new TRPCClientError("Unknown error", {
...opts,
cause
});
}
return new TRPCClientError(cause.message, {
...opts,
cause: getCauseFromUnknown(cause)
});
}
constructor(message, opts) {
var _a, _b;
const cause = opts == null ? void 0 : opts.cause;
super(message, {
cause
});
this.meta = opts == null ? void 0 : opts.meta;
this.cause = cause;
this.shape = (_a = opts == null ? void 0 : opts.result) == null ? void 0 : _a.error;
this.data = (_b = opts == null ? void 0 : opts.result) == null ? void 0 : _b.error.data;
this.name = "TRPCClientError";
Object.setPrototypeOf(this, TRPCClientError.prototype);
}
}
const isFunction = (fn) => typeof fn === "function";
function getFetch(customFetchImpl) {
if (customFetchImpl) {
return customFetchImpl;
}
if (typeof window !== "undefined" && isFunction(window.fetch)) {
return window.fetch;
}
if (typeof globalThis !== "undefined" && isFunction(globalThis.fetch)) {
return globalThis.fetch;
}
throw new Error("No fetch implementation found");
}
function getAbortController(customAbortControllerImpl) {
if (customAbortControllerImpl) {
return customAbortControllerImpl;
}
if (typeof window !== "undefined" && window.AbortController) {
return window.AbortController;
}
if (typeof globalThis !== "undefined" && globalThis.AbortController) {
return globalThis.AbortController;
}
return null;
}
function resolveHTTPLinkOptions(opts) {
return {
url: opts.url.toString().replace(/\/$/, ""),
fetch: opts.fetch,
AbortController: getAbortController(opts.AbortController)
};
}
function arrayToDict(array) {
const dict = {};
for (let index = 0; index < array.length; index++) {
const element = array[index];
dict[index] = element;
}
return dict;
}
const METHOD = {
query: "GET",
mutation: "POST"
};
function getInput(opts) {
return "input" in opts ? opts.runtime.transformer.serialize(opts.input) : arrayToDict(opts.inputs.map((_input) => opts.runtime.transformer.serialize(_input)));
}
const getUrl = (opts) => {
let url = opts.url + "/" + opts.path;
const queryParts = [];
if ("inputs" in opts) {
queryParts.push("batch=1");
}
if (opts.type === "query") {
const input = getInput(opts);
if (input !== void 0) {
queryParts.push(`input=${encodeURIComponent(JSON.stringify(input))}`);
}
}
if (queryParts.length) {
url += "?" + queryParts.join("&");
}
return url;
};
const getBody = (opts) => {
if (opts.type === "query") {
return void 0;
}
const input = getInput(opts);
return input !== void 0 ? JSON.stringify(input) : void 0;
};
const jsonHttpRequester = (opts) => {
return httpRequest({
...opts,
contentTypeHeader: "application/json",
getUrl,
getBody
});
};
async function fetchHTTPResponse(opts, ac) {
const url = opts.getUrl(opts);
const body = opts.getBody(opts);
const { type } = opts;
const resolvedHeaders = await opts.headers();
/* istanbul ignore if -- @preserve */
if (type === "subscription") {
throw new Error("Subscriptions should use wsLink");
}
const headers = {
...opts.contentTypeHeader ? {
"content-type": opts.contentTypeHeader
} : {},
...opts.batchModeHeader ? {
"trpc-batch-mode": opts.batchModeHeader
} : {},
...resolvedHeaders
};
return getFetch(opts.fetch)(url, {
method: METHOD[type],
signal: ac == null ? void 0 : ac.signal,
body,
headers
});
}
function httpRequest(opts) {
const ac = opts.AbortController ? new opts.AbortController() : null;
const meta = {};
let done = false;
const promise = new Promise((resolve, reject) => {
fetchHTTPResponse(opts, ac).then((_res) => {
meta.response = _res;
done = true;
return _res.json();
}).then((json) => {
meta.responseJSON = json;
resolve({
json,
meta
});
}).catch((err) => {
done = true;
reject(TRPCClientError.from(err, {
meta
}));
});
});
const cancel = () => {
if (!done) {
ac == null ? void 0 : ac.abort();
}
};
return {
promise,
cancel
};
}
const throwFatalError = () => {
throw new Error("Something went wrong. Please submit an issue at https://github.com/trpc/trpc/issues/new");
};
function dataLoader(batchLoader) {
let pendingItems = null;
let dispatchTimer = null;
const destroyTimerAndPendingItems = () => {
clearTimeout(dispatchTimer);
dispatchTimer = null;
pendingItems = null;
};
function groupItems(items) {
var _a, _b;
const groupedItems = [
[]
];
let index = 0;
while (true) {
const item = items[index];
if (!item) {
break;
}
const lastGroup = groupedItems[groupedItems.length - 1];
if (item.aborted) {
(_a = item.reject) == null ? void 0 : _a.call(item, new Error("Aborted"));
index++;
continue;
}
const isValid = batchLoader.validate(lastGroup.concat(item).map((it) => it.key));
if (isValid) {
lastGroup.push(item);
index++;
continue;
}
if (lastGroup.length === 0) {
(_b = item.reject) == null ? void 0 : _b.call(item, new Error("Input is too big for a single dispatch"));
index++;
continue;
}
groupedItems.push([]);
}
return groupedItems;
}
function dispatch() {
const groupedItems = groupItems(pendingItems);
destroyTimerAndPendingItems();
for (const items of groupedItems) {
if (!items.length) {
continue;
}
const batch = {
items,
cancel: throwFatalError
};
for (const item of items) {
item.batch = batch;
}
const unitResolver = (index, value) => {
var _a;
const item = batch.items[index];
(_a = item.resolve) == null ? void 0 : _a.call(item, value);
item.batch = null;
item.reject = null;
item.resolve = null;
};
const { promise, cancel } = batchLoader.fetch(batch.items.map((_item) => _item.key), unitResolver);
batch.cancel = cancel;
promise.then((result) => {
var _a;
for (let i = 0; i < result.length; i++) {
const value = result[i];
unitResolver(i, value);
}
for (const item of batch.items) {
(_a = item.reject) == null ? void 0 : _a.call(item, new Error("Missing result"));
item.batch = null;
}
}).catch((cause) => {
var _a;
for (const item of batch.items) {
(_a = item.reject) == null ? void 0 : _a.call(item, cause);
item.batch = null;
}
});
}
}
function load(key) {
const item = {
aborted: false,
key,
batch: null,
resolve: throwFatalError,
reject: throwFatalError
};
const promise = new Promise((resolve, reject) => {
item.reject = reject;
item.resolve = resolve;
if (!pendingItems) {
pendingItems = [];
}
pendingItems.push(item);
});
if (!dispatchTimer) {
dispatchTimer = setTimeout(dispatch);
}
const cancel = () => {
var _a;
item.aborted = true;
if ((_a = item.batch) == null ? void 0 : _a.items.every((item2) => item2.aborted)) {
item.batch.cancel();
item.batch = null;
}
};
return {
promise,
cancel
};
}
return {
load
};
}
function createHTTPBatchLink(requester) {
return function httpBatchLink2(opts) {
const resolvedOpts = resolveHTTPLinkOptions(opts);
const maxURLLength = opts.maxURLLength ?? Infinity;
return (runtime) => {
const batchLoader = (type) => {
const validate = (batchOps) => {
if (maxURLLength === Infinity) {
return true;
}
const path2 = batchOps.map((op) => op.path).join(",");
const inputs = batchOps.map((op) => op.input);
const url = getUrl({
...resolvedOpts,
runtime,
type,
path: path2,
inputs
});
return url.length <= maxURLLength;
};
const fetch = requester({
...resolvedOpts,
runtime,
type,
opts
});
return {
validate,
fetch
};
};
const query = dataLoader(batchLoader("query"));
const mutation = dataLoader(batchLoader("mutation"));
const subscription = dataLoader(batchLoader("subscription"));
const loaders = {
query,
subscription,
mutation
};
return ({ op }) => {
return observable((observer) => {
const loader = loaders[op.type];
const { promise, cancel } = loader.load(op);
let _res = void 0;
promise.then((res) => {
_res = res;
const transformed = transformResult(res.json, runtime);
if (!transformed.ok) {
observer.error(TRPCClientError.from(transformed.error, {
meta: res.meta
}));
return;
}
observer.next({
context: res.meta,
result: transformed.result
});
observer.complete();
}).catch((err) => {
observer.error(TRPCClientError.from(err, {
meta: _res == null ? void 0 : _res.meta
}));
});
return () => {
cancel();
};
});
};
};
};
}
const batchRequester = (requesterOpts) => {
return (batchOps) => {
const path2 = batchOps.map((op) => op.path).join(",");
const inputs = batchOps.map((op) => op.input);
const { promise, cancel } = jsonHttpRequester({
...requesterOpts,
path: path2,
inputs,
headers() {
if (!requesterOpts.opts.headers) {
return {};
}
if (typeof requesterOpts.opts.headers === "function") {
return requesterOpts.opts.headers({
opList: batchOps
});
}
return requesterOpts.opts.headers;
}
});
return {
promise: promise.then((res) => {
const resJSON = Array.isArray(res.json) ? res.json : batchOps.map(() => res.json);
const result = resJSON.map((item) => ({
meta: res.meta,
json: item
}));
return result;
}),
cancel
};
};
};
const httpBatchLink = createHTTPBatchLink(batchRequester);
class TRPCUntypedClient {
$request({ type, input, path: path2, context = {} }) {
const chain$ = createChain({
links: this.links,
op: {
id: ++this.requestId,
type,
path: path2,
input,
context
}
});
return chain$.pipe(share());
}
requestAsPromise(opts) {
const req$ = this.$request(opts);
const { promise, abort } = observableToPromise(req$);
const abortablePromise = new Promise((resolve, reject) => {
var _a;
(_a = opts.signal) == null ? void 0 : _a.addEventListener("abort", abort);
promise.then((envelope) => {
resolve(envelope.result.data);
}).catch((err) => {
reject(TRPCClientError.from(err));
});
});
return abortablePromise;
}
query(path2, input, opts) {
return this.requestAsPromise({
type: "query",
path: path2,
input,
context: opts == null ? void 0 : opts.context,
signal: opts == null ? void 0 : opts.signal
});
}
mutation(path2, input, opts) {
return this.requestAsPromise({
type: "mutation",
path: path2,
input,
context: opts == null ? void 0 : opts.context,
signal: opts == null ? void 0 : opts.signal
});
}
subscription(path2, input, opts) {
const observable$ = this.$request({
type: "subscription",
path: path2,
input,
context: opts == null ? void 0 : opts.context
});
return observable$.subscribe({
next(envelope) {
var _a, _b, _c;
if (envelope.result.type === "started") {
(_a = opts.onStarted) == null ? void 0 : _a.call(opts);
} else if (envelope.result.type === "stopped") {
(_b = opts.onStopped) == null ? void 0 : _b.call(opts);
} else {
(_c = opts.onData) == null ? void 0 : _c.call(opts, envelope.result.data);
}
},
error(err) {
var _a;
(_a = opts.onError) == null ? void 0 : _a.call(opts, err);
},
complete() {
var _a;
(_a = opts.onComplete) == null ? void 0 : _a.call(opts);
}
});
}
constructor(opts) {
this.requestId = 0;
const combinedTransformer = (() => {
const transformer = opts.transformer;
if (!transformer) {
return {
input: {
serialize: (data) => data,
deserialize: (data) => data
},
output: {
serialize: (data) => data,
deserialize: (data) => data
}
};
}
if ("input" in transformer) {
return opts.transformer;
}
return {
input: transformer,
output: transformer
};
})();
this.runtime = {
transformer: {
serialize: (data) => combinedTransformer.input.serialize(data),
deserialize: (data) => combinedTransformer.output.deserialize(data)
},
combinedTransformer
};
this.links = opts.links.map((link) => link(this.runtime));
}
}
const clientCallTypeMap = {
query: "query",
mutate: "mutation",
subscribe: "subscription"
};
const clientCallTypeToProcedureType = (clientCallType) => {
return clientCallTypeMap[clientCallType];
};
function createTRPCClientProxy(client) {
return createFlatProxy((key) => {
if (client.hasOwnProperty(key)) {
return client[key];
}
if (key === "__untypedClient") {
return client;
}
return createRecursiveProxy(({ path: path2, args }) => {
const pathCopy = [
key,
...path2
];
const procedureType = clientCallTypeToProcedureType(pathCopy.pop());
const fullPath = pathCopy.join(".");
return client[procedureType](fullPath, ...args);
});
});
}
function createTRPCProxyClient(opts) {
const client = new TRPCUntypedClient(opts);
const proxy = createTRPCClientProxy(client);
return proxy;
}
function getAPIClient() {
const globals = getGlobalOptions();
return createTRPCProxyClient({
links: [
httpBatchLink({
url: `${globals.serverAddr}/api/trpc`,
maxURLLength: 14e3,
headers() {
return {
authorization: `Bearer ${globals.apiKey}`
};
}
})
]
});
}
function getDefaultExportFromCjs(x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
}
var extraTypings = { exports: {} };
var commander = {};
var argument = {};
var error = {};
let CommanderError$3 = class CommanderError extends Error {
/**
* 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(exitCode, code, message) {
super(message);
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.code = code;
this.exitCode = exitCode;
this.nestedError = void 0;
}
};
let InvalidArgumentError$4 = class InvalidArgumentError extends CommanderError$3 {
/**
* Constructs the InvalidArgumentError class
* @param {string} [message] explanation of why argument is invalid
*/
constructor(message) {
super(1, "commander.invalidArgument", message);
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
}
};
error.CommanderError = CommanderError$3;
error.InvalidArgumentError = InvalidArgumentError$4;
const { InvalidArgumentError: InvalidArgumentError$3 } = error;
let Argument$3 = class 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(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);
}
}
/**
* Return argument name.
*
* @return {string}
*/
name() {
return this._name;
}
/**
* @package
*/
_concatValue(value, previous) {
if (previous === this.defaultValue || !Array.isArray(previous)) {
return [value];
}
return previous.concat(value);
}
/**
* Set the default value, and optionally supply the description to be displayed in the help.
*
* @param {*} value
* @param {string} [description]
* @return {Argument}
*/
default(value, description) {
this.defaultValue = value;
this.defaultValueDescription = description;
return this;
}
/**
* Set the custom handler for processing CLI command arguments into argument values.
*
* @param {Function} [fn]
* @return {Argument}
*/
argParser(fn) {
this.parseArg = fn;
return this;
}
/**
* Only allow argument value to be one of choices.
*
* @param {string[]} values
* @return {Argument}
*/
choices(values) {
this.argChoices = values.slice();
this.parseArg = (arg, previous) => {
if (!this.argChoices.includes(arg)) {
throw new InvalidArgumentError$3(
`Allowed choices are ${this.argChoices.join(", ")}.`
);
}
if (this.variadic) {
return this._concatValue(arg, previous);
}
return arg;
};
return this;
}
/**
* Make argument required.
*
* @returns {Argument}
*/
argRequired() {
this.required = true;
return this;
}
/**
* Make argument optional.
*
* @returns {Argument}
*/
argOptional() {
this.required = false;
return this;
}
};
function humanReadableArgName$2(arg) {
const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
}
argument.Argument = Argument$3;
argument.humanReadableArgName = humanReadableArgName$2;
var command = {};
var help = {};
const { humanReadableArgName: humanReadableArgName$1 } = argument;
let Help$3 = class Help {
constructor() {
this.helpWidth = void 0;
this.sortSubcommands = false;
this.sortOptions = false;
this.showGlobalOptions = false;
}
/**
* 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(cmd) {
const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
const helpCommand = cmd._getHelpCommand();
if (helpCommand && !helpCommand._hidden) {
visibleCommands.push(helpCommand);
}
if (this.sortSubcommands) {
visibleCommands.sort((a, b) => {
return a.name().localeCompare(b.name());
});
}
return visibleCommands;
}
/**
* Compare options for sort.
*
* @param {Option} a
* @param {Option} b
* @returns {number}
*/
compareOptions(a, b) {
const getSortKey = (option2) => {
return option2.short ? option2.short.replace(/^-/, "") : option2.long.replace(/^--/, "");
};
return getSortKey(a).localeCompare(getSortKey(b));
}
/**
* 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(cmd) {
const visibleOptions = cmd.options.filter((option2) => !option2.hidden);
const helpOption = cmd._getHelpOption();
if (helpOption && !helpOption.hidden) {
const removeShort = helpOption.short && cmd._findOption(helpOption.short);
const removeLong = helpOption.long && cmd._findOption(helpOption.long);
if (!removeShort && !removeLong) {
visibleOptions.push(helpOption);
} else if (helpOption.long && !removeLong) {
visibleOptions.push(
cmd.createOption(helpOption.long, helpOption.description)
);
} else if (helpOption.short && !removeShort) {
visibleOptions.push(
cmd.createOption(helpOption.short, helpOption.description)
);
}
}
if (this.sortOptions) {
visibleOptions.sort(this.compareOptions);
}
return visibleOptions;
}
/**
* Get an array of the visible global options. (Not including help.)
*
* @param {Command} cmd
* @returns {Option[]}
*/
visibleGlobalOptions(cmd) {
if (!this.showGlobalOptions) return [];
const globalOptions = [];
for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
const visibleOptions = ancestorCmd.options.filter(
(option2) => !option2.hidden
);
globalOptions.push(...visibleOptions);
}
if (this.sortOptions) {
globalOptions.sort(this.compareOptions);
}
return globalOptions;
}
/**
* Get an array of the arguments if any have a description.
*
* @param {Command} cmd
* @returns {Argument[]}
*/
visibleArguments(cmd) {
if (cmd._argsDescription) {
cmd.registeredArguments.forEach((argument2) => {
argument2.description = argument2.description || cmd._argsDescription[argument2.name()] || "";
});
}
if (cmd.registeredArguments.find((argument2) => argument2.description)) {
return cmd.registeredArguments;
}
return [];
}
/**
* Get the command term to show in the list of subcommands.
*
* @param {Command} cmd
* @returns {string}
*/
subcommandTerm(cmd) {
const args = cmd.registeredArguments.map((arg) => humanReadableArgName$1(arg)).join(" ");
return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
(args ? " " + args : "");
}
/**
* Get the option term to show in the list of options.
*
* @param {Option} option
* @returns {string}
*/
optionTerm(option2) {
return option2.flags;
}
/**
* Get the argument term to show in the list of arguments.
*
* @param {Argument} argument
* @returns {string}
*/
argumentTerm(argument2) {
return argument2.name();
}
/**
* Get the longest command term length.
*
* @param {Command} cmd
* @param {Help} helper
* @returns {number}
*/
longestSubcommandTermLength(cmd, helper) {
return helper.visibleCommands(cmd).reduce((max, command2) => {
return Math.max(max, helper.subcommandTerm(command2).length);
}, 0);
}
/**
* Get the longest option term length.
*
* @param {Command} cmd
* @param {Help} helper
* @returns {number}
*/
longestOptionTermLength(cmd, helper) {
return helper.visibleOptions(cmd).reduce((max, option2) => {
return Math.max(max, helper.optionTerm(option2).length);
}, 0);
}
/**
* Get the longest global option term length.
*
* @param {Command} cmd
* @param {Help} helper
* @returns {number}
*/
longestGlobalOptionTermLength(cmd, helper) {
return helper.visibleGlobalOptions(cmd).reduce((max, option2) => {
return Math.max(max, helper.optionTerm(option2).length);
}, 0);
}
/**
* Get the longest argument term length.
*
* @param {Command} cmd
* @param {Help} helper
* @returns {number}
*/
longestArgumentTermLength(cmd, helper) {
return helper.visibleArguments(cmd).reduce((max, argument2) => {
return Math.max(max, helper.argumentTerm(argument2).length);
}, 0);
}
/**
* Get the command usage to be displayed at the top of the built-in help.
*
* @param {Command} cmd
* @returns {string}
*/
commandUsage(cmd) {
let cmdName = cmd._name;
if (cmd._aliases[0]) {
cmdName = cmdName + "|" + cmd._aliases[0];
}
let ancestorCmdNames = "";
for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
}
return ancestorCmdNames + cmdName + " " + cmd.usage();
}
/**
* Get the description for the command.
*
* @param {Command} cmd
* @returns {string}
*/
commandDescription(cmd) {
return cmd.description();
}
/**
* Get the subcommand summary to show in the list of subcommands.
* (Fallback to description for backwards compatibility.)
*
* @param {Command} cmd
* @returns {string}
*/
subcommandDescription(cmd) {
return cmd.summary() || cmd.description();
}
/**
* Get the option description to show in the list of options.
*
* @param {Option} option
* @return {string}
*/
optionDescription(option2) {
const extraInfo = [];
if (option2.argChoices) {
extraInfo.push(
// use stringify to match the display of the default value
`choices: ${option2.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
);
}
if (option2.defaultValue !== void 0) {
const showDefault = option2.required || option2.optional || option2.isBoolean() && typeof option2.defaultValue === "boolean";
if (showDefault) {
extraInfo.push(
`default: ${option2.defaultValueDescription || JSON.stringify(option2.defaultValue)}`
);
}
}
if (option2.presetArg !== void 0 && option2.optional) {
extraInfo.push(`preset: ${JSON.stringify(option2.presetArg)}`);
}
if (option2.envVar !== void 0) {
extraInfo.push(`env: ${option2.envVar}`);
}
if (extraInfo.length > 0) {
return `${option2.description} (${extraInfo.join(", ")})`;
}
return option2.description;
}
/**
* Get the argument description to show in the list of arguments.
*
* @param {Argument} argument
* @return {string}
*/
argumentDescription(argument2) {
const extraInfo = [];
if (argument2.argChoices) {
extraInfo.push(
// use stringify to match the display of the default value
`choices: ${argument2.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
);
}
if (argument2.defaultValue !== void 0) {
extraInfo.push(
`default: ${argument2.defaultValueDescription || JSON.stringify(argument2.defaultValue)}`
);
}
if (extraInfo.length > 0) {
const extraDescripton = `(${extraInfo.join(", ")})`;
if (argument2.description) {
return `${argument2.description} ${extraDescripton}`;
}
return extraDescripton;
}
return argument2.description;
}
/**
* Generate the built-in help text.
*
* @param {Command} cmd
* @param {Help} helper
* @returns {string}
*/
formatHelp(cmd, helper) {
const termWidth = helper.padWidth(cmd, helper);
const helpWidth = helper.helpWidth || 80;
const itemIndentWidth = 2;
const itemSeparatorWidth = 2;
function formatItem(term, description) {
if (description) {
const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;
return helper.wrap(
fullText,
helpWidth - itemIndentWidth,
termWidth + itemSeparatorWidth
);
}
return term;
}
function formatList(textArray) {
return textArray.join("\n").replace(/^/gm, " ".repeat(itemIndentWidth));
}
let output = [`Usage: ${helper.commandUsage(cmd)}`, ""];
const commandDescription = helper.commandDescription(cmd);
if (commandDescription.length > 0) {
output = output.concat([
helper.wrap(commandDescription, helpWidth, 0),
""
]);
}
const argumentList = helper.visibleArguments(cmd).map((argument2) => {
return formatItem(
helper.argumentTerm(argument2),
helper.argumentDescription(argument2)
);
});
if (argumentList.length > 0) {
output = output.concat(["Arguments:", formatList(argumentList), ""]);
}
const optionList = helper.visibleOptions(cmd).map((option2) => {
return formatItem(
helper.optionTerm(option2),
helper.optionDescription(option2)
);
});
if (optionList.length > 0) {
output = output.concat(["Options:", formatList(optionList), ""]);
}
if (this.showGlobalOptions) {
const globalOptionList = helper.visibleGlobalOptions(cmd).map((option2) => {
return formatItem(
helper.optionTerm(option2),
helper.optionDescription(option2)
);
});
if (globalOptionList.length > 0) {
output = output.concat([
"Global Options:",
formatList(globalOptionList),
""
]);
}
}
const commandList = helper.visibleCommands(cmd).map((cmd2) => {
return formatItem(
helper.subcommandTerm(cmd2),
helper.subcommandDescription(cmd2)
);
});
if (commandList.length > 0) {
output = output.concat(["Commands:", formatList(commandList), ""]);
}
return output.join("\n");
}
/**
* Calculate the pad width from the maximum term length.
*
* @param {Command} cmd
* @param {Help} helper
* @returns {number}
*/
padWidth(cmd, helper) {
return Math.max(
helper.longestOptionTermLength(cmd, helper),
helper.longestGlobalOptionTermLength(cmd, helper),
helper.longestSubcommandTermLength(cmd, helper),
helper.longestArgumentTermLength(cmd, helper)
);
}
/**
* 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(str, width, indent, minColumnWidth = 40) {
const indents = " \\f\\t\\v  - \uFEFF";
const manualIndent = new RegExp(`[\\n][${indents}]+`);
if (str.match(manualIndent)) return str;
const columnWidth = width - indent;
if (columnWidth < minColumnWidth) return str;
const leadingStr = str.slice(0, indent);
const columnText = str.slice(indent).replace("\r\n", "\n");
const indentString = " ".repeat(indent);
const zeroWidthSpace = "";
const breaks = `\\s${zeroWidthSpace}`;
const regex = new RegExp(
`
|.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`,
"g"
);
const lines = columnText.match(regex) || [];
return leadingStr + lines.map((line, i) => {
if (line === "\n") return "";
return (i > 0 ? indentString : "") + line.trimEnd();
}).join("\n");
}
};
help.Help = Help$3;
var option = {};
const { InvalidArgumentError: InvalidArgumentError$2 } = error;
let Option$3 = class Option {
/**
* Initialize a new `Option` with the given `flags` and `description`.
*
* @param {string} flags
* @param {string} [description]
*/
constructor(flags, description) {
this.flags = flags;
this.description = description || "";
this.required = flags.includes("<");
this.optional = flags.includes("[");
this.variadic = /\w\.\.\.[>\]]$/.test(flags);
this.mandatory = false;
const optionFlags = splitOptionFlags(flags);
this.short = optionFlags.shortFlag;
this.long = optionFlags.longFlag;
this.negate = false;
if (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 = false;
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(value, description) {
this.defaultValue = value;
this.defaultValueDescription = description;
return 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(arg) {
this.presetArg = arg;
return 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(names) {
this.conflictsWith = this.conflictsWith.concat(names);
return 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(impliedOptionValues) {
let newImplied = impliedOptionValues;
if (typeof impliedOptionValues === "string") {
newImplied = { [impliedOptionValues]: true };
}
this.implied = Object.assign(this.implied || {}, newImplied);
return 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(name) {
this.envVar = name;
return this;
}
/**
* Set the custom handler for processing CLI option arguments into option values.
*
* @param {Function} [fn]
* @return {Option}
*/
argParser(fn) {
this.parseArg = fn;
return this;
}
/**
* Whether the option is mandatory and must have a value after parsing.
*
* @param {boolean} [mandatory=true]
* @return {Option}
*/
makeOptionMandatory(mandatory = true) {
this.mandatory = !!mandatory;
return this;
}
/**
* Hide option in help.
*
* @param {boolean} [hide=true]
* @return {Option}
*/
hideHelp(hide = true) {
this.hidden = !!hide;
return this;
}
/**
* @package
*/
_concatValue(value, previous) {
if (previous === this.defaultValue || !Array.isArray(previous)) {
return [value];
}
return previous.concat(value);
}
/**
* Only allow option value to be one of choices.
*
* @param {string[]} values
* @return {Option}
*/
choices(values) {
this.argChoices = values.slice();
this.parseArg = (arg, previous) => {
if (!this.argChoices.includes(arg)) {
throw new InvalidArgumentError$2(
`Allowed choices are ${this.argChoices.join(", ")}.`
);
}
if (this.variadic) {
return this._concatValue(arg, previous);
}
return arg;
};
return this;
}
/**
* Return option name.
*
* @return {string}
*/
name() {
if (this.long) {
return this.long.replace(/^--/, "");
}
return this.short.replace(/^-/, "");
}
/**
* Return option name, in a camelcase format that can be used
* as a object attribute key.
*
* @return {string}
*/
attributeName() {
return camelcase(this.name().replace(/^no-/, ""));
}
/**
* Check if `arg` matches the short or long flag.
*
* @param {string} arg
* @return {boolean}
* @package
*/
is(arg) {
return this.short === arg || this.long === arg;
}
/**
* 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;
}
};
let DualOptions$1 = class DualOptions {
/**
* @param {Option[]} options
*/
constructor(options) {
this.positiveOptions = /* @__PURE__ */ new Map();
this.negativeOptions = /* @__PURE__ */ new Map();
this.dualOptions = /* @__PURE__ */ new Set();
options.forEach((option2) => {
if (option2.negate) {
this.negativeOptions.set(option2.attributeName(), option2);
} else {
this.positiveOptions.set(option2.attributeName(), option2);
}
});
this.negativeOptions.forEach((value, key) => {
if (this.positiveOptions.has(key)) {
this.dualOptions.add(key);
}
});
}
/**
* Did the value come from the option, and not from possible matching dual option?
*
* @param {*} value
* @param {Option} option
* @returns {boolean}
*/
valueFromOption(value, option2) {
const optionKey = option2.attributeName();
if (!this.dualOptions.has(optionKey)) return true;
const preset = this.negativeOptions.get(optionKey).presetArg;
const negativeValue = preset !== void 0 ? preset : false;
return option2.negate === (negativeValue === value);
}
};
function camelcase(str) {
return str.split("-").reduce((str2, word) => {
return str2 + word[0].toUpperCase() + word.slice(1);
});
}
function splitOptionFlags(flags) {
let shortFlag;
let longFlag;
const flagParts = flags.split(/[ |,]+/);
if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1]))
shortFlag = flagParts.shift();
longFlag = flagParts.shift();
if (!shortFlag && /^-[^-]$/.test(longFlag)) {
shortFlag = longFlag;
longFlag = void 0;
}
return { shortFlag, longFlag };
}
option.Option = Option$3;
option.DualOptions = DualOptions$1;
var suggestSimilar$2 = {};
const maxDistance = 3;
function editDistance(a, b) {
if (Math.abs(a.length - b.length) > maxDistance)
return Math.max(a.length, b.length);
const d = [];
for (let i = 0; i <= a.length; i++) {
d[i] = [i];
}
for (let j = 0; j <= b.length; j++) {
d[0][j] = j;
}
for (let j = 1; j <= b.length; j++) {
for (let i = 1; i <= a.length; i++) {
let cost = 1;
if (a[i - 1] === b[j - 1]) {
cost = 0;
} else {
cost = 1;
}
d[i][j] = Math.min(
d[i - 1][j] + 1,
// deletion
d[i][j - 1] + 1,
// insertion
d[i - 1][j - 1] + cost
// substitution
);
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
}
}
}
return d[a.length][b.length];
}
function suggestSimilar$1(word, candidates) {
if (!candidates || candidates.length === 0) return "";
candidates = Array.from(new Set(candidates));
const searchingOptions = word.startsWith("--");
if (searchingOptions) {
word = word.slice(2);
candidates = candidates.map((candidate) => candidate.slice(2));
}
let similar = [];
let bestDistance = maxDistance;
const minSimilarity = 0.4;
candidates.forEach((candidate) => {
if (candidate.length <= 1) return;
const distance = editDistance(word, candidate);
const length = Math.max(word.length, candidate.length);
const similarity = (length - distance) / length;
if (similarity > minSimilarity) {
if (distance < bestDistance) {
bestDistance = distance;
similar = [candidate];
} else if (distance === bestDistance) {
similar.push(candidate);
}
}
});
similar.sort((a, b) => a.localeCompare(b));
if (searchingOptions) {
similar = similar.map((candidate) => `--${candidate}`);
}
if (similar.length > 1) {
return `
(Did you mean one of ${similar.join(", ")}?)`;
}
if (similar.length === 1) {
return `
(Did you mean ${similar[0]}?)`;
}
return "";
}
suggestSimilar$2.suggestSimilar = suggestSimilar$1;
const EventEmitter = require$$0.EventEmitter;
const childProcess = require$$1;
const path = require$$2;
const fs = require$$3;
const process = process$1;
const { Argument: Argument$2, humanReadableArgName } = argument;
const { CommanderError: CommanderError$2 } = error;
const { Help: Help$2 } = help;
const { Option: Option$2, DualOptions: DualOptions2 } = option;
const { suggestSimilar } = suggestSimilar$2;
let Command$2 = class Command extends EventEmitter {
/**
* Initialize a new `Command`.
*
* @param {string} [name]
*/
constructor(name) {
super();
this.commands = [];
this.options = [];
this.parent = null;
this._allowUnknownOption = false;
this._allowExcessArguments = true;
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._outputConfiguration = {
writeOut: (str) => process.stdout.write(str),
writeErr: (str) => process.stderr.write(str),
getOutHelpWidth: () => process.stdout.isTTY ? process.stdout.columns : void 0,
getErrHelpWidth: () => process.stderr.isTTY ? process.stderr.columns : void 0,
outputError: (str, write) => write(str)
};
this._hidden = false;
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(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;
}
/**
* @returns {Command[]}
* @private
*/
_getCommandAndAncestors() {
const result = [];
for (let command2 = this; command2; command2 = command2.parent) {
result.push(command2);
}
return result;
}
/**
* 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(nameAndArgs, actionOptsOrExecDesc, execOpts) {
let desc = actionOptsOrExecDesc;
let opts = execOpts;
if (typeof desc === "object" && desc !== null) {
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;
}
/**
* 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(name) {
return new Command(name);
}
/**
* 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 Help$2(), 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(configuration) {
if (configuration === void 0) return this._helpConfiguration;
this._helpConfiguration = configuration;
return 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(configuration) {
if (configuration === void 0) return this._outputConfiguration;
Object.assign(this._outputConfiguration, configuration);
return this;
}
/**
* Display the help or a custom message after an error occurs.
*
* @param {(boolean|string)} [displayHelp]
* @return {Command} `this` command for chaining
*/
showHelpAfterError(displayHelp = true) {
if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
this._showHelpAfterError = displayHelp;
return this;
}
/**
* Display suggestion of similar commands for unknown commands, or options for unknown options.
*
* @param {boolean} [displaySuggestion]
* @return {Command} `this` command for chaining
*/
showSuggestionAfterError(displaySuggestion = true) {
this._showSuggestionAfterError = !!displaySuggestion;
return 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(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;
}
/**
* 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(name, description) {
return new Argument$2(name, description);
}
/**
* 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(name, description, fn, defaultValue) {
const argument2 = this.createArgument(name, description);
if (typeof fn === "function") {
argument2.default(defaultValue).argParser(fn);
} else {
argument2.default(fn);
}
this.addArgument(argument2);
return 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(names) {
names.trim().split(/ +/).forEach((detail) => {
this.argument(detail);
});
return this;
}
/**
* Define argument syntax for command, adding a prepared argument.
*
* @param {Argument} argument
* @return {Command} `this` command for chaining
*/
addArgument(argument2) {
const previousArgument = this.registeredArguments.slice(-1)[0];
if (previousArgument && previousArgument.variadic) {
throw new Error(
`only the last argument can be variadic '${previousArgument.name()}'`
);
}
if (argument2.required && argument2.defaultValue !== void 0 && argument2.parseArg === void 0) {
throw new Error(
`a default value for a required argument is never used: '${argument2.name()}'`
);
}
this.registeredArguments.push(argument2);
return 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(enableOrNameAndArgs, description) {
if (typeof enableOrNameAndArgs === "boolean") {
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;
}
/**
* 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(helpCommand, deprecatedDescription) {
if (typeof helpCommand !== "object") {
this.helpCommand(helpCommand, deprecatedDescription);
return this;
}
this._addImplicitHelpCommand = true;
this._helpCommand = helpCommand;
return this;
}
/**
* Lazy create help command.
*
* @return {(Command|null)}
* @package
*/
_getHelpCommand() {
const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
if (hasImplicitHelpCommand) {
if (this._helpCommand === void 0) {
this.helpCommand(void 0, void 0);
}
return this._helpCommand;
}
return null;
}
/**
* Add hook for life cycle event.
*
* @param {string} event
* @param {Function} listener
* @return {Command} `this` command for chaining
*/
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;
}
/**
* 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(fn) {
if (fn) {
this._exitCallback = fn;
} else {
this._exitCallback = (err) => {
if (err.code !== "commander.executeSubCommandAsync") {
throw err;
}
};
}
return 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(exitCode, code, message) {
if (this._exitCallback) {
this._exitCallback(new CommanderError$2(exitCode, code, message));
}
process.exit(exitCode);
}
/**
* 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(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;
}
/**
* 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(flags, description) {
return new Option$2(flags, description);
}
/**
* Wrap parseArgs to catch 'commander.invalidArgument'.
*
* @param {(Option | Argument)} target
* @param {string} value
* @param {*} previous
* @param {string} invalidArgumentMessage
* @private
*/
_callParseArg(target, value, previous, invalidArgumentMessage) {
try {
return target.parseArg(value, previous);
} catch (err) {
if (err.code === "commander.invalidArgument") {
const message = `${invalidArgumentMessage} ${err.message}`;
this.error(message, { exitCode: err.exitCode, code: err.code });
}
throw err;
}
}
/**
* Check for option flag conflicts.
* Register option if no conflicts found, or throw on conflict.
*
* @param {Option} option
* @private
*/
_registerOption(option2) {
const matchingOption = option2.short && this._findOption(option2.short) || option2.long && this._findOption(option2.long);
if (matchingOption) {
const matchingFlag = option2.long && this._findOption(option2.long) ? option2.long : option2.short;
throw new Error(`Cannot add option '${option2.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
- already used by option '${matchingOption.flags}'`);
}
this.options.push(option2);
}
/**
* 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(command2) {
const knownBy = (cmd) => {
return [cmd.name()].concat(cmd.aliases());
};
const alreadyUsed = knownBy(command2).find(
(name) => this._findCommand(name)
);
if (alreadyUsed) {
const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
const newCmd = knownBy(command2).join("|");
throw new Error(
`cannot add command '${newCmd}' as already have command '${existingCmd}'`
);
}
this.commands.push(command2);
}
/**
* Add an option.
*
* @param {Option} option
* @return {Command} `this` command for chaining
*/
addOption(option2) {
this._registerOption(option2);
const oname = option2.name();
const name = option2.attributeName();
if (option2.negate) {
const positiveLongFlag = option2.long.replace(/^--no-/, "--");
if (!this._findOption(positiveLongFlag)) {
this.setOptionValueWithSource(
name,
option2.defaultValue === void 0 ? true : option2.defaultValue,
"default"
);
}
} else if (option2.defaultValue !== void 0) {
this.setOptionValueWithSource(name, option2.defaultValue, "default");
}
const handleOptionValue = (val, invalidValueMessage, valueSource) => {
if (val == null && option2.presetArg !== void 0) {
val = option2.presetArg;
}
const oldValue = this.getOptionValue(name);
if (val !== null && option2.parseArg) {
val = this._callParseArg(option2, val, oldValue, invalidValueMessage);
} else if (val !== null && option2.variadic) {
val = option2._concatValue(val, oldValue);
}
if (val == null) {
if (option2.negate) {
val = false;
} else if (option2.isBoolean() || option2.optional) {
val = true;
} else {
val = "";
}
}
this.setOptionValueWithSource(name, val, valueSource);
};
this.on("option:" + oname, (val) => {
const invalidValueMessage = `error: option '${option2.flags}' argument '${val}' is invalid.`;
handleOptionValue(val, invalidValueMessage, "cli");
});
if (option2.envVar) {
this.on("optionEnv:" + oname, (val) => {
const invalidValueMessage = `error: option '${option2.flags}' value '${val}' from env '${option2.envVar}' is invalid.`;
handleOptionValue(val, invalidValueMessage, "env");
});
}
return this;
}
/**
* Internal implementation shared by .option() and .requiredOption()
*
* @return {Command} `this` command for chaining
* @private
*/
_optionEx(config, flags, description, fn, defaultValue) {
if (typeof flags === "object" && flags instanceof Option$2) {
throw new Error(
"To add an Option object use addOption() instead of option() or requiredOption()"
);
}
const option2 = this.createOption(flags, description);
option2.makeOptionMandatory(!!config.mandatory);
if (typeof fn === "function") {
option2.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;
};
option2.default(defaultValue).argParser(fn);
} else {
option2.default(fn);
}
return this.addOption(option2);
}
/**
* 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(flags, description, parseArg, defaultValue) {
return this._optionEx({}, flags, description, parseArg, defaultValue);
}
/**
* 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(flags, description, parseArg, defaultValue) {
return this._optionEx(
{ mandatory: true },
flags,
description,
parseArg,
defaultValue
);
}
/**
* 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(combine = true) {
this._combineFlagAndOptionalValue = !!combine;
return 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(allowUnknown = true) {
this._allowUnknownOption = !!allowUnknown;
return 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(allowExcess = true) {
this._allowExcessArguments = !!allowExcess;
return 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(positional = true) {
this._enablePositionalOptions = !!positional;
return 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(passThrough = true) {
this._passThroughOptions = !!passThrough;
this._checkForBrokenPassThrough();
return 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(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;
}
/**
* Retrieve option value.
*
* @param {string} key
* @return {object} value
*/
getOptionValue(key) {
if (this._storeOptionsAsProperties) {
return this[key];
}
return this._optionValues[key];
}
/**
* Store option value.
*
* @param {string} key
* @param {object} value
* @return {Command} `this` command for chaining
*/
setOptionValue(key, value) {
return this.setOptionValueWithSource(key, value, 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(key, value, source) {
if (this._storeOptionsAsProperties) {
this[key] = value;
} else {
this._optionValues[key] = value;
}
this._optionValueSources[key] = source;
return this;
}
/**
* Get source of option value.
* Expected values are default | config | env | cli | implied
*
* @param {string} key
* @return {string}
*/
getOptionValueSource(key) {
return this._optionValueSources[key];
}
/**
* Get source of option value. See also .optsWithGlobals().
* Expected values are default | config | env | cli | implied
*
* @param {string} key
* @return {string}
*/
getOptionValueSourceWithGlobals(key) {
let source;
this._getCommandAndAncestors().forEach((cmd) => {
if (cmd.getOptionValueSource(key) !== void 0) {
source = cmd.getOptionValueSource(key);
}
});
return source;
}
/**
* 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(argv, parseOptions) {
var _a;
if (argv !== void 0 && !Array.isArray(argv)) {
throw new Error("first parameter to parse must be array or undefined");
}
parseOptions = parseOptions || {};
if (argv === void 0 && parseOptions.from === void 0) {
if ((_a = process.versions) == null ? void 0 : _a.electron) {
parseOptions.from = "electron";
}
const execArgv = process.execArgv ?? [];
if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
parseOptions.from = "eval";
}
}
if (argv === void 0) {
argv = process.argv;
}
this.rawArgs = argv.slice();
let userArgs;
switch (parseOptions.from) {
case void 0:
case "node":
this._scriptPath = argv[1];
userArgs = argv.slice(2);
break;
case "electron":
if (process.defaultApp) {
this._scriptPath = argv[1];
userArgs = argv.slice(2);
} else {
userArgs = argv.slice(1);
}
break;
case "user":
userArgs = argv.slice(0);
break;
case "eval":
userArgs = argv.slice(1);
break;
default:
throw new Error(
`unexpected parse option { from: '${parseOptions.from}' }`
);
}
if (!this._name && this._scriptPath)
this.nameFromFilename(this._scriptPath);
this._name = this._name || "program";
return userArgs;
}
/**
* Parse `argv`, setting options and invoking commands when defined.
*
* Use parseAsync instead of parse if any of your action handlers are async.
*
* Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
*
* Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
* - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
* - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
* - `'user'`: just user arguments
*
* @example
* program.parse(); // parse process.argv and auto-detect electron and special node flags
* program.parse(process.argv); // assume argv[0] is app and argv[1] is script
* program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
*
* @param {string[]} [argv] - optional, defaults to process.argv
* @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
* @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
* @return {Command} `this` command for chaining
*/
parse(argv, parseOptions) {
const userArgs = this._prepareUserArgs(argv, parseOptions);
this._parseCommand([], userArgs);
return this;
}
/**
* Parse `argv`, setting options and invoking commands when defined.
*
* Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
*
* Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
* - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
* - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
* - `'user'`: just user arguments
*
* @example
* await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
* await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
* await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
*
* @param {string[]} [argv]
* @param {object} [parseOptions]
* @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
* @return {Promise}
*/
async parseAsync(argv, parseOptions) {
const userArgs = this._prepareUserArgs(argv, parseOptions);
await this._parseCommand([], userArgs);
return this;
}
/**
* Execute a sub-command executable.
*
* @private
*/
_executeSubCommand(subcommand, args) {
args = args.slice();
let launchWithNode = false;
const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
function findFile(baseDir, baseName) {
const localBin = path.resolve(baseDir, baseName);
if (fs.existsSync(localBin)) return localBin;
if (sourceExt.includes(path.extname(baseName))) return void 0;
const foundExt = sourceExt.find(
(ext) => fs.existsSync(`${localBin}${ext}`)
);
if (foundExt) return `${localBin}${foundExt}`;
return void 0;
}
this._checkForMissingMandatoryOptions();
this._checkForConflictingOptions();
let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
let executableDir = this._executableDir || "";
if (this._scriptPath) {
let resolvedScriptPath;
try {
resolvedScriptPath = fs.realpathSync(this._scriptPath);
} catch (err) {
resolvedScriptPath = this._scriptPath;
}
executableDir = path.resolve(
path.dirname(resolvedScriptPath),
executableDir
);
}
if (executableDir) {
let localFile = findFile(executableDir, executableFile);
if (!localFile && !subcommand._executableFile && this._scriptPath) {
const legacyName = path.basename(
this._scriptPath,
path.extname(this._scriptPath)
);
if (legacyName !== this._name) {
localFile = findFile(
executableDir,
`${legacyName}-${subcommand._name}`
);
}
}
executableFile = localFile || executableFile;
}
launchWithNode = sourceExt.includes(path.extname(executableFile));
let proc;
if (process.platform !== "win32") {
if (launchWithNode) {
args.unshift(executableFile);
args = incrementNodeInspectorPort(process.execArgv).concat(args);
proc = childProcess.spawn(process.argv[0], args, { stdio: "inherit" });
} else {
proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
}
} else {
args.unshift(executableFile);
args = incrementNodeInspectorPort(process.execArgv).concat(args);
proc = childProcess.spawn(process.execPath, args, { stdio: "inherit" });
}
if (!proc.killed) {
const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
signals.forEach((signal) => {
process.on(signal, () => {
if (proc.killed === false && proc.exitCode === null) {
proc.kill(signal);
}
});
});
}
const exitCallback = this._exitCallback;
proc.on("close", (code) => {
code = code ?? 1;
if (!exitCallback) {
process.exit(code);
} else {
exitCallback(
new CommanderError$2(
code,
"commander.executeSubCommandAsync",
"(close)"
)
);
}
});
proc.on("error", (err) => {
if (err.code === "ENOENT") {
const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory";
const executableMissing = `'${executableFile}' does not exist
- if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
- ${executableDirMessage}`;
throw new Error(executableMissing);
} else if (err.code === "EACCES") {
throw new Error(`'${executableFile}' not executable`);
}
if (!exitCallback) {
process.exit(1);
} else {
const wrappedError = new CommanderError$2(
1,
"commander.executeSubCommandAsync",
"(error)"
);
wrappedError.nestedError = err;
exitCallback(wrappedError);
}
});
this.runningCommand = proc;
}
/**
* @private
*/
_dispatchSubcommand(commandName, operands, unknown) {
const subCommand = this._findCommand(commandName);
if (!subCommand) this.help({ error: true });
let promiseChain;
promiseChain = this._chainOrCallSubCommandHook(
promiseChain,
subCommand,
"preSubcommand"
);
promiseChain = this._chainOrCall(promiseChain, () => {
if (subCommand._executableHandler) {
this._executeSubCommand(subCommand, operands.concat(unknown));
} else {
return subCommand._parseCommand(operands, unknown);
}
});
return promiseChain;
}
/**
* Invoke help directly if possible, or dispatch if necessary.
* e.g. help foo
*
* @private
*/
_dispatchHelpCommand(subcommandName) {
var _a, _b;
if (!subcommandName) {
this.help();
}
const subCommand = this._findCommand(subcommandName);
if (subCommand && !subCommand._executableHandler) {
subCommand.help();
}
return this._dispatchSubcommand(
subcommandName,
[],
[((_a = this._getHelpOption()) == null ? void 0 : _a.long) ?? ((_b = this._getHelpOption()) == null ? void 0 : _b.short) ?? "--help"]
);
}
/**
* Check this.args against expected this.registeredArguments.
*
* @private
*/
_checkNumberOfArguments() {
this.registeredArguments.forEach((arg, i) => {
if (arg.required && this.args[i] == null) {
this.missingArgument(arg.name());
}
});
if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
return;
}
if (this.args.length > this.registeredArguments.length) {
this._excessArguments(this.args);
}
}
/**
* Process this.args using this.registeredArguments and save as this.processedArgs!
*
* @private
*/
_processArguments() {
const myParseArg = (argument2, value, previous) => {
let parsedValue = value;
if (value !== null && argument2.parseArg) {
const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument2.name()}'.`;
parsedValue = this._callParseArg(
argument2,
value,
previous,
invalidValueMessage
);
}
return parsedValue;
};
this._checkNumberOfArguments();
const processedArgs = [];
this.registeredArguments.forEach((declaredArg, index) => {
let value = declaredArg.defaultValue;
if (declaredArg.variadic) {
if (index < this.args.length) {
value = this.args.slice(index);
if (declaredArg.parseArg) {
value = value.reduce((processed, v) => {
return myParseArg(declaredArg, v, processed);
}, declaredArg.defaultValue);
}
} else if (value === void 0) {
value = [];
}
} else if (index < this.args.length) {
value = this.args[index];
if (declaredArg.parseArg) {
value = myParseArg(declaredArg, value, declaredArg.defaultValue);
}
}
processedArgs[index] = value;
});
this.processedArgs = processedArgs;
}
/**
* Once we have a promise we chain, but call synchronously until then.
*
* @param {(Promise|undefined)} promise
* @param {Function} fn
* @return {(Promise|undefined)}
* @private
*/
_chainOrCall(promise, fn) {
if (promise && promise.then && typeof promise.then === "function") {
return promise.then(() => fn());
}
return fn();
}
/**
*
* @param {(Promise|undefined)} promise
* @param {string} event
* @return {(Promise|undefined)}
* @private
*/
_chainOrCallHooks(promise, event) {
let result = promise;
const hooks = [];
this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
hookedCommand._lifeCycleHooks[event].forEach((callback) => {
hooks.push({ hookedCommand, callback });
});
});
if (event === "postAction") {
hooks.reverse();
}
hooks.forEach((hookDetail) => {
result = this._chainOrCall(result, () => {
return hookDetail.callback(hookDetail.hookedCommand, this);
});
});
return result;
}
/**
*
* @param {(Promise|undefined)} promise
* @param {Command} subCommand
* @param {string} event
* @return {(Promise|undefined)}
* @private
*/
_chainOrCallSubCommandHook(promise, subCommand, event) {
let result = promise;
if (this._lifeCycleHooks[event] !== void 0) {
this._lifeCycleHooks[event].forEach((hook) => {
result = this._chainOrCall(result, () => {
return hook(this, subCommand);
});
});
}
return result;
}
/**
* Process arguments in context of this command.
* Returns action result, in case it is a promise.
*
* @private
*/
_parseCommand(operands, unknown) {
const parsed = this.parseOptions(unknown);
this._parseOptionsEnv();
this._parseOptionsImplied();
operands = operands.concat(parsed.operands);
unknown = parsed.unknown;
this.args = operands.concat(unknown);
if (operands && this._findCommand(operands[0])) {
return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
}
if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
return this._dispatchHelpCommand(operands[1]);
}
if (this._defaultCommandName) {
this._outputHelpIfRequested(unknown);
return this._dispatchSubcommand(
this._defaultCommandName,
operands,
unknown
);
}
if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
this.help({ error: true });
}
this._outputHelpIfRequested(parsed.unknown);
this._checkForMissingMandatoryOptions();
this._checkForConflictingOptions();
const checkForUnknownOptions = () => {
if (parsed.unknown.length > 0) {
this.unknownOption(parsed.unknown[0]);
}
};
const commandEvent = `command:${this.name()}`;
if (this._actionHandler) {
checkForUnknownOptions();
this._processArguments();
let promiseChain;
promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
promiseChain = this._chainOrCall(
promiseChain,
() => this._actionHandler(this.processedArgs)
);
if (this.parent) {
promiseChain = this._chainOrCall(promiseChain, () => {
this.parent.emit(commandEvent, operands, unknown);
});
}
promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
return promiseChain;
}
if (this.parent && this.parent.listenerCount(commandEvent)) {
checkForUnknownOptions();
this._processArguments();
this.parent.emit(commandEvent, operands, unknown);
} else if (operands.length) {
if (this._findCommand("*")) {
return this._dispatchSubcommand("*", operands, unknown);
}
if (this.listenerCount("command:*")) {
this.emit("command:*", operands, unknown);
} else if (this.commands.length) {
this.unknownCommand();
} else {
checkForUnknownOptions();
this._processArguments();
}
} else if (this.commands.length) {
checkForUnknownOptions();
this.help({ error: true });
} else {
checkForUnknownOptions();
this._processArguments();
}
}
/**
* Find matching command.
*
* @private
* @return {Command | undefined}
*/
_findCommand(name) {
if (!name) return void 0;
return this.commands.find(
(cmd) => cmd._name === name || cmd._aliases.includes(name)
);
}
/**
* Return an option matching `arg` if any.
*
* @param {string} arg
* @return {Option}
* @package
*/
_findOption(arg) {
return this.options.find((option2) => option2.is(arg));
}
/**
* Display an error message if a mandatory option does not have a value.
* Called after checking for help flags in leaf subcommand.
*
* @private
*/
_checkForMissingMandatoryOptions() {
this._getCommandAndAncestors().forEach((cmd) => {
cmd.options.forEach((anOption) => {
if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
cmd.missingMandatoryOptionValue(anOption);
}
});
});
}
/**
* Display an error message if conflicting options are used together in this.
*
* @private
*/
_checkForConflictingLocalOptions() {
const definedNonDefaultOptions = this.options.filter((option2) => {
const optionKey = option2.attributeName();
if (this.getOptionValue(optionKey) === void 0) {
return false;
}
return this.getOptionValueSource(optionKey) !== "default";
});
const optionsWithConflicting = definedNonDefaultOptions.filter(
(option2) => option2.conflictsWith.length > 0
);
optionsWithConflicting.forEach((option2) => {
const conflictingAndDefined = definedNonDefaultOptions.find(
(defined) => option2.conflictsWith.includes(defined.attributeName())
);
if (conflictingAndDefined) {
this._conflictingOption(option2, conflictingAndDefined);
}
});
}
/**
* Display an error message if conflicting options are used together.
* Called after checking for help flags in leaf subcommand.
*
* @private
*/
_checkForConflictingOptions() {
this._getCommandAndAncestors().forEach((cmd) => {
cmd._checkForConflictingLocalOptions();
});
}
/**
* Parse options from `argv` removing known options,
* and return argv split into operands and unknown arguments.
*
* Examples:
*
* argv => operands, unknown
* --known kkk op => [op], []
* op --known kkk => [op], []
* sub --unknown uuu op => [sub], [--unknown uuu op]
* sub -- --unknown uuu op => [sub --unknown uuu op], []
*
* @param {string[]} argv
* @return {{operands: string[], unknown: string[]}}
*/
parseOptions(argv) {
const operands = [];
const unknown = [];
let dest = operands;
const args = argv.slice();
function maybeOption(arg) {
return arg.length > 1 && arg[0] === "-";
}
let activeVariadicOption = null;
while (args.length) {
const arg = args.shift();
if (arg === "--") {
if (dest === unknown) dest.push(arg);
dest.push(...args);
break;
}
if (activeVariadicOption && !maybeOption(arg)) {
this.emit(`option:${activeVariadicOption.name()}`, arg);
continue;
}
activeVariadicOption = null;
if (maybeOption(arg)) {
const option2 = this._findOption(arg);
if (option2) {
if (option2.required) {
const value = args.shift();
if (value === void 0) this.optionMissingArgument(option2);
this.emit(`option:${option2.name()}`, value);
} else if (option2.optional) {
let value = null;
if (args.length > 0 && !maybeOption(args[0])) {
value = args.shift();
}
this.emit(`option:${option2.name()}`, value);
} else {
this.emit(`option:${option2.name()}`);
}
activeVariadicOption = option2.variadic ? option2 : null;
continue;
}
}
if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
const option2 = this._findOption(`-${arg[1]}`);
if (option2) {
if (option2.required || option2.optional && this._combineFlagAndOptionalValue) {
this.emit(`option:${option2.name()}`, arg.slice(2));
} else {
this.emit(`option:${option2.name()}`);
args.unshift(`-${arg.slice(2)}`);
}
continue;
}
}
if (/^--[^=]+=/.test(arg)) {
const index = arg.indexOf("=");
const option2 = this._findOption(arg.slice(0, index));
if (option2 && (option2.required || option2.optional)) {
this.emit(`option:${option2.name()}`, arg.slice(index + 1));
continue;
}
}
if (maybeOption(arg)) {
dest = unknown;
}
if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
if (this._findCommand(arg)) {
operands.push(arg);
if (args.length > 0) unknown.push(...args);
break;
} else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
operands.push(arg);
if (args.length > 0) operands.push(...args);
break;
} else if (this._defaultCommandName) {
unknown.push(arg);
if (args.length > 0) unknown.push(...args);
break;
}
}
if (this._passThroughOptions) {
dest.push(arg);
if (args.length > 0) dest.push(...args);
break;
}
dest.push(arg);
}
return { operands, unknown };
}
/**
* Return an object containing local option values as key-value pairs.
*
* @return {object}
*/
opts() {
if (this._storeOptionsAsProperties) {
const result = {};
const len = this.options.length;
for (let i = 0; i < len; i++) {
const key = this.options[i].attributeName();
result[key] = key === this._versionOptionName ? this._version : this[key];
}
return result;
}
return this._optionValues;
}
/**
* Return an object containing merged local and global option values as key-value pairs.
*
* @return {object}
*/
optsWithGlobals() {
return this._getCommandAndAncestors().reduce(
(combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
{}
);
}
/**
* Display error message and exit (or call exitOverride).
*
* @param {string} message
* @param {object} [errorOptions]
* @param {string} [errorOptions.code] - an id string representing the error
* @param {number} [errorOptions.exitCode] - used with process.exit
*/
error(message, errorOptions) {
this._outputConfiguration.outputError(
`${message}
`,
this._outputConfiguration.writeErr
);
if (typeof this._showHelpAfterError === "string") {
this._outputConfiguration.writeErr(`${this._showHelpAfterError}
`);
} else if (this._showHelpAfterError) {
this._outputConfiguration.writeErr("\n");
this.outputHelp({ error: true });
}
const config = errorOptions || {};
const exitCode = config.exitCode || 1;
const code = config.code || "commander.error";
this._exit(exitCode, code, message);
}
/**
* Apply any option related environment variables, if option does
* not have a value from cli or client code.
*
* @private
*/
_parseOptionsEnv() {
this.options.forEach((option2) => {
if (option2.envVar && option2.envVar in process.env) {
const optionKey = option2.attributeName();
if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(
this.getOptionValueSource(optionKey)
)) {
if (option2.required || option2.optional) {
this.emit(`optionEnv:${option2.name()}`, process.env[option2.envVar]);
} else {
this.emit(`optionEnv:${option2.name()}`);
}
}
}
});
}
/**
* Apply any implied option values, if option is undefined or default value.
*
* @private
*/
_parseOptionsImplied() {
const dualHelper = new DualOptions2(this.options);
const hasCustomOptionValue = (optionKey) => {
return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
};
this.options.filter(
(option2) => option2.implied !== void 0 && hasCustomOptionValue(option2.attributeName()) && dualHelper.valueFromOption(
this.getOptionValue(option2.attributeName()),
option2
)
).forEach((option2) => {
Object.keys(option2.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
this.setOptionValueWithSource(
impliedKey,
option2.implied[impliedKey],
"implied"
);
});
});
}
/**
* Argument `name` is missing.
*
* @param {string} name
* @private
*/
missingArgument(name) {
const message = `error: missing required argument '${name}'`;
this.error(message, { code: "commander.missingArgument" });
}
/**
* `Option` is missing an argument.
*
* @param {Option} option
* @private
*/
optionMissingArgument(option2) {
const message = `error: option '${option2.flags}' argument missing`;
this.error(message, { code: "commander.optionMissingArgument" });
}
/**
* `Option` does not have a value, and is a mandatory option.
*
* @param {Option} option
* @private
*/
missingMandatoryOptionValue(option2) {
const message = `error: required option '${option2.flags}' not specified`;
this.error(message, { code: "commander.missingMandatoryOptionValue" });
}
/**
* `Option` conflicts with another option.
*
* @param {Option} option
* @param {Option} conflictingOption
* @private
*/
_conflictingOption(option2, conflictingOption) {
const findBestOptionFromValue = (option3) => {
const optionKey = option3.attributeName();
const optionValue = this.getOptionValue(optionKey);
const negativeOption = this.options.find(
(target) => target.negate && optionKey === target.attributeName()
);
const positiveOption = this.options.find(
(target) => !target.negate && optionKey === target.attributeName()
);
if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
return negativeOption;
}
return positiveOption || option3;
};
const getErrorMessage = (option3) => {
const bestOption = findBestOptionFromValue(option3);
const optionKey = bestOption.attributeName();
const source = this.getOptionValueSource(optionKey);
if (source === "env") {
return `environment variable '${bestOption.envVar}'`;
}
return `option '${bestOption.flags}'`;
};
const message = `error: ${getErrorMessage(option2)} cannot be used with ${getErrorMessage(conflictingOption)}`;
this.error(message, { code: "commander.conflictingOption" });
}
/**
* Unknown option `flag`.
*
* @param {string} flag
* @private
*/
unknownOption(flag) {
if (this._allowUnknownOption) return;
let suggestion = "";
if (flag.startsWith("--") && this._showSuggestionAfterError) {
let candidateFlags = [];
let command2 = this;
do {
const moreFlags = command2.createHelp().visibleOptions(command2).filter((option2) => option2.long).map((option2) => option2.long);
candidateFlags = candidateFlags.concat(moreFlags);
command2 = command2.parent;
} while (command2 && !command2._enablePositionalOptions);
suggestion = suggestSimilar(flag, candidateFlags);
}
const message = `error: unknown option '${flag}'${suggestion}`;
this.error(message, { code: "commander.unknownOption" });
}
/**
* Excess arguments, more than expected.
*
* @param {string[]} receivedArgs
* @private
*/
_excessArguments(receivedArgs) {
if (this._allowExcessArguments) return;
const expected = this.registeredArguments.length;
const s = expected === 1 ? "" : "s";
const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
this.error(message, { code: "commander.excessArguments" });
}
/**
* Unknown command.
*
* @private
*/
unknownCommand() {
const unknownName = this.args[0];
let suggestion = "";
if (this._showSuggestionAfterError) {
const candidateNames = [];
this.createHelp().visibleCommands(this).forEach((command2) => {
candidateNames.push(command2.name());
if (command2.alias()) candidateNames.push(command2.alias());
});
suggestion = suggestSimilar(unknownName, candidateNames);
}
const message = `error: unknown command '${unknownName}'${suggestion}`;
this.error(message, { code: "commander.unknownCommand" });
}
/**
* Get or set the program version.
*
* This method auto-registers the "-V, --version" option which will print the version number.
*
* You can optionally supply the flags and description to override the defaults.
*
* @param {string} [str]
* @param {string} [flags]
* @param {string} [description]
* @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
*/
version(str, flags, description) {
if (str === void 0) return this._version;
this._version = str;
flags = flags || "-V, --version";
description = description || "output the version number";
const versionOption = this.createOption(flags, description);
this._versionOptionName = versionOption.attributeName();
this._registerOption(versionOption);
this.on("option:" + versionOption.name(), () => {
this._outputConfiguration.writeOut(`${str}
`);
this._exit(0, "commander.version", str);
});
return this;
}
/**
* Set the description.
*
* @param {string} [str]
* @param {object} [argsDescription]
* @return {(string|Command)}
*/
description(str, argsDescription) {
if (str === void 0 && argsDescription === void 0)
return this._description;
this._description = str;
if (argsDescription) {
this._argsDescription = argsDescription;
}
return this;
}
/**
* Set the summary. Used when listed as subcommand of parent.
*
* @param {string} [str]
* @return {(string|Command)}
*/
summary(str) {
if (str === void 0) return this._summary;
this._summary = str;
return this;
}
/**
* Set an alias for the command.
*
* You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
*
* @param {string} [alias]
* @return {(string|Command)}
*/
alias(alias) {
var _a;
if (alias === void 0) return this._aliases[0];
let command2 = this;
if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
command2 = this.commands[this.commands.length - 1];
}
if (alias === command2._name)
throw new Error("Command alias can't be the same as its name");
const matchingCommand = (_a = this.parent) == null ? void 0 : _a._findCommand(alias);
if (matchingCommand) {
const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
throw new Error(
`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`
);
}
command2._aliases.push(alias);
return this;
}
/**
* Set aliases for the command.
*
* Only the first alias is shown in the auto-generated help.
*
* @param {string[]} [aliases]
* @return {(string[]|Command)}
*/
aliases(aliases) {
if (aliases === void 0) return this._aliases;
aliases.forEach((alias) => this.alias(alias));
return this;
}
/**
* Set / get the command usage `str`.
*
* @param {string} [str]
* @return {(string|Command)}
*/
usage(str) {
if (str === void 0) {
if (this._usage) return this._usage;
const args = this.registeredArguments.map((arg) => {
return humanReadableArgName(arg);
});
return [].concat(
this.options.length || this._helpOption !== null ? "[options]" : [],
this.commands.length ? "[command]" : [],
this.registeredArguments.length ? args : []
).join(" ");
}
this._usage = str;
return this;
}
/**
* Get or set the name of the command.
*
* @param {string} [str]
* @return {(string|Command)}
*/
name(str) {
if (str === void 0) return this._name;
this._name = str;
return this;
}
/**
* Set the name of the command from script filename, such as process.argv[1],
* or require.main.filename, or __filename.
*
* (Used internally and public although not documented in README.)
*
* @example
* program.nameFromFilename(require.main.filename);
*
* @param {string} filename
* @return {Command}
*/
nameFromFilename(filename) {
this._name = path.basename(filename, path.extname(filename));
return this;
}
/**
* Get or set the directory for searching for executable subcommands of this command.
*
* @example
* program.executableDir(__dirname);
* // or
* program.executableDir('subcommands');
*
* @param {string} [path]
* @return {(string|null|Command)}
*/
executableDir(path2) {
if (path2 === void 0) return this._executableDir;
this._executableDir = path2;
return this;
}
/**
* Return program help documentation.
*
* @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
* @return {string}
*/
helpInformation(contextOptions) {
const helper = this.createHelp();
if (helper.helpWidth === void 0) {
helper.helpWidth = contextOptions && contextOptions.error ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();
}
return helper.formatHelp(this, helper);
}
/**
* @private
*/
_getHelpContext(contextOptions) {
contextOptions = contextOptions || {};
const context = { error: !!contextOptions.error };
let write;
if (context.error) {
write = (arg) => this._outputConfiguration.writeErr(arg);
} else {
write = (arg) => this._outputConfiguration.writeOut(arg);
}
context.write = contextOptions.write || write;
context.command = this;
return context;
}
/**
* Output help information for this command.
*
* Outputs built-in help, and custom text added using `.addHelpText()`.
*
* @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
*/
outputHelp(contextOptions) {
var _a;
let deprecatedCallback;
if (typeof contextOptions === "function") {
deprecatedCallback = contextOptions;
contextOptions = void 0;
}
const context = this._getHelpContext(contextOptions);
this._getCommandAndAncestors().reverse().forEach((command2) => command2.emit("beforeAllHelp", context));
this.emit("beforeHelp", context);
let helpInformation = this.helpInformation(context);
if (deprecatedCallback) {
helpInformation = deprecatedCallback(helpInformation);
if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
throw new Error("outputHelp callback must return a string or a Buffer");
}
}
context.write(helpInformation);
if ((_a = this._getHelpOption()) == null ? void 0 : _a.long) {
this.emit(this._getHelpOption().long);
}
this.emit("afterHelp", context);
this._getCommandAndAncestors().forEach(
(command2) => command2.emit("afterAllHelp", context)
);
}
/**
* You can pass in flags and a description to customise the built-in help option.
* Pass in false to disable the built-in help option.
*
* @example
* program.helpOption('-?, --help' 'show help'); // customise
* program.helpOption(false); // disable
*
* @param {(string | boolean)} flags
* @param {string} [description]
* @return {Command} `this` command for chaining
*/
helpOption(flags, description) {
if (typeof flags === "boolean") {
if (flags) {
this._helpOption = this._helpOption ?? void 0;
} else {
this._helpOption = null;
}
return this;
}
flags = flags ?? "-h, --help";
description = description ?? "display help for command";
this._helpOption = this.createOption(flags, description);
return this;
}
/**
* Lazy create help option.
* Returns null if has been disabled with .helpOption(false).
*
* @returns {(Option | null)} the help option
* @package
*/
_getHelpOption() {
if (this._helpOption === void 0) {
this.helpOption(void 0, void 0);
}
return this._helpOption;
}
/**
* Supply your own option to use for the built-in help option.
* This is an alternative to using helpOption() to customise the flags and description etc.
*
* @param {Option} option
* @return {Command} `this` command for chaining
*/
addHelpOption(option2) {
this._helpOption = option2;
return this;
}
/**
* Output help information and exit.
*
* Outputs built-in help, and custom text added using `.addHelpText()`.
*
* @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
*/
help(contextOptions) {
this.outputHelp(contextOptions);
let exitCode = process.exitCode || 0;
if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
exitCode = 1;
}
this._exit(exitCode, "commander.help", "(outputHelp)");
}
/**
* Add additional text to be displayed with the built-in help.
*
* Position is 'before' or 'after' to affect just this command,
* and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
*
* @param {string} position - before or after built-in help
* @param {(string | Function)} text - string to add, or a function returning a string
* @return {Command} `this` command for chaining
*/
addHelpText(position, text) {
const allowedValues = ["beforeAll", "before", "after", "afterAll"];
if (!allowedValues.includes(position)) {
throw new Error(`Unexpected value for position to addHelpText.
Expecting one of '${allowedValues.join("', '")}'`);
}
const helpEvent = `${position}Help`;
this.on(helpEvent, (context) => {
let helpStr;
if (typeof text === "function") {
helpStr = text({ error: context.error, command: context.command });
} else {
helpStr = text;
}
if (helpStr) {
context.write(`${helpStr}
`);
}
});
return this;
}
/**
* Output help information if help flags specified
*
* @param {Array} args - array of options to search for help flags
* @private
*/
_outputHelpIfRequested(args) {
const helpOption = this._getHelpOption();
const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
if (helpRequested) {
this.outputHelp();
this._exit(0, "commander.helpDisplayed", "(outputHelp)");
}
}
};
function incrementNodeInspectorPort(args) {
return args.map((arg) => {
if (!arg.startsWith("--inspect")) {
return arg;
}
let debugOption;
let debugHost = "127.0.0.1";
let debugPort = "9229";
let match;
if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
debugOption = match[1];
} else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
debugOption = match[1];
if (/^\d+$/.test(match[3])) {
debugPort = match[3];
} else {
debugHost = match[3];
}
} else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
debugOption = match[1];
debugHost = match[3];
debugPort = match[4];
}
if (debugOption && debugPort !== "0") {
return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
}
return arg;
});
}
command.Command = Command$2;
const { Argument: Argument$1 } = argument;
const { Command: Command$1 } = command;
const { CommanderError: CommanderError$1, InvalidArgumentError: InvalidArgumentError$1 } = error;
const { Help: Help$1 } = help;
const { Option: Option$1 } = option;
commander.program = new Command$1();
commander.createCommand = (name) => new Command$1(name);
commander.createOption = (flags, description) => new Option$1(flags, description);
commander.createArgument = (name, description) => new Argument$1(name, description);
commander.Command = Command$1;
commander.Option = Option$1;
commander.Argument = Argument$1;
commander.Help = Help$1;
commander.CommanderError = CommanderError$1;
commander.InvalidArgumentError = InvalidArgumentError$1;
commander.InvalidOptionArgumentError = InvalidArgumentError$1;
(function(module, exports) {
const commander$1 = commander;
exports = module.exports = {};
exports.program = new commander$1.Command();
exports.Argument = commander$1.Argument;
exports.Command = commander$1.Command;
exports.CommanderError = commander$1.CommanderError;
exports.Help = commander$1.Help;
exports.InvalidArgumentError = commander$1.InvalidArgumentError;
exports.InvalidOptionArgumentError = commander$1.InvalidArgumentError;
exports.Option = commander$1.Option;
exports.createCommand = (name) => new commander$1.Command(name);
exports.createOption = (flags, description) => new commander$1.Option(flags, description);
exports.createArgument = (name, description) => new commander$1.Argument(name, description);
})(extraTypings, extraTypings.exports);
var extraTypingsExports = extraTypings.exports;
const extraTypingsCommander = /* @__PURE__ */ getDefaultExportFromCjs(extraTypingsExports);
const {
program: program$1,
createCommand,
createArgument,
createOption,
CommanderError: CommanderError2,
InvalidArgumentError: InvalidArgumentError2,
InvalidOptionArgumentError,
// deprecated old name
Command: Command2,
Argument: Argument2,
Option: Option2,
Help: Help2
} = extraTypingsCommander;
const helloWorldCmd = new Command2().name("hello-world").description("returns info about the server and stats");
helloWorldCmd.command("test").description("does something specific I guess").action(async () => {
const api = getAPIClient();
try {
console.dir(api);
} catch (error2) {
printErrorMessageWithReason(
"Something went horribly wrong",
error2
);
}
});
const __vite_import_meta_env__ = { "BASE_URL": "/", "CLI_VERSION": "0.0.1", "DEV": false, "MODE": "production", "PROD": true, "SSR": true };
const program = new Command2().name("lifetracker").description("A CLI interface to interact with my lifetracker api").addOption(
new Option2("--api-key <key>", "the API key to interact with the API").makeOptionMandatory(true).env("LIFETRACKER_API_KEY")
).addOption(
new Option2(
"--server-addr <addr>",
"the address of the server to connect to"
).makeOptionMandatory(true).env("LIFETRACKER_SERVER_ADDR")
).addOption(new Option2("--json", "to output the result as JSON")).version(
__vite_import_meta_env__ && "CLI_VERSION" in __vite_import_meta_env__ ? "0.0.1" : "0.0.0"
);
program.addCommand(helloWorldCmd);
setGlobalOptions(program.opts());
program.parse();