Skip to content

Commit

Permalink
remove onerror for this pr
Browse files Browse the repository at this point in the history
  • Loading branch information
jacoobes committed Dec 14, 2023
1 parent d28b8e6 commit 2ff48a9
Show file tree
Hide file tree
Showing 13 changed files with 181 additions and 280 deletions.
3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
},
"scripts": {
"watch": "tsup --watch",
"clean-modules": "rimraf node_modules/ && npm install",
"lint": "eslint src/**/*.ts",
"format": "eslint src/**/*.ts --fix",
"build:dev": "tsup --metafile",
Expand Down Expand Up @@ -47,7 +46,7 @@
"@types/node": "^18.15.11",
"@typescript-eslint/eslint-plugin": "5.58.0",
"@typescript-eslint/parser": "5.59.1",
"discord.js": "14.11.0",
"discord.js": "^14.11.0",
"esbuild": "^0.17.0",
"eslint": "8.39.0",
"prettier": "2.8.8",
Expand Down
7 changes: 1 addition & 6 deletions src/core/contracts/module-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import type {
CommandModule,
CommandModuleDefs,
Module,
OnError,
} from '../../types/core-modules';
import { CommandType } from '../structures';

Expand All @@ -12,15 +11,11 @@ interface MetadataAccess {
setMetadata(m: Module, c: CommandMeta): void;
}

interface OnErrorAccess {
getErrorCallback(m: Module): OnError;
setErrorCallback(m: Module, c: NonNullable<OnError>): void;
}
/**
* @since 2.0.0
* @internal - direct access to the module manager will be removed in version 4
*/
export interface ModuleManager extends MetadataAccess, OnErrorAccess {
export interface ModuleManager extends MetadataAccess {
get(id: string): string | undefined;

set(id: string, path: string): void;
Expand Down
3 changes: 1 addition & 2 deletions src/core/contracts/module-store.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import type { CommandMeta, Module, OnError } from '../../types/core-modules';
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>;
metadata: WeakMap<Module, CommandMeta>;
onError: WeakMap<Module, NonNullable<OnError>>;
}
11 changes: 3 additions & 8 deletions src/core/ioc/container.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,9 @@ export class CoreContainer<T extends Partial<Dependencies>> extends Container<T,
.subscribe({ complete: unsubscribe });

(this as Container<{}, {}>)
.add({
'@sern/errors': () => new DefaultServices.DefaultErrorHandling(),
'@sern/emitter': () => new SernEmitter(),
'@sern/store': () => new ModuleStore(),
})
.add({ '@sern/errors': () => new DefaultServices.DefaultErrorHandling(),
'@sern/emitter': () => new SernEmitter(),
'@sern/store': () => new ModuleStore() })
.add(ctx => {
return {
'@sern/modules': () =>
Expand All @@ -36,9 +34,6 @@ export class CoreContainer<T extends Partial<Dependencies>> extends Container<T,

isReady() {
return this.ready$.closed;
}
addExcluded() {

}
override async disposeAll() {

Expand Down
16 changes: 6 additions & 10 deletions src/core/module-loading.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { basename, extname, join, resolve, parse } from 'path';
import assert from 'assert';
import { createRequire } from 'node:module';
import type { ImportPayload, Wrapper } from '../types/core';
import type { Module, OnError } from '../types/core-modules';
import type { Module } from '../types/core-modules';

export type ModuleResult<T> = Promise<ImportPayload<T>>;

Expand All @@ -25,25 +25,21 @@ export type ModuleResult<T> = Promise<ImportPayload<T>>;
export async function importModule<T>(absPath: string) {
let fileModule = await import(absPath);

let commandModule = fileModule.default,
onError = fileModule.onError;
let commandModule = fileModule.default;

assert(commandModule , `Found no export @ ${absPath}. Forgot to ignore with "!"? (!${basename(absPath)})?`);
if ('default' in commandModule ) {
commandModule = commandModule.default;
}
return Result
.wrap(() => ({ module: commandModule.getInstance(), onError }))
.unwrapOr({ module: commandModule, onError }) as T;
}
interface FileExtras {
onError : OnError
.wrap(() => ({ module: commandModule.getInstance() }))
.unwrapOr({ module: commandModule }) as T;
}

export async function defaultModuleLoader<T extends Module>(absPath: string): ModuleResult<T> {
let { onError, module } = await importModule<{ module: T } & FileExtras>(absPath);
let { module } = await importModule<{ module: T }>(absPath);
assert(module, `Found an undefined module: ${absPath}`);
return { module, absPath, onError };
return { module, absPath };
}

export const fmtFileName = (fileName: string) => parse(fileName).name;
Expand Down
3 changes: 1 addition & 2 deletions src/core/structures/module-store.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { CommandMeta, Module, OnError } from '../../types/core-modules';
import { CommandMeta, Module } from '../../types/core-modules';
import { CoreModuleStore } from '../contracts';

/*
Expand All @@ -7,7 +7,6 @@ import { CoreModuleStore } from '../contracts';
* For interacting with modules, use the ModuleManager instead.
*/
export class ModuleStore implements CoreModuleStore {
onError = new WeakMap<Module, NonNullable<OnError>>();
metadata = new WeakMap<Module, CommandMeta>();
commands = new Map<string, string>();
}
9 changes: 1 addition & 8 deletions src/core/structures/services/module-manager.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as Id from '../../../core/id';
import { CoreModuleStore, ModuleManager } from '../../contracts';
import { Files } from '../../_internal';
import { CommandMeta, CommandModule, CommandModuleDefs, Module, OnError } from '../../../types/core-modules';
import { CommandMeta, CommandModule, CommandModuleDefs, Module } from '../../../types/core-modules';
import { CommandType } from '../enums';
/**
* @internal
Expand All @@ -12,13 +12,6 @@ export class DefaultModuleManager implements ModuleManager {
constructor(private moduleStore: CoreModuleStore) {}


getErrorCallback(m: Module): OnError {
return this.moduleStore.onError.get(m);
}
setErrorCallback(m: Module, c: NonNullable<OnError>): void {
this.moduleStore.onError.set(m, c);
}

getByNameCommandType<T extends CommandType>(name: string, commandType: T) {
const id = this.get(Id.create(name, commandType));
if (!id) {
Expand Down
20 changes: 7 additions & 13 deletions src/handlers/dispatchers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ 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 { CommandModule, Module, OnError, Processed } from '../types/core-modules';
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]) {
Expand All @@ -32,16 +32,16 @@ function interactionArg<T extends BaseInteraction>(interaction: T) {
return [interaction] as [T];
}

function intoPayload(module: Processed<Module>, onError: AnyFunction|undefined) {
function intoPayload(module: Processed<Module>, ) {
return pipe(
arrayifySource,
map(args => ({ module, args, onError })),
map(args => ({ module, args, })),
);
}

const createResult = createResultResolver<
Processed<Module>,
{ module: Processed<Module>; args: unknown[], onError: AnyFunction|undefined },
{ module: Processed<Module>; args: unknown[] },
unknown[]
>({
createStream: ({ module, args }) => from(module.onEvent).pipe(callPlugin(args)),
Expand All @@ -52,14 +52,14 @@ const createResult = createResultResolver<
* @param module
* @param source
*/
export function eventDispatcher(module: Processed<Module>, onError: OnError, source: unknown) {
export function eventDispatcher(module: Processed<Module>, source: unknown) {
assert.ok(source instanceof EventEmitter, `${source} is not an EventEmitter`);

const execute: OperatorFunction<unknown[], unknown> = concatMap(async args =>
module.execute(...args),
);
return fromEvent(source, module.name).pipe(
intoPayload(module, onError?.default),
intoPayload(module),
concatMap(createResult),
execute,
);
Expand All @@ -68,7 +68,6 @@ export function eventDispatcher(module: Processed<Module>, onError: OnError, sou
export function createDispatcher(payload: {
module: Processed<CommandModule>;
event: BaseInteraction;
onError: OnError
}) {
assert.ok(
CommandType.Text !== payload.module.type,
Expand All @@ -84,27 +83,22 @@ export function createDispatcher(payload: {
Error(SernError.NotSupportedInteraction + ` There is no autocomplete tag for this option`),
);
const { command, name, parent } = option;
const resolvedErrorHandler = parent
? 'option:'+parent+':'+name
: 'option:'+name

return {
...payload,
module: command as Processed<Module>, //autocomplete is not a true "module" warning cast!
args: [payload.event],
onError: payload.onError?.[resolvedErrorHandler]
};
}
return {
args: contextArgs(payload.event),
...payload,
onError: payload.onError?.default
};
}
default:
return {
args: interactionArg(payload.event),
...payload,
onError: payload.onError?.default
}
}
}
40 changes: 6 additions & 34 deletions src/handlers/event-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import { SernEmitter } from '../core';
import { Err, Ok, Result } from 'ts-results-es';
import type { AnyFunction, Awaitable } from '../types/utility';
import type { ControlPlugin } from '../types/core-plugin';
import type { AnyModule, CommandModule, Module, OnError, Processed } from '../types/core-modules';
import type { AnyModule, CommandModule, Module, Processed } from '../types/core-modules';
import type { ImportPayload } from '../types/core';
import assert from 'node:assert';

Expand Down Expand Up @@ -81,7 +81,6 @@ export function createInteractionHandler<T extends Interaction>(
.then(payload =>
Ok(createDispatcher({
module: payload.module,
onError: payload.onError,
event,
})));
},
Expand All @@ -104,7 +103,7 @@ export function createMessageHandler(
.defaultModuleLoader<Processed<CommandModule>>(fullPath)
.then(payload => {
const args = contextArgs(event, rest);
return Ok({ args, ...payload, onError: payload.onError?.default });
return Ok({ args, ...payload });
});
});
}
Expand Down Expand Up @@ -137,7 +136,6 @@ export function buildModules<T extends AnyModule>(
interface ExecutePayload {
module: Processed<Module>;
task: () => Awaitable<unknown>;
onError: AnyFunction|undefined
args: unknown[]
}
/**
Expand All @@ -155,7 +153,6 @@ export function executeModule(
{
module,
task,
onError,
args
}: ExecutePayload,
) {
Expand All @@ -167,29 +164,6 @@ export function executeModule(
emitter.emit('module.activate', SernEmitter.success(module));
return EMPTY;
}
if(onError) {
//Could be promise
const err = onError() as CommandError.Response
if(!err) {
const failure = SernEmitter.failure(module, "Handling onError: returned undefined");
return throwError(() => failure);
}
if(err.log) {
const { type, message } = err.log;
logger?.[type]({ message });
};
//args[0] will be Repliable ( has reply method ), unless it is autocomplete
const apiObject = args[0];
assert(apiObject && typeof apiObject === 'object', "Args[0] was falsy while trying to create onError");
assert(err.body, "Body of error response cannot be empty");
if('reply' in apiObject && typeof apiObject.reply === 'function') {
return from(apiObject.reply(err.body))
}
if('respond' in apiObject && typeof apiObject.respond === 'function') {
return from(apiObject.respond(err.body))
}
return EMPTY;
}
return throwError(() => SernEmitter.failure(module, result.error));

}),
Expand All @@ -207,7 +181,7 @@ export function executeModule(
*/
export function createResultResolver<
T extends { execute: (...args: any[]) => any; onEvent: ControlPlugin[] },
Args extends { module: T; onError: unknown, [key: string]: unknown },
Args extends { module: T; [key: string]: unknown },
Output,
>(config: {
onStop?: (module: T) => unknown;
Expand Down Expand Up @@ -240,9 +214,9 @@ export function callInitPlugins<T extends Processed<AnyModule>>(sernEmitter: Emi
SernEmitter.failure(module, SernError.PluginFailure),
);
},
onNext: ({ module, onError }) => {
onNext: ({ module }) => {
sernEmitter.emit('module.register', SernEmitter.success(module));
return { module, onError: onError as OnError };
return { module };
},
}),
);
Expand All @@ -257,13 +231,11 @@ export function makeModuleExecutor<
Args extends {
module: M;
args: unknown[];
onError: AnyFunction|undefined
},
>(onStop: (m: M) => unknown) {
const onNext = ({ args, module, onError }: Args) => ({
const onNext = ({ args, module }: Args) => ({
task: () => module.execute(...args),
module,
onError,
args
});
return concatMap(
Expand Down
10 changes: 5 additions & 5 deletions src/handlers/user-defined-events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,21 @@ import { SernError } from '../core/_internal';
import { buildModules, callInitPlugins, handleCrash, eventDispatcher } from './_internal';
import { Service } from '../core/ioc';
import type { DependencyList } from '../types/ioc';
import type { EventModule, OnError, Processed } from '../types/core-modules';
import type { EventModule, Processed } from '../types/core-modules';

export function eventsHandler(
[emitter, err, log, moduleManager, client]: DependencyList,
allPaths: ObservableInput<string>,
) {
//code smell
const intoDispatcher = (e: { module: Processed<EventModule>, onError: OnError }) => {
const intoDispatcher = (e: { module: Processed<EventModule> }) => {
switch (e.module.type) {
case EventType.Sern:
return eventDispatcher(e.module, e.onError, emitter);
return eventDispatcher(e.module, emitter);
case EventType.Discord:
return eventDispatcher(e.module, e.onError, client);
return eventDispatcher(e.module, client);
case EventType.External:
return eventDispatcher(e.module, e.onError, Service(e.module.emitter));
return eventDispatcher(e.module, Service(e.module.emitter));
default:
throw Error(SernError.InvalidModuleType + ' while creating event handler');
}
Expand Down
1 change: 0 additions & 1 deletion src/types/core-modules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ import { CommandType, Context, EventType } from '../../src/core';
import { AnyCommandPlugin, AnyEventPlugin, ControlPlugin, InitPlugin } from './core-plugin';
import { Awaitable, Args, SlashOptions, SernEventsMapping, AnyFunction } from './utility';

export type OnError = Record<string, AnyFunction>|undefined


export interface CommandMeta {
Expand Down
2 changes: 0 additions & 2 deletions src/types/core.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import { OnError } from "./core-modules";

export interface ImportPayload<T> {
module: T;
absPath: string;
onError: OnError
[key: string]: unknown;
}

Expand Down
Loading

0 comments on commit 2ff48a9

Please sign in to comment.