feat: Add Prettier configuration and improve code formatting across multiple files

This commit is contained in:
2025-10-13 23:53:20 -05:00
parent ff6ef6930e
commit fb5509cf79
5 changed files with 255 additions and 144 deletions
+6
View File
@@ -35,5 +35,11 @@
}, },
"dependencies": { "dependencies": {
"ws": "^8.18.0" "ws": "^8.18.0"
},
"prettier": {
"singleQuote": true,
"trailingComma": "all",
"printWidth": 120,
"tabWidth": 4
} }
} }
+9 -9
View File
@@ -1,17 +1,11 @@
// Base classes // Base classes
export { Client } from './services/client'; export { Client, Client as unicord } from './services/client';
export { Intent, Trait } from './types/common'; export { Intent, Trait } from './types/common';
// Consumable types // Consumable types
export type { ClientConfig } from './types/common'; export type { ClientConfig } from './types/common';
export type { Context } from './types/context'; export type { Context } from './types/context';
export { Expectation } from './types/common'; export { Expectation } from './types/common';
export { export { ChannelType, ChannelFlags, VideoQualityMode, SortOrderType, ForumLayoutType } from './types/channel';
ChannelType,
ChannelFlags,
VideoQualityMode,
SortOrderType,
ForumLayoutType
} from './types/channel';
// Consumable util classes // Consumable util classes
export { Guild } from './types/guild'; export { Guild } from './types/guild';
export { Role } from './types/role'; export { Role } from './types/role';
@@ -21,5 +15,11 @@ export { Message, type MessagePayload, ComponentStyle, ComponentType } from './t
export { Embed } from './types/embed'; export { Embed } from './types/embed';
export { Emoji } from './types/emoji'; export { Emoji } from './types/emoji';
// Other // Other
export { createCommandHandler, type InteractionData, type InteractionCommpoentData, type InteractionCommandData, type InteractionHandlerFunction } from './types/handler'; export {
createCommandHandler,
type InteractionData,
type InteractionCommpoentData,
type InteractionCommandData,
type InteractionHandlerFunction,
} from './types/handler';
export { ApplicationCommandType, ApplicationCommandOptionType as CommandOptionType } from './types/applicationCommand'; export { ApplicationCommandType, ApplicationCommandOptionType as CommandOptionType } from './types/applicationCommand';
+15 -11
View File
@@ -1,16 +1,22 @@
import { fromDiscord } from "../../types/common"; import { fromDiscord } from '../../types/common';
import type { Context } from "../../types/context"; import type { Context } from '../../types/context';
import type { API } from "../api"; import type { API } from '../api';
import type { Processor } from "../processor"; import type { Processor } from '../processor';
export class ObjectCache<T, K extends T> { export class ObjectCache<T, K extends T> {
cache: LRUCache<string, K>; cache: LRUCache<string, K>;
requests = new Map<string, Promise<K>>(); requests = new Map<string, Promise<K>>();
readonly type: string; readonly type: string;
constructor(protected api: API, processor: Processor, type: string, private readonly factory: { [fromDiscord]: (data: any) => K } & (new (data: T) => T), events: string[], capacity: number = 10_000) { constructor(
this.cache = new LRUCache<string, K>(10_000) protected api: API,
processor: Processor,
type: string,
private readonly factory: { [fromDiscord]: (data: any) => K } & (new (data: T) => T),
events: string[],
maxCapacity: number = 10_000,
) {
this.cache = new LRUCache<string, K>(maxCapacity);
this.type = type; this.type = type;
processor.events.register(events, async (_context: Context, e: Record<string, any>) => { processor.events.register(events, async (_context: Context, e: Record<string, any>) => {
this.cache.set(e.id, factory[fromDiscord](e)); this.cache.set(e.id, factory[fromDiscord](e));
@@ -49,10 +55,8 @@ export class ObjectCache<T, K extends T> {
}); });
// Save the request // Save the request
this.requests.set(object_id, req); this.requests.set(object_id, req);
// Remove the request from the cache if it succeeds // Remove the request from the cache when it finishes
req.then(() => this.requests.delete(object_id)); req.finally(() => this.requests.delete(object_id));
// Remove the request from the cache if it fails
req.catch(() => this.requests.delete(object_id));
// Return the request // Return the request
return req; return req;
} }
+30 -10
View File
@@ -1,4 +1,4 @@
import { Expectation, HandlerType, Intent, type ClientConfig } from '../types/common'; import { type DiscordAPIEvent, Expectation, HandlerType, Intent, type ClientConfig } from '../types/common';
import { Message, type DiscordMessage } from '../types/message'; import { Message, type DiscordMessage } from '../types/message';
import { exists, isNil } from '../utils/index'; import { exists, isNil } from '../utils/index';
import { API } from './api'; import { API } from './api';
@@ -95,9 +95,12 @@ export class Client {
* *
* @throws Will throw an error if an expectation cannot be resolved. * @throws Will throw an error if an expectation cannot be resolved.
*/ */
hydrate = async <T extends Hydrateable | Hydrated<Hydrateable, Array<Expectation>>, K extends Array<Expectation>>(data: T, expectations: K) => { hydrate = async <T extends Hydrateable | Hydrated<Hydrateable, Array<Expectation>>, K extends Array<Expectation>>(
data: T,
expectations: K,
) => {
return hydrate<T, K>(data, expectations, this, this.api); return hydrate<T, K>(data, expectations, this, this.api);
} };
/** /**
* A wrapper function that attempts to hydrate a given data object and returns a type guard function. * A wrapper function that attempts to hydrate a given data object and returns a type guard function.
@@ -110,17 +113,34 @@ export class Client {
* *
* @returns A promise that resolves to a type guard function. The type guard function returns `true` if the data object was successfully hydrated, otherwise `false`. * @returns A promise that resolves to a type guard function. The type guard function returns `true` if the data object was successfully hydrated, otherwise `false`.
*/ */
hydrator = async<T extends Hydrateable, K extends Expectation[]>(data: T, expectations: K) => { hydrator = async <T extends Hydrateable, K extends Expectation[]>(data: T, expectations: K) => {
return hydrator<T, K>(data, expectations, this, this.api); return hydrator<T, K>(data, expectations, this, this.api);
} };
sendMessage = async (channel_id: string, message: Message | string) => { sendMessage = async (channel_id: string, message: Message | string) => {
if (typeof message === 'string') { if (typeof message === 'string') {
message = new Message().setContent(message); message = new Message().setContent(message);
} }
return Message.fromDiscord(await this.api.post<DiscordMessage>(`/channels/${channel_id}/messages`, message.toJSON())); return Message.fromDiscord(
} await this.api.post<DiscordMessage>(`/channels/${channel_id}/messages`, message.toJSON()),
);
};
/**
* Makes a raw HTTP request to the Discord API.
* @param method HTTP method to use for the request (GET, POST, PUT, DELETE).
* @param endpoint The API endpoint to request; can start with a slash or be a full URL.
* @param body Optional body to send with the request, typically used for POST or PUT requests.
* @returns A promise that resolves to the response data of type T.
*/
rawRequest = async <T = Record<string, any>>(
method: 'GET' | 'POST' | 'PUT' | 'DELETE',
endpoint: string,
body?: Record<string, any>,
): Promise<T> => {
return this.api.request<T>(method, endpoint, body);
};
// chatCommands = { // chatCommands = {
// register: (name: string | string[], handler: Handler) => this.processor.chat_commands.register(name, handler), // register: (name: string | string[], handler: Handler) => this.processor.chat_commands.register(name, handler),
@@ -134,11 +154,11 @@ export class Client {
// has: (name: string) => this.processor.application_commands.has(name) // has: (name: string) => this.processor.application_commands.has(name)
// } // }
on = (event: string, handler: (...args: any[]) => void) => this.bus.on(event, handler); on = (event: DiscordAPIEvent, handler: (...args: any[]) => void) => this.bus.on(event, handler);
once = (event: string, handler: (...args: any[]) => void) => this.bus.once(event, handler); once = (event: DiscordAPIEvent, handler: (...args: any[]) => void) => this.bus.once(event, handler);
off = (event: string, handler: (...args: any[]) => void) => this.bus.off(event, handler); off = (event: DiscordAPIEvent, handler: (...args: any[]) => void) => this.bus.off(event, handler);
connect = () => this.gateway.connect(); connect = () => this.gateway.connect();
} }
+181 -100
View File
@@ -3,7 +3,7 @@ export type ClientConfig = {
application_id: string; application_id: string;
prefix?: string; prefix?: string;
intents?: Intent[]; intents?: Intent[];
} };
export enum Expectation { export enum Expectation {
Guild = 'guild', Guild = 'guild',
@@ -16,24 +16,26 @@ export enum HandlerType {
Events = 'events', Events = 'events',
ChatCommands = 'chat_commands', ChatCommands = 'chat_commands',
ApplicationCommands = 'application_commands', ApplicationCommands = 'application_commands',
Interactions = 'interactions' Interactions = 'interactions',
} }
export type Expects<T extends Array<Expectation>, K extends Expectation> = Extract<K, T[number]> extends never ? false : true; export type Expects<T extends Array<Expectation>, K extends Expectation> = Extract<K, T[number]> extends never
? false
: true;
export const clone: unique symbol = Symbol('clone') export const clone: unique symbol = Symbol('clone');
export const fromDiscord: unique symbol = Symbol('fromDiscord') export const fromDiscord: unique symbol = Symbol('fromDiscord');
export const execute: unique symbol = Symbol('execute') export const execute: unique symbol = Symbol('execute');
export const Trait: { export const Trait: {
clone: typeof clone clone: typeof clone;
fromDiscord: typeof fromDiscord fromDiscord: typeof fromDiscord;
execute: typeof execute execute: typeof execute;
} = { } = {
clone, clone,
fromDiscord, fromDiscord,
execute execute,
} };
export type EventPayload = any; export type EventPayload = any;
@@ -58,7 +60,7 @@ export type Payload = {
export enum InteractionResponseType { export enum InteractionResponseType {
Pong = 1, Pong = 1,
Message = 4, Message = 4,
DeferredMessage = 5 DeferredMessage = 5,
} }
export enum Intent { export enum Intent {
@@ -79,110 +81,189 @@ export enum Intent {
DIRECT_MESSAGE_TYPING = 1 << 14, DIRECT_MESSAGE_TYPING = 1 << 14,
MESSAGE_CONTENT = 1 << 15, MESSAGE_CONTENT = 1 << 15,
DEFAULT = 513, DEFAULT = 513,
ALL = 32767 ALL = 32767,
} }
export const IntentGroup: { [key in Intent]?: [string[], number] } = { export const IntentGroup: { [key in Intent]?: [string[], number] } = {
[Intent.GUILDS]: [[ [Intent.GUILDS]: [
"GUILD_CREATE", [
"GUILD_UPDATE", 'GUILD_CREATE',
"GUILD_DELETE", 'GUILD_UPDATE',
"GUILD_ROLE_CREATE", 'GUILD_DELETE',
"GUILD_ROLE_UPDATE", 'GUILD_ROLE_CREATE',
"GUILD_ROLE_DELETE", 'GUILD_ROLE_UPDATE',
"CHANNEL_CREATE", 'GUILD_ROLE_DELETE',
"CHANNEL_UPDATE", 'CHANNEL_CREATE',
"CHANNEL_DELETE", 'CHANNEL_UPDATE',
"CHANNEL_PINS_UPDATE", 'CHANNEL_DELETE',
"THREAD_CREATE", 'CHANNEL_PINS_UPDATE',
"THREAD_UPDATE", 'THREAD_CREATE',
"THREAD_DELETE", 'THREAD_UPDATE',
"THREAD_LIST_SYNC", 'THREAD_DELETE',
"THREAD_MEMBER_UPDATE", 'THREAD_LIST_SYNC',
"THREAD_MEMBERS_UPDATE *", 'THREAD_MEMBER_UPDATE',
"STAGE_INSTANCE_CREATE", 'THREAD_MEMBERS_UPDATE *',
"STAGE_INSTANCE_UPDATE", 'STAGE_INSTANCE_CREATE',
"STAGE_INSTANCE_DELETE" 'STAGE_INSTANCE_UPDATE',
], 0], 'STAGE_INSTANCE_DELETE',
],
0,
],
[Intent.GUILD_MEMBERS]: [[ [Intent.GUILD_MEMBERS]: [
"GUILD_MEMBER_ADD", ['GUILD_MEMBER_ADD', 'GUILD_MEMBER_UPDATE', 'GUILD_MEMBER_REMOVE', 'THREAD_MEMBERS_UPDATE *'],
"GUILD_MEMBER_UPDATE", 1,
"GUILD_MEMBER_REMOVE", ],
"THREAD_MEMBERS_UPDATE *",
], 1],
[Intent.GUILD_BANS]: [[ [Intent.GUILD_BANS]: [['GUILD_BAN_ADD', 'GUILD_BAN_REMOVE'], 2],
"GUILD_BAN_ADD",
"GUILD_BAN_REMOVE",
], 2],
[Intent.GUILD_EMOJIS_AND_STICKERS]: [[ [Intent.GUILD_EMOJIS_AND_STICKERS]: [['GUILD_EMOJIS_UPDATE', 'GUILD_STICKERS_UPDATE'], 3],
"GUILD_EMOJIS_UPDATE",
"GUILD_STICKERS_UPDATE",
], 3],
[Intent.GUILD_INTEGRATIONS]: [[ [Intent.GUILD_INTEGRATIONS]: [
"GUILD_INTEGRATIONS_UPDATE", ['GUILD_INTEGRATIONS_UPDATE', 'INTEGRATION_CREATE', 'INTEGRATION_UPDATE', 'INTEGRATION_DELETE'],
"INTEGRATION_CREATE", 4,
"INTEGRATION_UPDATE", ],
"INTEGRATION_DELETE",
], 4],
[Intent.GUILD_WEBHOOKS]: [[ [Intent.GUILD_WEBHOOKS]: [['WEBHOOKS_UPDATE'], 5],
"WEBHOOKS_UPDATE"
], 5],
[Intent.GUILD_INVITES]: [[ [Intent.GUILD_INVITES]: [['INVITE_CREATE', 'INVITE_DELETE'], 6],
"INVITE_CREATE",
"INVITE_DELETE",
], 6],
[Intent.GUILD_VOICE_STATES]: [[ [Intent.GUILD_VOICE_STATES]: [['VOICE_STATE_UPDATE'], 7],
"VOICE_STATE_UPDATE"
], 7],
[Intent.GUILD_PRESENCES]: [[ [Intent.GUILD_PRESENCES]: [['PRESENCE_UPDATE'], 8],
"PRESENCE_UPDATE"
], 8],
[Intent.GUILD_MESSAGES]: [[ [Intent.GUILD_MESSAGES]: [['MESSAGE_CREATE', 'MESSAGE_UPDATE', 'MESSAGE_DELETE', 'MESSAGE_DELETE_BULK'], 9],
"MESSAGE_CREATE",
"MESSAGE_UPDATE",
"MESSAGE_DELETE",
"MESSAGE_DELETE_BULK",
], 9],
[Intent.GUILD_MESSAGE_REACTIONS]: [[ [Intent.GUILD_MESSAGE_REACTIONS]: [
"MESSAGE_REACTION_ADD", [
"MESSAGE_REACTION_REMOVE", 'MESSAGE_REACTION_ADD',
"MESSAGE_REACTION_REMOVE_ALL", 'MESSAGE_REACTION_REMOVE',
"MESSAGE_REACTION_REMOVE_EMOJI", 'MESSAGE_REACTION_REMOVE_ALL',
], 10], 'MESSAGE_REACTION_REMOVE_EMOJI',
],
10,
],
[Intent.GUILD_MESSAGE_TYPING]: [[ [Intent.GUILD_MESSAGE_TYPING]: [['TYPING_START'], 11],
"TYPING_START"
], 11],
[Intent.DIRECT_MESSAGES]: [[ [Intent.DIRECT_MESSAGES]: [['MESSAGE_CREATE', 'MESSAGE_UPDATE', 'MESSAGE_DELETE', 'CHANNEL_PINS_UPDATE'], 12],
"MESSAGE_CREATE",
"MESSAGE_UPDATE",
"MESSAGE_DELETE",
"CHANNEL_PINS_UPDATE",
], 12],
[Intent.DIRECT_MESSAGE_REACTIONS]: [[ [Intent.DIRECT_MESSAGE_REACTIONS]: [
"MESSAGE_REACTION_ADD", [
"MESSAGE_REACTION_REMOVE", 'MESSAGE_REACTION_ADD',
"MESSAGE_REACTION_REMOVE_ALL", 'MESSAGE_REACTION_REMOVE',
"MESSAGE_REACTION_REMOVE_EMOJI", 'MESSAGE_REACTION_REMOVE_ALL',
], 13], 'MESSAGE_REACTION_REMOVE_EMOJI',
],
13,
],
[Intent.DIRECT_MESSAGE_TYPING]: [[ [Intent.DIRECT_MESSAGE_TYPING]: [['TYPING_START'], 14],
"TYPING_START"
], 14],
[Intent.MESSAGE_CONTENT]: [[ [Intent.MESSAGE_CONTENT]: [['MESSAGE_CONTENT'], 15],
"MESSAGE_CONTENT" };
], 15]
export type DiscordAPIEvent =
| 'READY'
| 'RESUMED'
| 'CHANNEL_CREATE'
| 'CHANNEL_UPDATE'
| 'CHANNEL_DELETE'
| 'CHANNEL_PINS_UPDATE'
| 'THREAD_CREATE'
| 'THREAD_UPDATE'
| 'THREAD_DELETE'
| 'THREAD_LIST_SYNC'
| 'THREAD_MEMBER_UPDATE'
| 'THREAD_MEMBERS_UPDATE *'
| 'STAGE_INSTANCE_CREATE'
| 'STAGE_INSTANCE_UPDATE'
| 'STAGE_INSTANCE_DELETE'
| 'GUILD_CREATE'
| 'GUILD_UPDATE'
| 'GUILD_DELETE'
| 'GUILD_ROLE_CREATE'
| 'GUILD_ROLE_UPDATE'
| 'GUILD_ROLE_DELETE'
| 'GUILD_MEMBER_ADD'
| 'GUILD_MEMBER_UPDATE'
| 'GUILD_MEMBER_REMOVE'
| 'GUILD_MEMBERS_CHUNK *'
| 'GUILD_BAN_ADD'
| 'GUILD_BAN_REMOVE'
| 'GUILD_EMOJIS_UPDATE'
| 'GUILD_STICKERS_UPDATE'
| 'GUILD_INTEGRATIONS_UPDATE'
| 'INTEGRATION_CREATE'
| 'INTEGRATION_UPDATE'
| 'INTEGRATION_DELETE'
| 'WEBHOOKS_UPDATE'
| 'INVITE_CREATE'
| 'INVITE_DELETE'
| 'VOICE_STATE_UPDATE'
| 'MESSAGE_CREATE'
| 'MESSAGE_UPDATE'
| 'MESSAGE_DELETE'
| 'MESSAGE_DELETE_BULK'
| 'MESSAGE_REACTION_ADD'
| 'MESSAGE_REACTION_REMOVE'
| 'MESSAGE_REACTION_REMOVE_ALL'
| 'MESSAGE_REACTION_REMOVE_EMOJI'
| 'TYPING_START'
| 'PRESENCE_UPDATE'
| 'APPLICATION_COMMAND_CREATE'
| 'APPLICATION_COMMAND_UPDATE'
| 'APPLICATION_COMMAND_DELETE';
export enum DiscordAPIEvents {
READY = 'READY',
RESUMED = 'RESUMED',
CHANNEL_CREATE = 'CHANNEL_CREATE',
CHANNEL_UPDATE = 'CHANNEL_UPDATE',
CHANNEL_DELETE = 'CHANNEL_DELETE',
CHANNEL_PINS_UPDATE = 'CHANNEL_PINS_UPDATE',
THREAD_CREATE = 'THREAD_CREATE',
THREAD_UPDATE = 'THREAD_UPDATE',
THREAD_DELETE = 'THREAD_DELETE',
THREAD_LIST_SYNC = 'THREAD_LIST_SYNC',
THREAD_MEMBER_UPDATE = 'THREAD_MEMBER_UPDATE',
THREAD_MEMBERS_UPDATE = 'THREAD_MEMBERS_UPDATE *',
STAGE_INSTANCE_CREATE = 'STAGE_INSTANCE_CREATE',
STAGE_INSTANCE_UPDATE = 'STAGE_INSTANCE_UPDATE',
STAGE_INSTANCE_DELETE = 'STAGE_INSTANCE_DELETE',
GUILD_CREATE = 'GUILD_CREATE',
GUILD_UPDATE = 'GUILD_UPDATE',
GUILD_DELETE = 'GUILD_DELETE',
GUILD_ROLE_CREATE = 'GUILD_ROLE_CREATE',
GUILD_ROLE_UPDATE = 'GUILD_ROLE_UPDATE',
GUILD_ROLE_DELETE = 'GUILD_ROLE_DELETE',
GUILD_MEMBER_ADD = 'GUILD_MEMBER_ADD',
GUILD_MEMBER_UPDATE = 'GUILD_MEMBER_UPDATE',
GUILD_MEMBER_REMOVE = 'GUILD_MEMBER_REMOVE',
GUILD_MEMBERS_CHUNK = 'GUILD_MEMBERS_CHUNK *',
GUILD_BAN_ADD = 'GUILD_BAN_ADD',
GUILD_BAN_REMOVE = 'GUILD_BAN_REMOVE',
GUILD_EMOJIS_UPDATE = 'GUILD_EMOJIS_UPDATE',
GUILD_STICKERS_UPDATE = 'GUILD_STICKERS_UPDATE',
GUILD_INTEGRATIONS_UPDATE = 'GUILD_INTEGRATIONS_UPDATE',
INTEGRATION_CREATE = 'INTEGRATION_CREATE',
INTEGRATION_UPDATE = 'INTEGRATION_UPDATE',
INTEGRATION_DELETE = 'INTEGRATION_DELETE',
WEBHOOKS_UPDATE = 'WEBHOOKS_UPDATE',
INVITE_CREATE = 'INVITE_CREATE',
INVITE_DELETE = 'INVITE_DELETE',
VOICE_STATE_UPDATE = 'VOICE_STATE_UPDATE',
MESSAGE_CREATE = 'MESSAGE_CREATE',
MESSAGE_UPDATE = 'MESSAGE_UPDATE',
MESSAGE_DELETE = 'MESSAGE_DELETE',
MESSAGE_DELETE_BULK = 'MESSAGE_DELETE_BULK',
MESSAGE_REACTION_ADD = 'MESSAGE_REACTION_ADD',
MESSAGE_REACTION_REMOVE = 'MESSAGE_REACTION_REMOVE',
MESSAGE_REACTION_REMOVE_ALL = 'MESSAGE_REACTION_REMOVE_ALL',
MESSAGE_REACTION_REMOVE_EMOJI = 'MESSAGE_REACTION_REMOVE_EMOJI',
TYPING_START = 'TYPING_START',
PRESENCE_UPDATE = 'PRESENCE_UPDATE',
APPLICATION_COMMAND_CREATE = 'APPLICATION_COMMAND_CREATE',
APPLICATION_COMMAND_UPDATE = 'APPLICATION_COMMAND_UPDATE',
APPLICATION_COMMAND_DELETE = 'APPLICATION_COMMAND_DELETE',
} }