refactor: remove unneeded signatures and fix imports

This commit is contained in:
Jacob Nguyen
2023-05-06 01:16:53 -05:00
parent 1fea6fa136
commit 1e1398fade
16 changed files with 44 additions and 148 deletions

View File

@@ -79,6 +79,7 @@ export function eventModule(mod: InputEvent): EventModule {
/** Create event modules from discord.js client events,
* This is an {@link eventModule} for discord events,
* where typings can be very bad.
* @Experimental
* @param mod
*/
export function discordEvent<T extends keyof ClientEvents>(mod: {

View File

@@ -1,11 +1,10 @@
import type { Container } from 'iti';
import type { AnyDependencies, DependencyConfiguration, MapDeps, ServerlessDependencies, WebsocketDependencies } from '../types/core';
import type { AnyDependencies, DependencyConfiguration, MapDeps, ServerlessDependencies, WebsocketDependencies, Wrapper } from '../types/core';
import { DefaultErrorHandling, DefaultLogging, DefaultModuleManager } from './contracts';
import { Result } from 'ts-results-es';
import { BehaviorSubject } from 'rxjs';
import { createContainer } from 'iti';
import { ModuleStore, SernEmitter } from './structures';
import { AnyWrapper, ServerlessWrapper, WebsocketWrapper } from './structures/wrapper';
export const containerSubject = new BehaviorSubject(defaultContainer());
@@ -100,22 +99,11 @@ const requiredDependencyKeys = [
'@sern/logger',
] as const;
/**
* @overload
*/
export function makeFetcher<Dep extends WebsocketDependencies>(containerConfig : WebsocketWrapper['containerConfig'])
: <const Keys extends (keyof Dep)[]>(ks: [...Keys]) => MapDeps<Dep, [...typeof requiredDependencyKeys, ...Keys]>;
/**
* @overload
*/
export function makeFetcher<Dep extends ServerlessDependencies>(containerConfig: ServerlessWrapper['containerConfig'])
: <const Keys extends (keyof Dep)[]>(ks: [...Keys]) => MapDeps<Dep, [...typeof requiredDependencyKeys, ...Keys]>;
/**
* A way for sern to grab only the necessary dependencies.
* Returns a function which allows for the user to call for more dependencies.
*/
export function makeFetcher<Dep extends AnyDependencies>(containerConfig : AnyWrapper['containerConfig']) {
export function makeFetcher<Dep extends AnyDependencies>(containerConfig : Wrapper['containerConfig']) {
return <const Keys extends (keyof Dep)[]>(otherKeys: [...Keys]) =>
containerConfig.get(...requiredDependencyKeys, ...otherKeys as (keyof AnyDependencies)[]) as MapDeps<
Dep,

View File

@@ -1,5 +1,4 @@
export * from './contracts';
export * from './platform';
export * from './plugins';
export * from './structures';
export { single, transient, useContainerRaw, makeDependencies } from './dependencies'

View File

@@ -3,12 +3,12 @@ import { type Result, Err, Ok } from 'ts-results-es';
import { Processed } from '../types/core';
import { Module } from '../types/module';
import * as assert from 'node:assert'
import * as util from 'node:util'
import util from 'node:util'
import { type Observable, from, mergeMap, ObservableInput } from 'rxjs';
import { readdir, stat } from 'fs/promises';
import { basename, join, resolve } from 'path';
type ModuleResult<T> = Promise<Result<Processed<T>, SernError>>
export type ModuleResult<T> = Promise<Result<Processed<T>, SernError>>
export type Loader<T> = (absPath: string) => ModuleResult<T>
export async function defaultModuleLoader<T extends Module>(

View File

@@ -50,13 +50,6 @@ export function callPlugin(args: unknown): OperatorFunction<
export const arrayifySource = map(src => (Array.isArray(src) ? (src as unknown[]) : [src]));
export const fillDefaults = <T extends AnyModule>({ module, absPath }: ImportPayload<T>) => {
module.description ??= '...'
return {
absPath,
module
} as ImportPayload<Processed<T>>;
};
/**
* If the current value in Result stream is an error, calls callback.

View File

@@ -1,40 +0,0 @@
export const enum DispatchType {
Websocket,
Serverless
}
export type PlatformStrategy =
| WebsocketStrategy
| ServerlessStrategy;
export interface WebsocketStrategy {
type: DispatchType.Websocket;
eventNames: [interactioncreate: string, messagecreate: string, ready: string]
defaultPrefix?: string;
}
export interface ServerlessStrategy {
type: DispatchType.Serverless;
}
export function makeWebsocketAdapter(
eventNames: [interactioncreate: string, messagecreate: string, ready: string],
defaultPrefix?: string
): WebsocketStrategy {
return {
type: DispatchType.Websocket,
eventNames,
defaultPrefix
};
}
export function makeServerlessAdapter(): ServerlessStrategy {
return {
type: DispatchType.Serverless,
};
}
export const discordjs = ( defaultPrefix?: string ) => makeWebsocketAdapter(
['interactionCreate', 'messageCreate', 'ready'],
defaultPrefix
)

View File

@@ -1,8 +1,6 @@
import type { CommandType } from '../structures/enums';
import type { PluginType } from '../structures/enums';
import type { CommandType, PluginType, EventType } from '../structures/enums';
import type { Module } from '../../types/module';
import type { Processed } from '../../types/core';
import { EventType } from '../structures/enums';
import { CommandArgsMatrix, EventArgsMatrix } from '../../types/module';
export interface InitArgs<T extends Processed<Module>> {

View File

@@ -14,7 +14,7 @@ export function makePlugin<V extends unknown[]>(
}
/**
* @since 2.5.0
*
* @__PURE__
*/
export function EventInitPlugin<I extends EventType>(
execute: (...args: EventArgs<I, PluginType.Init>) => PluginResult,
@@ -23,7 +23,7 @@ export function EventInitPlugin<I extends EventType>(
}
/**
* @since 2.5.0
*
* @__PURE__
*/
export function CommandInitPlugin<I extends CommandType>(
execute: (...args: CommandArgs<I, PluginType.Init>) => PluginResult,
@@ -32,7 +32,7 @@ export function CommandInitPlugin<I extends CommandType>(
}
/**
* @since 2.5.0
*
* @__PURE__
*/
export function CommandControlPlugin<I extends CommandType>(
execute: (...args: CommandArgs<I, PluginType.Control>) => PluginResult,
@@ -41,7 +41,7 @@ export function CommandControlPlugin<I extends CommandType>(
}
/**
* @since 2.5.0
*
* @__PURE__
*/
export function EventControlPlugin<I extends EventType>(
execute: (...args: EventArgs<I, PluginType.Control>) => PluginResult,

View File

@@ -1,18 +1,23 @@
import { AutocompleteInteraction, CommandInteraction, ModalSubmitInteraction } from "discord.js";
import { BaseInteraction, InteractionType, MessageComponentInteraction } from "discord.js";
import { AnySelectMenuInteraction, AutocompleteInteraction, ButtonInteraction, ChatInputCommandInteraction, MessageContextMenuCommandInteraction, ModalSubmitInteraction, UserContextMenuCommandInteraction } from "discord.js";
import { InteractionType } from "discord.js";
export function isMessageComponent(i: BaseInteraction): i is MessageComponentInteraction {
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: BaseInteraction): i is CommandInteraction {
export function isCommand(i: InteractionTypable): i is AnyCommandInteraction {
return i.type === InteractionType.ApplicationCommand;
}
export function isAutocomplete(i: BaseInteraction): i is AutocompleteInteraction {
export function isAutocomplete(i: InteractionTypable): i is AutocompleteInteraction {
return i.type === InteractionType.ApplicationCommandAutocomplete;
}
export function isModal(i: BaseInteraction): i is ModalSubmitInteraction {
export function isModal(i: InteractionTypable): i is ModalSubmitInteraction {
return i.type === InteractionType.ModalSubmit;
}

View File

@@ -3,7 +3,6 @@ import { SernError } from './errors';
import * as assert from 'node:assert'
/**
* @since 3.0.0
*/

View File

@@ -1,49 +0,0 @@
import type { ServerlessDependencies, WebsocketDependencies } from '../../types/core';
import { DispatchType, ServerlessStrategy, WebsocketStrategy } from '../platform';
export interface DefaultWrapper {
commands: string;
defaultPrefix?: string;
events?: string;
containerConfig: {
get: (...keys: (keyof WebsocketDependencies)[]) => unknown[];
}
}
export interface WebsocketWrapper {
readonly platform: WebsocketStrategy;
commands: string;
/**
* @deprecated
* Please specify this in platform specification
*/
defaultPrefix?: string;
events?: string;
containerConfig: {
get: (...keys: (keyof WebsocketDependencies)[]) => unknown[];
}
}
/**
* @deprecated
* Type alias for WebsocketWrapper
*/
export type Wrapper = WebsocketWrapper | ServerlessWrapper
export interface ServerlessWrapper {
readonly platform: ServerlessStrategy
commands: string[];
events?: string[];
containerConfig: {
get: (...keys: (keyof ServerlessDependencies)[]) => unknown[];
}
}
export type AnyWrapper =
| WebsocketWrapper
| ServerlessWrapper
export function isServerless(wrapper: AnyWrapper): wrapper is ServerlessWrapper {
return wrapper.platform.type === DispatchType.Serverless;
}

View File

@@ -23,10 +23,9 @@ export function makeInteractionCreate([s, err, log, modules, client]: [
Logging | undefined,
ModuleManager,
EventEmitter
],
platform: WebsocketStrategy
]
) {
const interactionStream$ = sharedObservable<Interaction>(client, platform.eventNames[0]);
const interactionStream$ = sharedObservable<Interaction>(client, 'interactionCreate');
const handle = createInteractionHandler<Interaction>(interactionStream$, modules);
const interactionHandler$ = merge(
handle(isMessageComponent),

View File

@@ -37,15 +37,16 @@ export function makeMessageCreate(
ModuleManager,
EventEmitter,
],
platform: WebsocketStrategy
defaultPrefix: string | undefined
) {
if(!platform.defaultPrefix) {
if(!defaultPrefix) {
log?.debug({ message: 'No prefix found. message handler shut down' })
return EMPTY.subscribe()
}
const messageStream$ = sharedObservable<Message>(client, platform.eventNames[1]);
const handler = createMessageHandler(messageStream$, platform.defaultPrefix, modules);
const messageStream$ = sharedObservable<Message>(client, 'messageCreate');
const handler = createMessageHandler(messageStream$, defaultPrefix, modules);
const messageHandler = handler(
ignoreNonBot(platform.defaultPrefix) as (m: Message) => m is Message
ignoreNonBot(defaultPrefix) as (m: Message) => m is Message
)
return messageHandler
.pipe(

View File

@@ -14,11 +14,8 @@ import { buildModules } from './generic';
export function startReadyEvent(
[sEmitter, errorHandler, , moduleManager, client]: ServerlessDependencyList | WebsocketDependencyList,
input: ObservableInput<string>,
platform: PlatformStrategy,
) {
const ready$ = platform.type === DispatchType.Serverless
? of(null)
: fromEvent(client!, platform.eventNames[2]).pipe(take(1));
const ready$ = fromEvent(client!, 'interactionCreate').pipe(take(1));
return ready$
.pipe(
buildModules(input, sEmitter),
@@ -36,7 +33,6 @@ export function startReadyEvent(
}),
)
.subscribe(module => {
console.log(module)
const result = registerModule(moduleManager, module as Processed<Module>);
if (result.err) {
errorHandler.crash(Error(SernError.InvalidModuleType));

View File

@@ -4,8 +4,7 @@ import { startReadyEvent } from './events/ready';
import { makeMessageCreate } from './events/messages';
import { makeFetcher, makeDependencies } from '../core/dependencies';
import { err, ok } from '../core/functions';
import { DefaultWrapper } from '../core/structures/wrapper';
import { discordjs } from '../core';
import { Wrapper } from '../types/core';
import { getCommands } from '../core/module-loading';
/**
* @since 1.0.0
@@ -23,7 +22,7 @@ import { getCommands } from '../core/module-loading';
* })
* ```
*/
export function init(wrapper: DefaultWrapper) {
export function init(wrapper: Wrapper) {
const startTime = performance.now();
const dependenciesAnd = makeFetcher(wrapper.containerConfig);
const dependencies = dependenciesAnd(['@sern/modules', '@sern/client']);
@@ -32,10 +31,9 @@ export function init(wrapper: DefaultWrapper) {
dependenciesAnd(['@sern/client']), wrapper.events, wrapper.containerConfig
);
}
const platform = discordjs(wrapper.defaultPrefix);
startReadyEvent(dependencies, getCommands(wrapper.commands), platform);
makeMessageCreate(dependencies, platform);
makeInteractionCreate(dependencies, platform);
startReadyEvent(dependencies, getCommands(wrapper.commands));
makeMessageCreate(dependencies, wrapper.defaultPrefix);
makeInteractionCreate(dependencies);
const endTime = performance.now();
dependencies[2]?.info({ message: `sern : ${(endTime - startTime).toFixed(2)} ms` });

View File

@@ -60,3 +60,11 @@ export interface ImportPayload<T> {
absPath: string
};
export interface Wrapper {
commands: string;
defaultPrefix?: string;
events?: string;
containerConfig: {
get: (...keys: (keyof WebsocketDependencies)[]) => unknown[];
}
}