fix: remove unused console log

This commit is contained in:
FreeAoi 2024-03-23 00:15:02 -06:00
parent 0a225b6c3b
commit 6d8b895d07

View File

@ -1,353 +1,352 @@
import type { SeyfertNumberOption, SeyfertStringOption } from '../..'; import type { SeyfertNumberOption, SeyfertStringOption } from '../..';
import type { Attachment } from '../../builders'; import type { Attachment } from '../../builders';
import type { import type {
APIApplicationCommandBasicOption, APIApplicationCommandBasicOption,
APIApplicationCommandOption, APIApplicationCommandOption,
APIApplicationCommandSubcommandGroupOption, APIApplicationCommandSubcommandGroupOption,
FlatObjectKeys, FlatObjectKeys,
LocaleString, LocaleString,
PermissionStrings, PermissionStrings,
} from '../../common'; } from '../../common';
import { ApplicationCommandOptionType, ApplicationCommandType, magicImport } from '../../common'; import { ApplicationCommandOptionType, ApplicationCommandType, magicImport } from '../../common';
import type { AllChannels, AutocompleteInteraction, GuildRole, InteractionGuildMember, User } from '../../structures'; import type { AllChannels, AutocompleteInteraction, GuildRole, InteractionGuildMember, User } from '../../structures';
import type { Groups, IntegrationTypes, InteractionContextTypes, RegisteredMiddlewares } from '../decorators'; import type { Groups, IntegrationTypes, InteractionContextTypes, RegisteredMiddlewares } from '../decorators';
import type { OptionResolver } from '../optionresolver'; import type { OptionResolver } from '../optionresolver';
import type { CommandContext } from './chatcontext'; import type { CommandContext } from './chatcontext';
import type { import type {
DefaultLocale, DefaultLocale,
NextFunction, NextFunction,
OKFunction, OKFunction,
OnOptionsReturnObject, OnOptionsReturnObject,
PassFunction, PassFunction,
StopFunction, StopFunction,
UsingClient, UsingClient,
} from './shared'; } from './shared';
export interface ReturnOptionsTypes { export interface ReturnOptionsTypes {
1: never; // subcommand 1: never; // subcommand
2: never; // subcommandgroup 2: never; // subcommandgroup
3: string; 3: string;
4: number; // integer 4: number; // integer
5: boolean; 5: boolean;
6: InteractionGuildMember | User; 6: InteractionGuildMember | User;
7: AllChannels; 7: AllChannels;
8: GuildRole; 8: GuildRole;
9: GuildRole | AllChannels | User; 9: GuildRole | AllChannels | User;
10: number; // number 10: number; // number
11: Attachment; 11: Attachment;
} }
type Wrap<N extends ApplicationCommandOptionType> = N extends type Wrap<N extends ApplicationCommandOptionType> = N extends
| ApplicationCommandOptionType.Subcommand | ApplicationCommandOptionType.Subcommand
| ApplicationCommandOptionType.SubcommandGroup | ApplicationCommandOptionType.SubcommandGroup
? never ? never
: { : {
required?: boolean; required?: boolean;
value?( value?(
data: { context: CommandContext; value: ReturnOptionsTypes[N] }, data: { context: CommandContext; value: ReturnOptionsTypes[N] },
ok: OKFunction<any>, ok: OKFunction<any>,
fail: StopFunction, fail: StopFunction,
): void; ): void;
} & { } & {
description: string; description: string;
description_localizations?: APIApplicationCommandBasicOption['description_localizations']; description_localizations?: APIApplicationCommandBasicOption['description_localizations'];
name_localizations?: APIApplicationCommandBasicOption['name_localizations']; name_localizations?: APIApplicationCommandBasicOption['name_localizations'];
locales?: { locales?: {
name?: FlatObjectKeys<DefaultLocale>; name?: FlatObjectKeys<DefaultLocale>;
description?: FlatObjectKeys<DefaultLocale>; description?: FlatObjectKeys<DefaultLocale>;
}; };
}; };
export type __TypeWrapper<T extends ApplicationCommandOptionType> = Wrap<T>; export type __TypeWrapper<T extends ApplicationCommandOptionType> = Wrap<T>;
export type __TypesWrapper = { export type __TypesWrapper = {
[P in keyof typeof ApplicationCommandOptionType]: `${(typeof ApplicationCommandOptionType)[P]}` extends `${infer D extends [P in keyof typeof ApplicationCommandOptionType]: `${(typeof ApplicationCommandOptionType)[P]}` extends `${infer D extends
number}` number}`
? Wrap<D> ? Wrap<D>
: never; : never;
}; };
export type AutocompleteCallback = (interaction: AutocompleteInteraction) => any; export type AutocompleteCallback = (interaction: AutocompleteInteraction) => any;
export type OnAutocompleteErrorCallback = (interaction: AutocompleteInteraction, error: unknown) => any; export type OnAutocompleteErrorCallback = (interaction: AutocompleteInteraction, error: unknown) => any;
export type CommandBaseOption = __TypesWrapper[keyof __TypesWrapper]; export type CommandBaseOption = __TypesWrapper[keyof __TypesWrapper];
export type CommandBaseAutocompleteOption = __TypesWrapper[keyof __TypesWrapper] & { export type CommandBaseAutocompleteOption = __TypesWrapper[keyof __TypesWrapper] & {
autocomplete: AutocompleteCallback; autocomplete: AutocompleteCallback;
onAutocompleteError?: OnAutocompleteErrorCallback; onAutocompleteError?: OnAutocompleteErrorCallback;
}; };
export type CommandAutocompleteOption = CommandBaseAutocompleteOption & { name: string }; export type CommandAutocompleteOption = CommandBaseAutocompleteOption & { name: string };
export type __CommandOption = CommandBaseOption; //| CommandBaseAutocompleteOption; export type __CommandOption = CommandBaseOption; //| CommandBaseAutocompleteOption;
export type CommandOption = __CommandOption & { name: string }; export type CommandOption = __CommandOption & { name: string };
export type OptionsRecord = Record<string, __CommandOption & { type: ApplicationCommandOptionType }>; export type OptionsRecord = Record<string, __CommandOption & { type: ApplicationCommandOptionType }>;
type KeysWithoutRequired<T extends OptionsRecord> = { type KeysWithoutRequired<T extends OptionsRecord> = {
[K in keyof T]-?: T[K]['required'] extends true ? never : K; [K in keyof T]-?: T[K]['required'] extends true ? never : K;
}[keyof T]; }[keyof T];
type ContextOptionsAux<T extends OptionsRecord> = { type ContextOptionsAux<T extends OptionsRecord> = {
[K in Exclude<keyof T, KeysWithoutRequired<T>>]: T[K]['value'] extends (...args: any) => any [K in Exclude<keyof T, KeysWithoutRequired<T>>]: T[K]['value'] extends (...args: any) => any
? Parameters<Parameters<T[K]['value']>[1]>[0] ? Parameters<Parameters<T[K]['value']>[1]>[0]
: T[K] extends SeyfertStringOption | SeyfertNumberOption : T[K] extends SeyfertStringOption | SeyfertNumberOption
? T[K]['choices'] extends NonNullable<SeyfertStringOption['choices'] | SeyfertNumberOption['choices']> ? T[K]['choices'] extends NonNullable<SeyfertStringOption['choices'] | SeyfertNumberOption['choices']>
? T[K]['choices'][number]['value'] ? T[K]['choices'][number]['value']
: ReturnOptionsTypes[T[K]['type']] : ReturnOptionsTypes[T[K]['type']]
: ReturnOptionsTypes[T[K]['type']]; : ReturnOptionsTypes[T[K]['type']];
} & { } & {
[K in KeysWithoutRequired<T>]?: T[K]['value'] extends (...args: any) => any [K in KeysWithoutRequired<T>]?: T[K]['value'] extends (...args: any) => any
? Parameters<Parameters<T[K]['value']>[1]>[0] ? Parameters<Parameters<T[K]['value']>[1]>[0]
: T[K] extends SeyfertStringOption | SeyfertNumberOption : T[K] extends SeyfertStringOption | SeyfertNumberOption
? T[K]['choices'] extends NonNullable<SeyfertStringOption['choices'] | SeyfertNumberOption['choices']> ? T[K]['choices'] extends NonNullable<SeyfertStringOption['choices'] | SeyfertNumberOption['choices']>
? T[K]['choices'][number]['value'] ? T[K]['choices'][number]['value']
: ReturnOptionsTypes[T[K]['type']] : ReturnOptionsTypes[T[K]['type']]
: ReturnOptionsTypes[T[K]['type']]; : ReturnOptionsTypes[T[K]['type']];
}; };
export type ContextOptions<T extends OptionsRecord> = ContextOptionsAux<T>; export type ContextOptions<T extends OptionsRecord> = ContextOptionsAux<T>;
class BaseCommand { class BaseCommand {
middlewares: (keyof RegisteredMiddlewares)[] = []; middlewares: (keyof RegisteredMiddlewares)[] = [];
__filePath?: string; __filePath?: string;
__t?: { name: string | undefined; description: string | undefined }; __t?: { name: string | undefined; description: string | undefined };
__d?: true; __d?: true;
__tGroups?: Record< __tGroups?: Record<
string /* name for group*/, string /* name for group*/,
{ {
name: string | undefined; name: string | undefined;
description: string | undefined; description: string | undefined;
defaultDescription: string; defaultDescription: string;
} }
>; >;
guild_id?: string[]; guild_id?: string[];
name!: string; name!: string;
type!: number; // ApplicationCommandType.ChatInput | ApplicationCommandOptionType.Subcommand type!: number; // ApplicationCommandType.ChatInput | ApplicationCommandOptionType.Subcommand
nsfw?: boolean; nsfw?: boolean;
description!: string; description!: string;
default_member_permissions?: string; default_member_permissions?: string;
integration_types?: IntegrationTypes[]; integration_types?: IntegrationTypes[];
contexts?: InteractionContextTypes[]; contexts?: InteractionContextTypes[];
botPermissions?: bigint; botPermissions?: bigint;
name_localizations?: Partial<Record<LocaleString, string>>; name_localizations?: Partial<Record<LocaleString, string>>;
description_localizations?: Partial<Record<LocaleString, string>>; description_localizations?: Partial<Record<LocaleString, string>>;
options?: CommandOption[] | SubCommand[]; options?: CommandOption[] | SubCommand[];
/** @internal */ /** @internal */
async __runOptions( async __runOptions(
ctx: CommandContext<{}, never>, ctx: CommandContext<{}, never>,
resolver: OptionResolver, resolver: OptionResolver,
): Promise<[boolean, OnOptionsReturnObject]> { ): Promise<[boolean, OnOptionsReturnObject]> {
if (!this?.options?.length) { if (!this?.options?.length) {
return [false, {}]; return [false, {}];
} }
const data: OnOptionsReturnObject = {}; const data: OnOptionsReturnObject = {};
let errored = false; let errored = false;
for (const i of this.options ?? []) { for (const i of this.options ?? []) {
try { try {
const option = this.options!.find(x => x.name === i.name) as __CommandOption; const option = this.options!.find(x => x.name === i.name) as __CommandOption;
const value = const value =
resolver.getHoisted(i.name)?.value !== undefined resolver.getHoisted(i.name)?.value !== undefined
? await new Promise( ? await new Promise(
(res, rej) => (res, rej) =>
option.value?.({ context: ctx, value: resolver.getValue(i.name) } as never, res, rej) || option.value?.({ context: ctx, value: resolver.getValue(i.name) } as never, res, rej) ||
res(resolver.getValue(i.name)), res(resolver.getValue(i.name)),
) )
: undefined; : undefined;
if (value === undefined) { if (value === undefined) {
if (option.required) { if (option.required) {
errored = true; errored = true;
data[i.name] = { data[i.name] = {
failed: true, failed: true,
value: `${i.name} is required but returned no value`, value: `${i.name} is required but returned no value`,
}; };
continue; continue;
} }
} }
// @ts-expect-error // @ts-expect-error
ctx.options[i.name] = value; ctx.options[i.name] = value;
data[i.name] = { data[i.name] = {
failed: false, failed: false,
value, value,
}; };
} catch (e) { } catch (e) {
errored = true; errored = true;
data[i.name] = { data[i.name] = {
failed: true, failed: true,
value: e instanceof Error ? e.message : `${e}`, value: e instanceof Error ? e.message : `${e}`,
}; };
} }
} }
return [errored, data]; return [errored, data];
} }
/** @internal */ /** @internal */
static __runMiddlewares( static __runMiddlewares(
context: CommandContext<{}, never>, context: CommandContext<{}, never>,
middlewares: (keyof RegisteredMiddlewares)[], middlewares: (keyof RegisteredMiddlewares)[],
global: boolean, global: boolean,
): Promise<{ error?: string; pass?: boolean }> { ): Promise<{ error?: string; pass?: boolean }> {
if (!middlewares.length) { if (!middlewares.length) {
return Promise.resolve({}); return Promise.resolve({});
} }
let index = 0; let index = 0;
return new Promise(res => { return new Promise(res => {
let running = true; let running = true;
const pass: PassFunction = () => { const pass: PassFunction = () => {
if (!running) { if (!running) {
return; return;
} }
running = false; running = false;
return res({ pass: true }); return res({ pass: true });
}; };
const next: NextFunction<any> = obj => { const next: NextFunction<any> = obj => {
if (!running) { if (!running) {
return; return;
} }
context[global ? 'globalMetadata' : 'metadata'] ??= {}; context[global ? 'globalMetadata' : 'metadata'] ??= {};
// @ts-expect-error // @ts-expect-error
context[global ? 'globalMetadata' : 'metadata'][middlewares[index]] = obj; context[global ? 'globalMetadata' : 'metadata'][middlewares[index]] = obj;
if (++index >= middlewares.length) { if (++index >= middlewares.length) {
running = false; running = false;
return res({}); return res({});
} }
context.client.middlewares![middlewares[index]]({ context, next, stop, pass }); context.client.middlewares![middlewares[index]]({ context, next, stop, pass });
}; };
const stop: StopFunction = err => { const stop: StopFunction = err => {
if (!running) { if (!running) {
return; return;
} }
running = false; running = false;
return res({ error: err }); return res({ error: err });
}; };
context.client.middlewares![middlewares[0]]({ context, next, stop, pass }); context.client.middlewares![middlewares[0]]({ context, next, stop, pass });
}); });
} }
/** @internal */ /** @internal */
__runMiddlewares(context: CommandContext<{}, never>) { __runMiddlewares(context: CommandContext<{}, never>) {
return BaseCommand.__runMiddlewares(context, this.middlewares as (keyof RegisteredMiddlewares)[], false); return BaseCommand.__runMiddlewares(context, this.middlewares as (keyof RegisteredMiddlewares)[], false);
} }
/** @internal */ /** @internal */
__runGlobalMiddlewares(context: CommandContext<{}, never>) { __runGlobalMiddlewares(context: CommandContext<{}, never>) {
return BaseCommand.__runMiddlewares( return BaseCommand.__runMiddlewares(
context, context,
(context.client.options?.globalMiddlewares ?? []) as (keyof RegisteredMiddlewares)[], (context.client.options?.globalMiddlewares ?? []) as (keyof RegisteredMiddlewares)[],
true, true,
); );
} }
toJSON() { toJSON() {
const data = { const data = {
name: this.name, name: this.name,
type: this.type, type: this.type,
nsfw: this.nsfw || false, nsfw: this.nsfw || false,
description: this.description, description: this.description,
name_localizations: this.name_localizations, name_localizations: this.name_localizations,
description_localizations: this.description_localizations, description_localizations: this.description_localizations,
guild_id: this.guild_id, guild_id: this.guild_id,
default_member_permissions: this.default_member_permissions, default_member_permissions: this.default_member_permissions,
contexts: this.contexts, contexts: this.contexts,
integration_types: this.integration_types, integration_types: this.integration_types,
} as { } as {
name: BaseCommand['name']; name: BaseCommand['name'];
type: BaseCommand['type']; type: BaseCommand['type'];
nsfw: BaseCommand['nsfw']; nsfw: BaseCommand['nsfw'];
description: BaseCommand['description']; description: BaseCommand['description'];
name_localizations: BaseCommand['name_localizations']; name_localizations: BaseCommand['name_localizations'];
description_localizations: BaseCommand['description_localizations']; description_localizations: BaseCommand['description_localizations'];
guild_id: BaseCommand['guild_id']; guild_id: BaseCommand['guild_id'];
default_member_permissions: BaseCommand['default_member_permissions']; default_member_permissions: BaseCommand['default_member_permissions'];
contexts: BaseCommand['contexts']; contexts: BaseCommand['contexts'];
integration_types: BaseCommand['integration_types']; integration_types: BaseCommand['integration_types'];
}; };
if (data.contexts) console.log(data); return data;
return data; }
}
async reload() {
async reload() { delete require.cache[this.__filePath!];
delete require.cache[this.__filePath!]; const __tempCommand = await magicImport(this.__filePath!).then(x => x.default ?? x);
const __tempCommand = await magicImport(this.__filePath!).then(x => x.default ?? x);
Object.setPrototypeOf(this, __tempCommand.prototype);
Object.setPrototypeOf(this, __tempCommand.prototype); }
}
run?(context: CommandContext<any>): any;
run?(context: CommandContext<any>): any; onAfterRun?(context: CommandContext<any>, error: unknown | undefined): any;
onAfterRun?(context: CommandContext<any>, error: unknown | undefined): any; onRunError?(context: CommandContext<any>, error: unknown): any;
onRunError?(context: CommandContext<any>, error: unknown): any; onOptionsError?(context: CommandContext<{}, never>, metadata: OnOptionsReturnObject): any;
onOptionsError?(context: CommandContext<{}, never>, metadata: OnOptionsReturnObject): any; onMiddlewaresError?(context: CommandContext<{}, never>, error: string): any;
onMiddlewaresError?(context: CommandContext<{}, never>, error: string): any; onPermissionsFail?(context: CommandContext<{}, never>, permissions: PermissionStrings): any;
onPermissionsFail?(context: CommandContext<{}, never>, permissions: PermissionStrings): any; onInternalError?(client: UsingClient, error?: unknown): any;
onInternalError?(client: UsingClient, error?: unknown): any; }
}
export class Command extends BaseCommand {
export class Command extends BaseCommand { type = ApplicationCommandType.ChatInput;
type = ApplicationCommandType.ChatInput;
groups?: Parameters<typeof Groups>[0];
groups?: Parameters<typeof Groups>[0]; toJSON() {
toJSON() { const options: APIApplicationCommandOption[] = [];
const options: APIApplicationCommandOption[] = [];
for (const i of this.options ?? []) {
for (const i of this.options ?? []) { if (!(i instanceof SubCommand)) {
if (!(i instanceof SubCommand)) { options.push({ ...i, autocomplete: 'autocomplete' in i } as APIApplicationCommandBasicOption);
options.push({ ...i, autocomplete: 'autocomplete' in i } as APIApplicationCommandBasicOption); continue;
continue; }
} if (i.group) {
if (i.group) { if (!options.find(x => x.name === i.group)) {
if (!options.find(x => x.name === i.group)) { options.push({
options.push({ type: ApplicationCommandOptionType.SubcommandGroup,
type: ApplicationCommandOptionType.SubcommandGroup, name: i.group,
name: i.group, description: this.groups![i.group].defaultDescription,
description: this.groups![i.group].defaultDescription, description_localizations: Object.fromEntries(this.groups?.[i.group].description ?? []),
description_localizations: Object.fromEntries(this.groups?.[i.group].description ?? []), name_localizations: Object.fromEntries(this.groups?.[i.group].name ?? []),
name_localizations: Object.fromEntries(this.groups?.[i.group].name ?? []), options: [],
options: [], });
}); }
} const group = options.find(x => x.name === i.group) as APIApplicationCommandSubcommandGroupOption;
const group = options.find(x => x.name === i.group) as APIApplicationCommandSubcommandGroupOption; group.options?.push(i.toJSON());
group.options?.push(i.toJSON()); continue;
continue; }
} options.push(i.toJSON());
options.push(i.toJSON()); }
}
return {
return { ...super.toJSON(),
...super.toJSON(), options,
options, };
}; }
}
onRunError(context: CommandContext<any>, error: unknown): any {
onRunError(context: CommandContext<any>, error: unknown): any { context.client.logger.fatal(`${this.name}.<onRunError>`, context.author.id, error);
context.client.logger.fatal(`${this.name}.<onRunError>`, context.author.id, error); }
} onOptionsError(context: CommandContext<{}, never>, metadata: OnOptionsReturnObject): any {
onOptionsError(context: CommandContext<{}, never>, metadata: OnOptionsReturnObject): any { context.client.logger.fatal(`${this.name}.<onOptionsError>`, context.author.id, metadata);
context.client.logger.fatal(`${this.name}.<onOptionsError>`, context.author.id, metadata); }
} onMiddlewaresError(context: CommandContext<{}, never>, error: string): any {
onMiddlewaresError(context: CommandContext<{}, never>, error: string): any { context.client.logger.fatal(`${this.name}.<onMiddlewaresError>`, context.author.id, error);
context.client.logger.fatal(`${this.name}.<onMiddlewaresError>`, context.author.id, error); }
} onPermissionsFail(context: CommandContext<{}, never>, permissions: PermissionStrings): any {
onPermissionsFail(context: CommandContext<{}, never>, permissions: PermissionStrings): any { context.client.logger.fatal(`${this.name}.<onPermissionsFail>`, context.author.id, permissions);
context.client.logger.fatal(`${this.name}.<onPermissionsFail>`, context.author.id, permissions); }
} onInternalError(client: UsingClient, error?: unknown): any {
onInternalError(client: UsingClient, error?: unknown): any { client.logger.fatal(`${this.name}.<onInternalError>`, error);
client.logger.fatal(`${this.name}.<onInternalError>`, error); }
} }
}
export abstract class SubCommand extends BaseCommand {
export abstract class SubCommand extends BaseCommand { type = ApplicationCommandOptionType.Subcommand;
type = ApplicationCommandOptionType.Subcommand; group?: string;
group?: string; declare options?: CommandOption[];
declare options?: CommandOption[];
toJSON() {
toJSON() { return {
return { ...super.toJSON(),
...super.toJSON(), options: (this.options ?? []).map(
options: (this.options ?? []).map( x => ({ ...x, autocomplete: 'autocomplete' in x }) as APIApplicationCommandBasicOption,
x => ({ ...x, autocomplete: 'autocomplete' in x }) as APIApplicationCommandBasicOption, ),
), };
}; }
}
abstract run(context: CommandContext<any>): any;
abstract run(context: CommandContext<any>): any; }
}