Skip to content

Commit

Permalink
dynamic customIds
Browse files Browse the repository at this point in the history
  • Loading branch information
jacoobes committed May 22, 2024
1 parent 814fc4f commit 327e56f
Show file tree
Hide file tree
Showing 7 changed files with 27 additions and 26 deletions.
1 change: 0 additions & 1 deletion src/core/id.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ export function reconstruct<T extends Interaction>(event: T) {
case InteractionType.MessageComponent: {
let id = event.customId;
const data = parseParams(event, id, `_C${event.componentType}`)
console.log(data)
return [data];
}
case InteractionType.ApplicationCommand:
Expand Down
2 changes: 1 addition & 1 deletion src/core/ioc/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ async function composeRoot(
conf: DependencyConfiguration,
) {
//container should have no client or logger yet.
const hasLogger = conf.exclude?.has('@sern/logger');
const hasLogger = container.hasKey('@sern/logger');
if (!hasLogger) {
__add_container('@sern/logger', new __Services.DefaultLogging());
}
Expand Down
31 changes: 15 additions & 16 deletions src/handlers/event-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ import { resultPayload, isAutocomplete, treeSearch } from '../core/functions'
interface ExecutePayload {
module: Module;
args: unknown[];
deps: Dependencies
deps: Dependencies;
params?: string;
[key: string]: unknown
}

Expand Down Expand Up @@ -52,9 +53,10 @@ interface DispatchPayload {
module: Processed<CommandModule>;
event: BaseInteraction;
defaultPrefix?: string;
deps: Dependencies
deps: Dependencies;
params?: string
};
export function createDispatcher({ module, event, defaultPrefix, deps }: DispatchPayload): ExecutePayload {
export function createDispatcher({ module, event, defaultPrefix, deps, params }: DispatchPayload): ExecutePayload {
assert.ok(CommandType.Text !== module.type,
SernError.MismatchEvent + 'Found text command in interaction stream');

Expand All @@ -68,13 +70,12 @@ export function createDispatcher({ module, event, defaultPrefix, deps }: Dispatc
args: [event],
deps };
}

switch (module.type) {
case CommandType.Slash:
case CommandType.Both: {
return { module, args: [Context.wrap(event, defaultPrefix)], deps };
}
default: return { module, args: [event], deps };
default: return { module, args: [event], deps, params };
}
}
function createGenericHandler<Source, Narrowed extends Source, Output>(
Expand Down Expand Up @@ -113,24 +114,22 @@ export function createInteractionHandler<T extends Interaction>(
deps: Dependencies,
defaultPrefix?: string
) {
const mg = deps['@sern/modules']
const mg = deps['@sern/modules'];
return createGenericHandler<Interaction, T, Result<ReturnType<typeof createDispatcher>, void>>(
source,
async event => {
const possibleIds = Id.reconstruct(event);
let modules = possibleIds
.map(({ id }) => mg.get(id))
.filter((id): id is Module => id !== undefined);
.map(({ id, params }) => ({ module: mg.get(id), params }))
.filter((id) => id !== undefined);

if(modules.length == 0) {
return Err.EMPTY;
}
const [ module ] = modules;
const [{module, params}] = modules;
return Ok(createDispatcher({
module: module as Processed<CommandModule>,
event,
defaultPrefix,
deps
event, defaultPrefix, deps, params
}));
});
}
Expand Down Expand Up @@ -218,10 +217,10 @@ export async function callInitPlugins(module: Module, deps: Dependencies, sEmitt
return _module
}

async function callPlugins({ args, module, deps }: ExecutePayload) {
async function callPlugins({ args, module, deps, params }: ExecutePayload) {
let state = {};
for(const plugin of module.onEvent??[]) {
const result = await plugin.execute(...args, { state, deps, type: module.type === CommandType.Text?'text':'slash' });
const result = await plugin.execute(...args, { state, deps, params, type: module.type });
if(result.isErr()) {
return result;
}
Expand All @@ -236,9 +235,9 @@ async function callPlugins({ args, module, deps }: ExecutePayload) {
* @param onStop emits a failure response to the SernEmitter
*/
export function intoTask(onStop: (m: Module) => unknown) {
const onNext = ({ args, module, deps }: ExecutePayload, state: Record<string, unknown>) => ({
const onNext = ({ args, module, deps, params }: ExecutePayload, state: Record<string, unknown>) => ({
module,
args: [...args, { state, deps, type: module.type === CommandType.Text?'text':'slash' }],
args: [...args, { state, deps, params, type: module.type }],
deps
});
return createResultResolver({ onStop, onNext });
Expand Down
3 changes: 1 addition & 2 deletions src/handlers/ready.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as Files from '../core/module-loading'
import { once } from 'events';
import { once } from 'node:events';
import { resultPayload } from '../core/functions';
import { PayloadType } from '..';
import { CommandType } from '../core/structures/enums';
Expand All @@ -25,7 +25,6 @@ export default async function(dir: string, deps : UnpackedDependencies) {
throw Error(`Found ${module.name} at ${module.meta.absPath}, which has incorrect \`type\``);
}
const resultModule = await callInitPlugins(module, deps, sEmitter);
console.log(resultModule)
// FREEZE! no more writing!!
commands.set(resultModule.meta.id, Object.freeze(resultModule));
sEmitter.emit('module.register', resultPayload(PayloadType.Success, resultModule));
Expand Down
3 changes: 2 additions & 1 deletion src/types/core-modules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ import { Awaitable, SernEventsMapping } from './utility';
export type SDT = {
state: Record<string,unknown>;
deps: Dependencies;
type: 'slash' | 'text'
type: 'slash' | 'text',
params?: string
};

export type Processed<T> = T & { name: string; description: string };
Expand Down
3 changes: 2 additions & 1 deletion src/types/core-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,13 @@

import type { Err, Ok, Result } from 'ts-results-es';
import type {
CommandModuleDefs,
Module,
Processed,
SDT,
} from './core-modules';
import type { Awaitable } from './utility';
import type { CommandType, PluginType } from '../core/structures/enums'
import type { CommandType, EventType, PluginType } from '../core/structures/enums'
import type { Context } from '../core/structures/context'
import type {
ButtonInteraction,
Expand Down
10 changes: 6 additions & 4 deletions src/types/ioc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,13 @@ export type IntoDependencies<Tuple extends [...any[]]> = {

/**
* @deprecated This old signature will be incompatible with future versions of sern.
* ```ts
* To switch your old code:
await makeDependencies(({ add }) => {
add('@sern/client', new Client())
})
* ```
*/
export interface DependencyConfiguration {
/*
* @deprecated. Loggers will be opt-in the future
*/
exclude?: Set<'@sern/logger'>;
build: (root: Container) => Container;
}

0 comments on commit 327e56f

Please sign in to comment.