Compare commits
No commits in common. "376c78e8fe198a7e8500d8651912b1a94121428f" and "d3c2a7470979bbba987bea455368781cc1589477" have entirely different histories.
376c78e8fe
...
d3c2a74709
108
.eslintrc.json
108
.eslintrc.json
@ -1,31 +1,33 @@
|
|||||||
{
|
{
|
||||||
"env": {
|
|
||||||
"es6": true,
|
|
||||||
"node": true
|
|
||||||
},
|
|
||||||
"extends": [ "eslint:recommended", "plugin:@typescript-eslint/recommended" ],
|
|
||||||
"globals": {
|
|
||||||
"Atomics": "readonly",
|
|
||||||
"SharedArrayBuffer": "readonly"
|
|
||||||
},
|
|
||||||
"parser": "@typescript-eslint/parser",
|
"parser": "@typescript-eslint/parser",
|
||||||
"plugins": [ "@typescript-eslint" ],
|
"plugins": [
|
||||||
"parserOptions": {
|
"@typescript-eslint"
|
||||||
"ecmaVersion": 2022,
|
],
|
||||||
"sourceType": "module"
|
"extends": [
|
||||||
},
|
"eslint:recommended",
|
||||||
|
"plugin:@typescript-eslint/recommended"
|
||||||
|
],
|
||||||
"rules": {
|
"rules": {
|
||||||
|
"max-len": [
|
||||||
|
"warn",
|
||||||
|
{
|
||||||
|
"code": 140,
|
||||||
|
"ignoreComments": true,
|
||||||
|
"ignoreStrings": true,
|
||||||
|
"ignoreTemplateLiterals": true,
|
||||||
|
"ignoreRegExpLiterals": true
|
||||||
|
}
|
||||||
|
],
|
||||||
"accessor-pairs": "warn",
|
"accessor-pairs": "warn",
|
||||||
"array-callback-return": "warn",
|
"array-callback-return": "warn",
|
||||||
"array-bracket-newline": [ "warn", "consistent" ],
|
"arrow-parens": "warn",
|
||||||
"array-bracket-spacing": [ "warn", "always", { "objectsInArrays": false, "arraysInArrays": false }],
|
|
||||||
"arrow-spacing": "warn",
|
"arrow-spacing": "warn",
|
||||||
"block-scoped-var": "warn",
|
"block-scoped-var": "warn",
|
||||||
"block-spacing": [ "warn", "always" ],
|
"block-spacing": "warn",
|
||||||
"brace-style": [ "warn", "1tbs" ],
|
"brace-style": "warn",
|
||||||
"callback-return": "warn",
|
"callback-return": "warn",
|
||||||
"camelcase": "warn",
|
"camelcase": "warn",
|
||||||
"comma-dangle": [ "warn", "only-multiline" ],
|
// "comma-dangle": "warn",
|
||||||
"comma-spacing": [
|
"comma-spacing": [
|
||||||
"warn",
|
"warn",
|
||||||
{
|
{
|
||||||
@ -45,10 +47,6 @@
|
|||||||
"allowKeywords": true
|
"allowKeywords": true
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"dot-location": [
|
|
||||||
"error",
|
|
||||||
"property"
|
|
||||||
],
|
|
||||||
"eol-last": [
|
"eol-last": [
|
||||||
"warn",
|
"warn",
|
||||||
"never"
|
"never"
|
||||||
@ -58,25 +56,37 @@
|
|||||||
"func-name-matching": "warn",
|
"func-name-matching": "warn",
|
||||||
"func-names": "warn",
|
"func-names": "warn",
|
||||||
"func-style": "warn",
|
"func-style": "warn",
|
||||||
"function-paren-newline": "warn",
|
"function-paren-newline": [
|
||||||
|
"warn",
|
||||||
|
"consistent"
|
||||||
|
],
|
||||||
"generator-star-spacing": "warn",
|
"generator-star-spacing": "warn",
|
||||||
"grouped-accessor-pairs": "warn",
|
"grouped-accessor-pairs": "warn",
|
||||||
"guard-for-in": "warn",
|
"guard-for-in": "warn",
|
||||||
"handle-callback-err": "warn",
|
"handle-callback-err": "warn",
|
||||||
"id-blacklist": "warn",
|
"id-blacklist": "warn",
|
||||||
"id-match": "warn",
|
"id-match": "warn",
|
||||||
"implicit-arrow-linebreak": "warn",
|
"implicit-arrow-linebreak": ["warn", "unix"],
|
||||||
"indent": "warn",
|
"indent": [
|
||||||
|
"warn",
|
||||||
|
4,
|
||||||
|
{
|
||||||
|
"SwitchCase": 1
|
||||||
|
}
|
||||||
|
],
|
||||||
"init-declarations": "warn",
|
"init-declarations": "warn",
|
||||||
"jsx-quotes": [ "warn", "prefer-single" ],
|
"jsx-quotes": "warn",
|
||||||
"key-spacing": [ "warn", { "beforeColon": false, "afterColon": true }],
|
"key-spacing": "warn",
|
||||||
"keyword-spacing": [ "warn", { "after": true, "before": true }],
|
|
||||||
"linebreak-style": [
|
"linebreak-style": [
|
||||||
"error",
|
"warn",
|
||||||
"unix"
|
"windows"
|
||||||
],
|
],
|
||||||
"lines-around-comment": "warn",
|
"lines-around-comment": "warn",
|
||||||
"lines-around-directive": "warn",
|
"lines-around-directive": "warn",
|
||||||
|
"lines-between-class-members": [
|
||||||
|
"warn",
|
||||||
|
"always"
|
||||||
|
],
|
||||||
"max-classes-per-file": "warn",
|
"max-classes-per-file": "warn",
|
||||||
"max-nested-callbacks": "warn",
|
"max-nested-callbacks": "warn",
|
||||||
"new-parens": "warn",
|
"new-parens": "warn",
|
||||||
@ -96,17 +106,17 @@
|
|||||||
"no-extend-native": "warn",
|
"no-extend-native": "warn",
|
||||||
"no-extra-bind": "warn",
|
"no-extra-bind": "warn",
|
||||||
"no-extra-label": "warn",
|
"no-extra-label": "warn",
|
||||||
"no-extra-parens": "warn",
|
// "no-extra-parens": "warn",
|
||||||
"no-floating-decimal": "warn",
|
"no-floating-decimal": "warn",
|
||||||
"no-implicit-coercion": "warn",
|
"no-implicit-coercion": "warn",
|
||||||
"no-implicit-globals": "warn",
|
"no-implicit-globals": "warn",
|
||||||
"no-implied-eval": "error",
|
"no-implied-eval": "warn",
|
||||||
"no-import-assign": "warn",
|
"no-import-assign": "warn",
|
||||||
"no-invalid-this": "warn",
|
"no-invalid-this": "warn",
|
||||||
"no-iterator": "warn",
|
"no-iterator": "warn",
|
||||||
"no-label-var": "warn",
|
"no-label-var": "warn",
|
||||||
|
// "no-labels": "warn",
|
||||||
"no-lone-blocks": "warn",
|
"no-lone-blocks": "warn",
|
||||||
"no-lonely-if": "warn",
|
|
||||||
"no-loop-func": "warn",
|
"no-loop-func": "warn",
|
||||||
"no-mixed-requires": "warn",
|
"no-mixed-requires": "warn",
|
||||||
"no-multi-assign": "warn",
|
"no-multi-assign": "warn",
|
||||||
@ -115,7 +125,6 @@
|
|||||||
"no-multiple-empty-lines": "warn",
|
"no-multiple-empty-lines": "warn",
|
||||||
"no-native-reassign": "warn",
|
"no-native-reassign": "warn",
|
||||||
"no-negated-in-lhs": "warn",
|
"no-negated-in-lhs": "warn",
|
||||||
"no-negated-condition": "error",
|
|
||||||
"no-nested-ternary": "warn",
|
"no-nested-ternary": "warn",
|
||||||
"no-new": "warn",
|
"no-new": "warn",
|
||||||
"no-new-func": "warn",
|
"no-new-func": "warn",
|
||||||
@ -138,16 +147,14 @@
|
|||||||
"no-sequences": "warn",
|
"no-sequences": "warn",
|
||||||
"no-setter-return": "warn",
|
"no-setter-return": "warn",
|
||||||
"no-spaced-func": "warn",
|
"no-spaced-func": "warn",
|
||||||
"@typescript-eslint/no-shadow": "error",
|
|
||||||
"no-tabs": "warn",
|
"no-tabs": "warn",
|
||||||
"no-template-curly-in-string": "error",
|
"no-template-curly-in-string": "warn",
|
||||||
"no-throw-literal": "warn",
|
"no-throw-literal": "warn",
|
||||||
"no-undef-init": "error",
|
"no-undef-init": "warn",
|
||||||
"no-undefined": "error",
|
|
||||||
"no-unmodified-loop-condition": "warn",
|
"no-unmodified-loop-condition": "warn",
|
||||||
"no-unneeded-ternary": "error",
|
"no-unneeded-ternary": "warn",
|
||||||
"no-unused-expressions": "warn",
|
"no-unused-expressions": "warn",
|
||||||
"no-use-before-define": "error",
|
"no-use-before-define": "warn",
|
||||||
"no-useless-call": "warn",
|
"no-useless-call": "warn",
|
||||||
"no-useless-computed-key": "warn",
|
"no-useless-computed-key": "warn",
|
||||||
"no-useless-concat": "warn",
|
"no-useless-concat": "warn",
|
||||||
@ -156,25 +163,26 @@
|
|||||||
"no-useless-return": "warn",
|
"no-useless-return": "warn",
|
||||||
"no-var": "warn",
|
"no-var": "warn",
|
||||||
"no-void": "warn",
|
"no-void": "warn",
|
||||||
"no-whitespace-before-property": "error",
|
"no-whitespace-before-property": "warn",
|
||||||
"nonblock-statement-body-position": [ "warn", "below" ],
|
"nonblock-statement-body-position": [
|
||||||
|
"warn",
|
||||||
|
"any",
|
||||||
|
{}
|
||||||
|
],
|
||||||
"object-curly-spacing": [
|
"object-curly-spacing": [
|
||||||
"warn",
|
"warn",
|
||||||
"always"
|
"always"
|
||||||
],
|
],
|
||||||
"object-property-newline": [ "warn", { "allowAllPropertiesOnSameLine": true }],
|
|
||||||
"object-shorthand": "warn",
|
"object-shorthand": "warn",
|
||||||
"one-var-declaration-per-line": "warn",
|
"one-var-declaration-per-line": "warn",
|
||||||
"operator-assignment": "warn",
|
"operator-assignment": "warn",
|
||||||
"operator-linebreak": [ "warn", "before" ],
|
|
||||||
"padding-line-between-statements": "warn",
|
"padding-line-between-statements": "warn",
|
||||||
"padded-blocks": [ "warn", { "switches": "never" }, { "allowSingleLineBlocks": true }],
|
|
||||||
"prefer-arrow-callback": "warn",
|
"prefer-arrow-callback": "warn",
|
||||||
"prefer-const": "warn",
|
"prefer-const": "warn",
|
||||||
"prefer-destructuring": "warn",
|
"prefer-destructuring": "warn",
|
||||||
"prefer-exponentiation-operator": "warn",
|
"prefer-exponentiation-operator": "warn",
|
||||||
"prefer-numeric-literals": "warn",
|
"prefer-numeric-literals": "warn",
|
||||||
"prefer-object-spread": "error",
|
"prefer-object-spread": "warn",
|
||||||
"prefer-promise-reject-errors": "warn",
|
"prefer-promise-reject-errors": "warn",
|
||||||
"prefer-regex-literals": "warn",
|
"prefer-regex-literals": "warn",
|
||||||
"prefer-rest-params": "warn",
|
"prefer-rest-params": "warn",
|
||||||
@ -182,19 +190,17 @@
|
|||||||
"require-jsdoc": "warn",
|
"require-jsdoc": "warn",
|
||||||
"require-unicode-regexp": "warn",
|
"require-unicode-regexp": "warn",
|
||||||
"rest-spread-spacing": "warn",
|
"rest-spread-spacing": "warn",
|
||||||
"semi": "error",
|
"semi": "warn",
|
||||||
"semi-spacing": "warn",
|
"semi-spacing": "warn",
|
||||||
"semi-style": [
|
"semi-style": [
|
||||||
"warn",
|
"warn",
|
||||||
"last"
|
"last"
|
||||||
],
|
],
|
||||||
"space-before-blocks": "warn",
|
"space-before-blocks": "warn",
|
||||||
"space-before-function-paren": [ "error", "always" ],
|
|
||||||
"space-in-parens": [
|
"space-in-parens": [
|
||||||
"warn",
|
"warn",
|
||||||
"never"
|
"never"
|
||||||
],
|
],
|
||||||
"spaced-comment": [ "warn", "always" ],
|
|
||||||
"strict": "warn",
|
"strict": "warn",
|
||||||
"switch-colon-spacing": "warn",
|
"switch-colon-spacing": "warn",
|
||||||
"symbol-description": "warn",
|
"symbol-description": "warn",
|
||||||
@ -209,7 +215,7 @@
|
|||||||
],
|
],
|
||||||
"vars-on-top": "warn",
|
"vars-on-top": "warn",
|
||||||
"wrap-iife": "warn",
|
"wrap-iife": "warn",
|
||||||
"wrap-regex": "error",
|
"wrap-regex": "warn",
|
||||||
"yield-star-spacing": "warn",
|
"yield-star-spacing": "warn",
|
||||||
"yoda": [
|
"yoda": [
|
||||||
"warn",
|
"warn",
|
||||||
|
22
package.json
22
package.json
@ -1,24 +1,11 @@
|
|||||||
{
|
{
|
||||||
"name": "commandparser",
|
"name": "commandparser",
|
||||||
"version": "1.2.0",
|
"version": "1.1.2",
|
||||||
"description": "Parser meant to parse commands and their options for discord bots",
|
"description": "Parser meant to parse commands and their options for discord bots",
|
||||||
|
"main": "build/index.js",
|
||||||
"author": "Navy.gif",
|
"author": "Navy.gif",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"private": false,
|
"private": false,
|
||||||
"repository": "",
|
|
||||||
|
|
||||||
"type": "module",
|
|
||||||
"main": "build/cjs/index.js",
|
|
||||||
"module": "build/esm/index.js",
|
|
||||||
"types": "./build/esm/index.d.ts",
|
|
||||||
"exports": {
|
|
||||||
".": {
|
|
||||||
"import": "./build/esm/index.js",
|
|
||||||
"require": "./build/cjs/index.js",
|
|
||||||
"default": "./build/cjs/index.js",
|
|
||||||
"types": "./build/esm/index.d.ts"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@babel/core": "^7.20.12",
|
"@babel/core": "^7.20.12",
|
||||||
"@babel/preset-env": "^7.20.2",
|
"@babel/preset-env": "^7.20.2",
|
||||||
@ -30,8 +17,11 @@
|
|||||||
"jest": "^29.4.2",
|
"jest": "^29.4.2",
|
||||||
"typescript": "^4.7.4"
|
"typescript": "^4.7.4"
|
||||||
},
|
},
|
||||||
|
"files": [
|
||||||
|
"build"
|
||||||
|
],
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "tsc && tsc -p tsconfig.cjs.json && node ./scripts/declareTypes.js",
|
"build": "tsc",
|
||||||
"test": "tsc && jest",
|
"test": "tsc && jest",
|
||||||
"release": "tsc && yarn publish",
|
"release": "tsc && yarn publish",
|
||||||
"lint": "eslint --fix"
|
"lint": "eslint --fix"
|
||||||
|
@ -1,3 +0,0 @@
|
|||||||
import fs from 'node:fs';
|
|
||||||
fs.writeFileSync('./build/cjs/package.json', JSON.stringify({ type: 'commonjs' }));
|
|
||||||
fs.writeFileSync('./build/esm/package.json', JSON.stringify({ type: 'module' }));
|
|
127
src/Parser.ts
127
src/Parser.ts
@ -23,7 +23,7 @@ type ParserOptions = {
|
|||||||
commands: Iterable<Command>,
|
commands: Iterable<Command>,
|
||||||
prefix?: string,
|
prefix?: string,
|
||||||
debug?: boolean,
|
debug?: boolean,
|
||||||
resolver?: IResolver<unknown, unknown, unknown, unknown, unknown>
|
resolver: IResolver<unknown, unknown, unknown, unknown, unknown>
|
||||||
}
|
}
|
||||||
|
|
||||||
class ParseError extends Error {}
|
class ParseError extends Error {}
|
||||||
@ -38,28 +38,25 @@ class Parser extends EventEmitter {
|
|||||||
|
|
||||||
prefix: string;
|
prefix: string;
|
||||||
|
|
||||||
resolver?: IResolver<unknown, unknown, unknown, unknown, unknown>;
|
resolver: IResolver<unknown, unknown, unknown, unknown, unknown>;
|
||||||
|
|
||||||
constructor ({ commands, prefix, debug = false, resolver }: ParserOptions) {
|
constructor({ commands, prefix, debug = false, resolver }: ParserOptions) {
|
||||||
|
|
||||||
super();
|
super();
|
||||||
|
|
||||||
this._debug = debug;
|
this._debug = debug;
|
||||||
this.commands = new ExtendedMap<string, Command>();
|
this.commands = new ExtendedMap<string, Command>();
|
||||||
for (const command of commands)
|
for (const command of commands) this.commands.set(command.name, command);
|
||||||
this.commands.set(command.name, command);
|
|
||||||
this.resolver = resolver;
|
this.resolver = resolver;
|
||||||
|
|
||||||
this.prefix = prefix || '';
|
this.prefix = prefix || '';
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private matchCommand (name: string): Command | null {
|
private matchCommand(name: string): Command | null {
|
||||||
let command = null;
|
let command = null;
|
||||||
if (this.commands.has(name))
|
if (this.commands.has(name)) command = this.commands.get(name);
|
||||||
command = this.commands.get(name);
|
else command = this.commands.find((c) => c.aliases.includes(name));
|
||||||
else
|
|
||||||
command = this.commands.find((c) => c.aliases.includes(name));
|
|
||||||
return command || null;
|
return command || null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -75,21 +72,16 @@ class Parser extends EventEmitter {
|
|||||||
* @memberof Parser
|
* @memberof Parser
|
||||||
*/
|
*/
|
||||||
// eslint-disable-next-line @typescript-eslint/ban-types
|
// eslint-disable-next-line @typescript-eslint/ban-types
|
||||||
async parseMessage (
|
async parseMessage(message: string, prefix = this.prefix,
|
||||||
message: string, prefix = this.prefix,
|
guild?: unknown, commandFilter?: (command: Command) => boolean): Promise<ParseResult | null> {
|
||||||
guild?: unknown, commandFilter?: (command: Command) => boolean
|
|
||||||
): Promise<ParseResult | null> {
|
|
||||||
|
|
||||||
if (!message.startsWith(prefix) || !message.length)
|
if (!message.startsWith(prefix) || !message.length) return null;
|
||||||
return null;
|
|
||||||
let params: string[] = message.replace(prefix, '').split(' ').filter((str) => str.length);
|
let params: string[] = message.replace(prefix, '').split(' ').filter((str) => str.length);
|
||||||
const commandName = params.shift();
|
const commandName = params.shift();
|
||||||
if (!commandName)
|
if (!commandName) return null;
|
||||||
return null;
|
|
||||||
|
|
||||||
const command = this.matchCommand(commandName);
|
const command = this.matchCommand(commandName);
|
||||||
if (!command)
|
if (!command) return null;
|
||||||
return null;
|
|
||||||
this.debug(`Matched command ${command.name}`);
|
this.debug(`Matched command ${command.name}`);
|
||||||
|
|
||||||
if (commandFilter && typeof commandFilter === 'function') {
|
if (commandFilter && typeof commandFilter === 'function') {
|
||||||
@ -109,27 +101,24 @@ class Parser extends EventEmitter {
|
|||||||
// Parse out subcommands
|
// Parse out subcommands
|
||||||
if (subcommandGroups.length || subcommands.length) {
|
if (subcommandGroups.length || subcommands.length) {
|
||||||
this.debug(`Expecting subcommand`);
|
this.debug(`Expecting subcommand`);
|
||||||
if (!params.length)
|
if(!params.length) throw new ParseError('Expected a subcommand(group), got nothing');
|
||||||
throw new ParseError('Expected a subcommand(group), got nothing');
|
const [first, second, ...rest] = params;
|
||||||
const [ first, second, ...rest ] = params;
|
|
||||||
group = command.subcommandGroup(first);
|
group = command.subcommandGroup(first);
|
||||||
|
|
||||||
// Depending on how thoroughly I want to support old style commands this might have to try and resolve to other options
|
// Depending on how thoroughly I want to support old style commands this might have to try and resolve to other options
|
||||||
// But for now I'm followin discord's structure for commands
|
// But for now I'm followin discord's structure for commands
|
||||||
if (group) {
|
if (!group) {
|
||||||
subcommand = command.subcommand(second);
|
|
||||||
params = rest;
|
|
||||||
} else {
|
|
||||||
subcommand = command.subcommand(first);
|
subcommand = command.subcommand(first);
|
||||||
params = [];
|
params = [];
|
||||||
if (second)
|
if (second) params.push(second, ...rest);
|
||||||
params.push(second, ...rest);
|
} else {
|
||||||
|
subcommand = command.subcommand(second);
|
||||||
|
params = rest;
|
||||||
}
|
}
|
||||||
parseResult.subcommand = subcommand?.name || null;
|
parseResult.subcommand = subcommand?.name || null;
|
||||||
parseResult.subcommandGroup = group?.name || null;
|
parseResult.subcommandGroup = group?.name || null;
|
||||||
|
|
||||||
if (!subcommand)
|
if (!subcommand) throw new ParseError(`Expecting subcommand, one of ${subcommands.map((s) => s.name)}`); //return { showUsage: true, verbose: true };
|
||||||
throw new ParseError(`Expecting subcommand, one of ${subcommands.map((s) => s.name)}`); // return { showUsage: true, verbose: true };
|
|
||||||
this.debug(`Got ${subcommand.name}`);
|
this.debug(`Got ${subcommand.name}`);
|
||||||
|
|
||||||
}
|
}
|
||||||
@ -137,7 +126,7 @@ class Parser extends EventEmitter {
|
|||||||
const activeCommand = subcommand || command;
|
const activeCommand = subcommand || command;
|
||||||
const flags = activeCommand.options.filter((opt) => opt.flag);
|
const flags = activeCommand.options.filter((opt) => opt.flag);
|
||||||
|
|
||||||
params = Util.parseQuotes(params.join(' ')).map(([ str ]: (string | boolean)[]): string => str.toString());
|
params = Util.parseQuotes(params.join(' ')).map(([str]: (string | boolean)[]): string => str.toString());
|
||||||
this.debug(`Given params: "${params.join('", "')}"`);
|
this.debug(`Given params: "${params.join('", "')}"`);
|
||||||
let currentFlag = null;
|
let currentFlag = null;
|
||||||
|
|
||||||
@ -149,11 +138,10 @@ class Parser extends EventEmitter {
|
|||||||
if (currentFlag) { // Add potential value resolveables to the flag's raw value until next flag is hit, if there is one
|
if (currentFlag) { // Add potential value resolveables to the flag's raw value until next flag is hit, if there is one
|
||||||
this.debug(`Appending value to ${currentFlag.name}: ${params[index]}`);
|
this.debug(`Appending value to ${currentFlag.name}: ${params[index]}`);
|
||||||
if (currentFlag.plural) { // The parse function only parses consecutive values
|
if (currentFlag.plural) { // The parse function only parses consecutive values
|
||||||
if (!currentFlag.rawValue)
|
if (!currentFlag.rawValue) currentFlag.rawValue = [];
|
||||||
currentFlag.rawValue = [];
|
|
||||||
currentFlag.rawValue.push(params[index]);
|
currentFlag.rawValue.push(params[index]);
|
||||||
} else {
|
} else {
|
||||||
currentFlag.rawValue = [ params[index] ];
|
currentFlag.rawValue = [params[index]];
|
||||||
currentFlag = null;
|
currentFlag = null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -167,16 +155,14 @@ class Parser extends EventEmitter {
|
|||||||
aliased = f.valueAsAlias && f.choices.some((c) => c === _flag);
|
aliased = f.valueAsAlias && f.choices.some((c) => c === _flag);
|
||||||
return f.name === _flag || aliased;
|
return f.name === _flag || aliased;
|
||||||
});
|
});
|
||||||
if (!flag)
|
if (!flag) throw new ParseError(`Unrecognised flag: ${_flag}`);
|
||||||
throw new ParseError(`Unrecognised flag: ${_flag}`);
|
|
||||||
this.debug(`Matched flag: ${flag.name} with ${_flag}`);
|
this.debug(`Matched flag: ${flag.name} with ${_flag}`);
|
||||||
|
|
||||||
params.splice(index, 1, '');
|
params.splice(index, 1, '');
|
||||||
if (aliased) {
|
if (aliased) {
|
||||||
(args[flag.name] = flag.clone([ _flag ], this.resolver)).aliased = true;
|
(args[flag.name] = flag.clone([_flag], this.resolver)).aliased = true;
|
||||||
currentFlag = null;
|
currentFlag = null;
|
||||||
} else {
|
} else {
|
||||||
// eslint-disable-next-line no-undefined
|
|
||||||
currentFlag = flag.clone(undefined, this.resolver);
|
currentFlag = flag.clone(undefined, this.resolver);
|
||||||
args[flag.name] = currentFlag;
|
args[flag.name] = currentFlag;
|
||||||
}
|
}
|
||||||
@ -192,11 +178,10 @@ class Parser extends EventEmitter {
|
|||||||
if (flag.choices.length) {
|
if (flag.choices.length) {
|
||||||
throw new ParseError(`Invalid choice for ${flag.name}, Valid choices are ${flag.choices.join(', ')}.`);
|
throw new ParseError(`Invalid choice for ${flag.name}, Valid choices are ${flag.choices.join(', ')}.`);
|
||||||
}
|
}
|
||||||
throw new ParseError(`Failed to parse value for ${flag.name}, expected value type: ${flag.type}`); // return { option: flag, ...result.removed };
|
throw new ParseError(`Failed to parse value for ${flag.name}, expected value type: ${flag.type}`); //return { option: flag, ...result.removed };
|
||||||
}
|
}
|
||||||
this.debug(`Cleaning up params after ${flag.name}`);
|
this.debug(`Cleaning up params after ${flag.name}`);
|
||||||
for (const r of result.removed)
|
for (const r of result.removed) params.splice(params.indexOf(r), 1);
|
||||||
params.splice(params.indexOf(r), 1);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
this.debug(`Params after parsing "${params.join('", "')}"`);
|
this.debug(`Params after parsing "${params.join('", "')}"`);
|
||||||
@ -213,25 +198,22 @@ class Parser extends EventEmitter {
|
|||||||
|
|
||||||
this.debug(`Trying ${option.name}, plural: ${option.plural}`);
|
this.debug(`Trying ${option.name}, plural: ${option.plural}`);
|
||||||
|
|
||||||
// eslint-disable-next-line no-undefined
|
|
||||||
const cloned = option.clone(undefined, this.resolver);
|
const cloned = option.clone(undefined, this.resolver);
|
||||||
let removed: string[] = [],
|
let removed: string[] = [],
|
||||||
error = false;
|
error = false;
|
||||||
if (cloned.plural) { // E.g. if the type is CHANNEL**S**, parse out any potential channels from the message
|
if (cloned.plural) { // E.g. if the type is CHANNEL**S**, parse out any potential channels from the message
|
||||||
cloned.rawValue = params;
|
cloned.rawValue = params;
|
||||||
({ removed } = await cloned.parse(guild));
|
({ removed } = await cloned.parse(guild));
|
||||||
} else
|
} else for (let index = 0; index < params.length;) { // Attempt to parse out a value from each param
|
||||||
for (let index = 0; index < params.length;) { // Attempt to parse out a value from each param
|
if (params[index] === null) {
|
||||||
if (params[index] === null) {
|
|
||||||
index++;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
cloned.rawValue = [ params[index] ];
|
|
||||||
({ removed, error } = await cloned.parse(guild));
|
|
||||||
if (!error)
|
|
||||||
break;
|
|
||||||
index++;
|
index++;
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
|
cloned.rawValue = [params[index]];
|
||||||
|
({ removed, error } = await cloned.parse(guild));
|
||||||
|
if (!error) break;
|
||||||
|
index++;
|
||||||
|
}
|
||||||
if (error) {
|
if (error) {
|
||||||
this.debug(`Failed to parse any values for ${option.name} with params "${option.rawValue?.join('", "')}"`);
|
this.debug(`Failed to parse any values for ${option.name} with params "${option.rawValue?.join('", "')}"`);
|
||||||
continue;
|
continue;
|
||||||
@ -239,8 +221,7 @@ class Parser extends EventEmitter {
|
|||||||
|
|
||||||
args[cloned.name] = cloned;
|
args[cloned.name] = cloned;
|
||||||
// Clean up params for string parsing
|
// Clean up params for string parsing
|
||||||
for (const r of removed)
|
for (const r of removed) params.splice(params.indexOf(r), 1, '');
|
||||||
params.splice(params.indexOf(r), 1, '');
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -263,29 +244,23 @@ class Parser extends EventEmitter {
|
|||||||
tmpString += ` ${str}`;
|
tmpString += ` ${str}`;
|
||||||
tmpString = tmpString.trim();
|
tmpString = tmpString.trim();
|
||||||
}
|
}
|
||||||
if (tmpString.length)
|
if (tmpString.length) strings.push(tmpString);
|
||||||
strings.push(tmpString);
|
|
||||||
|
|
||||||
if (strings.length)
|
if (strings.length) for (const strOpt of stringOpts) {
|
||||||
for (const strOpt of stringOpts) {
|
const val = strings.shift();
|
||||||
const val = strings.shift();
|
if (!val) break;
|
||||||
if (!val)
|
const cloned = strOpt.clone([val], this.resolver);
|
||||||
break;
|
await cloned.parse(guild);
|
||||||
const cloned = strOpt.clone([ val ], this.resolver);
|
args[cloned.name] = cloned;
|
||||||
await cloned.parse(guild);
|
}
|
||||||
args[cloned.name] = cloned;
|
|
||||||
}
|
|
||||||
|
|
||||||
// This part is obsolete now, I think, the string option checks the choice value
|
// This part is obsolete now, I think, the string option checks the choice value
|
||||||
for (const arg of Object.values(args)) {
|
for (const arg of Object.values(args)) {
|
||||||
if (!arg.choices.length)
|
if (!arg.choices.length) continue;
|
||||||
continue;
|
|
||||||
if (!arg.choices.some((choice) => {
|
if (!arg.choices.some((choice) => {
|
||||||
if (typeof arg.value === 'string' && typeof choice === 'string')
|
if (typeof arg.value === 'string' && typeof choice === 'string') return arg.value.toLowerCase() === choice.toLowerCase();
|
||||||
return arg.value.toLowerCase() === choice.toLowerCase();
|
|
||||||
return arg.value === choice;
|
return arg.value === choice;
|
||||||
}))
|
})) throw new ParseError(`Invalid choice: ${arg.name} value must be one of ${arg.choices.join(', ')}`); //return { error: true, index: 'O_COMMANDHANDLER_INVALID_CHOICE', params: { option: arg.name, value: arg.value, choices: arg.choices.map((c) => c).join('`, `') } };
|
||||||
throw new ParseError(`Invalid choice: ${arg.name} value must be one of ${arg.choices.join(', ')}`); // return { error: true, index: 'O_COMMANDHANDLER_INVALID_CHOICE', params: { option: arg.name, value: arg.value, choices: arg.choices.map((c) => c).join('`, `') } };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
this.debug(`Making sure required options were given.`);
|
this.debug(`Making sure required options were given.`);
|
||||||
@ -293,16 +268,14 @@ class Parser extends EventEmitter {
|
|||||||
if (!args[req.name])
|
if (!args[req.name])
|
||||||
throw new ParseError(`${req.name} is a required option`);
|
throw new ParseError(`${req.name} is a required option`);
|
||||||
|
|
||||||
if (strings.length)
|
if (strings.length) throw new ParseError(`Unrecognised option(s): "${strings.join('", "')}"`);//return { error: true, index: 'O_COMMANDHANDLER_UNRECOGNISED_OPTIONS', params: { opts: strings.join('`, `') } };
|
||||||
throw new ParseError(`Unrecognised option(s): "${strings.join('", "')}"`);// return { error: true, index: 'O_COMMANDHANDLER_UNRECOGNISED_OPTIONS', params: { opts: strings.join('`, `') } };
|
|
||||||
|
|
||||||
return parseResult;
|
return parseResult;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private debug (message: string) {
|
private debug(message: string) {
|
||||||
if (this._debug)
|
if(this._debug) this.emit('debug', `[PARSER] ${message}`);
|
||||||
this.emit('debug', `[PARSER] ${message}`);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -8,60 +8,55 @@ import { ArgsResult } from "../Parser";
|
|||||||
abstract class Command implements ICommand {
|
abstract class Command implements ICommand {
|
||||||
|
|
||||||
name: string;
|
name: string;
|
||||||
|
|
||||||
aliases: string[];
|
aliases: string[];
|
||||||
|
|
||||||
options: CommandOption[];
|
options: CommandOption[];
|
||||||
|
|
||||||
constructor (def: CommandDefinition) {
|
constructor(def: CommandDefinition) {
|
||||||
|
|
||||||
if (typeof def !== 'object')
|
if (typeof def !== 'object') throw new Error('Missing command definition');
|
||||||
throw new Error('Missing command definition');
|
|
||||||
|
|
||||||
if (!def.name)
|
if (!def.name) throw new Error('Missing name for command');
|
||||||
throw new Error('Missing name for command');
|
|
||||||
this.name = def.name;
|
this.name = def.name;
|
||||||
|
|
||||||
this.aliases = def.aliases || [];
|
this.aliases = def.aliases || [];
|
||||||
|
|
||||||
this.options = [];
|
this.options = [];
|
||||||
for (const opt of def.options || []) {
|
for (const opt of def.options || []) {
|
||||||
if (opt instanceof CommandOption)
|
if (opt instanceof CommandOption) this.options.push(opt);
|
||||||
this.options.push(opt);
|
else this.options.push(new CommandOption(opt));
|
||||||
else
|
|
||||||
this.options.push(new CommandOption(opt));
|
|
||||||
}
|
}
|
||||||
if (this.options.some(opt => [ OptionType.SUB_COMMAND, OptionType.SUB_COMMAND_GROUP ].includes(opt.type))
|
if (this.options.some(opt => [OptionType.SUB_COMMAND, OptionType.SUB_COMMAND_GROUP].includes(opt.type))
|
||||||
&& this.options.some(opt => ![ OptionType.SUB_COMMAND, OptionType.SUB_COMMAND_GROUP ].includes(opt.type)))
|
&& this.options.some(opt => ![OptionType.SUB_COMMAND, OptionType.SUB_COMMAND_GROUP].includes(opt.type))) throw new Error('Cannot have subcommand(group)s on the same level as an option')
|
||||||
throw new Error('Cannot have subcommand(group)s on the same level as an option');
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
abstract execute(message: unknown, args: ArgsResult): Promise<unknown>;
|
abstract execute(message: unknown, args: ArgsResult): Promise<unknown>;
|
||||||
|
|
||||||
get subcommands (): SubcommandOption[] {
|
get subcommands(): SubcommandOption[] {
|
||||||
return this._subcommands(this.options);
|
return this._subcommands(this.options);
|
||||||
}
|
}
|
||||||
|
|
||||||
get subcommandGroups (): SubcommandGroupOption[] {
|
get subcommandGroups(): SubcommandGroupOption[] {
|
||||||
return this.options.filter((opt) => opt.type === OptionType.SUB_COMMAND_GROUP);
|
return this.options.filter((opt) => opt.type === OptionType.SUB_COMMAND_GROUP);
|
||||||
}
|
}
|
||||||
|
|
||||||
subcommand (name: string): SubcommandOption | null {
|
subcommand(name: string): SubcommandOption | null {
|
||||||
name = name.toLowerCase();
|
name = name.toLowerCase();
|
||||||
return this.subcommands.find((cmd) => cmd.name === name || cmd.aliases.includes(name)) || null;
|
return this.subcommands.find((cmd) => cmd.name === name || cmd.aliases.includes(name)) || null;
|
||||||
}
|
}
|
||||||
|
|
||||||
subcommandGroup (name: string): SubcommandGroupOption | null {
|
subcommandGroup(name: string): SubcommandGroupOption | null {
|
||||||
name = name.toLowerCase();
|
name = name.toLowerCase();
|
||||||
return this.subcommandGroups.find((grp) => grp.name === name || grp.aliases.includes(name)) || null;
|
return this.subcommandGroups.find((grp) => grp.name === name || grp.aliases.includes(name)) || null;
|
||||||
}
|
}
|
||||||
|
|
||||||
private _subcommands (options: CommandOption[]): SubcommandOption[] {
|
private _subcommands(options: CommandOption[]): SubcommandOption[] {
|
||||||
const subcommands: SubcommandOption[] = [];
|
const subcommands: SubcommandOption[] = [];
|
||||||
for (const opt of options) {
|
for (const opt of options) {
|
||||||
if (opt.type === OptionType.SUB_COMMAND)
|
if (opt.type === OptionType.SUB_COMMAND) subcommands.push(opt);
|
||||||
subcommands.push(opt);
|
else if(opt.type === OptionType.SUB_COMMAND_GROUP) subcommands.push(...this._subcommands(opt.options));
|
||||||
else if (opt.type === OptionType.SUB_COMMAND_GROUP)
|
|
||||||
subcommands.push(...this._subcommands(opt.options));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return subcommands;
|
return subcommands;
|
||||||
|
@ -1,4 +1,3 @@
|
|||||||
/* eslint-disable no-undefined */
|
|
||||||
import ICommandOption, { Choice, CommandOptionDefinition, DependsOnMode, OptionType, ParseResult } from "../interfaces/CommandOption";
|
import ICommandOption, { Choice, CommandOptionDefinition, DependsOnMode, OptionType, ParseResult } from "../interfaces/CommandOption";
|
||||||
import IResolver from "../interfaces/Resolver";
|
import IResolver from "../interfaces/Resolver";
|
||||||
|
|
||||||
@ -43,9 +42,9 @@ class CommandOption implements ICommandOption {
|
|||||||
|
|
||||||
strict: boolean;
|
strict: boolean;
|
||||||
|
|
||||||
private resolver?: IResolver<unknown, unknown, unknown, unknown, unknown>|undefined;
|
private resolver?: IResolver<unknown, unknown, unknown, unknown, unknown>|undefined = undefined;
|
||||||
|
|
||||||
constructor (def: CommandOptionDefinition|CommandOption|ICommandOption) {
|
constructor(def: CommandOptionDefinition|CommandOption|ICommandOption) {
|
||||||
|
|
||||||
this.name = def.name;
|
this.name = def.name;
|
||||||
this.aliases = def.aliases || [];
|
this.aliases = def.aliases || [];
|
||||||
@ -56,25 +55,18 @@ class CommandOption implements ICommandOption {
|
|||||||
|
|
||||||
this.options = [];
|
this.options = [];
|
||||||
for (const opt of def.options || []) {
|
for (const opt of def.options || []) {
|
||||||
if (opt instanceof CommandOption)
|
if (opt instanceof CommandOption) this.options.push(opt);
|
||||||
this.options.push(opt);
|
else this.options.push(new CommandOption(opt));
|
||||||
else
|
|
||||||
this.options.push(new CommandOption(opt));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.type === OptionType.SUB_COMMAND_GROUP && this.options.some(opt => opt.type === OptionType.SUB_COMMAND_GROUP))
|
if (this.type === OptionType.SUB_COMMAND_GROUP && this.options.some(opt => opt.type === OptionType.SUB_COMMAND_GROUP)) throw new Error('Cannot nest subcommand groups');
|
||||||
throw new Error('Cannot nest subcommand groups');
|
if (this.type === OptionType.SUB_COMMAND && this.options.some(opt => opt.type === OptionType.SUB_COMMAND_GROUP)) throw new Error('Cannot have subcommand groups under a subcommand');
|
||||||
if (this.type === OptionType.SUB_COMMAND && this.options.some(opt => opt.type === OptionType.SUB_COMMAND_GROUP))
|
if (this.type === OptionType.SUB_COMMAND && this.options.some(opt => opt.type === OptionType.SUB_COMMAND)) throw new Error('Cannot nest subcommands');
|
||||||
throw new Error('Cannot have subcommand groups under a subcommand');
|
if (![OptionType.SUB_COMMAND, OptionType.SUB_COMMAND_GROUP].includes(this.type)
|
||||||
if (this.type === OptionType.SUB_COMMAND && this.options.some(opt => opt.type === OptionType.SUB_COMMAND))
|
&& this.options.some(opt => [OptionType.SUB_COMMAND, OptionType.SUB_COMMAND_GROUP].includes(opt.type))) throw new Error('Cannot have subcommand(group)s under an option');
|
||||||
throw new Error('Cannot nest subcommands');
|
|
||||||
if (![ OptionType.SUB_COMMAND, OptionType.SUB_COMMAND_GROUP ].includes(this.type)
|
|
||||||
&& this.options.some(opt => [ OptionType.SUB_COMMAND, OptionType.SUB_COMMAND_GROUP ].includes(opt.type)))
|
|
||||||
throw new Error('Cannot have subcommand(group)s under an option');
|
|
||||||
|
|
||||||
if (this.options.some(opt => [ OptionType.SUB_COMMAND, OptionType.SUB_COMMAND_GROUP ].includes(opt.type))
|
if (this.options.some(opt => [OptionType.SUB_COMMAND, OptionType.SUB_COMMAND_GROUP].includes(opt.type))
|
||||||
&& this.options.some(opt => ![ OptionType.SUB_COMMAND, OptionType.SUB_COMMAND_GROUP ].includes(opt.type)))
|
&& this.options.some(opt => ![OptionType.SUB_COMMAND, OptionType.SUB_COMMAND_GROUP].includes(opt.type))) throw new Error('Cannot have subcommand(group)s on the same level as an option')
|
||||||
throw new Error('Cannot have subcommand(group)s on the same level as an option');
|
|
||||||
|
|
||||||
this.choices = def.choices || [];
|
this.choices = def.choices || [];
|
||||||
|
|
||||||
@ -89,18 +81,16 @@ class CommandOption implements ICommandOption {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
clone (rawValue?: string[], resolver?: IResolver<unknown, unknown, unknown, unknown, unknown>): CommandOption {
|
clone(rawValue?: string[], resolver?: IResolver<unknown, unknown, unknown, unknown, unknown>): CommandOption {
|
||||||
const opt = new CommandOption(this);
|
const opt = new CommandOption(this);
|
||||||
opt.rawValue = rawValue;
|
opt.rawValue = rawValue;
|
||||||
opt.resolver = resolver;
|
opt.resolver = resolver || undefined;
|
||||||
return opt;
|
return opt;
|
||||||
}
|
}
|
||||||
|
|
||||||
async parse (guild?: unknown): Promise<ParseResult> {
|
async parse(guild?: unknown): Promise<ParseResult> {
|
||||||
if (!this[OptionType[this.type]])
|
if (!this[OptionType[this.type]]) throw new Error(`Missing parsing function for ${this.type}`);
|
||||||
throw new Error(`Missing parsing function for ${this.type}`);
|
if (typeof this[OptionType[this.type]] !== 'function') throw new Error(`Expected function type for memberr ${OptionType[this.type]}`);
|
||||||
if (typeof this[OptionType[this.type]] !== 'function')
|
|
||||||
throw new Error(`Expected function type for memberr ${OptionType[this.type]}`);
|
|
||||||
this.guild = guild;
|
this.guild = guild;
|
||||||
// eslint-disable-next-line @typescript-eslint/ban-types
|
// eslint-disable-next-line @typescript-eslint/ban-types
|
||||||
const func = this[OptionType[this.type]] as Function;
|
const func = this[OptionType[this.type]] as Function;
|
||||||
@ -109,73 +99,56 @@ class CommandOption implements ICommandOption {
|
|||||||
return result as ParseResult;
|
return result as ParseResult;
|
||||||
}
|
}
|
||||||
|
|
||||||
get plural (): boolean {
|
get plural(): boolean {
|
||||||
return this.type.toString().endsWith('S');
|
return this.type.toString().endsWith('S');
|
||||||
}
|
}
|
||||||
|
|
||||||
protected async MEMBER () {
|
protected async MEMBER() {
|
||||||
if (!this.resolver)
|
if (!this.resolver) throw new Error('Missing resolver');
|
||||||
throw new Error('Missing resolver');
|
if(!this.rawValue) throw new Error('Missing raw value');
|
||||||
if (!this.rawValue)
|
|
||||||
throw new Error('Missing raw value');
|
|
||||||
const member = await this.resolver?.resolveMember(this.rawValue[0], this.strict, this.guild);
|
const member = await this.resolver?.resolveMember(this.rawValue[0], this.strict, this.guild);
|
||||||
if (!member)
|
if (!member) return { error: true };
|
||||||
return { error: true };
|
|
||||||
return { value: member, removed: this.rawValue };
|
return { value: member, removed: this.rawValue };
|
||||||
}
|
}
|
||||||
|
|
||||||
protected STRING () {
|
protected STRING() {
|
||||||
if (!this.rawValue)
|
if (!this.rawValue) return { error: true };
|
||||||
return { error: true };
|
if (this.aliased) return { value: this.rawValue.join(' '), removed: [] };
|
||||||
if (this.aliased)
|
|
||||||
return { value: this.rawValue.join(' '), removed: [] };
|
|
||||||
if (this.choices.length) {
|
if (this.choices.length) {
|
||||||
const found = this.choices.find((c) => {
|
const found = this.choices.find((c) => {
|
||||||
const choice = c as string;
|
const choice = c as string;
|
||||||
return choice.toLowerCase() === this.rawValue?.join(' ').toLowerCase();
|
return choice.toLowerCase() === this.rawValue?.join(' ').toLowerCase();
|
||||||
});
|
});
|
||||||
if (found)
|
if (found) return { value: found, removed: this.rawValue };
|
||||||
return { value: found, removed: this.rawValue };
|
|
||||||
return { error: true };
|
return { error: true };
|
||||||
}
|
}
|
||||||
return { value: this.rawValue.join(' '), removed: this.rawValue };
|
return { value: this.rawValue.join(' '), removed: this.rawValue };
|
||||||
}
|
}
|
||||||
|
|
||||||
protected INTEGER () {
|
protected INTEGER() {
|
||||||
if (!this.rawValue)
|
if (!this.rawValue) return { error: true };
|
||||||
return { error: true };
|
|
||||||
const integer = parseInt(this.rawValue[0]);
|
const integer = parseInt(this.rawValue[0]);
|
||||||
if (isNaN(integer))
|
if(isNaN(integer)) return { error: true };
|
||||||
return { error: true };
|
if (this.minimum !== undefined && integer < this.minimum) return { error: true };
|
||||||
if (this.minimum !== undefined && integer < this.minimum)
|
if (this.maximum !== undefined && integer > this.maximum) return { error: true };
|
||||||
return { error: true };
|
return { value: integer, removed: [this.rawValue[0]] };
|
||||||
if (this.maximum !== undefined && integer > this.maximum)
|
|
||||||
return { error: true };
|
|
||||||
return { value: integer, removed: [ this.rawValue[0] ] };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
protected FLOAT () {
|
protected FLOAT() {
|
||||||
if (!this.rawValue)
|
if (!this.rawValue) return { error: true };
|
||||||
return { error: true };
|
|
||||||
const float = parseFloat(this.rawValue[0]);
|
const float = parseFloat(this.rawValue[0]);
|
||||||
if (isNaN(float))
|
if(isNaN(float)) return { error: true };
|
||||||
return { error: true };
|
if (this.minimum !== undefined && float < this.minimum) return { error: true };
|
||||||
if (this.minimum !== undefined && float < this.minimum)
|
if (this.maximum !== undefined && float > this.maximum) return { error: true };
|
||||||
return { error: true };
|
return { value: (float), removed: [this.rawValue[0]] };
|
||||||
if (this.maximum !== undefined && float > this.maximum)
|
|
||||||
return { error: true };
|
|
||||||
return { value: float, removed: [ this.rawValue[0] ] };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
protected BOOLEAN () {
|
protected BOOLEAN() {
|
||||||
if (!this.rawValue)
|
if (!this.rawValue) return { error: true };
|
||||||
return { error: true };
|
|
||||||
const boolean = this.resolver?.resolveBoolean(this.rawValue[0]) || null;
|
const boolean = this.resolver?.resolveBoolean(this.rawValue[0]) || null;
|
||||||
if (boolean === null && this.valueOptional)
|
if (boolean === null && this.valueOptional) return { value: this.defaultValue, removed: [] };
|
||||||
return { value: this.defaultValue, removed: [] };
|
else if(boolean === null) return { error: true };
|
||||||
else if (boolean === null)
|
return { value: boolean, removed: [this.rawValue[0]] };
|
||||||
return { error: true };
|
|
||||||
return { value: boolean, removed: [ this.rawValue[0] ] };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -2,7 +2,7 @@ import { CommandOptionDefinition, OptionType } from "../interfaces/CommandOption
|
|||||||
import CommandOption from "./CommandOption";
|
import CommandOption from "./CommandOption";
|
||||||
|
|
||||||
class SubcommandGroupOption extends CommandOption {
|
class SubcommandGroupOption extends CommandOption {
|
||||||
constructor (def: CommandOptionDefinition) {
|
constructor(def: CommandOptionDefinition) {
|
||||||
super({ ...def, type: OptionType.SUB_COMMAND_GROUP });
|
super({ ...def, type: OptionType.SUB_COMMAND_GROUP });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -2,7 +2,7 @@ import { CommandOptionDefinition, OptionType } from "../interfaces/CommandOption
|
|||||||
import CommandOption from "./CommandOption";
|
import CommandOption from "./CommandOption";
|
||||||
|
|
||||||
class SubcommandOption extends CommandOption {
|
class SubcommandOption extends CommandOption {
|
||||||
constructor (def: CommandOptionDefinition) {
|
constructor(def: CommandOptionDefinition) {
|
||||||
super({ ...def, type: OptionType.SUB_COMMAND });
|
super({ ...def, type: OptionType.SUB_COMMAND });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,10 +1,10 @@
|
|||||||
class ExtendedMap<K, V> extends Map<K, V> {
|
class ExtendedMap<K, V> extends Map<K, V> {
|
||||||
|
|
||||||
find (fn: (element: V, key: K) => boolean): V | void {
|
find(fn: (element: V, key: K) => boolean): V | undefined {
|
||||||
for (const [ key, val ] of this) {
|
for (const [key, val] of this) {
|
||||||
if (fn(val, key))
|
if (fn(val, key)) return val;
|
||||||
return val;
|
|
||||||
}
|
}
|
||||||
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -1,22 +1,21 @@
|
|||||||
type TQuotePairs ={[key: string]: string}
|
type TQuotePairs ={[key: string]: string}
|
||||||
const QuotePairs: TQuotePairs = {
|
const QuotePairs: TQuotePairs = {
|
||||||
'"': '"', // regular double
|
'"': '"', //regular double
|
||||||
"'": "'", // regular single
|
"'": "'", //regular single
|
||||||
"‘": "’", // smart single
|
"‘": "’", //smart single
|
||||||
"“": "”" // smart double
|
"“": "”" //smart double
|
||||||
};
|
};
|
||||||
|
|
||||||
const StartQuotes = Object.keys(QuotePairs);
|
const StartQuotes = Object.keys(QuotePairs);
|
||||||
const QuoteMarks = StartQuotes.concat(Object.values(QuotePairs));
|
const QuoteMarks = StartQuotes.concat(Object.values(QuotePairs));
|
||||||
|
|
||||||
class Util {
|
class Util {
|
||||||
private constructor () {
|
private constructor() {
|
||||||
throw new Error('Utility class may not be instantiated');
|
throw new Error('Utility class may not be instantiated');
|
||||||
}
|
}
|
||||||
|
|
||||||
public static parseQuotes (string: string): (string|boolean)[][] {
|
public static parseQuotes(string: string): (string|boolean)[][] {
|
||||||
if (!string)
|
if (!string) return [];
|
||||||
return [];
|
|
||||||
|
|
||||||
let quoted = false,
|
let quoted = false,
|
||||||
wordStart = true,
|
wordStart = true,
|
||||||
@ -39,7 +38,7 @@ class Util {
|
|||||||
if (quoted) {
|
if (quoted) {
|
||||||
word += char;
|
word += char;
|
||||||
} else if (word !== '') {
|
} else if (word !== '') {
|
||||||
words.push([ word, isQuote ]);
|
words.push([word, isQuote]);
|
||||||
isQuote = false;
|
isQuote = false;
|
||||||
startQuote = '';
|
startQuote = '';
|
||||||
word = '';
|
word = '';
|
||||||
@ -76,13 +75,13 @@ class Util {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (endQuote) {
|
if (endQuote) {
|
||||||
words.push([ word, true ]);
|
words.push([word, true]);
|
||||||
} else {
|
} else {
|
||||||
word.split(/\s/u).forEach((subWord, i) => {
|
word.split(/\s/u).forEach((subWord, i) => {
|
||||||
if (i === 0) {
|
if (i === 0) {
|
||||||
words.push([ startQuote + subWord, false ]);
|
words.push([startQuote + subWord, false]);
|
||||||
} else {
|
} else {
|
||||||
words.push([ subWord, false ]);
|
words.push([subWord, false]);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -1,9 +0,0 @@
|
|||||||
{
|
|
||||||
"extends": "./tsconfig.json",
|
|
||||||
"compilerOptions": {
|
|
||||||
"declaration": false,
|
|
||||||
"sourceMap": false,
|
|
||||||
"module": "CommonJS",
|
|
||||||
"outDir": "./build/cjs"
|
|
||||||
}
|
|
||||||
}
|
|
@ -11,10 +11,10 @@
|
|||||||
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
|
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
|
||||||
|
|
||||||
/* Language and Environment */
|
/* Language and Environment */
|
||||||
"target": "ES2022", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
|
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
|
||||||
"lib": ["ES2022"], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
|
"lib": ["ES2017", "ES2018.Regexp"], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
|
||||||
// "jsx": "preserve", /* Specify what JSX code is generated. */
|
// "jsx": "preserve", /* Specify what JSX code is generated. */
|
||||||
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
|
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
|
||||||
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
|
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
|
||||||
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
|
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
|
||||||
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
|
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
|
||||||
@ -25,29 +25,22 @@
|
|||||||
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
|
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
|
||||||
|
|
||||||
/* Modules */
|
/* Modules */
|
||||||
"module": "ES2022", /* Specify what module code is generated. */
|
"module": "CommonJS", /* Specify what module code is generated. */
|
||||||
|
// "module": "AMD",
|
||||||
// "rootDir": "./", /* Specify the root folder within your source files. */
|
// "rootDir": "./", /* Specify the root folder within your source files. */
|
||||||
"moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
|
// "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
|
||||||
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
|
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
|
||||||
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
|
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
|
||||||
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
|
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
|
||||||
"typeRoots": [
|
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
|
||||||
"./node_modules/@types",
|
|
||||||
"./@types"
|
|
||||||
], /* Specify multiple folders that act like './node_modules/@types'. */
|
|
||||||
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
|
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
|
||||||
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
|
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
|
||||||
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
|
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
|
||||||
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
|
|
||||||
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
|
|
||||||
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
|
|
||||||
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
|
|
||||||
// "resolveJsonModule": true, /* Enable importing .json files. */
|
// "resolveJsonModule": true, /* Enable importing .json files. */
|
||||||
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
|
|
||||||
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
|
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
|
||||||
|
|
||||||
/* JavaScript Support */
|
/* JavaScript Support */
|
||||||
"allowJs": false, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
|
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
|
||||||
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
|
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
|
||||||
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
|
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
|
||||||
|
|
||||||
@ -55,10 +48,9 @@
|
|||||||
"declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
|
"declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
|
||||||
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
|
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
|
||||||
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
|
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
|
||||||
"sourceMap": true, /* Create source map files for emitted JavaScript files. */
|
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
|
||||||
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
|
// "outFile": "./out.js", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
|
||||||
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
|
"outDir": "./build", /* Specify an output folder for all emitted files. */
|
||||||
"outDir": "./build/esm", /* Specify an output folder for all emitted files. */
|
|
||||||
// "removeComments": true, /* Disable emitting comments. */
|
// "removeComments": true, /* Disable emitting comments. */
|
||||||
// "noEmit": true, /* Disable emitting files from a compilation. */
|
// "noEmit": true, /* Disable emitting files from a compilation. */
|
||||||
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
|
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
|
||||||
@ -66,10 +58,11 @@
|
|||||||
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
|
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
|
||||||
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
|
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
|
||||||
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
|
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
|
||||||
|
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
|
||||||
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
|
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
|
||||||
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
|
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
|
||||||
// "newLine": "crlf", /* Set the newline character for emitting files. */
|
// "newLine": "crlf", /* Set the newline character for emitting files. */
|
||||||
"stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
|
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
|
||||||
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
|
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
|
||||||
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
|
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
|
||||||
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
|
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
|
||||||
@ -78,7 +71,6 @@
|
|||||||
|
|
||||||
/* Interop Constraints */
|
/* Interop Constraints */
|
||||||
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
|
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
|
||||||
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
|
|
||||||
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
|
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
|
||||||
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
|
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
|
||||||
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
|
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
|
||||||
@ -86,19 +78,19 @@
|
|||||||
|
|
||||||
/* Type Checking */
|
/* Type Checking */
|
||||||
"strict": true, /* Enable all strict type-checking options. */
|
"strict": true, /* Enable all strict type-checking options. */
|
||||||
"noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
|
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
|
||||||
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
|
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
|
||||||
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
|
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
|
||||||
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
|
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
|
||||||
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
|
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
|
||||||
"noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
|
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
|
||||||
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
|
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
|
||||||
"alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
|
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
|
||||||
"noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
|
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
|
||||||
"noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
|
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
|
||||||
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
|
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
|
||||||
"noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
|
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
|
||||||
"noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
|
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
|
||||||
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
|
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
|
||||||
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
|
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
|
||||||
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
|
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
|
||||||
@ -108,6 +100,5 @@
|
|||||||
/* Completeness */
|
/* Completeness */
|
||||||
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
|
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
|
||||||
"skipLibCheck": true /* Skip type checking all .d.ts files. */
|
"skipLibCheck": true /* Skip type checking all .d.ts files. */
|
||||||
},
|
}
|
||||||
"compileOnSave": true
|
|
||||||
}
|
}
|
Loading…
Reference in New Issue
Block a user