Compare commits

..

2 Commits

Author SHA1 Message Date
376c78e8fe
Update to support both cjs and esm
Some checks failed
continuous-integration/drone/push Build is failing
2023-04-13 20:18:40 +03:00
12a3bd1143
v1.2.0 2023-04-13 20:03:25 +03:00
12 changed files with 296 additions and 211 deletions

View File

@ -1,33 +1,31 @@
{ {
"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": [ "plugins": [ "@typescript-eslint" ],
"@typescript-eslint" "parserOptions": {
], "ecmaVersion": 2022,
"extends": [ "sourceType": "module"
"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",
"arrow-parens": "warn", "array-bracket-newline": [ "warn", "consistent" ],
"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", "block-spacing": [ "warn", "always" ],
"brace-style": "warn", "brace-style": [ "warn", "1tbs" ],
"callback-return": "warn", "callback-return": "warn",
"camelcase": "warn", "camelcase": "warn",
// "comma-dangle": "warn", "comma-dangle": [ "warn", "only-multiline" ],
"comma-spacing": [ "comma-spacing": [
"warn", "warn",
{ {
@ -47,6 +45,10 @@
"allowKeywords": true "allowKeywords": true
} }
], ],
"dot-location": [
"error",
"property"
],
"eol-last": [ "eol-last": [
"warn", "warn",
"never" "never"
@ -56,37 +58,25 @@
"func-name-matching": "warn", "func-name-matching": "warn",
"func-names": "warn", "func-names": "warn",
"func-style": "warn", "func-style": "warn",
"function-paren-newline": [ "function-paren-newline": "warn",
"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", "unix"], "implicit-arrow-linebreak": "warn",
"indent": [ "indent": "warn",
"warn",
4,
{
"SwitchCase": 1
}
],
"init-declarations": "warn", "init-declarations": "warn",
"jsx-quotes": "warn", "jsx-quotes": [ "warn", "prefer-single" ],
"key-spacing": "warn", "key-spacing": [ "warn", { "beforeColon": false, "afterColon": true }],
"keyword-spacing": [ "warn", { "after": true, "before": true }],
"linebreak-style": [ "linebreak-style": [
"warn", "error",
"windows" "unix"
], ],
"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",
@ -106,17 +96,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": "warn", "no-implied-eval": "error",
"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",
@ -125,6 +115,7 @@
"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",
@ -147,14 +138,16 @@
"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": "warn", "no-template-curly-in-string": "error",
"no-throw-literal": "warn", "no-throw-literal": "warn",
"no-undef-init": "warn", "no-undef-init": "error",
"no-undefined": "error",
"no-unmodified-loop-condition": "warn", "no-unmodified-loop-condition": "warn",
"no-unneeded-ternary": "warn", "no-unneeded-ternary": "error",
"no-unused-expressions": "warn", "no-unused-expressions": "warn",
"no-use-before-define": "warn", "no-use-before-define": "error",
"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",
@ -163,26 +156,25 @@
"no-useless-return": "warn", "no-useless-return": "warn",
"no-var": "warn", "no-var": "warn",
"no-void": "warn", "no-void": "warn",
"no-whitespace-before-property": "warn", "no-whitespace-before-property": "error",
"nonblock-statement-body-position": [ "nonblock-statement-body-position": [ "warn", "below" ],
"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": "warn", "prefer-object-spread": "error",
"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",
@ -190,17 +182,19 @@
"require-jsdoc": "warn", "require-jsdoc": "warn",
"require-unicode-regexp": "warn", "require-unicode-regexp": "warn",
"rest-spread-spacing": "warn", "rest-spread-spacing": "warn",
"semi": "warn", "semi": "error",
"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",
@ -215,7 +209,7 @@
], ],
"vars-on-top": "warn", "vars-on-top": "warn",
"wrap-iife": "warn", "wrap-iife": "warn",
"wrap-regex": "warn", "wrap-regex": "error",
"yield-star-spacing": "warn", "yield-star-spacing": "warn",
"yoda": [ "yoda": [
"warn", "warn",

View File

@ -1,11 +1,24 @@
{ {
"name": "commandparser", "name": "commandparser",
"version": "1.1.2", "version": "1.2.0",
"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",
@ -17,11 +30,8 @@
"jest": "^29.4.2", "jest": "^29.4.2",
"typescript": "^4.7.4" "typescript": "^4.7.4"
}, },
"files": [
"build"
],
"scripts": { "scripts": {
"build": "tsc", "build": "tsc && tsc -p tsconfig.cjs.json && node ./scripts/declareTypes.js",
"test": "tsc && jest", "test": "tsc && jest",
"release": "tsc && yarn publish", "release": "tsc && yarn publish",
"lint": "eslint --fix" "lint": "eslint --fix"

3
scripts/declareTypes.js Normal file
View File

@ -0,0 +1,3 @@
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' }));

View File

@ -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,25 +38,28 @@ 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) this.commands.set(command.name, command); for (const command of commands)
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)) command = this.commands.get(name); if (this.commands.has(name))
else command = this.commands.find((c) => c.aliases.includes(name)); command = this.commands.get(name);
else
command = this.commands.find((c) => c.aliases.includes(name));
return command || null; return command || null;
} }
@ -72,16 +75,21 @@ 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(message: string, prefix = this.prefix, async parseMessage (
guild?: unknown, commandFilter?: (command: Command) => boolean): Promise<ParseResult | null> { message: string, prefix = this.prefix,
guild?: unknown, commandFilter?: (command: Command) => boolean
): Promise<ParseResult | null> {
if (!message.startsWith(prefix) || !message.length) return null; if (!message.startsWith(prefix) || !message.length)
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) return null; if (!commandName)
return null;
const command = this.matchCommand(commandName); const command = this.matchCommand(commandName);
if (!command) return null; if (!command)
return null;
this.debug(`Matched command ${command.name}`); this.debug(`Matched command ${command.name}`);
if (commandFilter && typeof commandFilter === 'function') { if (commandFilter && typeof commandFilter === 'function') {
@ -101,24 +109,27 @@ 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) throw new ParseError('Expected a subcommand(group), got nothing'); if (!params.length)
const [first, second, ...rest] = params; throw new ParseError('Expected a subcommand(group), got nothing');
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(first);
params = [];
if (second) params.push(second, ...rest);
} else {
subcommand = command.subcommand(second); subcommand = command.subcommand(second);
params = rest; params = rest;
} else {
subcommand = command.subcommand(first);
params = [];
if (second)
params.push(second, ...rest);
} }
parseResult.subcommand = subcommand?.name || null; parseResult.subcommand = subcommand?.name || null;
parseResult.subcommandGroup = group?.name || null; parseResult.subcommandGroup = group?.name || null;
if (!subcommand) throw new ParseError(`Expecting subcommand, one of ${subcommands.map((s) => s.name)}`); //return { showUsage: true, verbose: true }; if (!subcommand)
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}`);
} }
@ -126,7 +137,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;
@ -138,10 +149,11 @@ 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) currentFlag.rawValue = []; if (!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;
} }
} }
@ -155,14 +167,16 @@ 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) throw new ParseError(`Unrecognised flag: ${_flag}`); if (!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;
} }
@ -178,10 +192,11 @@ 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) params.splice(params.indexOf(r), 1); for (const r of result.removed)
params.splice(params.indexOf(r), 1);
} }
this.debug(`Params after parsing "${params.join('", "')}"`); this.debug(`Params after parsing "${params.join('", "')}"`);
@ -198,20 +213,23 @@ 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 for (let index = 0; index < params.length;) { // Attempt to parse out a value from each param } else
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++; index++;
continue; continue;
} }
cloned.rawValue = [params[index]]; cloned.rawValue = [ params[index] ];
({ removed, error } = await cloned.parse(guild)); ({ removed, error } = await cloned.parse(guild));
if (!error) break; if (!error)
break;
index++; index++;
} }
if (error) { if (error) {
@ -221,7 +239,8 @@ 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) params.splice(params.indexOf(r), 1, ''); for (const r of removed)
params.splice(params.indexOf(r), 1, '');
} }
@ -244,23 +263,29 @@ class Parser extends EventEmitter {
tmpString += ` ${str}`; tmpString += ` ${str}`;
tmpString = tmpString.trim(); tmpString = tmpString.trim();
} }
if (tmpString.length) strings.push(tmpString); if (tmpString.length)
strings.push(tmpString);
if (strings.length) for (const strOpt of stringOpts) { if (strings.length)
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;
const cloned = strOpt.clone([ val ], this.resolver);
await cloned.parse(guild); await cloned.parse(guild);
args[cloned.name] = cloned; 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) continue; if (!arg.choices.length)
continue;
if (!arg.choices.some((choice) => { if (!arg.choices.some((choice) => {
if (typeof arg.value === 'string' && typeof choice === 'string') return arg.value.toLowerCase() === choice.toLowerCase(); if (typeof arg.value === 'string' && typeof choice === 'string')
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.`);
@ -268,14 +293,16 @@ 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) throw new ParseError(`Unrecognised option(s): "${strings.join('", "')}"`);//return { error: true, index: 'O_COMMANDHANDLER_UNRECOGNISED_OPTIONS', params: { opts: strings.join('`, `') } }; if (strings.length)
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) this.emit('debug', `[PARSER] ${message}`); if (this._debug)
this.emit('debug', `[PARSER] ${message}`);
} }
} }

View File

@ -8,55 +8,60 @@ 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') throw new Error('Missing command definition'); if (typeof def !== 'object')
throw new Error('Missing command definition');
if (!def.name) throw new Error('Missing name for command'); if (!def.name)
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) this.options.push(opt); if (opt instanceof CommandOption)
else this.options.push(new CommandOption(opt)); this.options.push(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))) throw new Error('Cannot have subcommand(group)s on the same level as an option') && 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');
} }
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) subcommands.push(opt); if (opt.type === OptionType.SUB_COMMAND)
else if(opt.type === OptionType.SUB_COMMAND_GROUP) subcommands.push(...this._subcommands(opt.options)); subcommands.push(opt);
else if (opt.type === OptionType.SUB_COMMAND_GROUP)
subcommands.push(...this._subcommands(opt.options));
} }
return subcommands; return subcommands;

View File

@ -1,3 +1,4 @@
/* 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";
@ -42,9 +43,9 @@ class CommandOption implements ICommandOption {
strict: boolean; strict: boolean;
private resolver?: IResolver<unknown, unknown, unknown, unknown, unknown>|undefined = undefined; private resolver?: IResolver<unknown, unknown, unknown, unknown, unknown>|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 || [];
@ -55,18 +56,25 @@ class CommandOption implements ICommandOption {
this.options = []; this.options = [];
for (const opt of def.options || []) { for (const opt of def.options || []) {
if (opt instanceof CommandOption) this.options.push(opt); if (opt instanceof CommandOption)
else this.options.push(new CommandOption(opt)); this.options.push(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)) throw new Error('Cannot nest subcommand groups'); if (this.type === OptionType.SUB_COMMAND_GROUP && 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_GROUP)) throw new Error('Cannot have subcommand groups under a subcommand'); throw new Error('Cannot nest subcommand groups');
if (this.type === OptionType.SUB_COMMAND && this.options.some(opt => opt.type === OptionType.SUB_COMMAND)) throw new Error('Cannot nest subcommands'); if (this.type === OptionType.SUB_COMMAND && this.options.some(opt => opt.type === OptionType.SUB_COMMAND_GROUP))
if (![OptionType.SUB_COMMAND, OptionType.SUB_COMMAND_GROUP].includes(this.type) throw new Error('Cannot have subcommand groups under a subcommand');
&& 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.type === OptionType.SUB_COMMAND && this.options.some(opt => opt.type === OptionType.SUB_COMMAND))
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))) throw new Error('Cannot have subcommand(group)s on the same level as an option') && 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');
this.choices = def.choices || []; this.choices = def.choices || [];
@ -81,16 +89,18 @@ 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 || undefined; opt.resolver = resolver;
return opt; return opt;
} }
async parse(guild?: unknown): Promise<ParseResult> { async parse (guild?: unknown): Promise<ParseResult> {
if (!this[OptionType[this.type]]) throw new Error(`Missing parsing function for ${this.type}`); if (!this[OptionType[this.type]])
if (typeof this[OptionType[this.type]] !== 'function') throw new Error(`Expected function type for memberr ${OptionType[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]}`);
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;
@ -99,56 +109,73 @@ 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) throw new Error('Missing resolver'); if (!this.resolver)
if(!this.rawValue) throw new Error('Missing raw value'); throw new Error('Missing resolver');
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) return { error: true }; if (!member)
return { error: true };
return { value: member, removed: this.rawValue }; return { value: member, removed: this.rawValue };
} }
protected STRING() { protected STRING () {
if (!this.rawValue) return { error: true }; if (!this.rawValue)
if (this.aliased) return { value: this.rawValue.join(' '), removed: [] }; return { error: true };
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) return { value: found, removed: this.rawValue }; if (found)
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) return { error: true }; if (!this.rawValue)
return { error: true };
const integer = parseInt(this.rawValue[0]); const integer = parseInt(this.rawValue[0]);
if(isNaN(integer)) return { error: true }; if (isNaN(integer))
if (this.minimum !== undefined && integer < this.minimum) return { error: true }; return { error: true };
if (this.maximum !== undefined && integer > this.maximum) return { error: true }; if (this.minimum !== undefined && integer < this.minimum)
return { value: integer, removed: [this.rawValue[0]] }; return { error: true };
if (this.maximum !== undefined && integer > this.maximum)
return { error: true };
return { value: integer, removed: [ this.rawValue[0] ] };
} }
protected FLOAT() { protected FLOAT () {
if (!this.rawValue) return { error: true }; if (!this.rawValue)
return { error: true };
const float = parseFloat(this.rawValue[0]); const float = parseFloat(this.rawValue[0]);
if(isNaN(float)) return { error: true }; if (isNaN(float))
if (this.minimum !== undefined && float < this.minimum) return { error: true }; return { error: true };
if (this.maximum !== undefined && float > this.maximum) return { error: true }; if (this.minimum !== undefined && float < this.minimum)
return { value: (float), removed: [this.rawValue[0]] }; return { error: true };
if (this.maximum !== undefined && float > this.maximum)
return { error: true };
return { value: float, removed: [ this.rawValue[0] ] };
} }
protected BOOLEAN() { protected BOOLEAN () {
if (!this.rawValue) return { error: true }; if (!this.rawValue)
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) return { value: this.defaultValue, removed: [] }; if (boolean === null && this.valueOptional)
else if(boolean === null) return { error: true }; return { value: this.defaultValue, removed: [] };
return { value: boolean, removed: [this.rawValue[0]] }; else if (boolean === null)
return { error: true };
return { value: boolean, removed: [ this.rawValue[0] ] };
} }
} }

View File

@ -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 });
} }
} }

View File

@ -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 });
} }
} }

View File

@ -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 | undefined { find (fn: (element: V, key: K) => boolean): V | void {
for (const [key, val] of this) { for (const [ key, val ] of this) {
if (fn(val, key)) return val; if (fn(val, key))
return val;
} }
return undefined;
} }
} }

View File

@ -1,21 +1,22 @@
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) return []; if (!string)
return [];
let quoted = false, let quoted = false,
wordStart = true, wordStart = true,
@ -38,7 +39,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 = '';
@ -75,13 +76,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 ]);
} }
}); });
} }

9
tsconfig.cjs.json Normal file
View File

@ -0,0 +1,9 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"declaration": false,
"sourceMap": false,
"module": "CommonJS",
"outDir": "./build/cjs"
}
}

View File

@ -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": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ "target": "ES2022", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
"lib": ["ES2017", "ES2018.Regexp"], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ "lib": ["ES2022"], /* 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 TC39 stage 2 draft decorators. */ // "experimentalDecorators": true, /* Enable experimental support for legacy experimental 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,22 +25,29 @@
// "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": "CommonJS", /* Specify what module code is generated. */ "module": "ES2022", /* 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": [], /* Specify multiple folders that act like './node_modules/@types'. */ "typeRoots": [
"./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": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ "allowJs": false, /* 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'. */
@ -48,9 +55,10 @@
"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. */
// "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. */ // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
"outDir": "./build", /* Specify an output folder for all emitted files. */ // "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/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. */
@ -58,11 +66,10 @@
// "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. */
@ -71,6 +78,7 @@
/* 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. */
@ -78,19 +86,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. */
@ -100,5 +108,6 @@
/* 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
} }