meocord 1.4.0 → 1.5.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -18,6 +18,7 @@ While still growing, MeoCord provides a solid foundation for developers to creat
18
18
  - [Configuration](#configuration)
19
19
  - [CLI Usage](#cli-usage)
20
20
  - [Development Guide](#development-guide)
21
+ - [Custom Decorators](#custom-decorators)
21
22
  - [Deployment Guide](#deployment-guide)
22
23
  - [Contributing](#contributing)
23
24
  - [License](#license)
@@ -484,6 +485,104 @@ Once built, you can deploy or run the application efficiently.
484
485
 
485
486
  ---
486
487
 
488
+ ## Custom Decorators
489
+
490
+ MeoCord exports two helpers from `meocord/common` for building your own decorators: `applyDecorators` and `SetMetadata`.
491
+
492
+ ### `applyDecorators` — compose decorators into one
493
+
494
+ Combine multiple existing decorators into a single reusable one. Useful for bundling a common guard pattern so you don't repeat it on every command.
495
+
496
+ ```typescript
497
+ import { applyDecorators } from 'meocord/common'
498
+ import { UseGuard } from 'meocord/decorator'
499
+ import { DefaultGuard, GlobalRateLimiterGuard, RateLimiterGuard } from '@src/guards'
500
+
501
+ // Reusable decorator that applies a standard guard stack
502
+ export const Protected = () =>
503
+ applyDecorators(
504
+ UseGuard(DefaultGuard, GlobalRateLimiterGuard),
505
+ )
506
+
507
+ // With configurable rate limit
508
+ export const RateLimited = (limit: number) =>
509
+ applyDecorators(
510
+ UseGuard(DefaultGuard, { provide: RateLimiterGuard, params: { limit } }),
511
+ )
512
+ ```
513
+
514
+ Usage on a controller:
515
+
516
+ ```typescript
517
+ import { Controller } from 'meocord/decorator'
518
+ import { Protected, RateLimited } from '@src/common/decorators'
519
+
520
+ @Controller()
521
+ export class ProfileController {
522
+ @Command('profile', CommandType.SLASH)
523
+ @Protected()
524
+ async profile(interaction: ChatInputCommandInteraction) { ... }
525
+
526
+ @Command('wish', CommandType.SLASH)
527
+ @RateLimited(3)
528
+ async wish(interaction: ChatInputCommandInteraction) { ... }
529
+ }
530
+ ```
531
+
532
+ ### `SetMetadata` + custom guard — attach and read custom metadata
533
+
534
+ Use `SetMetadata` to tag commands with arbitrary data, then read it inside a guard.
535
+
536
+ **1. Define the metadata decorator:**
537
+
538
+ ```typescript
539
+ import { SetMetadata } from 'meocord/common'
540
+
541
+ export const Roles = (...roles: string[]) => SetMetadata('roles', roles)
542
+ ```
543
+
544
+ **2. Read it in a guard:**
545
+
546
+ ```typescript
547
+ import { Guard } from 'meocord/decorator'
548
+ import { type GuardInterface } from 'meocord/interface'
549
+ import type { ChatInputCommandInteraction } from 'discord.js'
550
+
551
+ @Guard()
552
+ export class RolesGuard implements GuardInterface {
553
+ async canActivate(interaction: ChatInputCommandInteraction): Promise<boolean> {
554
+ const required: string[] = Reflect.getMetadata('roles', interaction.constructor) ?? []
555
+ if (!required.length) return true
556
+
557
+ const memberRoles = interaction.member?.roles
558
+ // ... check member has at least one required role
559
+ return true
560
+ }
561
+ }
562
+ ```
563
+
564
+ **3. Apply both on a command:**
565
+
566
+ ```typescript
567
+ import { applyDecorators } from 'meocord/common'
568
+ import { UseGuard } from 'meocord/decorator'
569
+
570
+ export const RequireRoles = (...roles: string[]) =>
571
+ applyDecorators(
572
+ Roles(...roles),
573
+ UseGuard(RolesGuard),
574
+ )
575
+
576
+ @Controller()
577
+ export class AdminController {
578
+ @Command('ban', CommandType.SLASH)
579
+ @RequireRoles('admin', 'moderator')
580
+ async ban(interaction: ChatInputCommandInteraction) { ... }
581
+ }
582
+ ```
583
+
584
+ ---
585
+
487
586
  ## Deployment Guide
488
587
 
489
588
  Install all necessary dependencies, including development dependencies, before building:
@@ -571,6 +670,12 @@ Thank you for helping make **MeoCord** better!
571
670
 
572
671
  ---
573
672
 
673
+ ## Release Notes
674
+
675
+ Full release history is available on the [GitHub Releases](https://github.com/l7aromeo/meocord/releases) page.
676
+
677
+ ---
678
+
574
679
  ## License
575
680
 
576
681
  **MeoCord Framework** is licensed under the [MIT License](./LICENSE).
@@ -0,0 +1,215 @@
1
+ 'use strict';
2
+
3
+ require('reflect-metadata');
4
+ var inversify = require('inversify');
5
+ var discord_js = require('discord.js');
6
+ var enum_index = require('../enum/index.cjs');
7
+
8
+ const COMMAND_METADATA_KEY = Symbol('commands');
9
+ const MESSAGE_HANDLER_METADATA_KEY = Symbol('message_handlers');
10
+ const REACTION_HANDLER_METADATA_KEY = Symbol('reaction_handlers');
11
+ /**
12
+ * Decorator to register message handlers in the controller.
13
+ *
14
+ * @param keyword - An optional keyword to filter messages this handler should respond to.
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * @MessageHandler('hello')
19
+ * async handleHelloMessage(message: Message) {
20
+ * await message.reply('Hello! How can I help you?');
21
+ * }
22
+ *
23
+ * @MessageHandler()
24
+ * async handleAnyMessage(message: Message) {
25
+ * console.log(`Received a message: ${message.content}`);
26
+ * }
27
+ * ```
28
+ */ function MessageHandler(keyword) {
29
+ return function(target, propertyKey, _descriptor) {
30
+ const handlers = Reflect.getMetadata(MESSAGE_HANDLER_METADATA_KEY, target) || [];
31
+ handlers.push({
32
+ keyword,
33
+ method: propertyKey.toString()
34
+ });
35
+ Reflect.defineMetadata(MESSAGE_HANDLER_METADATA_KEY, handlers, target);
36
+ };
37
+ }
38
+ /**
39
+ * Decorator to register reaction handlers in the controller.
40
+ *
41
+ * @param emoji - Optional emoji name to filter reactions this handler should respond to.
42
+ *
43
+ * @example
44
+ * ```typescript
45
+ * @ReactionHandler('👍')
46
+ * async handleThumbsUpReaction(reaction: MessageReaction, { user }: ReactionHandlerOptions) {
47
+ * console.log(`User ${user.username} reacted with 👍`);
48
+ * }
49
+ *
50
+ * @ReactionHandler()
51
+ * async handleAnyReaction(reaction: MessageReaction, { user }: ReactionHandlerOptions) {
52
+ * console.log(`User ${user.username} reacted with ${reaction.emoji.name}`);
53
+ * }
54
+ * ```
55
+ */ function ReactionHandler(emoji) {
56
+ return function(target, propertyKey, _descriptor) {
57
+ const handlers = Reflect.getMetadata(REACTION_HANDLER_METADATA_KEY, target) || [];
58
+ handlers.push({
59
+ emoji,
60
+ method: propertyKey.toString()
61
+ });
62
+ Reflect.defineMetadata(REACTION_HANDLER_METADATA_KEY, handlers, target);
63
+ };
64
+ }
65
+ /**
66
+ * Retrieves reaction handlers metadata from a given controller.
67
+ *
68
+ * @param controller - The controller class instance.
69
+ * @returns An array of reaction handler metadata objects.
70
+ */ function getReactionHandlers(controller) {
71
+ return Reflect.getMetadata(REACTION_HANDLER_METADATA_KEY, controller) || [];
72
+ }
73
+ /**
74
+ * Retrieves message handlers metadata from a given controller.
75
+ *
76
+ * @param controller - The controller class instance.
77
+ * @returns An array of message handler method names.
78
+ */ function getMessageHandlers(controller) {
79
+ return Reflect.getMetadata(MESSAGE_HANDLER_METADATA_KEY, controller) || [];
80
+ }
81
+ /**
82
+ * Helper function to create regex and parameter mappings from a pattern string.
83
+ *
84
+ * @param pattern - The pattern string to parse.
85
+ * @returns An object containing the generated regex and parameter names.
86
+ */ function createRegexFromPattern(pattern) {
87
+ const params = [];
88
+ // Escape special characters except for {} and -
89
+ const escapedPattern = pattern.replace(/[/\\^$*+?.()|[\]]/g, '\\$&') // Removed hyphen `-` from this list
90
+ ;
91
+ // Replace placeholders with named capturing groups
92
+ const regexPattern = escapedPattern.replace(/\{(\w+)}/g, (_, param)=>{
93
+ if (!/^\w+$/.test(param)) {
94
+ throw new Error(`Invalid parameter name: ${param}. Parameter names must be alphanumeric.`);
95
+ }
96
+ params.push(param);
97
+ return `(?<${param}>[a-zA-Z0-9]+)`;
98
+ });
99
+ // Construct the final regex
100
+ const regex = new RegExp(`^${regexPattern}$`);
101
+ return {
102
+ regex,
103
+ params
104
+ };
105
+ }
106
+ /**
107
+ * Decorator to register command methods in a controller.
108
+ *
109
+ * @param commandName - The name or pattern of the command.
110
+ * @param builderOrType - A command builder class or a command type from `CommandType`.
111
+ *
112
+ * @example
113
+ * ```typescript
114
+ * @Command('help', CommandType.SLASH)
115
+ * public async handleHelp(interaction: ChatInputCommandInteraction) {
116
+ * await interaction.reply('This is the help command!')
117
+ * }
118
+ *
119
+ * @Command('stats-{id}', CommandType.BUTTON)
120
+ * public async handleStats(message: ButtonInteraction, { id }) {
121
+ * await message.reply(`Fetching stats for ID: ${id}`);
122
+ * }
123
+ * ```
124
+ */ function Command(commandName, builderOrType) {
125
+ return function(target, propertyKey, _descriptor) {
126
+ const originalMethod = _descriptor.value;
127
+ if (!originalMethod) {
128
+ throw new Error(`Missing implementation for method ${propertyKey}`);
129
+ }
130
+ // Wrap original method for interaction type validation
131
+ _descriptor.value = function(interaction, params) {
132
+ const expectedInteraction = commandType === enum_index.CommandType.BUTTON && interaction instanceof discord_js.ButtonInteraction || commandType === enum_index.CommandType.SELECT_MENU && interaction instanceof discord_js.StringSelectMenuInteraction || commandType === enum_index.CommandType.SLASH && interaction instanceof discord_js.ChatInputCommandInteraction || commandType === enum_index.CommandType.CONTEXT_MENU && interaction instanceof discord_js.ContextMenuCommandInteraction || commandType === enum_index.CommandType.MODAL_SUBMIT && interaction instanceof discord_js.ModalSubmitInteraction;
133
+ if (!expectedInteraction) {
134
+ throw new Error(`Invalid interaction type passed to @Command for method: ${propertyKey}`);
135
+ }
136
+ return originalMethod.apply(this, [
137
+ interaction,
138
+ params
139
+ ]);
140
+ };
141
+ // Retrieve existing metadata or initialize it
142
+ const commands = Reflect.getMetadata(COMMAND_METADATA_KEY, target) || {};
143
+ let builderInstance;
144
+ let commandType;
145
+ let regex;
146
+ let dynamicParams = [];
147
+ // Determine command type and builder
148
+ if (typeof builderOrType === 'function') {
149
+ const builderObj = new builderOrType();
150
+ builderInstance = builderObj.build(commandName);
151
+ commandType = Reflect.getMetadata(enum_index.MetadataKey.CommandType, builderOrType);
152
+ if (!(commandType in enum_index.CommandType)) {
153
+ throw new Error(`Metadata for 'commandType' is missing on builder ${builderOrType.name}`);
154
+ }
155
+ } else {
156
+ commandType = builderOrType;
157
+ }
158
+ if (commandType !== enum_index.CommandType.SLASH && commandType !== enum_index.CommandType.CONTEXT_MENU) {
159
+ const { regex: generatedRegex, params } = createRegexFromPattern(commandName);
160
+ regex = generatedRegex;
161
+ dynamicParams = params;
162
+ }
163
+ // Ensure commandName supports multiple entries
164
+ if (!commands[commandName]) {
165
+ commands[commandName] = [];
166
+ }
167
+ commands[commandName].push({
168
+ methodName: propertyKey,
169
+ builder: builderInstance,
170
+ type: commandType,
171
+ regex,
172
+ dynamicParams
173
+ });
174
+ Reflect.defineMetadata(COMMAND_METADATA_KEY, commands, target);
175
+ };
176
+ }
177
+ /**
178
+ * Retrieves the command map for a given controller.
179
+ *
180
+ * @param controller - The controller class instance.
181
+ * @returns A record containing command metadata indexed by command names.
182
+ */ function getCommandMap(controller) {
183
+ return Reflect.getMetadata(COMMAND_METADATA_KEY, controller);
184
+ }
185
+ /**
186
+ * Decorator to mark a class as a controller that can later be registered to the App class `(app.ts)` using the `@MeoCord` decorator.
187
+ *
188
+ * @example
189
+ * ```typescript
190
+ * @Controller()
191
+ * export class PingSlashController {
192
+ * constructor(private pingService: PingService) {}
193
+ *
194
+ * @Command('ping', PingCommandBuilder)
195
+ * async ping(interaction: ChatInputCommandInteraction) {
196
+ * const response = await this.pingService.handlePing()
197
+ * await interaction.reply(response)
198
+ * }
199
+ * }
200
+ * ```
201
+ */ function Controller() {
202
+ return function(target) {
203
+ if (!Reflect.hasMetadata(enum_index.MetadataKey.Injectable, target)) {
204
+ inversify.injectable()(target);
205
+ }
206
+ };
207
+ }
208
+
209
+ exports.Command = Command;
210
+ exports.Controller = Controller;
211
+ exports.MessageHandler = MessageHandler;
212
+ exports.ReactionHandler = ReactionHandler;
213
+ exports.getCommandMap = getCommandMap;
214
+ exports.getMessageHandlers = getMessageHandlers;
215
+ exports.getReactionHandlers = getReactionHandlers;
@@ -10,7 +10,57 @@ require('fs');
10
10
  require('jiti');
11
11
  require('chalk');
12
12
 
13
-
13
+ /**
14
+ * MeoCord Framework
15
+ * Copyright (c) 2025 Ukasyah Rahmatullah Zada
16
+ * SPDX-License-Identifier: MIT
17
+ */ /**
18
+ * Composes multiple class or method decorators into a single decorator.
19
+ *
20
+ * @example
21
+ * ```typescript
22
+ * export const Protected = () => applyDecorators(
23
+ * UseGuard(DefaultGuard, GlobalRateLimiterGuard),
24
+ * )
25
+ *
26
+ * @Controller()
27
+ * @Protected()
28
+ * export class PingController {}
29
+ * ```
30
+ */ function applyDecorators(...decorators) {
31
+ return function(target, propertyKey, descriptor) {
32
+ for (const decorator of decorators){
33
+ if (propertyKey !== undefined && descriptor !== undefined) {
34
+ decorator(target, propertyKey, descriptor);
35
+ } else {
36
+ decorator(target);
37
+ }
38
+ }
39
+ return descriptor;
40
+ };
41
+ }
42
+ /**
43
+ * Attaches arbitrary metadata to a class or method. Use alongside `Reflect.getMetadata` to read it back.
44
+ *
45
+ * @example
46
+ * ```typescript
47
+ * export const Roles = (...roles: string[]) => SetMetadata('roles', roles)
48
+ *
49
+ * @Command('admin', CommandType.SLASH)
50
+ * @Roles('admin', 'moderator')
51
+ * async adminCommand(interaction: ChatInputCommandInteraction) {}
52
+ * ```
53
+ */ function SetMetadata(metadataKey, metadataValue) {
54
+ return function(target, propertyKey) {
55
+ if (propertyKey !== undefined) {
56
+ Reflect.defineMetadata(metadataKey, metadataValue, target, propertyKey);
57
+ } else {
58
+ Reflect.defineMetadata(metadataKey, metadataValue, target);
59
+ }
60
+ };
61
+ }
14
62
 
15
63
  exports.Logger = theme.Logger;
16
64
  exports.Theme = theme.Theme;
65
+ exports.SetMetadata = SetMetadata;
66
+ exports.applyDecorators = applyDecorators;