Skip to content

Commit

Permalink
fix faiklling test
Browse files Browse the repository at this point in the history
  • Loading branch information
jacoobes committed May 21, 2024
1 parent e0f6a4c commit e700297
Show file tree
Hide file tree
Showing 10 changed files with 152 additions and 246 deletions.
11 changes: 1 addition & 10 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,19 +46,10 @@
"@types/node-cron": "^3.0.11",
"@typescript-eslint/eslint-plugin": "5.58.0",
"@typescript-eslint/parser": "5.59.1",
"discord.js": "^14.11.0",
"discord.js": "^14.x.x",
"eslint": "8.39.0",
"prettier": "2.8.8",
"typescript": "5.0.2"
},
"prettier": {
"semi": true,
"trailingComma": "all",
"singleQuote": true,
"printWidth": 100,
"tabWidth": 4,
"arrowParens": "avoid"
},
"eslintConfig": {
"parser": "@typescript-eslint/parser",
"extends": [
Expand Down
33 changes: 10 additions & 23 deletions src/handlers/event-utils.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,8 @@
import type { Interaction, Message, BaseInteraction } from 'discord.js';
import {
EMPTY,
Observable,
concatMap,
filter,
throwError,
fromEvent,
map,
type OperatorFunction,
catchError,
finalize,
pipe,
from,
EMPTY, type Observable, concatMap, filter,
throwError, fromEvent, map, type OperatorFunction,
catchError, finalize, pipe, from,
} from 'rxjs';
import * as Id from '../core/id'
import type { Emitter } from '../core/interfaces';
Expand Down Expand Up @@ -49,7 +40,7 @@ export function eventDispatcher(deps: Dependencies, module: Module, source: unkn
`${source} cannot be constructed into an event listener`);
const execute: OperatorFunction<unknown[]|undefined, unknown> =
concatMap(async args => {
if(args) return module.execute.apply(null, args);
if(args) return Reflect.apply(module.execute, null, args);
});
//@ts-ignore
return fromEvent(source, module.name!)
Expand Down Expand Up @@ -81,11 +72,7 @@ export function createDispatcher({ module, event, defaultPrefix, deps }: Dispatc
switch (module.type) {
case CommandType.Slash:
case CommandType.Both: {
return {
module,
args: [Context.wrap(event, defaultPrefix)],
deps
};
return { module, args: [Context.wrap(event, defaultPrefix)], deps };
}
default: return { module, args: [event], deps };
}
Expand Down Expand Up @@ -198,7 +185,7 @@ export function executeModule(
* @returns receiver function for flattening a stream of data
*/
export function createResultResolver<Output>(config: {
onStop?: (module: Module) => unknown;
onStop?: (module: Module, err?: string) => unknown;
onNext: (args: ExecutePayload, map: Record<string, unknown>) => Output;
}) {
const { onStop, onNext } = config;
Expand All @@ -207,7 +194,7 @@ export function createResultResolver<Output>(config: {
if(task.isOk()) {
return onNext(payload, task.value) as Output;
} else {
onStop?.(payload.module);
onStop?.(payload.module, String(task.error));
}
};
};
Expand All @@ -231,7 +218,7 @@ export async function callInitPlugins(module: Module, deps: Dependencies, sEmitt
async function callPlugins({ args, module, deps }: ExecutePayload) {
let state = {};
for(const plugin of module.onEvent) {
const result = await plugin.execute(...args, { state, deps });
const result = await plugin.execute(...args, { state, deps, type: module.type === CommandType.Text?'text':'slash' });
if(result.isErr()) {
return result;
}
Expand All @@ -248,10 +235,10 @@ async function callPlugins({ args, module, deps }: ExecutePayload) {
export function intoTask(onStop: (m: Module) => unknown) {
const onNext = ({ args, module, deps }: ExecutePayload, state: Record<string, unknown>) => ({
module,
args: [...args, { state, deps }],
args: [...args, { state, deps, type: module.type === CommandType.Text?'text':'slash' }],
deps
});
return createResultResolver({ onStop, onNext })
return createResultResolver({ onStop, onNext });
}

export const handleCrash =
Expand Down
8 changes: 3 additions & 5 deletions src/handlers/message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,8 @@ function hasPrefix(prefix: string, content: string) {
return prefixInContent.localeCompare(prefix, undefined, { sensitivity: 'accent' }) === 0;
}

export default function (
deps: UnpackedDependencies,
defaultPrefix?: string
) {
export default
function (deps: UnpackedDependencies, defaultPrefix?: string) {
const {"@sern/emitter": emitter,
'@sern/logger': log,
'@sern/client': client} = deps
Expand All @@ -38,7 +36,7 @@ export default function (
const msgCommands$ = handle(isNonBot(defaultPrefix));

return msgCommands$.pipe(
filterTap((e) => emitter.emit('warning', resultPayload(PayloadType.Warning, undefined, e))),
filterTap(e => emitter.emit('warning', resultPayload(PayloadType.Warning, undefined, e))),
concatMap(intoTask(module => {
const result = resultPayload(PayloadType.Failure, module, SernError.PluginFailure);
emitter.emit('module.activate', result);
Expand Down
2 changes: 1 addition & 1 deletion src/handlers/ready.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import * as Files from '../core/module-loading'
import { once } from 'events';
import { resultPayload } from '../core/functions';
import { PayloadType } from '..';
import { CommandType, SernError } from '../core/structures/enums';
import { CommandType } from '../core/structures/enums';
import { Module } from '../types/core-modules';
import { UnpackedDependencies } from '../types/utility';
import { callInitPlugins } from './event-utils';
Expand Down
33 changes: 18 additions & 15 deletions src/types/core-modules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,13 @@ import { Context } from '../core/structures/context'
import { AnyPlugin, ControlPlugin, InitPlugin } from './core-plugin';
import { Awaitable, SernEventsMapping } from './utility';

type ToBeDecided = {
//state, deps, type (very original)
export type SDT = {
state: Record<string,unknown>;
deps: Dependencies
}
deps: Dependencies;
type: 'slash' | 'text'
};

export type Processed<T> = T & { name: string; description: string };

export interface Module {
Expand Down Expand Up @@ -63,47 +66,47 @@ export interface CronEventCommand extends Module {

export interface ContextMenuUser extends Module {
type: CommandType.CtxUser;
execute: (ctx: UserContextMenuCommandInteraction, tbd: ToBeDecided) => Awaitable<unknown>;
execute: (ctx: UserContextMenuCommandInteraction, tbd: SDT) => Awaitable<unknown>;
}

export interface ContextMenuMsg extends Module {
type: CommandType.CtxMsg;
execute: (ctx: MessageContextMenuCommandInteraction, tbd: ToBeDecided) => Awaitable<unknown>;
execute: (ctx: MessageContextMenuCommandInteraction, tbd: SDT) => Awaitable<unknown>;
}

export interface ButtonCommand extends Module {
type: CommandType.Button;
execute: (ctx: ButtonInteraction, tbd: ToBeDecided) => Awaitable<unknown>;
execute: (ctx: ButtonInteraction, tbd: SDT) => Awaitable<unknown>;
}

export interface StringSelectCommand extends Module {
type: CommandType.StringSelect;
execute: (ctx: StringSelectMenuInteraction, tbd: ToBeDecided) => Awaitable<unknown>;
execute: (ctx: StringSelectMenuInteraction, tbd: SDT) => Awaitable<unknown>;
}

export interface ChannelSelectCommand extends Module {
type: CommandType.ChannelSelect;
execute: (ctx: ChannelSelectMenuInteraction, tbd: ToBeDecided) => Awaitable<unknown>;
execute: (ctx: ChannelSelectMenuInteraction, tbd: SDT) => Awaitable<unknown>;
}

export interface RoleSelectCommand extends Module {
type: CommandType.RoleSelect;
execute: (ctx: RoleSelectMenuInteraction, tbd: ToBeDecided) => Awaitable<unknown>;
execute: (ctx: RoleSelectMenuInteraction, tbd: SDT) => Awaitable<unknown>;
}

export interface MentionableSelectCommand extends Module {
type: CommandType.MentionableSelect;
execute: (ctx: MentionableSelectMenuInteraction, tbd: ToBeDecided) => Awaitable<unknown>;
execute: (ctx: MentionableSelectMenuInteraction, tbd: SDT) => Awaitable<unknown>;
}

export interface UserSelectCommand extends Module {
type: CommandType.UserSelect;
execute: (ctx: UserSelectMenuInteraction, tbd: ToBeDecided) => Awaitable<unknown>;
execute: (ctx: UserSelectMenuInteraction, tbd: SDT) => Awaitable<unknown>;
}

export interface ModalSubmitCommand extends Module {
type: CommandType.Modal;
execute: (ctx: ModalSubmitInteraction, tbd: ToBeDecided) => Awaitable<unknown>;
execute: (ctx: ModalSubmitInteraction, tbd: SDT) => Awaitable<unknown>;
}

export interface AutocompleteCommand {
Expand All @@ -119,21 +122,21 @@ export interface DiscordEventCommand<T extends keyof ClientEvents = keyof Client
}
export interface TextCommand extends Module {
type: CommandType.Text;
execute: (ctx: Context, tbd: ToBeDecided) => Awaitable<unknown>;
execute: (ctx: Context, tbd: SDT) => Awaitable<unknown>;
}

export interface SlashCommand extends Module {
type: CommandType.Slash;
description: string;
options?: SernOptionsData[];
execute: (ctx: Context, tbd: ToBeDecided) => Awaitable<unknown>;
execute: (ctx: Context, tbd: SDT) => Awaitable<unknown>;
}

export interface BothCommand extends Module {
type: CommandType.Both;
description: string;
options?: SernOptionsData[];
execute: (ctx: Context, tbd: ToBeDecided) => Awaitable<unknown>;
execute: (ctx: Context, tbd: SDT) => Awaitable<unknown>;
}

export type EventModule = DiscordEventCommand | SernEventCommand | ExternalEventCommand | CronEventCommand;
Expand Down
25 changes: 13 additions & 12 deletions src/types/core-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import type { Err, Ok, Result } from 'ts-results-es';
import type {
Module,
Processed,
SDT,
} from './core-modules';
import type { Awaitable } from './utility';
import type { CommandType, PluginType } from '../core/structures/enums'
Expand Down Expand Up @@ -62,16 +63,16 @@ export type AnyPlugin = ControlPlugin | InitPlugin<[InitArgs<Processed<Module>>]
export type CommandArgs<I extends CommandType = CommandType > = CommandArgsMatrix[I]

interface CommandArgsMatrix {
[CommandType.Text]: [Context];
[CommandType.Slash]: [Context];
[CommandType.Both]: [Context];
[CommandType.CtxMsg]: [MessageContextMenuCommandInteraction];
[CommandType.CtxUser]: [UserContextMenuCommandInteraction];
[CommandType.Button]: [ButtonInteraction];
[CommandType.StringSelect]: [StringSelectMenuInteraction];
[CommandType.RoleSelect]: [RoleSelectMenuInteraction];
[CommandType.ChannelSelect]: [ChannelSelectMenuInteraction];
[CommandType.MentionableSelect]: [MentionableSelectMenuInteraction];
[CommandType.UserSelect]: [UserSelectMenuInteraction];
[CommandType.Modal]: [ModalSubmitInteraction];
[CommandType.Text]: [Context, SDT];
[CommandType.Slash]: [Context, SDT];
[CommandType.Both]: [Context, SDT];
[CommandType.CtxMsg]: [MessageContextMenuCommandInteraction, SDT];
[CommandType.CtxUser]: [UserContextMenuCommandInteraction, SDT];
[CommandType.Button]: [ButtonInteraction, SDT];
[CommandType.StringSelect]: [StringSelectMenuInteraction, SDT];
[CommandType.RoleSelect]: [RoleSelectMenuInteraction, SDT];
[CommandType.ChannelSelect]: [ChannelSelectMenuInteraction, SDT];
[CommandType.MentionableSelect]: [MentionableSelectMenuInteraction, SDT];
[CommandType.UserSelect]: [UserSelectMenuInteraction, SDT];
[CommandType.Modal]: [ModalSubmitInteraction, SDT];
}
1 change: 0 additions & 1 deletion src/types/dependencies.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,5 @@ import { CoreDependencies } from './ioc';

declare global {
interface Dependencies extends CoreDependencies {}

}

5 changes: 0 additions & 5 deletions test/core/create-plugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,12 @@ import { describe, it, expect } from 'vitest';
import {
CommandControlPlugin,
CommandInitPlugin,
EventControlPlugin,
EventInitPlugin,
} from '../../src/core/create-plugins';
import { PluginType, controller } from '../../src';

describe('create-plugins', () => {
it('should make proper control plugins', () => {
const pl = EventControlPlugin(() => controller.next());
expect(pl).to.have.all.keys(['type', 'execute']);
expect(pl.type).toBe(PluginType.Control);
expect(pl.execute).an('function');
const pl2 = CommandControlPlugin(() => controller.next());
expect(pl2).to.have.all.keys(['type', 'execute']);
expect(pl2.type).toBe(PluginType.Control);
Expand Down
27 changes: 9 additions & 18 deletions test/handlers/dispatchers.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { beforeEach, describe, expect, vi, it } from 'vitest';
import { eventDispatcher } from '../../src/handlers/event-utils';
import { faker } from '@faker-js/faker';
import { TestScheduler } from 'rxjs/testing';
import { Module } from '../../src/types/core-modules';
import { Processed } from '../../src/types/core-modules';
import { EventEmitter } from 'events';
Expand All @@ -19,12 +18,13 @@ function createRandomModule(): Processed<Module> {
};
}

const testScheduler = new TestScheduler((actual, expected) => {
// asserting the two objects are equal - required
// for TestScheduler assertions to work via your test framework
// e.g. using chai.
expect(actual).deep.equal(expected);
});
function mockDeps() {
return {
'@sern/client': {}
}
}



describe('eventDispatcher standard', () => {
let m: Processed<Module>;
Expand All @@ -35,19 +35,10 @@ describe('eventDispatcher standard', () => {
});

it('should throw', () => {
expect(() => eventDispatcher(m, 'not event emitter')).toThrowError();
expect(() => eventDispatcher(mockDeps(), m, 'not event emitter')).toThrowError();
});

it("Shouldn't throw", () => {
expect(() => eventDispatcher(m, ee)).not.toThrowError();
expect(() => eventDispatcher(mockDeps(), m, ee)).not.toThrowError();
});
//TODO
// it('Should be called once', () => {
// const s = eventDispatcher(m, ee);
// console.log(m)
// s.subscribe();
// ee.emit(m.name);
// console.log(m.execute)
// expect(m.execute).toHaveBeenCalledOnce();
// });
});
Loading

0 comments on commit e700297

Please sign in to comment.