mirror of
https://github.com/sern-handler/handler
synced 2026-06-06 01:16:55 +00:00
Compare commits
21 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2106522812 | ||
|
|
ce8c4bf649 | ||
|
|
e89b918390 | ||
|
|
f8b69ae542 | ||
|
|
48f9f6ec16 | ||
|
|
86ebb221ed | ||
|
|
4efdbb21fb | ||
|
|
07b11b357b | ||
|
|
ac7f47c590 | ||
| 45cbda7b42 | |||
|
|
5cad432589 | ||
|
|
044a10dace | ||
|
|
9d5c6c714f | ||
|
|
4f2387119a | ||
|
|
a6fa4e3dcb | ||
|
|
c281832db2 | ||
|
|
a359f73fa2 | ||
| 655bb8d358 | |||
| e8d5029834 | |||
|
|
b0399f9507 | ||
|
|
b962dae36c |
2
.github/workflows/continuous-integration.yml
vendored
2
.github/workflows/continuous-integration.yml
vendored
@@ -23,7 +23,7 @@ jobs:
|
||||
uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@64ed1c7eab4cce3362f8c340dee64e5eaeef8f7c # v3
|
||||
uses: actions/setup-node@1a4442cacd436585916779262731d5b162bc6ec7 # v3
|
||||
with:
|
||||
node-version: 17
|
||||
|
||||
|
||||
34
.github/workflows/npm-publish-dev.yml
vendored
Normal file
34
.github/workflows/npm-publish-dev.yml
vendored
Normal file
@@ -0,0 +1,34 @@
|
||||
name: Continuous Delivery
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- 'src/**'
|
||||
- 'package.json'
|
||||
|
||||
jobs:
|
||||
Publish:
|
||||
name: Publishing Dev
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Check out Git repository
|
||||
uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@64ed1c7eab4cce3362f8c340dee64e5eaeef8f7c # v3
|
||||
with:
|
||||
node-version: 18
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
|
||||
- name: Install Node.js dependencies
|
||||
run: npm i && npm run build:dev
|
||||
|
||||
- name: Publish to npm
|
||||
run: |
|
||||
npm version premajor --preid "dev.$(git rev-parse --verify --short HEAD)" --git-tag-version=false
|
||||
npm publish --tag dev
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
2
.github/workflows/npm-publish.yml
vendored
2
.github/workflows/npm-publish.yml
vendored
@@ -11,7 +11,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3
|
||||
- uses: actions/setup-node@5e21ff4d9bc1a8cf6de233a3057d20ec6b3fb69d # v3
|
||||
- uses: actions/setup-node@1a4442cacd436585916779262731d5b162bc6ec7 # v3
|
||||
with:
|
||||
node-version: 17
|
||||
- run: yarn --immutable
|
||||
|
||||
2
.github/workflows/test.yml
vendored
2
.github/workflows/test.yml
vendored
@@ -20,7 +20,7 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3
|
||||
- name: Use Node.js ${{ matrix.node-version }}
|
||||
uses: actions/setup-node@5e21ff4d9bc1a8cf6de233a3057d20ec6b3fb69d # v3
|
||||
uses: actions/setup-node@1a4442cacd436585916779262731d5b162bc6ec7 # v3
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
cache: 'npm'
|
||||
|
||||
28
CHANGELOG.md
28
CHANGELOG.md
@@ -1,5 +1,33 @@
|
||||
# Changelog
|
||||
|
||||
## [3.3.3](https://github.com/sern-handler/handler/compare/v3.3.2...v3.3.3) (2024-02-25)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* rm deprecated class modules, clean up, rm indirection ([#355](https://github.com/sern-handler/handler/issues/355)) ([48f9f6e](https://github.com/sern-handler/handler/commit/48f9f6ec16e650d574bd24dcbb0ed176933bfe17))
|
||||
* singleton init not being fired when inserting function ([07b11b3](https://github.com/sern-handler/handler/commit/07b11b357baac0c3c7055c022bc353995c80f766))
|
||||
* typings and cleanup ([#356](https://github.com/sern-handler/handler/issues/356)) ([ce8c4bf](https://github.com/sern-handler/handler/commit/ce8c4bf6492b9680fb1c1a530d3e0028f214ad2f))
|
||||
|
||||
## [3.3.2](https://github.com/sern-handler/handler/compare/v3.3.1...v3.3.2) (2024-01-08)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* presence feature not working on cjs applications ([#351](https://github.com/sern-handler/handler/issues/351)) ([4f23871](https://github.com/sern-handler/handler/commit/4f2387119acfde036d0d1626553e9050f55627d1))
|
||||
|
||||
## [3.3.1](https://github.com/sern-handler/handler/compare/v3.3.0...v3.3.1) (2024-01-07)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* crashing when slash command is used as text command ([#349](https://github.com/sern-handler/handler/issues/349)) ([a359f73](https://github.com/sern-handler/handler/commit/a359f73fa24127a4964d411c8c1c0dfea5edc0f1))
|
||||
|
||||
|
||||
### Reverts
|
||||
|
||||
* the last commit ([655bb8d](https://github.com/sern-handler/handler/commit/655bb8d35815fe0ce9797d8b169310a07b284ae0))
|
||||
|
||||
## [3.3.0](https://github.com/sern-handler/handler/compare/v3.2.1...v3.3.0) (2023-12-27)
|
||||
|
||||
|
||||
|
||||
23
README.md
23
README.md
@@ -42,26 +42,6 @@ export default commandModule({
|
||||
});
|
||||
```
|
||||
</details>
|
||||
<details><summary>modal.ts</summary>
|
||||
|
||||
```ts
|
||||
export default commandModule({
|
||||
type: CommandType.Modal,
|
||||
//Installed a plugin to make sure modal fields pass a validation.
|
||||
plugins : [
|
||||
assertFields({
|
||||
fields: {
|
||||
name: /^([^0-9]*)$/
|
||||
},
|
||||
failure: (errors, modal) => modal.reply('your submission did not pass the validations')
|
||||
})
|
||||
],
|
||||
execute : (modal) => {
|
||||
modal.reply('thanks for the submission!');
|
||||
}
|
||||
})
|
||||
```
|
||||
</details>
|
||||
|
||||
|
||||
## 🤖 Bots Using sern
|
||||
@@ -72,7 +52,8 @@ export default commandModule({
|
||||
- [Murayama](https://github.com/murayamabot/murayama), :pepega:
|
||||
- [Protector (WIP)](https://github.com/needhamgary/Protector), Just a simple bot to help enhance a private minecraft server.
|
||||
- [SmokinWeed 💨](https://github.com/Peter-MJ-Parker/sern-bud), A fun bot for a small - but growing - server.
|
||||
|
||||
- [Man Nomic](https://github.com/jacoobes/man-nomic), A simple information bot to provide information to the nomic-ai discord community.
|
||||
- [Linear-Discord](https://github.com/sern-handler/linear-discord) Display and manage a linear dashboard.
|
||||
## 💻 CLI
|
||||
|
||||
It is **highly encouraged** to use the [command line interface](https://github.com/sern-handler/cli) for your project. Don't forget to view it.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@sern/handler",
|
||||
"packageManager": "yarn@3.5.0",
|
||||
"version": "3.3.0",
|
||||
"version": "3.3.3",
|
||||
"description": "A complete, customizable, typesafe, & reactive framework for discord bots.",
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.mjs",
|
||||
@@ -48,7 +48,6 @@
|
||||
"@typescript-eslint/eslint-plugin": "5.58.0",
|
||||
"@typescript-eslint/parser": "5.59.1",
|
||||
"discord.js": "^14.11.0",
|
||||
"esbuild": "^0.17.0",
|
||||
"eslint": "8.39.0",
|
||||
"prettier": "2.8.8",
|
||||
"tsup": "^6.7.0",
|
||||
@@ -95,5 +94,8 @@
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/sern-handler/handler.git"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 18.16.x"
|
||||
},
|
||||
"homepage": "https://sern.dev"
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
export * as Id from './id';
|
||||
export * from './operators';
|
||||
export * from './predicates';
|
||||
export * as Files from './module-loading';
|
||||
export * from './functions';
|
||||
export type { VoidResult } from '../types/core-plugin';
|
||||
export { SernError } from './structures/enums';
|
||||
export { ModuleStore } from './structures/module-store';
|
||||
export * as DefaultServices from './structures/services';
|
||||
export { useContainerRaw } from './ioc/base'
|
||||
export * as __Services from './structures/services';
|
||||
export { useContainerRaw } from './ioc/base';
|
||||
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
import type { Awaitable } from '../../types/utility';
|
||||
|
||||
/**
|
||||
* Represents a Disposable contract.
|
||||
* Let dependencies implement this to dispose and cleanup.
|
||||
*/
|
||||
export interface Disposable {
|
||||
dispose(): Awaitable<unknown>;
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
//i deleted it, hmm so how should we allow users to enable localization?
|
||||
// a
|
||||
import type { AnyFunction } from '../../types/utility';
|
||||
|
||||
export interface Emitter {
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import type { CommandModule,Processed, EventModule } from "../../types/core-modules";
|
||||
|
||||
/**
|
||||
* @since 2.0.0
|
||||
*/
|
||||
|
||||
16
src/core/contracts/hooks.ts
Normal file
16
src/core/contracts/hooks.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
|
||||
/**
|
||||
* Represents an initialization contract.
|
||||
* Let dependencies implement this to initiate some logic.
|
||||
*/
|
||||
export interface Init {
|
||||
init(): unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents a Disposable contract.
|
||||
* Let dependencies implement this to dispose and cleanup.
|
||||
*/
|
||||
export interface Disposable {
|
||||
dispose(): unknown;
|
||||
}
|
||||
@@ -2,6 +2,5 @@ export * from './error-handling';
|
||||
export * from './logging';
|
||||
export * from './module-manager';
|
||||
export * from './module-store';
|
||||
export * from './init';
|
||||
export * from './hooks';
|
||||
export * from './emitter';
|
||||
export * from './disposable'
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
import type { Awaitable } from '../../types/utility';
|
||||
|
||||
/**
|
||||
* Represents an initialization contract.
|
||||
* Let dependencies implement this to initiate some logic.
|
||||
*/
|
||||
export interface Init {
|
||||
init(): Awaitable<unknown>;
|
||||
}
|
||||
@@ -16,12 +16,19 @@ interface MetadataAccess {
|
||||
* @internal - direct access to the module manager will be removed in version 4
|
||||
*/
|
||||
export interface ModuleManager extends MetadataAccess {
|
||||
get(id: string): string | undefined;
|
||||
get(id: string): Module | undefined;
|
||||
|
||||
set(id: string, path: string): void;
|
||||
getPublishableCommands(): Promise<CommandModule[]>;
|
||||
set(id: string, path: Module): void;
|
||||
/**
|
||||
* @deprecated
|
||||
*/
|
||||
getPublishableCommands(): CommandModule[];
|
||||
|
||||
/*
|
||||
* @deprecated
|
||||
*/
|
||||
getByNameCommandType<T extends CommandType>(
|
||||
name: string,
|
||||
commandType: T,
|
||||
): Promise<CommandModuleDefs[T]> | undefined;
|
||||
): CommandModuleDefs[T] | undefined;
|
||||
}
|
||||
|
||||
@@ -4,6 +4,6 @@ import type { CommandMeta, Module } from '../../types/core-modules';
|
||||
* Represents a core module store that stores IDs mapped to file paths.
|
||||
*/
|
||||
export interface CoreModuleStore {
|
||||
commands: Map<string, string>;
|
||||
commands: Map<string, Module>;
|
||||
metadata: WeakMap<Module, CommandMeta>;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { CommandType, EventType, PluginType } from './structures';
|
||||
import type { Plugin, PluginResult, EventArgs, CommandArgs } from '../types/core-plugin';
|
||||
import type { ClientEvents } from 'discord.js';
|
||||
import { err, ok } from './functions';
|
||||
|
||||
export function makePlugin<V extends unknown[]>(
|
||||
type: PluginType,
|
||||
@@ -60,3 +61,12 @@ export function DiscordEventControlPlugin<T extends keyof ClientEvents>(
|
||||
) {
|
||||
return makePlugin(PluginType.Control, execute);
|
||||
}
|
||||
|
||||
/**
|
||||
* @since 1.0.0
|
||||
* The object passed into every plugin to control a command's behavior
|
||||
*/
|
||||
export const controller = {
|
||||
next: ok,
|
||||
stop: err,
|
||||
};
|
||||
|
||||
@@ -1,9 +1,19 @@
|
||||
import { Err, Ok } from 'ts-results-es';
|
||||
import { ApplicationCommandOptionType, AutocompleteInteraction } from 'discord.js';
|
||||
import type { SernAutocompleteData, SernOptionsData } from '../types/core-modules';
|
||||
import type { Module, SernAutocompleteData, SernOptionsData } from '../types/core-modules';
|
||||
import type { AnyCommandPlugin, AnyEventPlugin, Plugin } from '../types/core-plugin';
|
||||
import { PluginType } from './structures';
|
||||
import type {
|
||||
AnySelectMenuInteraction,
|
||||
ButtonInteraction,
|
||||
ChatInputCommandInteraction,
|
||||
MessageContextMenuCommandInteraction,
|
||||
ModalSubmitInteraction,
|
||||
UserContextMenuCommandInteraction,
|
||||
AutocompleteInteraction
|
||||
} from 'discord.js';
|
||||
import { ApplicationCommandOptionType, InteractionType } from 'discord.js';
|
||||
import { PayloadType, PluginType } from './structures';
|
||||
import assert from 'assert';
|
||||
import type { Payload } from '../types/utility';
|
||||
|
||||
//function wrappers for empty ok / err
|
||||
export const ok = /* @__PURE__*/ () => Ok.EMPTY;
|
||||
@@ -40,7 +50,7 @@ export function treeSearch(
|
||||
if (options === undefined) return undefined;
|
||||
//clone to prevent mutation of original command module
|
||||
const _options = options.map(a => ({ ...a }));
|
||||
let subcommands = new Set();
|
||||
const subcommands = new Set();
|
||||
while (_options.length > 0) {
|
||||
const cur = _options.pop()!;
|
||||
switch (cur.type) {
|
||||
@@ -61,7 +71,7 @@ export function treeSearch(
|
||||
const choice = iAutocomplete.options.getFocused(true);
|
||||
assert(
|
||||
'command' in cur,
|
||||
'No command property found for autocomplete option',
|
||||
'No `command` property found for autocomplete option',
|
||||
);
|
||||
if (subcommands.size > 0) {
|
||||
const parent = iAutocomplete.options.getSubcommand();
|
||||
@@ -81,3 +91,33 @@ export function treeSearch(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
interface InteractionTypable {
|
||||
type: InteractionType;
|
||||
}
|
||||
//discord.js pls fix ur typings or i will >:(
|
||||
type AnyMessageComponentInteraction = AnySelectMenuInteraction | ButtonInteraction;
|
||||
type AnyCommandInteraction =
|
||||
| ChatInputCommandInteraction
|
||||
| MessageContextMenuCommandInteraction
|
||||
| UserContextMenuCommandInteraction;
|
||||
|
||||
export function isMessageComponent(i: InteractionTypable): i is AnyMessageComponentInteraction {
|
||||
return i.type === InteractionType.MessageComponent;
|
||||
}
|
||||
export function isCommand(i: InteractionTypable): i is AnyCommandInteraction {
|
||||
return i.type === InteractionType.ApplicationCommand;
|
||||
}
|
||||
export function isAutocomplete(i: InteractionTypable): i is AutocompleteInteraction {
|
||||
return i.type === InteractionType.ApplicationCommandAutocomplete;
|
||||
}
|
||||
|
||||
export function isModal(i: InteractionTypable): i is ModalSubmitInteraction {
|
||||
return i.type === InteractionType.ModalSubmit;
|
||||
}
|
||||
|
||||
export function resultPayload<T extends PayloadType>
|
||||
(type: T, module?: Module, reason?: unknown) {
|
||||
return { type, module, reason } as Payload & { type : T };
|
||||
}
|
||||
|
||||
@@ -4,20 +4,20 @@ import { CommandType, EventType } from './structures';
|
||||
/**
|
||||
* Construct unique ID for a given interaction object.
|
||||
* @param event The interaction object for which to create an ID.
|
||||
* @returns A unique string ID based on the type and properties of the interaction object.
|
||||
* @returns An array of unique string IDs based on the type and properties of the interaction object.
|
||||
*/
|
||||
export function reconstruct<T extends Interaction>(event: T) {
|
||||
switch (event.type) {
|
||||
case InteractionType.MessageComponent: {
|
||||
return `${event.customId}_C${event.componentType}`;
|
||||
return [`${event.customId}_C${event.componentType}`];
|
||||
}
|
||||
case InteractionType.ApplicationCommand:
|
||||
case InteractionType.ApplicationCommandAutocomplete: {
|
||||
return `${event.commandName}_A${event.commandType}`;
|
||||
return [`${event.commandName}_A${event.commandType}`, `${event.commandName}_B`];
|
||||
}
|
||||
//Modal interactions are classified as components for sern
|
||||
case InteractionType.ModalSubmit: {
|
||||
return `${event.customId}_C1`;
|
||||
return [`${event.customId}_M`];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -27,37 +27,39 @@ export function reconstruct<T extends Interaction>(event: T) {
|
||||
*/
|
||||
const appBitField = 0b000000001111;
|
||||
|
||||
// Each index represents the exponent of a CommandType.
|
||||
// Every CommandType is a power of two.
|
||||
export const CommandTypeDiscordApi = [
|
||||
1, // CommandType.Text
|
||||
ApplicationCommandType.ChatInput,
|
||||
ApplicationCommandType.User,
|
||||
ApplicationCommandType.Message,
|
||||
ComponentType.Button,
|
||||
ComponentType.StringSelect,
|
||||
1, // CommandType.Modal
|
||||
ComponentType.UserSelect,
|
||||
ComponentType.RoleSelect,
|
||||
ComponentType.MentionableSelect,
|
||||
ComponentType.ChannelSelect,
|
||||
];
|
||||
/*
|
||||
* Generates a number based on CommandType.
|
||||
* This corresponds to an ApplicationCommandType or ComponentType
|
||||
* TextCommands are 0 as they aren't either or.
|
||||
*/
|
||||
function apiType(t: CommandType | EventType) {
|
||||
if (t === CommandType.Both || t === CommandType.Modal) return 1;
|
||||
return CommandTypeDiscordApi[Math.log2(t)];
|
||||
}
|
||||
|
||||
const TypeMap = new Map<number, number>([
|
||||
[CommandType.Text, 0],
|
||||
[CommandType.Both, 0],
|
||||
[CommandType.Slash, ApplicationCommandType.ChatInput],
|
||||
[CommandType.CtxUser, ApplicationCommandType.User],
|
||||
[CommandType.CtxMsg, ApplicationCommandType.Message],
|
||||
[CommandType.Button, ComponentType.Button],
|
||||
[CommandType.Modal, InteractionType.ModalSubmit],
|
||||
[CommandType.StringSelect, ComponentType.StringSelect],
|
||||
[CommandType.UserSelect, ComponentType.UserSelect],
|
||||
[CommandType.MentionableSelect, ComponentType.MentionableSelect],
|
||||
[CommandType.RoleSelect, ComponentType.RoleSelect],
|
||||
[CommandType.ChannelSelect, ComponentType.ChannelSelect]]);
|
||||
|
||||
/*
|
||||
* Generates an id based on name and CommandType.
|
||||
* A is for any ApplicationCommand. C is for any ComponentCommand
|
||||
* Then, another number generated by apiType function is appended
|
||||
* Then, another number fetched from TypeMap
|
||||
*/
|
||||
export function create(name: string, type: CommandType | EventType) {
|
||||
if(type == CommandType.Text) {
|
||||
return `${name}_T`;
|
||||
}
|
||||
if(type == CommandType.Both) {
|
||||
return `${name}_B`;
|
||||
}
|
||||
if(type == CommandType.Modal) {
|
||||
return `${name}_M`;
|
||||
}
|
||||
const am = (appBitField & type) !== 0 ? 'A' : 'C';
|
||||
return name + '_' + am + apiType(type);
|
||||
return `${name}_${am}${TypeMap.get(type)!}`
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,18 +1,40 @@
|
||||
import * as assert from 'assert';
|
||||
import { composeRoot, useContainer } from './dependency-injection';
|
||||
import type { DependencyConfiguration } from '../../types/ioc';
|
||||
import { useContainer } from './dependency-injection';
|
||||
import type { CoreDependencies, DependencyConfiguration } from '../../types/ioc';
|
||||
import { CoreContainer } from './container';
|
||||
import { Result } from 'ts-results-es'
|
||||
import { DefaultServices } from '../_internal';
|
||||
import { Result } from 'ts-results-es';
|
||||
import { __Services } from '../_internal';
|
||||
import { AnyFunction } from '../../types/utility';
|
||||
import type { Logging } from '../contracts/logging';
|
||||
import type { UnpackFunction } from 'iti';
|
||||
//SIDE EFFECT: GLOBAL DI
|
||||
let containerSubject: CoreContainer<Partial<Dependencies>>;
|
||||
|
||||
/**
|
||||
* @deprecated
|
||||
* @internal
|
||||
* Don't use this unless you know what you're doing. Destroys old containerSubject if it exists and disposes everything
|
||||
* then it will swap
|
||||
*/
|
||||
export async function __swap_container(c: CoreContainer<Partial<Dependencies>>) {
|
||||
if(containerSubject) {
|
||||
await containerSubject.disposeAll()
|
||||
}
|
||||
containerSubject = c;
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
* Don't use this unless you know what you're doing. Destroys old containerSubject if it exists and disposes everything
|
||||
* then it will swap
|
||||
*/
|
||||
export function __add_container(key: string,v : Insertable) {
|
||||
containerSubject.add({ [key]: v });
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the underlying data structure holding all dependencies.
|
||||
* Exposes methods from iti
|
||||
* Use the Service API. The container should be readonly
|
||||
* Use the Service API. The container should be readonly from the consumer side
|
||||
*/
|
||||
export function useContainerRaw() {
|
||||
assert.ok(
|
||||
@@ -22,19 +44,32 @@ export function useContainerRaw() {
|
||||
return containerSubject;
|
||||
}
|
||||
|
||||
const dependencyBuilder = (container: any, excluded: string[]) => {
|
||||
type Insertable =
|
||||
| ((container: CoreContainer<Dependencies>) => unknown )
|
||||
| Record<PropertyKey, unknown>
|
||||
export function disposeAll(logger: Logging|undefined) {
|
||||
containerSubject
|
||||
?.disposeAll()
|
||||
.then(() => logger?.info({ message: 'Cleaning container and crashing' }));
|
||||
}
|
||||
type UnpackedDependencies = {
|
||||
[K in keyof Dependencies]: UnpackFunction<Dependencies[K]>
|
||||
}
|
||||
type Insertable =
|
||||
| ((container: UnpackedDependencies) => unknown)
|
||||
| object
|
||||
const dependencyBuilder = (container: any, excluded: string[] ) => {
|
||||
return {
|
||||
/**
|
||||
* Insert a dependency into your container.
|
||||
* Supply the correct key and dependency
|
||||
*/
|
||||
add(key: keyof Dependencies, v: Insertable) {
|
||||
Result
|
||||
.wrap(() => container.add({ [key]: v}))
|
||||
.expect("Failed to add " + key);
|
||||
if(typeof v !== 'function') {
|
||||
Result.wrap(() => container.add({ [key]: v}))
|
||||
.expect("Failed to add " + key);
|
||||
} else {
|
||||
Result.wrap(() =>
|
||||
container.add((cntr: UnpackedDependencies) => ({ [key]: v(cntr)} )))
|
||||
.expect("Failed to add " + key);
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Exclude any dependencies from being added.
|
||||
@@ -43,15 +78,21 @@ const dependencyBuilder = (container: any, excluded: string[]) => {
|
||||
exclude(...keys: (keyof Dependencies)[]) {
|
||||
keys.forEach(key => excluded.push(key));
|
||||
},
|
||||
|
||||
/**
|
||||
* @param key the key of the dependency
|
||||
* @param v The dependency to swap out.
|
||||
* Swap out a preexisting dependency.
|
||||
*/
|
||||
swap(key: keyof Dependencies, v: Insertable) {
|
||||
Result
|
||||
.wrap(() => container.upsert({ [key]: v }))
|
||||
.expect("Failed to update " + key);
|
||||
if(typeof v !== 'function') {
|
||||
Result.wrap(() => container.upsert({ [key]: v}))
|
||||
.expect("Failed to update " + key);
|
||||
} else {
|
||||
Result.wrap(() =>
|
||||
container.upsert((cntr: UnpackedDependencies) => ({ [key]: v(cntr)})))
|
||||
.expect("Failed to update " + key);
|
||||
}
|
||||
},
|
||||
/**
|
||||
* @param key the key of the dependency
|
||||
@@ -63,35 +104,58 @@ const dependencyBuilder = (container: any, excluded: string[]) => {
|
||||
* Swap out a preexisting dependency.
|
||||
*/
|
||||
addDisposer(key: keyof Dependencies, cleanup: AnyFunction) {
|
||||
Result
|
||||
.wrap(() => container.addDisposer({ [key] : cleanup }))
|
||||
.expect("Failed to addDisposer for" + key);
|
||||
Result.wrap(() => container.addDisposer({ [key] : cleanup }))
|
||||
.expect("Failed to addDisposer for" + key);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
type CallbackBuilder = (c: ReturnType<typeof dependencyBuilder>) => any
|
||||
|
||||
type ValidDependencyConfig =
|
||||
| CallbackBuilder
|
||||
| ((c: ReturnType<typeof dependencyBuilder>) => any)
|
||||
| DependencyConfiguration;
|
||||
|
||||
export const insertLogger = (containerSubject: CoreContainer<any>) => {
|
||||
containerSubject
|
||||
.upsert({'@sern/logger': () => new DefaultServices.DefaultLogging});
|
||||
|
||||
/**
|
||||
* Given the user's conf, check for any excluded/included dependency keys.
|
||||
* Then, call conf.build to get the rest of the users' dependencies.
|
||||
* Finally, update the containerSubject with the new container state
|
||||
* @param conf
|
||||
*/
|
||||
function composeRoot(
|
||||
container: CoreContainer<Partial<Dependencies>>,
|
||||
conf: DependencyConfiguration,
|
||||
) {
|
||||
//container should have no client or logger yet.
|
||||
const hasLogger = conf.exclude?.has('@sern/logger');
|
||||
if (!hasLogger) {
|
||||
__add_container('@sern/logger', new __Services.DefaultLogging);
|
||||
}
|
||||
//Build the container based on the callback provided by the user
|
||||
conf.build(container as CoreContainer<Omit<CoreDependencies, '@sern/client'>>);
|
||||
|
||||
if (!hasLogger) {
|
||||
container.get('@sern/logger')?.info({ message: 'All dependencies loaded successfully.' });
|
||||
}
|
||||
|
||||
container.ready();
|
||||
}
|
||||
|
||||
export async function makeDependencies<const T extends Dependencies>
|
||||
(conf: ValidDependencyConfig) {
|
||||
//Until there are more optional dependencies, just check if the logger exists
|
||||
//SIDE EFFECT
|
||||
containerSubject = new CoreContainer();
|
||||
if(typeof conf === 'function') {
|
||||
const excluded: string[] = [];
|
||||
conf(dependencyBuilder(containerSubject, excluded));
|
||||
if(!excluded.includes('@sern/logger')
|
||||
&& !containerSubject.getTokens()['@sern/logger']) {
|
||||
insertLogger(containerSubject);
|
||||
//We only include logger if it does not exist
|
||||
const includeLogger =
|
||||
!excluded.includes('@sern/logger')
|
||||
&& !containerSubject.hasKey('@sern/logger');
|
||||
|
||||
if(includeLogger) {
|
||||
__add_container('@sern/logger', new __Services.DefaultLogging);
|
||||
}
|
||||
|
||||
containerSubject.ready();
|
||||
} else {
|
||||
composeRoot(containerSubject, conf);
|
||||
@@ -100,5 +164,3 @@ export async function makeDependencies<const T extends Dependencies>
|
||||
return useContainer<T>();
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { Container } from 'iti';
|
||||
import { Disposable, SernEmitter } from '../';
|
||||
import { Disposable } from '../';
|
||||
import * as assert from 'node:assert';
|
||||
import { Subject } from 'rxjs';
|
||||
import { DefaultServices, ModuleStore } from '../_internal';
|
||||
import * as Hooks from './hooks'
|
||||
import { __Services, ModuleStore } from '../_internal';
|
||||
import * as Hooks from './hooks';
|
||||
import { EventEmitter } from 'node:events';
|
||||
|
||||
|
||||
/**
|
||||
@@ -17,36 +18,39 @@ export class CoreContainer<T extends Partial<Dependencies>> extends Container<T,
|
||||
assert.ok(!this.isReady(), 'Listening for dispose & init should occur prior to sern being ready.');
|
||||
|
||||
const { unsubscribe } = Hooks.createInitListener(this);
|
||||
|
||||
this.ready$
|
||||
.subscribe({ complete: unsubscribe });
|
||||
|
||||
(this as Container<{}, {}>)
|
||||
.add({ '@sern/errors': () => new DefaultServices.DefaultErrorHandling(),
|
||||
'@sern/emitter': () => new SernEmitter(),
|
||||
'@sern/store': () => new ModuleStore() })
|
||||
.add({ '@sern/errors': () => new __Services.DefaultErrorHandling,
|
||||
'@sern/emitter': () => new EventEmitter({ captureRejections: true }),
|
||||
'@sern/store': () => new ModuleStore })
|
||||
.add(ctx => {
|
||||
return {
|
||||
'@sern/modules': () =>
|
||||
new DefaultServices.DefaultModuleManager(ctx['@sern/store']),
|
||||
};
|
||||
return { '@sern/modules': new __Services.DefaultModuleManager(ctx['@sern/store'])};
|
||||
});
|
||||
}
|
||||
|
||||
isReady() {
|
||||
return this.ready$.closed;
|
||||
}
|
||||
|
||||
hasKey(key: string): boolean {
|
||||
return Boolean((this as Container<any,any>)._context[key]);
|
||||
}
|
||||
|
||||
override async disposeAll() {
|
||||
|
||||
const otherDisposables = Object
|
||||
.entries(this._context)
|
||||
.flatMap(([key, value]) =>
|
||||
'dispose' in value ? [key] : []);
|
||||
|
||||
for(const key of otherDisposables) {
|
||||
otherDisposables.forEach(key => {
|
||||
//possible source of bug: dispose is a property.
|
||||
this.addDisposer({ [key]: (dep: Disposable) => dep.dispose() } as never);
|
||||
}
|
||||
await super.disposeAll()
|
||||
})
|
||||
await super.disposeAll();
|
||||
}
|
||||
|
||||
ready() {
|
||||
this.ready$.complete();
|
||||
this.ready$.unsubscribe();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { CoreDependencies, DependencyConfiguration, IntoDependencies } from '../../types/ioc';
|
||||
import { insertLogger, useContainerRaw } from './base';
|
||||
import { CoreContainer } from './container';
|
||||
import assert from 'node:assert';
|
||||
import type { IntoDependencies } from '../../types/ioc';
|
||||
import { useContainerRaw } from './base';
|
||||
|
||||
/**
|
||||
* @__PURE__
|
||||
@@ -25,6 +25,7 @@ export function transient<T>(cb: () => () => T) {
|
||||
* The new Service api, a cleaner alternative to useContainer
|
||||
* To obtain intellisense, ensure a .d.ts file exists in the root of compilation.
|
||||
* Usually our scaffolding tool takes care of this.
|
||||
* Note: this method only works AFTER your container has been initiated
|
||||
* @since 3.0.0
|
||||
* @example
|
||||
* ```ts
|
||||
@@ -34,7 +35,9 @@ export function transient<T>(cb: () => () => T) {
|
||||
*
|
||||
*/
|
||||
export function Service<const T extends keyof Dependencies>(key: T) {
|
||||
return useContainerRaw().get(key)!;
|
||||
const dep = useContainerRaw().get(key)!;
|
||||
assert(dep, "Requested key " + key + " returned undefined");
|
||||
return dep;
|
||||
}
|
||||
/**
|
||||
* @since 3.0.0
|
||||
@@ -46,32 +49,9 @@ export function Services<const T extends (keyof Dependencies)[]>(...keys: [...T]
|
||||
return keys.map(k => container.get(k)!) as IntoDependencies<T>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Given the user's conf, check for any excluded dependency keys.
|
||||
* Then, call conf.build to get the rest of the users' dependencies.
|
||||
* Finally, update the containerSubject with the new container state
|
||||
* @param conf
|
||||
*/
|
||||
export function composeRoot(
|
||||
container: CoreContainer<Partial<Dependencies>>,
|
||||
conf: DependencyConfiguration,
|
||||
) {
|
||||
//container should have no client or logger yet.
|
||||
const hasLogger = conf.exclude?.has('@sern/logger');
|
||||
if (!hasLogger) {
|
||||
insertLogger(container);
|
||||
}
|
||||
//Build the container based on the callback provided by the user
|
||||
conf.build(container as CoreContainer<Omit<CoreDependencies, '@sern/client'>>);
|
||||
|
||||
if (!hasLogger) {
|
||||
container.get('@sern/logger')?.info({ message: 'All dependencies loaded successfully.' });
|
||||
}
|
||||
|
||||
container.ready();
|
||||
}
|
||||
|
||||
export function useContainer<const T extends Dependencies>() {
|
||||
return <V extends (keyof T)[]>(...keys: [...V]) =>
|
||||
keys.map(key => useContainerRaw().get(key as keyof Dependencies)) as IntoDependencies<V>;
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ type HookName = 'init';
|
||||
export const createInitListener = (coreContainer : CoreContainer<any>) => {
|
||||
const initCalled = new Set<PropertyKey>();
|
||||
const hasCallableMethod = createPredicate(initCalled);
|
||||
const unsubscribe = coreContainer.on('containerUpserted', async (event) => {
|
||||
const unsubscribe = coreContainer.on('containerUpserted', async event => {
|
||||
|
||||
if(isNotHookable(event)) {
|
||||
return;
|
||||
@@ -21,6 +21,7 @@ export const createInitListener = (coreContainer : CoreContainer<any>) => {
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
return { unsubscribe };
|
||||
}
|
||||
|
||||
|
||||
@@ -1,24 +1,24 @@
|
||||
import { Result } from 'ts-results-es';
|
||||
import { type Observable, from, mergeMap, ObservableInput } from 'rxjs';
|
||||
import { readdir, stat } from 'fs/promises';
|
||||
import { basename, extname, join, resolve, parse } from 'path';
|
||||
import { basename, extname, join, resolve, parse, dirname } from 'path';
|
||||
import assert from 'assert';
|
||||
import { createRequire } from 'node:module';
|
||||
import type { ImportPayload, Wrapper } from '../types/core';
|
||||
import type { Module } from '../types/core-modules';
|
||||
import { existsSync } from 'fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import type { Logging } from './contracts/logging';
|
||||
|
||||
export const shouldHandle = (path: string, fpath: string) => {
|
||||
const newPath = new URL(fpath+extname(path), path).href;
|
||||
return {
|
||||
exists: existsSync(fileURLToPath(newPath)),
|
||||
path: newPath
|
||||
}
|
||||
const file_name = fpath+extname(path);
|
||||
let newPath = join(dirname(path), file_name)
|
||||
.replace(/file:\\?/, "");
|
||||
return { exists: existsSync(newPath),
|
||||
path: 'file:///'+newPath };
|
||||
}
|
||||
|
||||
|
||||
export type ModuleResult<T> = Promise<ImportPayload<T>>;
|
||||
|
||||
/**
|
||||
* Import any module based on the absolute path.
|
||||
* This can accept four types of exported modules
|
||||
@@ -41,9 +41,7 @@ export async function importModule<T>(absPath: string) {
|
||||
if ('default' in commandModule ) {
|
||||
commandModule = commandModule.default;
|
||||
}
|
||||
return Result
|
||||
.wrap(() => ({ module: commandModule.getInstance() }))
|
||||
.unwrapOr({ module: commandModule }) as T;
|
||||
return { module: commandModule } as T;
|
||||
}
|
||||
|
||||
export async function defaultModuleLoader<T extends Module>(absPath: string): ModuleResult<T> {
|
||||
@@ -79,11 +77,9 @@ const isSkippable = (filename: string) => {
|
||||
|
||||
async function deriveFileInfo(dir: string, file: string) {
|
||||
const fullPath = join(dir, file);
|
||||
return {
|
||||
fullPath,
|
||||
fileStats: await stat(fullPath),
|
||||
base: basename(file),
|
||||
};
|
||||
return { fullPath,
|
||||
fileStats: await stat(fullPath),
|
||||
base: basename(file) };
|
||||
}
|
||||
|
||||
async function* readPaths(dir: string): AsyncGenerator<string> {
|
||||
@@ -109,11 +105,11 @@ async function* readPaths(dir: string): AsyncGenerator<string> {
|
||||
|
||||
const requir = createRequire(import.meta.url);
|
||||
|
||||
export function loadConfig(wrapper: Wrapper | 'file'): Wrapper {
|
||||
export function loadConfig(wrapper: Wrapper | 'file', log: Logging | undefined): Wrapper {
|
||||
if (wrapper !== 'file') {
|
||||
return wrapper;
|
||||
}
|
||||
console.log('Experimental loading of sern.config.json');
|
||||
log?.info({ message: 'Experimental loading of sern.config.json'});
|
||||
const config = requir(resolve('sern.config.json'));
|
||||
|
||||
const makePath = (dir: PropertyKey) =>
|
||||
@@ -121,21 +117,18 @@ export function loadConfig(wrapper: Wrapper | 'file'): Wrapper {
|
||||
? join('dist', config.paths[dir]!)
|
||||
: join(config.paths[dir]!);
|
||||
|
||||
console.log('Loading config: ', config);
|
||||
log?.info({ message: 'Loading config: ' + JSON.stringify(config, null, 4) });
|
||||
const commandsPath = makePath('commands');
|
||||
|
||||
console.log('Commands path is set to', commandsPath);
|
||||
log?.info({ message: `Commands path is set to ${commandsPath}` });
|
||||
let eventsPath: string | undefined;
|
||||
if (config.paths.events) {
|
||||
eventsPath = makePath('events');
|
||||
console.log('Events path is set to', eventsPath);
|
||||
log?.info({ message: `Events path is set to ${eventsPath} `});
|
||||
}
|
||||
|
||||
|
||||
return {
|
||||
defaultPrefix: config.defaultPrefix,
|
||||
commands: commandsPath,
|
||||
events: eventsPath,
|
||||
};
|
||||
return { defaultPrefix: config.defaultPrefix,
|
||||
commands: commandsPath,
|
||||
events: eventsPath };
|
||||
|
||||
}
|
||||
|
||||
@@ -1,19 +1,13 @@
|
||||
import { ClientEvents } from 'discord.js';
|
||||
import { CommandType, EventType, PluginType } from '../core/structures';
|
||||
import { EventType } from '../core/structures';
|
||||
import type {
|
||||
AnyCommandPlugin,
|
||||
AnyEventPlugin,
|
||||
CommandArgs,
|
||||
ControlPlugin,
|
||||
EventArgs,
|
||||
InitPlugin,
|
||||
} from '../types/core-plugin';
|
||||
import type {
|
||||
CommandModule,
|
||||
EventModule,
|
||||
InputCommand,
|
||||
InputEvent,
|
||||
Module,
|
||||
} from '../types/core-modules';
|
||||
import { partitionPlugins } from './_internal';
|
||||
import type { Awaitable } from '../types/utility';
|
||||
@@ -61,53 +55,3 @@ export function discordEvent<T extends keyof ClientEvents>(mod: {
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @deprecated
|
||||
*/
|
||||
function prepareClassPlugins(c: Module) {
|
||||
const [onEvent, initPlugins] = partitionPlugins(c.plugins);
|
||||
c.plugins = initPlugins as InitPlugin[];
|
||||
c.onEvent = onEvent as ControlPlugin[];
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated
|
||||
* Will be removed in future
|
||||
*/
|
||||
export abstract class CommandExecutable<const Type extends CommandType = CommandType> {
|
||||
abstract type: Type;
|
||||
plugins: AnyCommandPlugin[] = [];
|
||||
private static _instance: CommandModule;
|
||||
|
||||
static getInstance() {
|
||||
if (!CommandExecutable._instance) {
|
||||
//@ts-ignore
|
||||
CommandExecutable._instance = new this();
|
||||
prepareClassPlugins(CommandExecutable._instance);
|
||||
}
|
||||
return CommandExecutable._instance;
|
||||
}
|
||||
|
||||
abstract execute(...args: CommandArgs<Type, PluginType.Control>): Awaitable<unknown>;
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated
|
||||
* Will be removed in future
|
||||
*/
|
||||
export abstract class EventExecutable<Type extends EventType> {
|
||||
abstract type: Type;
|
||||
plugins: AnyEventPlugin[] = [];
|
||||
|
||||
private static _instance: EventModule;
|
||||
static getInstance() {
|
||||
if (!EventExecutable._instance) {
|
||||
//@ts-ignore
|
||||
EventExecutable._instance = new this();
|
||||
prepareClassPlugins(EventExecutable._instance);
|
||||
}
|
||||
return EventExecutable._instance;
|
||||
}
|
||||
abstract execute(...args: EventArgs<Type, PluginType.Control>): Awaitable<unknown>;
|
||||
}
|
||||
|
||||
@@ -28,16 +28,15 @@ export function filterMapTo<V>(item: () => V): OperatorFunction<boolean, V> {
|
||||
return concatMap(shouldKeep => (shouldKeep ? of(item()) : EMPTY));
|
||||
}
|
||||
|
||||
interface PluginExecutable {
|
||||
execute: (...args: unknown[]) => PluginResult;
|
||||
};
|
||||
/**
|
||||
* Calls any plugin with {args}.
|
||||
* @param args if an array, its spread and plugin called.
|
||||
*/
|
||||
export function callPlugin(args: unknown): OperatorFunction<
|
||||
{
|
||||
execute: (...args: unknown[]) => PluginResult;
|
||||
},
|
||||
VoidResult
|
||||
> {
|
||||
export function callPlugin(args: unknown): OperatorFunction<PluginExecutable, VoidResult>
|
||||
{
|
||||
return concatMap(async plugin => {
|
||||
if (Array.isArray(args)) {
|
||||
return plugin.execute(...args);
|
||||
@@ -72,15 +71,12 @@ export function handleError<C>(crashHandler: ErrorHandling, logging?: Logging) {
|
||||
}
|
||||
// Temporary until i get rxjs operators working on ts-results-es
|
||||
export const filterTap = <K, R>(onErr: (e: R) => void): OperatorFunction<Result<K, R>, K> =>
|
||||
pipe(
|
||||
concatMap(result => {
|
||||
pipe(concatMap(result => {
|
||||
if(result.isOk()) {
|
||||
return of(result.value)
|
||||
}
|
||||
onErr(result.error);
|
||||
return EMPTY
|
||||
|
||||
})
|
||||
)
|
||||
}))
|
||||
|
||||
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
import type {
|
||||
AnySelectMenuInteraction,
|
||||
AutocompleteInteraction,
|
||||
ButtonInteraction,
|
||||
ChatInputCommandInteraction,
|
||||
MessageContextMenuCommandInteraction,
|
||||
ModalSubmitInteraction,
|
||||
UserContextMenuCommandInteraction,
|
||||
} from 'discord.js';
|
||||
import { InteractionType } from 'discord.js';
|
||||
|
||||
interface InteractionTypable {
|
||||
type: InteractionType;
|
||||
}
|
||||
//discord.js pls fix ur typings or i will >:(
|
||||
type AnyMessageComponentInteraction = AnySelectMenuInteraction | ButtonInteraction;
|
||||
type AnyCommandInteraction =
|
||||
| ChatInputCommandInteraction
|
||||
| MessageContextMenuCommandInteraction
|
||||
| UserContextMenuCommandInteraction;
|
||||
|
||||
export function isMessageComponent(i: InteractionTypable): i is AnyMessageComponentInteraction {
|
||||
return i.type === InteractionType.MessageComponent;
|
||||
}
|
||||
export function isCommand(i: InteractionTypable): i is AnyCommandInteraction {
|
||||
return i.type === InteractionType.ApplicationCommand;
|
||||
}
|
||||
export function isAutocomplete(i: InteractionTypable): i is AutocompleteInteraction {
|
||||
return i.type === InteractionType.ApplicationCommandAutocomplete;
|
||||
}
|
||||
|
||||
export function isModal(i: InteractionTypable): i is ModalSubmitInteraction {
|
||||
return i.type === InteractionType.ModalSubmit;
|
||||
}
|
||||
@@ -22,13 +22,11 @@ export type Config <T extends (keyof Dependencies)[]> =
|
||||
|
||||
/**
|
||||
* A small wrapper to provide type inference.
|
||||
* Create a Presence module which **MUST** be put in a file called presence.<language-extension>
|
||||
* Create a Presence module which **MUST** be put in a file called presence.(language-extension)
|
||||
* adjacent to the file where **Sern.init** is CALLED.
|
||||
*/
|
||||
export function module<T extends (keyof Dependencies)[]>
|
||||
(conf: Config<T>) {
|
||||
return conf;
|
||||
}
|
||||
export function module<T extends (keyof Dependencies)[]>(conf: Config<T>)
|
||||
{ return conf; }
|
||||
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
import type { ReplyOptions } from "../../types/utility";
|
||||
import type { Logging } from "../contracts";
|
||||
|
||||
export interface Response {
|
||||
type: 'fail' | 'continue';
|
||||
body?: ReplyOptions;
|
||||
log?: { type: keyof Logging; message: unknown }
|
||||
}
|
||||
|
||||
export const of = () => {
|
||||
const payload = {
|
||||
type: 'fail',
|
||||
body: undefined,
|
||||
log : undefined
|
||||
} as Record<PropertyKey, unknown>
|
||||
|
||||
return {
|
||||
/**
|
||||
* @param {'fail' | 'continue'} p a status to determine if the error will
|
||||
* terminate your application or continue. Warning and
|
||||
*/
|
||||
status: (p: 'fail' | 'continue') => {
|
||||
payload.type = p;
|
||||
return payload;
|
||||
},
|
||||
/**
|
||||
* @param {keyof Logging} type Determine to log to logger[type].
|
||||
* @param {T} message the message to log
|
||||
*
|
||||
* Log this error with the logger.
|
||||
*/
|
||||
log: <T=string>(type: keyof Logging, message: T) => {
|
||||
payload.log = { type, message };
|
||||
return payload;
|
||||
},
|
||||
reply: (bodyContent: ReplyOptions) => {
|
||||
payload.body = bodyContent;
|
||||
return payload;
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import {
|
||||
import type {
|
||||
BaseInteraction,
|
||||
ChatInputCommandInteraction,
|
||||
Client,
|
||||
@@ -114,7 +114,7 @@ export class Context extends CoreContext<Message, ChatInputCommandInteraction> {
|
||||
if ('interaction' in wrappable) {
|
||||
return new Context(Ok(wrappable));
|
||||
}
|
||||
assert.ok(wrappable.isChatInputCommand());
|
||||
assert.ok(wrappable.isChatInputCommand(), "Context created with bad interaction.");
|
||||
return new Context(Err(wrappable));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import * as assert from 'node:assert';
|
||||
*/
|
||||
export abstract class CoreContext<M, I> {
|
||||
protected constructor(protected ctx: Either<M, I>) {
|
||||
assert.ok(typeof ctx === 'object' && ctx != null);
|
||||
assert.ok(typeof ctx === 'object' && ctx != null, "Context was nonobject or null");
|
||||
}
|
||||
get message(): M {
|
||||
return this.ctx.expect(SernError.MismatchEvent);
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
export { CommandType, PluginType, PayloadType, EventType } from './enums';
|
||||
export * from './context';
|
||||
export * from './sern-emitter';
|
||||
export * from './services';
|
||||
export * from './module-store';
|
||||
export * as CommandError from './command-error';
|
||||
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
import { CommandMeta, Module } from '../../types/core-modules';
|
||||
import { CoreModuleStore } from '../contracts';
|
||||
|
||||
/*
|
||||
* @internal
|
||||
* @deprecated
|
||||
* Version 4.0.0 will internalize this api. Please refrain from using ModuleStore!
|
||||
* For interacting with modules, use the ModuleManager instead.
|
||||
*/
|
||||
export class ModuleStore implements CoreModuleStore {
|
||||
export class ModuleStore {
|
||||
metadata = new WeakMap<Module, CommandMeta>();
|
||||
commands = new Map<string, string>();
|
||||
commands = new Map<string, Module>();
|
||||
}
|
||||
|
||||
@@ -1,89 +0,0 @@
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { PayloadType } from '../../core/structures';
|
||||
import { Module } from '../../types/core-modules';
|
||||
import { SernEventsMapping, Payload } from '../../types/utility';
|
||||
|
||||
/**
|
||||
* @since 1.0.0
|
||||
*/
|
||||
export class SernEmitter extends EventEmitter {
|
||||
constructor() {
|
||||
super({ captureRejections: true });
|
||||
}
|
||||
/**
|
||||
* Listening to sern events with on. This event stays on until a crash or a normal exit
|
||||
* @param eventName
|
||||
* @param listener what to do with the data
|
||||
*/
|
||||
public override on<T extends keyof SernEventsMapping>(
|
||||
eventName: T,
|
||||
listener: (...args: SernEventsMapping[T][]) => void,
|
||||
): this {
|
||||
return super.on(eventName, listener);
|
||||
}
|
||||
/**
|
||||
* Listening to sern events with on. This event stays on until a crash or a normal exit
|
||||
* @param eventName
|
||||
* @param listener what to do with the data
|
||||
*/
|
||||
public override once<T extends keyof SernEventsMapping>(
|
||||
eventName: T,
|
||||
listener: (...args: SernEventsMapping[T][]) => void,
|
||||
): this {
|
||||
return super.once(eventName, listener);
|
||||
}
|
||||
/**
|
||||
* Listening to sern events with on. This event stays on until a crash or a normal exit
|
||||
* @param eventName
|
||||
* @param args the arguments for emitting the eventName
|
||||
*/
|
||||
public override emit<T extends keyof SernEventsMapping>(
|
||||
eventName: T,
|
||||
...args: SernEventsMapping[T]
|
||||
): boolean {
|
||||
return super.emit(eventName, ...args);
|
||||
}
|
||||
private static payload<T extends Payload>(
|
||||
type: PayloadType,
|
||||
module?: Module,
|
||||
reason?: unknown,
|
||||
) {
|
||||
return { type, module, reason } as T;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a compliant SernEmitter failure payload
|
||||
* @param module
|
||||
* @param reason
|
||||
*/
|
||||
static failure(module?: Module, reason?: unknown) {
|
||||
//The generic cast Payload & { type : PayloadType.* } coerces the type to be a failure payload
|
||||
// same goes to the other methods below
|
||||
return SernEmitter.payload<Payload & { type: PayloadType.Failure }>(
|
||||
PayloadType.Failure,
|
||||
module,
|
||||
reason,
|
||||
);
|
||||
}
|
||||
/**
|
||||
* Creates a compliant SernEmitter module success payload
|
||||
* @param module
|
||||
*/
|
||||
static success(module: Module) {
|
||||
return SernEmitter.payload<Payload & { type: PayloadType.Success }>(
|
||||
PayloadType.Success,
|
||||
module,
|
||||
);
|
||||
}
|
||||
/**
|
||||
* Creates a compliant SernEmitter module warning payload
|
||||
* @param reason
|
||||
*/
|
||||
static warning(reason: unknown) {
|
||||
return SernEmitter.payload<Payload & { type: PayloadType.Warning }>(
|
||||
PayloadType.Warning,
|
||||
undefined,
|
||||
reason,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
import * as Id from '../../../core/id';
|
||||
import { CoreModuleStore, ModuleManager } from '../../contracts';
|
||||
import { Files } from '../../_internal';
|
||||
import { CommandMeta, CommandModule, CommandModuleDefs, Module } from '../../../types/core-modules';
|
||||
import { CommandType } from '../enums';
|
||||
/**
|
||||
@@ -13,11 +12,11 @@ export class DefaultModuleManager implements ModuleManager {
|
||||
|
||||
|
||||
getByNameCommandType<T extends CommandType>(name: string, commandType: T) {
|
||||
const id = this.get(Id.create(name, commandType));
|
||||
if (!id) {
|
||||
const module = this.get(Id.create(name, commandType));
|
||||
if (!module) {
|
||||
return undefined;
|
||||
}
|
||||
return Files.importModule<CommandModuleDefs[T]>(id);
|
||||
return module as CommandModuleDefs[T];
|
||||
}
|
||||
|
||||
setMetadata(m: Module, c: CommandMeta): void {
|
||||
@@ -35,17 +34,18 @@ export class DefaultModuleManager implements ModuleManager {
|
||||
get(id: string) {
|
||||
return this.moduleStore.commands.get(id);
|
||||
}
|
||||
set(id: string, path: string): void {
|
||||
set(id: string, path: CommandModule): void {
|
||||
this.moduleStore.commands.set(id, path);
|
||||
}
|
||||
//not tested
|
||||
getPublishableCommands(): Promise<CommandModule[]> {
|
||||
getPublishableCommands(): CommandModule[] {
|
||||
const entries = this.moduleStore.commands.entries();
|
||||
const publishable = 0b000000110;
|
||||
return Promise.all(
|
||||
Array.from(entries)
|
||||
.filter(([id]) => !(Number.parseInt(id.at(-1)!) & publishable))
|
||||
.map(([, path]) => Files.importModule<CommandModule>(path)),
|
||||
);
|
||||
return Array.from(entries)
|
||||
.filter(([id]) => {
|
||||
const last_entry = id.at(-1);
|
||||
return last_entry == 'B' || !(publishable & Number.parseInt(last_entry!));
|
||||
})
|
||||
.map(([, path]) => path as CommandModule);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,15 +11,13 @@ import {
|
||||
import { createResultResolver } from './event-utils';
|
||||
import { BaseInteraction, Message } from 'discord.js';
|
||||
import { CommandType, Context } from '../core';
|
||||
import type { AnyFunction, Args } from '../types/utility';
|
||||
import type { Args } from '../types/utility';
|
||||
import { inspect } from 'node:util'
|
||||
import type { CommandModule, Module, Processed } from '../types/core-modules';
|
||||
|
||||
//TODO: refactor dispatchers so that it implements a strategy for each different type of payload?
|
||||
export function dispatchMessage(module: Processed<CommandModule>, args: [Context, Args]) {
|
||||
return {
|
||||
module,
|
||||
args,
|
||||
};
|
||||
return { module, args };
|
||||
}
|
||||
|
||||
export function contextArgs(wrappable: Message | BaseInteraction, messageArgs?: string[]) {
|
||||
@@ -75,11 +73,8 @@ export function createDispatcher(payload: {
|
||||
case CommandType.Both: {
|
||||
if (isAutocomplete(payload.event)) {
|
||||
const option = treeSearch(payload.event, payload.module.options);
|
||||
assert.ok(
|
||||
option,
|
||||
Error(SernError.NotSupportedInteraction + ` There is no autocomplete tag for this option`),
|
||||
);
|
||||
const { command, name, parent } = option;
|
||||
assert.ok(option, SernError.NotSupportedInteraction + ` There is no autocomplete tag for ` + inspect(payload.module));
|
||||
const { command } = option;
|
||||
|
||||
return {
|
||||
...payload,
|
||||
@@ -87,14 +82,8 @@ export function createDispatcher(payload: {
|
||||
args: [payload.event],
|
||||
};
|
||||
}
|
||||
return {
|
||||
module: payload.module,
|
||||
args: contextArgs(payload.event),
|
||||
};
|
||||
return { module: payload.module, args: contextArgs(payload.event) };
|
||||
}
|
||||
default: return {
|
||||
module: payload.module,
|
||||
args: [payload.event],
|
||||
};
|
||||
default: return { module: payload.module, args: [payload.event] };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,9 +8,9 @@ import {
|
||||
of,
|
||||
throwError,
|
||||
tap,
|
||||
MonoTypeOperatorFunction,
|
||||
catchError,
|
||||
finalize,
|
||||
map,
|
||||
} from 'rxjs';
|
||||
import {
|
||||
Files,
|
||||
@@ -21,17 +21,16 @@ import {
|
||||
handleError,
|
||||
SernError,
|
||||
VoidResult,
|
||||
useContainerRaw,
|
||||
resultPayload,
|
||||
} from '../core/_internal';
|
||||
import { Emitter, ErrorHandling, Logging, ModuleManager } from '../core';
|
||||
import { Emitter, ErrorHandling, Logging, ModuleManager, PayloadType } from '../core';
|
||||
import { contextArgs, createDispatcher } from './dispatchers';
|
||||
import { ObservableInput, pipe } from 'rxjs';
|
||||
import { SernEmitter } from '../core';
|
||||
import { Err, Ok, Result } from 'ts-results-es';
|
||||
import type { AnyFunction, Awaitable } from '../types/utility';
|
||||
import type { Awaitable } from '../types/utility';
|
||||
import type { ControlPlugin } from '../types/core-plugin';
|
||||
import type { AnyModule, CommandModule, Module, Processed } from '../types/core-modules';
|
||||
import type { ImportPayload } from '../types/core';
|
||||
import type { AnyModule, CommandMeta, CommandModule, Module, Processed } from '../types/core-modules';
|
||||
import { disposeAll } from '../core/ioc/base';
|
||||
|
||||
function createGenericHandler<Source, Narrowed extends Source, Output>(
|
||||
source: Observable<Source>,
|
||||
@@ -71,19 +70,17 @@ export function createInteractionHandler<T extends Interaction>(
|
||||
return createGenericHandler<Interaction, T, Result<ReturnType<typeof createDispatcher>, void>>(
|
||||
source,
|
||||
async event => {
|
||||
const fullPath = mg.get(Id.reconstruct(event));
|
||||
if(!fullPath) {
|
||||
return Err.EMPTY
|
||||
const possibleIds = Id.reconstruct(event);
|
||||
let fullPaths= possibleIds
|
||||
.map(id => mg.get(id))
|
||||
.filter((id): id is Module => id !== undefined);
|
||||
|
||||
if(fullPaths.length == 0) {
|
||||
return Err.EMPTY;
|
||||
}
|
||||
return Files
|
||||
.defaultModuleLoader<Processed<CommandModule>>(fullPath)
|
||||
.then(payload =>
|
||||
Ok(createDispatcher({
|
||||
module: payload.module,
|
||||
event,
|
||||
})));
|
||||
},
|
||||
);
|
||||
const [ path ] = fullPaths;
|
||||
return Ok(createDispatcher({ module: path as Processed<CommandModule>, event }));
|
||||
});
|
||||
}
|
||||
|
||||
export function createMessageHandler(
|
||||
@@ -93,45 +90,44 @@ export function createMessageHandler(
|
||||
) {
|
||||
return createGenericHandler(source, async event => {
|
||||
const [prefix, ...rest] = fmt(event.content, defaultPrefix);
|
||||
const fullPath = mg.get(`${prefix}_A1`);
|
||||
|
||||
let fullPath = mg.get(`${prefix}_T`);
|
||||
if(!fullPath) {
|
||||
return Err('Possibly undefined behavior: could not find a static id to resolve')
|
||||
fullPath = mg.get(`${prefix}_B`);
|
||||
if(!fullPath) {
|
||||
return Err('Possibly undefined behavior: could not find a static id to resolve');
|
||||
}
|
||||
}
|
||||
return Files
|
||||
.defaultModuleLoader<Processed<CommandModule>>(fullPath)
|
||||
.then((payload)=> {
|
||||
const args = contextArgs(event, rest);
|
||||
return Ok({ args, ...payload });
|
||||
|
||||
});
|
||||
return Ok({ args: contextArgs(event, rest), module: fullPath as Processed<CommandModule> })
|
||||
});
|
||||
}
|
||||
/**
|
||||
* IMPURE SIDE EFFECT
|
||||
* This function assigns remaining, incomplete data to each imported module.
|
||||
*/
|
||||
function assignDefaults<T extends Module>(
|
||||
moduleManager: ModuleManager,
|
||||
): MonoTypeOperatorFunction<ImportPayload<T>> {
|
||||
return tap(({ module, absPath }) => {
|
||||
module.name ??= Files.filename(absPath);
|
||||
module.description ??= '...';
|
||||
moduleManager.setMetadata(module, {
|
||||
isClass: module.constructor.name === 'Function',
|
||||
fullPath: absPath,
|
||||
id: Id.create(module.name, module.type),
|
||||
});
|
||||
function assignDefaults() {
|
||||
return map(({ module, absPath }) => {
|
||||
const processed = {
|
||||
name: module.name ?? Files.filename(absPath),
|
||||
description: module.description ?? '...',
|
||||
...module
|
||||
}
|
||||
return {
|
||||
module: processed,
|
||||
absPath,
|
||||
metadata: {
|
||||
isClass: module.constructor.name === 'Function',
|
||||
fullPath: absPath,
|
||||
id: Id.create(processed.name, module.type),
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function buildModules<T extends AnyModule>(
|
||||
input: ObservableInput<string>,
|
||||
moduleManager: ModuleManager,
|
||||
) {
|
||||
return Files
|
||||
.buildModuleStream<Processed<T>>(input)
|
||||
.pipe(assignDefaults(moduleManager));
|
||||
.pipe(assignDefaults());
|
||||
}
|
||||
|
||||
|
||||
@@ -163,15 +159,17 @@ export function executeModule(
|
||||
concatMap(() => Result.wrapAsync(async () => task())),
|
||||
concatMap(result => {
|
||||
if (result.isOk()) {
|
||||
emitter.emit('module.activate', SernEmitter.success(module));
|
||||
emitter.emit('module.activate', resultPayload(PayloadType.Success, module));
|
||||
return EMPTY;
|
||||
}
|
||||
return throwError(() => SernEmitter.failure(module, result.error));
|
||||
return throwError(() => resultPayload(PayloadType.Failure, module, result.error));
|
||||
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* A higher order function that
|
||||
* - creates a stream of {@link VoidResult} { config.createStream }
|
||||
@@ -211,14 +209,11 @@ export function callInitPlugins<T extends Processed<AnyModule>>(sernEmitter: Emi
|
||||
createResultResolver({
|
||||
createStream: args => from(args.module.plugins).pipe(callPlugin(args)),
|
||||
onStop: (module: T) => {
|
||||
sernEmitter.emit(
|
||||
'module.register',
|
||||
SernEmitter.failure(module, SernError.PluginFailure),
|
||||
);
|
||||
sernEmitter.emit('module.register', resultPayload(PayloadType.Failure, module, SernError.PluginFailure));
|
||||
},
|
||||
onNext: ({ module }) => {
|
||||
sernEmitter.emit('module.register', SernEmitter.success(module));
|
||||
return { module };
|
||||
onNext: (payload) => {
|
||||
sernEmitter.emit('module.register', resultPayload(PayloadType.Success, payload.module));
|
||||
return payload as { module: T; metadata: CommandMeta };
|
||||
},
|
||||
}),
|
||||
);
|
||||
@@ -258,8 +253,5 @@ export const handleCrash = (err: ErrorHandling, log?: Logging) =>
|
||||
log?.info({
|
||||
message: 'A stream closed or reached end of lifetime',
|
||||
});
|
||||
useContainerRaw()
|
||||
?.disposeAll()
|
||||
.then(() => log?.info({ message: 'Cleaning container and crashing' }));
|
||||
}),
|
||||
);
|
||||
disposeAll(log);
|
||||
}));
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Interaction } from 'discord.js';
|
||||
import { mergeMap, merge } from 'rxjs';
|
||||
import { SernEmitter } from '../core';
|
||||
import { PayloadType } from '../core';
|
||||
import {
|
||||
isAutocomplete,
|
||||
isCommand,
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
sharedEventStream,
|
||||
SernError,
|
||||
filterTap,
|
||||
resultPayload,
|
||||
} from '../core/_internal';
|
||||
import { createInteractionHandler, executeModule, makeModuleExecutor } from './_internal';
|
||||
import type { DependencyList } from '../types/ioc';
|
||||
@@ -25,9 +26,8 @@ export function interactionHandler([emitter, err, log, modules, client]: Depende
|
||||
);
|
||||
return interactionHandler$
|
||||
.pipe(
|
||||
filterTap(e => emitter.emit('warning', SernEmitter.warning(e))),
|
||||
filterTap(e => emitter.emit('warning', resultPayload(PayloadType.Warning, undefined, e))),
|
||||
makeModuleExecutor(module =>
|
||||
emitter.emit('module.activate', SernEmitter.failure(module, SernError.PluginFailure))),
|
||||
mergeMap(payload => executeModule(emitter, log, err, payload)),
|
||||
);
|
||||
emitter.emit('module.activate', resultPayload(PayloadType.Failure, module, SernError.PluginFailure))),
|
||||
mergeMap(payload => executeModule(emitter, log, err, payload)));
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { mergeMap, EMPTY } from 'rxjs';
|
||||
import type { Message } from 'discord.js';
|
||||
import { SernEmitter } from '../core';
|
||||
import { sharedEventStream, SernError, filterTap } from '../core/_internal';
|
||||
import { PayloadType } from '../core';
|
||||
import { sharedEventStream, SernError, filterTap, resultPayload } from '../core/_internal';
|
||||
import { createMessageHandler, executeModule, makeModuleExecutor } from './_internal';
|
||||
import type { DependencyList } from '../types/ioc';
|
||||
|
||||
@@ -38,10 +38,10 @@ export function messageHandler(
|
||||
const msgCommands$ = handle(isNonBot(defaultPrefix));
|
||||
|
||||
return msgCommands$.pipe(
|
||||
filterTap((e) => emitter.emit('warning', SernEmitter.warning(e))),
|
||||
filterTap((e) => emitter.emit('warning', resultPayload(PayloadType.Warning, undefined, e))),
|
||||
makeModuleExecutor(module => {
|
||||
emitter.emit('module.activate', SernEmitter.failure(module, SernError.PluginFailure));
|
||||
const result = resultPayload(PayloadType.Failure, module, SernError.PluginFailure);
|
||||
emitter.emit('module.activate', result);
|
||||
}),
|
||||
mergeMap(payload => executeModule(emitter, log, err, payload)),
|
||||
);
|
||||
mergeMap(payload => executeModule(emitter, log, err, payload)));
|
||||
}
|
||||
|
||||
@@ -19,7 +19,6 @@ const parseConfig = async (conf: Promise<Presence.Result>) => {
|
||||
.pipe(scan(onRepeat, s),
|
||||
startWith(s));
|
||||
}
|
||||
//take 1?
|
||||
return of(s).pipe(take(1));
|
||||
})
|
||||
};
|
||||
@@ -37,10 +36,10 @@ export const presenceHandler = (path: string, setPresence: SetPresence) => {
|
||||
})
|
||||
const module$ = from(presence);
|
||||
return module$.pipe(
|
||||
//compose:.
|
||||
//compose:
|
||||
//call the execute function, passing that result into parseConfig.
|
||||
//concatMap resolves the promise, and passes it to the next concatMap.
|
||||
concatMap(fn => parseConfig(fn())),
|
||||
// subscribe to the observable parseConfig yields, and set the presence.
|
||||
concatMap(conf => conf.pipe(map(setPresence))))
|
||||
concatMap(conf => conf.pipe(map(setPresence))));
|
||||
}
|
||||
|
||||
@@ -1,29 +1,31 @@
|
||||
import { ObservableInput, concat, first, fromEvent, ignoreElements, pipe } from 'rxjs';
|
||||
import { ObservableInput, concat, first, fromEvent, ignoreElements, pipe, tap } from 'rxjs';
|
||||
import { CommandType } from '../core/structures';
|
||||
import { SernError } from '../core/_internal';
|
||||
import { Result } from 'ts-results-es';
|
||||
import { ModuleManager } from '../core/contracts';
|
||||
import { Logging, ModuleManager } from '../core/contracts';
|
||||
import { buildModules, callInitPlugins } from './_internal';
|
||||
import * as assert from 'node:assert';
|
||||
import * as util from 'node:util';
|
||||
import type { DependencyList } from '../types/ioc';
|
||||
import type { AnyModule, Processed } from '../types/core-modules';
|
||||
import type { AnyModule, CommandMeta, Processed } from '../types/core-modules';
|
||||
|
||||
export function startReadyEvent(
|
||||
[sEmitter, , , moduleManager, client]: DependencyList,
|
||||
export function readyHandler(
|
||||
[sEmitter, , log , moduleManager, client]: DependencyList,
|
||||
allPaths: ObservableInput<string>,
|
||||
) {
|
||||
const ready$ = fromEvent(client!, 'ready').pipe(once());
|
||||
|
||||
return concat(ready$, buildModules<AnyModule>(allPaths, moduleManager))
|
||||
//Todo: add module manager on on ready
|
||||
const ready$ = fromEvent(client!, 'ready').pipe(once(log));
|
||||
|
||||
return concat(ready$, buildModules<AnyModule>(allPaths))
|
||||
.pipe(callInitPlugins(sEmitter))
|
||||
.subscribe(({ module }) => {
|
||||
register(moduleManager, module)
|
||||
.subscribe(({ module, metadata }) => {
|
||||
register(moduleManager, module, metadata)
|
||||
.expect(SernError.InvalidModuleType + ' ' + util.inspect(module));
|
||||
});
|
||||
}
|
||||
|
||||
const once = () => pipe(
|
||||
const once = (log: Logging | undefined) => pipe(
|
||||
tap(() => { log?.info({ message: "Waiting on discord client to be ready..." }) }),
|
||||
first(),
|
||||
ignoreElements())
|
||||
|
||||
@@ -31,16 +33,22 @@ const once = () => pipe(
|
||||
function register<T extends Processed<AnyModule>>(
|
||||
manager: ModuleManager,
|
||||
module: T,
|
||||
metadata:CommandMeta
|
||||
): Result<void, void> {
|
||||
const { id, fullPath } = manager.getMetadata(module)!;
|
||||
manager.setMetadata(module, metadata)!;
|
||||
|
||||
const validModuleType = module.type >= 0 && module.type <= 1 << 10;
|
||||
assert.ok(
|
||||
validModuleType,
|
||||
`Found ${module.name} at ${fullPath}, which does not have a valid type`,
|
||||
//@ts-ignore
|
||||
`Found ${module.name} at ${metadata.fullPath}, which does not have a valid type`,
|
||||
);
|
||||
if (module.type === CommandType.Both || module.type === CommandType.Text) {
|
||||
module.alias?.forEach(a => manager.set(`${a}_A1`, fullPath));
|
||||
if (module.type === CommandType.Both) {
|
||||
module.alias?.forEach(a => manager.set(`${a}_B`, module));
|
||||
} else {
|
||||
if(module.type === CommandType.Text){
|
||||
module.alias?.forEach(a => manager.set(`${a}_T`, module));
|
||||
}
|
||||
}
|
||||
return Result.wrap(() => manager.set(id, fullPath));
|
||||
return Result.wrap(() => manager.set(metadata.id, module));
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ export function eventsHandler(
|
||||
throw Error(SernError.InvalidModuleType + ' while creating event handler');
|
||||
}
|
||||
};
|
||||
buildModules<EventModule>(allPaths, moduleManager)
|
||||
buildModules<EventModule>(allPaths)
|
||||
.pipe(
|
||||
callInitPlugins(emitter),
|
||||
map(intoDispatcher),
|
||||
|
||||
@@ -46,13 +46,8 @@ export {
|
||||
commandModule,
|
||||
eventModule,
|
||||
discordEvent,
|
||||
EventExecutable,
|
||||
CommandExecutable,
|
||||
} from './core/modules';
|
||||
|
||||
export * as Presence from './core/presences'
|
||||
|
||||
export {
|
||||
useContainerRaw
|
||||
} from './core/_internal'
|
||||
export { controller } from './sern';
|
||||
|
||||
|
||||
38
src/sern.ts
38
src/sern.ts
@@ -1,11 +1,11 @@
|
||||
import { handleCrash } from './handlers/_internal';
|
||||
import callsites from 'callsites';
|
||||
import { err, ok, Files } from './core/_internal';
|
||||
import { Files } from './core/_internal';
|
||||
import { merge } from 'rxjs';
|
||||
import { Services } from './core/ioc';
|
||||
import { Wrapper } from './types/core';
|
||||
import { eventsHandler } from './handlers/user-defined-events';
|
||||
import { startReadyEvent } from './handlers/ready-event';
|
||||
import { readyHandler } from './handlers/ready-event';
|
||||
import { messageHandler } from './handlers/message-event';
|
||||
import { interactionHandler } from './handlers/interaction-event';
|
||||
import { presenceHandler } from './handlers/presence';
|
||||
@@ -23,25 +23,30 @@ import { Client } from 'discord.js';
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
|
||||
export function init(maybeWrapper: Wrapper | 'file') {
|
||||
const startTime = performance.now();
|
||||
const wrapper = Files.loadConfig(maybeWrapper);
|
||||
const dependencies = useDependencies();
|
||||
const dependencies = Services('@sern/emitter',
|
||||
'@sern/errors',
|
||||
'@sern/logger',
|
||||
'@sern/modules',
|
||||
'@sern/client');
|
||||
const logger = dependencies[2],
|
||||
errorHandler = dependencies[1];
|
||||
|
||||
const wrapper = Files.loadConfig(maybeWrapper, logger);
|
||||
if (wrapper.events !== undefined) {
|
||||
eventsHandler(dependencies, Files.getFullPathTree(wrapper.events));
|
||||
}
|
||||
|
||||
const initCallsite = callsites()[1].getFileName();
|
||||
const presencePath = Files.shouldHandle(initCallsite!, "presence");
|
||||
//Ready event: load all modules and when finished, time should be taken and logged
|
||||
startReadyEvent(dependencies, Files.getFullPathTree(wrapper.commands))
|
||||
readyHandler(dependencies, Files.getFullPathTree(wrapper.commands))
|
||||
.add(() => {
|
||||
logger?.info({ message: "Client signaled ready, registering modules" });
|
||||
const time = ((performance.now() - startTime) / 1000).toFixed(2);
|
||||
dependencies[0].emit('modulesLoaded');
|
||||
logger?.info({ message: `sern: registered all modules in ${time} s`, });
|
||||
logger?.info({ message: `sern: registered in ${time} s`, });
|
||||
if(presencePath.exists) {
|
||||
const setPresence = async (p: any) => {
|
||||
return (dependencies[4] as Client).user?.setPresence(p);
|
||||
@@ -55,22 +60,3 @@ export function init(maybeWrapper: Wrapper | 'file') {
|
||||
// listening to the message stream and interaction stream
|
||||
merge(messages$, interactions$).pipe(handleCrash(errorHandler, logger)).subscribe();
|
||||
}
|
||||
|
||||
function useDependencies() {
|
||||
return Services(
|
||||
'@sern/emitter',
|
||||
'@sern/errors',
|
||||
'@sern/logger',
|
||||
'@sern/modules',
|
||||
'@sern/client',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @since 1.0.0
|
||||
* The object passed into every plugin to control a command's behavior
|
||||
*/
|
||||
export const controller = {
|
||||
next: ok,
|
||||
stop: err,
|
||||
};
|
||||
|
||||
@@ -20,7 +20,6 @@ import { AnyCommandPlugin, AnyEventPlugin, ControlPlugin, InitPlugin } from './c
|
||||
import { Awaitable, Args, SlashOptions, SernEventsMapping } from './utility';
|
||||
|
||||
|
||||
|
||||
export interface CommandMeta {
|
||||
fullPath: string;
|
||||
id: string;
|
||||
|
||||
@@ -33,9 +33,9 @@ import type {
|
||||
TextCommand,
|
||||
UserSelectCommand,
|
||||
} from './core-modules';
|
||||
import { Args, Awaitable, Payload, SlashOptions } from './utility';
|
||||
import { CommandType, Context, EventType, PluginType } from '../core';
|
||||
import {
|
||||
import type { Args, Awaitable, Payload, SlashOptions } from './utility';
|
||||
import type { CommandType, Context, EventType, PluginType } from '../core';
|
||||
import type {
|
||||
ButtonInteraction,
|
||||
ChannelSelectMenuInteraction,
|
||||
ClientEvents,
|
||||
|
||||
@@ -26,11 +26,15 @@ export type DependencyList = [
|
||||
|
||||
export interface CoreDependencies {
|
||||
'@sern/client': () => Contracts.Emitter;
|
||||
'@sern/logger'?: () => Contracts.Logging;
|
||||
'@sern/emitter': () => Contracts.Emitter;
|
||||
/**
|
||||
* @deprecated
|
||||
* Will be removed and turned internal
|
||||
*/
|
||||
'@sern/store': () => Contracts.CoreModuleStore;
|
||||
'@sern/modules': () => Contracts.ModuleManager;
|
||||
'@sern/errors': () => Contracts.ErrorHandling;
|
||||
'@sern/logger'?: () => Contracts.Logging;
|
||||
}
|
||||
|
||||
export type DependencyFromKey<T extends keyof Dependencies> = Dependencies[T];
|
||||
@@ -39,8 +43,13 @@ export type IntoDependencies<Tuple extends [...any[]]> = {
|
||||
[Index in keyof Tuple]: UnpackFunction<NonNullable<DependencyFromKey<Tuple[Index]>>>; //Unpack and make NonNullable
|
||||
} & { length: Tuple['length'] };
|
||||
|
||||
/**
|
||||
* @deprecated This old signature will be incompatible with future versions of sern.
|
||||
*/
|
||||
export interface DependencyConfiguration {
|
||||
//@deprecated. Loggers will always be included in the future
|
||||
/*
|
||||
* @deprecated. Loggers will be opt-in the future
|
||||
*/
|
||||
exclude?: Set<'@sern/logger'>;
|
||||
build: (
|
||||
root: Container<Omit<CoreDependencies, '@sern/client'>, {}>,
|
||||
|
||||
@@ -29,5 +29,4 @@ export type Payload =
|
||||
| { type: PayloadType.Warning; reason: string };
|
||||
|
||||
|
||||
|
||||
export type ReplyOptions = string | Omit<InteractionReplyOptions, 'fetchReply'> | MessageReplyOptions;
|
||||
|
||||
64
test/core/id.test.ts
Normal file
64
test/core/id.test.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
import { CommandType } from '../../src/core';
|
||||
import * as Id from '../../src/core/id'
|
||||
import { expect, test } from 'vitest'
|
||||
|
||||
test('id -> Text', () => {
|
||||
const bothCmdId = Id.create("ping", CommandType.Text)
|
||||
expect(bothCmdId).toBe("ping_T")
|
||||
})
|
||||
|
||||
test('id -> Both', () => {
|
||||
const bothCmdId = Id.create("ping", CommandType.Both)
|
||||
expect(bothCmdId).toBe("ping_B")
|
||||
})
|
||||
|
||||
test('id -> CtxMsg', () => {
|
||||
const bothCmdId = Id.create("ping", CommandType.CtxMsg)
|
||||
expect(bothCmdId).toBe("ping_A3")
|
||||
})
|
||||
test('id -> CtxUsr', () => {
|
||||
const bothCmdId = Id.create("ping", CommandType.CtxUser)
|
||||
expect(bothCmdId).toBe("ping_A2")
|
||||
})
|
||||
test('id -> Modal', () => {
|
||||
const modal = Id.create("my-modal", CommandType.Modal)
|
||||
expect(modal).toBe("my-modal_M");
|
||||
})
|
||||
|
||||
test('id -> Button', () => {
|
||||
const modal = Id.create("my-button", CommandType.Button)
|
||||
expect(modal).toBe("my-button_C2");
|
||||
})
|
||||
|
||||
test('id -> Slash', () => {
|
||||
const modal = Id.create("myslash", CommandType.Slash)
|
||||
expect(modal).toBe("myslash_A1");
|
||||
})
|
||||
|
||||
test('id -> StringSelect', () => {
|
||||
const modal = Id.create("mystringselect", CommandType.StringSelect)
|
||||
expect(modal).toBe("mystringselect_C3");
|
||||
})
|
||||
|
||||
test('id -> UserSelect', () => {
|
||||
const modal = Id.create("myuserselect", CommandType.UserSelect)
|
||||
expect(modal).toBe("myuserselect_C5");
|
||||
})
|
||||
|
||||
test('id -> RoleSelect', () => {
|
||||
const modal = Id.create("myroleselect", CommandType.RoleSelect)
|
||||
expect(modal).toBe("myroleselect_C6");
|
||||
})
|
||||
|
||||
test('id -> MentionSelect', () => {
|
||||
const modal = Id.create("mymentionselect", CommandType.MentionableSelect)
|
||||
expect(modal).toBe("mymentionselect_C7");
|
||||
})
|
||||
|
||||
test('id -> ChannelSelect', () => {
|
||||
const modal = Id.create("mychannelselect", CommandType.ChannelSelect)
|
||||
expect(modal).toBe("mychannelselect_C8");
|
||||
})
|
||||
|
||||
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { CoreContainer } from '../../src/core/ioc/container';
|
||||
import { EventEmitter } from 'events';
|
||||
import { DefaultLogging, Disposable, Init, Logging } from '../../src/core';
|
||||
import { DefaultLogging, Disposable, Emitter, Init, Logging } from '../../src/core';
|
||||
import { CoreDependencies } from '../../src/types/ioc';
|
||||
|
||||
describe('ioc container', () => {
|
||||
let container: CoreContainer<{}> = new CoreContainer();
|
||||
let dependency: Logging & Init & Disposable;
|
||||
let dependency2: Emitter
|
||||
beforeEach(() => {
|
||||
dependency = {
|
||||
init: vi.fn(),
|
||||
@@ -16,6 +17,11 @@ describe('ioc container', () => {
|
||||
debug(): void {},
|
||||
dispose: vi.fn()
|
||||
};
|
||||
dependency2 = {
|
||||
addListener: vi.fn(),
|
||||
removeListener: vi.fn(),
|
||||
emit: vi.fn()
|
||||
};
|
||||
container = new CoreContainer();
|
||||
});
|
||||
const wait = (seconds: number) => new Promise((resolve) => setTimeout(resolve, seconds));
|
||||
@@ -83,4 +89,25 @@ describe('ioc container', () => {
|
||||
container.ready();
|
||||
expect(dependency.init).toHaveBeenCalledTimes(0);
|
||||
});
|
||||
|
||||
it('should init dependency depending on something else', () => {
|
||||
container.add({ '@sern/client': dependency2 });
|
||||
container.upsert((cntr) => ({
|
||||
'@sern/logger': dependency
|
||||
}));
|
||||
container.ready();
|
||||
expect(dependency.init).toHaveBeenCalledTimes(1);
|
||||
})
|
||||
|
||||
it('should detect a key already exists', () => {
|
||||
container.add({ '@sern/client': dependency2 });
|
||||
expect(container.hasKey('@sern/client')).toBeTruthy()
|
||||
})
|
||||
|
||||
|
||||
it('should detect a key already exists', () => {
|
||||
container.add({ '@sern/client': () => dependency2 });
|
||||
expect(container.hasKey('@sern/client')).toBeTruthy()
|
||||
})
|
||||
|
||||
});
|
||||
|
||||
@@ -74,4 +74,7 @@ describe('services', () => {
|
||||
expect(consoleMock).toHaveBeenCalledOnce();
|
||||
expect(consoleMock).toHaveBeenLastCalledWith({ message: 'error' });
|
||||
});
|
||||
|
||||
|
||||
|
||||
});
|
||||
|
||||
@@ -2,7 +2,6 @@ import { describe, expect, it, vi } from 'vitest';
|
||||
import * as Id from '../../src/core/id';
|
||||
import { faker } from '@faker-js/faker';
|
||||
import { CommandModule, CommandType, commandModule } from '../../src';
|
||||
import { CommandTypeDiscordApi } from '../../src/core/id';
|
||||
|
||||
function createRandomCommandModules() {
|
||||
const randomCommandType = [
|
||||
@@ -41,32 +40,8 @@ describe('id resolution', () => {
|
||||
const metadata = modules.map(createMetadata);
|
||||
metadata.forEach((meta, idx) => {
|
||||
const associatedModule = modules[idx];
|
||||
const am = (appBitField & associatedModule.type) !== 0 ? 'A' : 'C';
|
||||
let uid = 0;
|
||||
if (
|
||||
associatedModule.type === CommandType.Both ||
|
||||
associatedModule.type === CommandType.Modal
|
||||
) {
|
||||
uid = 1;
|
||||
} else {
|
||||
uid = CommandTypeDiscordApi[Math.log2(associatedModule.type)];
|
||||
}
|
||||
expect(meta.id).toBe(associatedModule.name + '_' + am + uid);
|
||||
const uid = Id.create(associatedModule.name!, associatedModule.type!);
|
||||
expect(meta.id).toBe(uid);
|
||||
});
|
||||
});
|
||||
|
||||
it('maps commands type to discord components or application commands', () => {
|
||||
expect(CommandTypeDiscordApi[Math.log2(CommandType.Text)]).toBe(1);
|
||||
|
||||
expect(CommandTypeDiscordApi[1]).toBe(1);
|
||||
expect(CommandTypeDiscordApi[Math.log2(CommandType.CtxUser)]).toBe(2);
|
||||
expect(CommandTypeDiscordApi[Math.log2(CommandType.CtxMsg)]).toBe(3);
|
||||
expect(CommandTypeDiscordApi[Math.log2(CommandType.Button)]).toBe(2);
|
||||
expect(CommandTypeDiscordApi[Math.log2(CommandType.StringSelect)]).toBe(3);
|
||||
expect(CommandTypeDiscordApi[Math.log2(CommandType.UserSelect)]).toBe(5);
|
||||
expect(CommandTypeDiscordApi[Math.log2(CommandType.RoleSelect)]).toBe(6);
|
||||
expect(CommandTypeDiscordApi[Math.log2(CommandType.MentionableSelect)]).toBe(7);
|
||||
expect(CommandTypeDiscordApi[Math.log2(CommandType.ChannelSelect)]).toBe(8);
|
||||
expect(CommandTypeDiscordApi[6]).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -629,7 +629,6 @@ __metadata:
|
||||
"@typescript-eslint/parser": 5.59.1
|
||||
callsites: ^3.1.0
|
||||
discord.js: ^14.11.0
|
||||
esbuild: ^0.17.0
|
||||
eslint: 8.39.0
|
||||
iti: ^0.6.0
|
||||
prettier: 2.8.8
|
||||
@@ -1449,7 +1448,7 @@ __metadata:
|
||||
languageName: node
|
||||
linkType: hard
|
||||
|
||||
"esbuild@npm:^0.17.0, esbuild@npm:^0.17.6":
|
||||
"esbuild@npm:^0.17.6":
|
||||
version: 0.17.19
|
||||
resolution: "esbuild@npm:0.17.19"
|
||||
dependencies:
|
||||
|
||||
Reference in New Issue
Block a user