UNPKG

argparse-ts

Version:

Modern CLI arguments parser for node.js

758 lines 30.8 kB
"use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __values = (this && this.__values) || function(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; var __read = (this && this.__read) || function (o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; }; var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Router = exports.ArgsParser = exports.ParsedArgumentsCollection = void 0; var utils_1 = require("./utils/utils"); var help_1 = require("./utils/help"); var validation_1 = require("./utils/validation"); var cast_1 = require("./utils/cast"); var actions_1 = require("./utils/actions"); var exceptions_1 = require("./exceptions"); /** * A collection of parsed arguments. * * @category Classes */ var ParsedArgumentsCollection = /** @class */ (function () { function ParsedArgumentsCollection() { /** * A collection of parsed positional arguments. */ this.positionalArgs = {}; /** * A collection of parsed optional arguments. */ this.optionArgs = {}; } Object.defineProperty(ParsedArgumentsCollection.prototype, "positional", { /** * Returns positional arguments as a record. */ get: function () { return __assign({}, this.positionalArgs); }, enumerable: false, configurable: true }); Object.defineProperty(ParsedArgumentsCollection.prototype, "options", { /** * Returns options as a record. */ get: function () { return __assign({}, this.optionArgs); }, enumerable: false, configurable: true }); /** * Retrieves an argument value. * @param name - The name of the argument. * @returns The value of the argument, or undefined if not found. */ ParsedArgumentsCollection.prototype.get = function (name) { var _a, _b; var formattedName = this.formatName(name); if (this.isPositional(name)) { return ((_a = this.positional[formattedName]) !== null && _a !== void 0 ? _a : undefined); } return ((_b = this.optionArgs[formattedName]) !== null && _b !== void 0 ? _b : undefined); }; /** * Checks if an argument exists in the collection. * @param name - The name of the argument. * @returns True if the argument exists, otherwise false. */ ParsedArgumentsCollection.prototype.has = function (name) { var _a, _b; var formattedName = this.formatName(name); if (this.isPositional(name)) { return ((_a = this.positional[formattedName]) !== null && _a !== void 0 ? _a : undefined) !== undefined; } return ((_b = this.optionArgs[formattedName]) !== null && _b !== void 0 ? _b : undefined) !== undefined; }; /** * Adds a new argument to the collection. * @param name - The name of the argument. * @param value - The value of the argument. * @returns The instance of ParsedArgumentsCollection for chaining. */ ParsedArgumentsCollection.prototype.add = function (name, value) { var formattedName = this.formatName(name); if (this.isPositional(name)) { this.positionalArgs[formattedName] = value; } else { this.optionArgs[formattedName] = value; } return this; }; /** * Formats the argument name by removing leading dashes. * @param name - The argument name. * @returns The formatted name. */ ParsedArgumentsCollection.prototype.formatName = function (name) { return name.replace(/^--/, ''); }; /** * Checks if the argument is positional. * @param name - The argument name. * @returns True if the argument is positional, otherwise false. */ ParsedArgumentsCollection.prototype.isPositional = function (name) { return !name.startsWith('--'); }; return ParsedArgumentsCollection; }()); exports.ParsedArgumentsCollection = ParsedArgumentsCollection; /** * Parser for command-line arguments. * * @category Classes */ var ArgsParser = /** @class */ (function () { /** * Constructs an instance of ArgsParser with the provided argument configurations. * * @param config - Configuration options for the parser. * @param args - An array of argument configurations. */ function ArgsParser(config, args) { var e_1, _a; if (args === void 0) { args = []; } /** * Maps argument names to their configuration. */ this.argsMap = new Map(); /** * Maps argument aliases to their corresponding names. */ this.aliasMap = new Map(); /** * Tracks used argument names and aliases to prevent duplicates. */ this.usedArgs = new Set(); this.config = this.formatConfig(config); try { for (var args_1 = __values(args), args_1_1 = args_1.next(); !args_1_1.done; args_1_1 = args_1.next()) { var arg = args_1_1.value; this.addArgument(arg); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (args_1_1 && !args_1_1.done && (_a = args_1.return)) _a.call(args_1); } finally { if (e_1) throw e_1.error; } } } Object.defineProperty(ArgsParser.prototype, "help", { /** * Retrieves the help message. */ get: function () { var e_2, _a, e_3, _b; var positionalArgs = this.getPositionalArguments(); var optionArgs = this.getOptionArguments(); var positionalArgsRows = []; try { for (var positionalArgs_1 = __values(positionalArgs), positionalArgs_1_1 = positionalArgs_1.next(); !positionalArgs_1_1.done; positionalArgs_1_1 = positionalArgs_1.next()) { var arg = positionalArgs_1_1.value; positionalArgsRows.push.apply(positionalArgsRows, __spreadArray([], __read((0, help_1.formatArgHelp)(arg)), false)); } } catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (positionalArgs_1_1 && !positionalArgs_1_1.done && (_a = positionalArgs_1.return)) _a.call(positionalArgs_1); } finally { if (e_2) throw e_2.error; } } var optionalArgsRows = []; try { for (var optionArgs_1 = __values(optionArgs), optionArgs_1_1 = optionArgs_1.next(); !optionArgs_1_1.done; optionArgs_1_1 = optionArgs_1.next()) { var arg = optionArgs_1_1.value; optionalArgsRows.push.apply(optionalArgsRows, __spreadArray([], __read((0, help_1.formatArgHelp)(arg)), false)); } } catch (e_3_1) { e_3 = { error: e_3_1 }; } finally { try { if (optionArgs_1_1 && !optionArgs_1_1.done && (_b = optionArgs_1.return)) _b.call(optionArgs_1); } finally { if (e_3) throw e_3.error; } } var result = []; if (positionalArgsRows.length > 0) { result.push.apply(result, __spreadArray([['Positional arguments:'], ['']], __read((0, help_1.tabTableRows)(positionalArgsRows)), false)); } if (optionalArgsRows.length > 0) { result.push.apply(result, __spreadArray([['Options:'], ['']], __read((0, help_1.tabTableRows)(optionalArgsRows)), false)); } return (0, help_1.convertToTable)(result, 1); }, enumerable: false, configurable: true }); /** * Adds a new argument configuration to the parser. * * @param config - The argument configuration. * @returns The instance of ArgsParser for chaining. * * @example * ``` * const parser = new ArgsParser(); * parser.addArgument({ * name: '--flag', * alias: '-f', * type: 'boolean', * const: true, * default: false, * }); * ``` */ ArgsParser.prototype.addArgument = function (config) { (0, validation_1.validateArgConfig)(config, this.getUsedArgs()); this.argsMap.set(config.name, this.extendArgConfig(config)); this.usedArgs.add(config.name); if (config.alias !== undefined) { this.aliasMap.set(config.alias, config.name); this.usedArgs.add(config.alias); } return this; }; /** * Adds an action configuration to the parser. * * @param config - The action configuration. * * @returns The updated parser. */ ArgsParser.prototype.addAction = function (config) { return this.addArgument(__assign(__assign({}, config), { type: 'boolean', const: true })); }; /** * Adds a help action to the parser. * * @param name - The name of the help action. * @param alias - The alias of the help action. * * @returns The updated parser. */ ArgsParser.prototype.addHelpAction = function (name, alias) { return this.addAction({ name: name !== null && name !== void 0 ? name : '--help', alias: (name === undefined && alias === undefined) ? '-h' : alias, action: 'help', description: 'Show help and exit', }); }; /** * Adds a version action to the parser. * * @param name - The name of the version action. * @param alias - The alias of the version action. * * @returns The updated parser. */ ArgsParser.prototype.addVersionAction = function (name, alias) { return this.addAction({ name: name !== null && name !== void 0 ? name : '--version', alias: (name === undefined && alias === undefined) ? '-v' : alias, action: 'version', description: 'Show version and exit', }); }; /** * Parses the given argument string and returns a collection of parsed arguments. * * @param argv - The argument string. * * @returns A ParsedArgumentsCollection containing the parsed arguments. * * @example * ``` * const parser = new ArgsParser([ * { * name: 'action', * description: 'Action to perform', * type: 'string', * }, * { * name: '--flag', * description: 'Flag', * alias: '-f', * type: 'boolean', * const: true, * default: false, * }, * { * name: '--values', * description: 'Values', * alias: '-v', * type: 'string', * nargs: '*', * default: [], * } * ]); * * const argv = ['make', '--flag', '-v', 'a', 'b', 'c']; * const parsedArgs = parser.parse(argv); * * console.log(parsedArgs.positional); // { action: 'make' } * console.log(parsedArgs.optional); // { flag: true, values: ['a', 'b', 'c'] } * console.log(parsedArgs.get('--values')); // ['a', 'b', 'c'] * ``` */ ArgsParser.prototype.parse = function (argv) { // Initialize a new collection to store the parsed arguments with their values var result = new ParsedArgumentsCollection(); // Parse the input arguments array into positional and optional parts var _a = __read((0, utils_1.parseArgsArray)(argv), 2), parsedPositional = _a[0], parsedOptions = _a[1]; var error = undefined; try { this.processPositionalArgs(parsedPositional, this.getPositionalArguments(), result); } catch (e) { error = this.processException(e, error); } try { this.processOptions(parsedOptions, this.getOptionArguments(), result); } catch (e) { error = this.processException(e, error); } if (error) { this.processExit(1, error); } return result; }; /** * Processes positional arguments. * * @param parsedValues - A parsed array of positional argument values. * @param argConfigs - An array of extended argument configurations. * @param result - The collection where parsed arguments will be added. * * @returns The number of positional arguments processed. */ ArgsParser.prototype.processPositionalArgs = function (parsedValues, argConfigs, result) { var count = 0; // Reverse the parsed positional arguments for easier processing parsedValues = __spreadArray([], __read(parsedValues), false).reverse(); // Process positional arguments for (var i = 0; i < argConfigs.length; ++i) { var argConfig = argConfigs[i]; // Get the remaining positional arguments configurations var remainingArgConfigs = argConfigs.slice(i + 1); // Check if there are enough positional arguments left (0, validation_1.checkEnoughPositionalValues)(parsedValues, argConfig, remainingArgConfigs); // Read the correct number of positional arguments var value = this.readPositionalArgValues(parsedValues, argConfig, remainingArgConfigs); // Add the parsed argument to the result result.add(argConfig.name, this.processArgValue(value, argConfig, result, value.length > 0)); ++count; } if (!this.config.ignoreUnrecognized) { // Check if all positional arguments were used (0, validation_1.checkAllPositionalValuesUsed)(parsedValues); } return count; }; /** * Processes optional arguments. * * @param parsedValuesMap - A map of parsed optional argument keys to their string values. * @param argConfigs - An array of extended argument configurations. * @param result - The collection where parsed arguments will be added. * * @returns The number of optional arguments processed. */ ArgsParser.prototype.processOptions = function (parsedValuesMap, argConfigs, result) { var e_4, _a, e_5, _b; var count = 0; var argConfigsSet = new Set(argConfigs); // Retrieve the optional argument configurations map var argConfigsMap = this.getArgConfigMap(Object.keys(parsedValuesMap)); if (!this.config.ignoreUnrecognized) { // Check if all options were recognized (0, validation_1.checkAllOptionsRecognized)(parsedValuesMap, argConfigsMap); } try { // Process options for (var _c = __values(Object.entries(parsedValuesMap)), _d = _c.next(); !_d.done; _d = _c.next()) { var _e = __read(_d.value, 2), key = _e[0], value = _e[1]; if (argConfigsMap[key] === undefined) { continue; } var argConfig = argConfigsMap[key]; result.add(argConfig.name, this.processArgValue(value, argConfig, result, true)); argConfigsSet.delete(argConfig); ++count; } } catch (e_4_1) { e_4 = { error: e_4_1 }; } finally { try { if (_d && !_d.done && (_a = _c.return)) _a.call(_c); } finally { if (e_4) throw e_4.error; } } try { // Process optional arguments that were not set and add default if necessary for (var argConfigsSet_1 = __values(argConfigsSet), argConfigsSet_1_1 = argConfigsSet_1.next(); !argConfigsSet_1_1.done; argConfigsSet_1_1 = argConfigsSet_1.next()) { var argConfig = argConfigsSet_1_1.value; var value = this.processArgValue([], argConfig, result, false); if ('default' in argConfig) { result.add(argConfig.name, value); } ++count; } } catch (e_5_1) { e_5 = { error: e_5_1 }; } finally { try { if (argConfigsSet_1_1 && !argConfigsSet_1_1.done && (_b = argConfigsSet_1.return)) _b.call(argConfigsSet_1); } finally { if (e_5) throw e_5.error; } } return count; }; ArgsParser.prototype.processException = function (e, previous) { if ((0, exceptions_1.isExceptionInstanceOf)(e, exceptions_1.StopException)) { this.processExit(0, e); } if (previous) { return previous; } if ((0, exceptions_1.isExceptionInstanceOf)(e, exceptions_1.ArgsParserError)) { return e; } throw e; }; ArgsParser.prototype.processExit = function (exitCode, e) { if (process !== undefined) { if (exitCode === 0 && this.config.exitOnStop) { process.exit(exitCode); } if (exitCode !== 0 && this.config.exitOnError) { console.error("Error: ".concat(e.message)); process.exit(exitCode); } } throw e; }; /** * Processes a single argument value. * * @param value - The value(s) being processed. * @param argConfig - The configuration of the argument. * @param parsed - The parsed result * @param isset - Whether the argument is set. * * @returns The processed value, or undefined if the argument is not set. */ ArgsParser.prototype.processArgValue = function (value, argConfig, parsed, isset) { var validator = (0, validation_1.createValueValidator)(argConfig); var caster = (0, cast_1.createValueCaster)(argConfig); validator.validateBeforeCast(value, isset); var result = caster.cast(value, isset); validator.validateAfterCast(result); if (isset && argConfig.action !== undefined) { result = this.processAction(argConfig, parsed, result); } return result; }; ArgsParser.prototype.processAction = function (config, parsed, value) { switch (true) { case config.action === 'help': return (0, actions_1.helpAction)(value, parsed, this); case config.action === 'version': return (0, actions_1.versionAction)(value, parsed, this); case (typeof config.action === 'function'): return config.action(value, parsed, this); } return value; // TODO maybe throw unknown action }; /** * Retrieves the positional arguments. * * @returns An array of positional argument configurations. */ ArgsParser.prototype.getPositionalArguments = function () { return __spreadArray([], __read(this.argsMap.values()), false).filter(function (x) { return x.positional; }); }; /** * Retrieves the optional arguments. * * @returns An array of optional argument configurations. */ ArgsParser.prototype.getOptionArguments = function () { return __spreadArray([], __read(this.argsMap.values()), false).filter(function (x) { return !x.positional; }); }; /** * Retrieves a set of used argument names and aliases. * * @returns A set of used argument names and aliases. */ ArgsParser.prototype.getUsedArgs = function () { return new Set(this.usedArgs); }; /** * Retrieves a map of argument configurations for the given keys. * * @param keys - The keys to retrieve. * * @returns A map of argument configurations, where each key is one of the given keys and the value * is the corresponding ArgConfigExtended. */ ArgsParser.prototype.getArgConfigMap = function (keys) { var e_6, _a; var result = {}; try { for (var keys_1 = __values(keys), keys_1_1 = keys_1.next(); !keys_1_1.done; keys_1_1 = keys_1.next()) { var key = keys_1_1.value; result[key] = this.getArgConfig(key); } } catch (e_6_1) { e_6 = { error: e_6_1 }; } finally { try { if (keys_1_1 && !keys_1_1.done && (_a = keys_1.return)) _a.call(keys_1); } finally { if (e_6) throw e_6.error; } } return result; }; /** * Retrieves the argument configuration for a given key. * * @param key - The argument key. * * @returns The corresponding ArgConfigExtended. */ ArgsParser.prototype.getArgConfig = function (key) { var _a; return this.argsMap.get((_a = this.aliasMap.get(key)) !== null && _a !== void 0 ? _a : key); }; /** * Extends an argument configuration with extra information. * * @param config - The argument configuration. * * @returns The argument configuration extended with extra information. */ ArgsParser.prototype.extendArgConfig = function (config) { return __assign(__assign({}, config), (0, utils_1.buildArgExtraConfig)(config)); }; /** * Reads the value of the positional argument based on the nargs configuration. * * @param parsedValues - The parsed positional arguments. * @param argConfig - The argument configuration. * @param remainingArgConfigs - The remaining argument configurations. * * @returns The value of the positional argument. */ ArgsParser.prototype.readPositionalArgValues = function (parsedValues, argConfig, remainingArgConfigs) { var toReadCount = this.getArgsCountToRead(argConfig, remainingArgConfigs, parsedValues); var value = []; for (var i = 0; i < toReadCount; ++i) { value.push(parsedValues.pop()); } return value; }; /** * Determines the number of arguments to read based on the nargs configuration. * * @param argConfig - The configuration specifying how many arguments can be read. * @param remainingArgConfigs - The remaining arguments to read. * @param values - The total number of available arguments. * * @returns The number of arguments to read. */ ArgsParser.prototype.getArgsCountToRead = function (argConfig, remainingArgConfigs, values) { // If the argument is required and not multiple, read one value. if (argConfig.required && !argConfig.multiple) { return Math.min(1, values.length); } // The total number of arguments that must be read by the remaining arguments. var minRemainingValuesCount = remainingArgConfigs.reduce(function (acc, x) { return acc + x.minValuesCount; }, 0); // The maximum number of arguments that can be read for the current argument. var maxCurrentValuesCount = values.length - minRemainingValuesCount; if (maxCurrentValuesCount < 0) { // If there are not enough values to read, read as many as are available. maxCurrentValuesCount = Math.min(argConfig.minValuesCount, values.length); } // If the argument is not multiple, read only one value. if (!argConfig.multiple) { return Math.min(1, maxCurrentValuesCount); } // If the argument has a fixed number of values, read that many. if (argConfig.valuesCount !== undefined) { return Math.min(argConfig.valuesCount, maxCurrentValuesCount); } // Otherwise, read as many values as are available. return maxCurrentValuesCount; }; ArgsParser.prototype.formatConfig = function (config) { var _a, _b, _c; return __assign(__assign({}, config), { exitOnError: (_a = config.exitOnError) !== null && _a !== void 0 ? _a : true, exitOnStop: (_b = config.exitOnStop) !== null && _b !== void 0 ? _b : true, ignoreUnrecognized: (_c = config.ignoreUnrecognized) !== null && _c !== void 0 ? _c : false }); }; return ArgsParser; }()); exports.ArgsParser = ArgsParser; /** * A class representing a router for command-line arguments. * * @category Classes * @category Router */ var Router = /** @class */ (function () { /** * Creates a new Router instance. * * @param config - The configuration for the router. * @param routes - The routes for the router. */ function Router(config, routes) { this.routes = routes; this.parser = new ArgsParser(__assign(__assign({}, config), { ignoreUnrecognized: true })); this.parser.addArgument({ name: 'action', type: 'string', description: 'Action to run', choices: Object.keys(routes), }); this.parser.addHelpAction(); this.parser.addVersionAction(); } /** * Runs the router. * * @param argv - The argument string. */ Router.prototype.run = function (argv) { var passedArgv = argv !== null && argv !== void 0 ? argv : process.argv.slice(2); var parsed = this.parser.parse(passedArgv); var actionName = parsed.get('action'); var actionArgsParser = new ArgsParser({ name: "".concat(this.parser.config.name, " ").concat(actionName), }); this.routes[actionName](actionArgsParser, passedArgv.slice(1)); }; /** * Runs the router asynchronously. * * @param argv - The argument string. */ Router.prototype.runAsync = function (argv) { return __awaiter(this, void 0, void 0, function () { var passedArgv, parsed, actionName, actionArgsParser; return __generator(this, function (_a) { switch (_a.label) { case 0: passedArgv = argv !== null && argv !== void 0 ? argv : process.argv.slice(2); parsed = this.parser.parse(passedArgv); actionName = parsed.get('action'); actionArgsParser = new ArgsParser({ name: "".concat(this.parser.config.name, " ").concat(actionName), }); return [4 /*yield*/, this.routes[actionName](actionArgsParser, passedArgv.slice(1))]; case 1: _a.sent(); return [2 /*return*/]; } }); }); }; return Router; }()); exports.Router = Router; //# sourceMappingURL=classes.js.map