tearing it up

This commit is contained in:
Jacob Nguyen
2024-04-28 18:44:58 -05:00
parent 599a02c9df
commit 3d10ee1c59
7 changed files with 24 additions and 74 deletions

View File

@@ -10,17 +10,14 @@ import type { Logging } from './contracts/logging';
export const parseCallsite = (fpath: string) => {
const pathobj =
path.parse(fpath.replace(/file:\\?/, "")
.split(path.sep)
.join(path.posix.sep))
return {
name: pathobj.name,
absPath : path.posix.format(pathobj)
}
const pathobj = path.parse(fpath.replace(/file:\\?/, "")
.split(path.sep)
.join(path.posix.sep))
return { name: pathobj.name,
absPath : path.posix.format(pathobj) }
}
export const shouldHandle = (pth: string, fpath: string) => {
const file_name = fpath+path.extname(pth);
export const shouldHandle = (pth: string, filenam: string) => {
const file_name = filenam+path.extname(pth);
let newPath = path.join(path.dirname(pth), file_name)
.replace(/file:\\?/, "");
return { exists: existsSync(newPath),
@@ -49,7 +46,7 @@ export async function importModule<T>(absPath: string) {
let commandModule = fileModule.default;
assert(commandModule , `Found no export @ ${absPath}. Forgot to ignore with "!"? (!${path.basename(absPath)})?`);
if ('default' in commandModule ) {
if ('default' in commandModule) {
commandModule = commandModule.default;
}
return { module: commandModule } as T;
@@ -72,8 +69,7 @@ export const fmtFileName = (fileName: string) => path.parse(fileName).name;
export function buildModuleStream<T extends Module>(
input: ObservableInput<string>,
): Observable<ImportPayload<T>> {
return from(input)
.pipe(mergeMap(defaultModuleLoader<T>));
return from(input).pipe(mergeMap(defaultModuleLoader<T>));
}
export const getFullPathTree = (dir: string) => readPaths(path.resolve(dir));

View File

@@ -18,8 +18,9 @@ import {
} from 'rxjs';
import { Emitter, ErrorHandling, Logging } from './contracts';
import util from 'node:util';
import type { PluginResult, VoidResult } from '../types/core-plugin';
import type { PluginResult } from '../types/core-plugin';
import type { Result } from 'ts-results-es'
import type { VoidResult } from './_internal';
/**
* if {src} is true, mapTo V, else ignore
* @param item

View File

@@ -30,8 +30,7 @@ export function contextArgs(wrappable: Message | BaseInteraction, messageArgs?:
function intoPayload(module: Processed<Module>, ) {
return pipe(
arrayifySource,
map(args => ({ module, args, })),
);
map(args => ({ module, args, })));
}
const createResult = createResultResolver<

View File

@@ -103,31 +103,11 @@ export function createMessageHandler(
/**
* This function assigns remaining, incomplete data to each imported module.
*/
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>,
) {
return Files
.buildModuleStream<Processed<T>>(input)
.pipe(assignDefaults());
return Files.buildModuleStream<Processed<T>>(input);
}

View File

@@ -1,6 +1,5 @@
import { ObservableInput, concat, first, fromEvent, ignoreElements, pipe, tap } from 'rxjs';
import { CommandType } from '../core/structures';
import { SernError } from '../core/_internal';
import { SernError, _Module } from '../core/_internal';
import { Result } from 'ts-results-es';
import { Logging, ModuleManager } from '../core/contracts';
import { buildModules, callInitPlugins } from './_internal';
@@ -16,39 +15,14 @@ export function readyHandler(
//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, metadata }) => {
register(moduleManager, module, metadata)
.expect(SernError.InvalidModuleType + ' ' + util.inspect(module));
});
concat(ready$)
//.pipe(callInitPlugins(sEmitter))
// const validModuleType = module.type >= 0 && module.type <= 1 << 10;
// assert.ok(validModuleType,
// `Found ${module.name} at ${module.meta.fullPath}, which does not have a valid type`);
}
const once = (log: Logging | undefined) => pipe(
tap(() => { log?.info({ message: "Waiting on discord client to be ready..." }) }),
first(),
ignoreElements())
function register<T extends Processed<AnyModule>>(
manager: ModuleManager,
module: T,
metadata:CommandMeta
): Result<void, void> {
manager.setMetadata(module, metadata)!;
const validModuleType = module.type >= 0 && module.type <= 1 << 10;
assert.ok(
validModuleType,
//@ts-ignore
`Found ${module.name} at ${metadata.fullPath}, which does not have a valid type`,
);
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(metadata.id, module));
}

View File

@@ -9,7 +9,8 @@ import { readyHandler } from './handlers/ready-event';
import { messageHandler } from './handlers/message-event';
import { interactionHandler } from './handlers/interaction-event';
import { presenceHandler } from './handlers/presence';
import { Client } from 'discord.js';
import type { Client } from 'discord.js';
/**
* @since 1.0.0
@@ -31,8 +32,8 @@ export function init(maybeWrapper: Wrapper | 'file') {
'@sern/modules',
'@sern/client');
const logger = dependencies[2],
errorHandler = dependencies[1];
errorHandler = dependencies[1];
const wrapper = Files.loadConfig(maybeWrapper, logger);
if (wrapper.events !== undefined) {
eventsHandler(dependencies, Files.getFullPathTree(wrapper.events));
@@ -40,6 +41,7 @@ export function init(maybeWrapper: Wrapper | 'file') {
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
readyHandler(dependencies, Files.getFullPathTree(wrapper.commands))
.add(() => {

View File

@@ -109,7 +109,6 @@ export interface DiscordEventCommand<T extends keyof ClientEvents = keyof Client
}
export interface TextCommand extends Module {
type: CommandType.Text;
alias?: string[];
execute: (ctx: Context, args: ['text', string[]]) => Awaitable<unknown>;
}
@@ -122,7 +121,6 @@ export interface SlashCommand extends Module {
export interface BothCommand extends Module {
type: CommandType.Both;
alias?: string[];
description: string;
options?: SernOptionsData[];
execute: (ctx: Context, args: Args) => Awaitable<unknown>;