Skip to content

Commit

Permalink
boss call
Browse files Browse the repository at this point in the history
  • Loading branch information
jacoobes committed Jan 28, 2024
1 parent 8c3f502 commit f020e78
Show file tree
Hide file tree
Showing 15 changed files with 60 additions and 139 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,6 @@
},
"homepage": "https://sern.dev",
"peerDependencies": {
"shrimple-locales": "^0.1.2"
"shrimple-locales": "^0.2.0"
}
}
1 change: 1 addition & 0 deletions src/core/_internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ export { SernError } from './structures/enums';
export { ModuleStore } from './structures/module-store';
export * as DefaultServices from './structures/services';
export { useContainerRaw } from './ioc/base'

16 changes: 10 additions & 6 deletions src/core/functions.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { Err, Ok } from 'ts-results-es';
import { ApplicationCommandOptionType, AutocompleteInteraction } from 'discord.js';
import type { SernAutocompleteData, SernOptionsData } from '../types/core-modules';
import type { Module, SernAutocompleteData, SernOptionsData } from '../types/core-modules';
import type { AnyCommandPlugin, AnyEventPlugin, Plugin } from '../types/core-plugin';
import type {
AnySelectMenuInteraction,
Expand All @@ -9,12 +8,12 @@ import type {
MessageContextMenuCommandInteraction,
ModalSubmitInteraction,
UserContextMenuCommandInteraction,
AutocompleteInteraction
} from 'discord.js';
import { InteractionType } from 'discord.js';


import { PluginType } from './structures';
import { ApplicationCommandOptionType, InteractionType } from 'discord.js'
import { PayloadType, PluginType } from './structures';
import assert from 'assert';
import { Payload } from '../types/utility';

//function wrappers for empty ok / err
export const ok = /* @__PURE__*/ () => Ok.EMPTY;
Expand Down Expand Up @@ -117,3 +116,8 @@ export function isAutocomplete(i: InteractionTypable): i is AutocompleteInteract
export function isModal(i: InteractionTypable): i is ModalSubmitInteraction {
return i.type === InteractionType.ModalSubmit;
}

export function resultPayload<T extends PayloadType>
(type: T, module?: Module, reason?: unknown) {
return { type, module, reason } as Payload & { type : T };
}
20 changes: 3 additions & 17 deletions src/core/ioc/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,6 @@ import { Result } from 'ts-results-es';
import { DefaultServices } from '../_internal';
import { AnyFunction } from '../../types/utility';
import type { Logging } from '../contracts/logging';
import { requir } from '../module-loading';
import { fileURLToPath } from 'node:url';
import path from 'path';

//SIDE EFFECT: GLOBAL DI
let containerSubject: CoreContainer<Partial<Dependencies>>;
Expand Down Expand Up @@ -95,13 +92,6 @@ export const insertLogger = (containerSubject: CoreContainer<any>) => {
.upsert({'@sern/logger': () => new DefaultServices.DefaultLogging});
}

const insertLocalizer = async (containerSubject: CoreContainer<any>) => {
const packageDirectory = fileURLToPath(import.meta.url);
const pathToLocalizer= path.resolve(packageDirectory, "../", "optional", "localizer");
const { ShrimpleLocalizer } = requir(pathToLocalizer);
containerSubject
.upsert({'@sern/localizer': new ShrimpleLocalizer() });
}

/**
* Given the user's conf, check for any excluded/included dependency keys.
Expand All @@ -118,9 +108,9 @@ function composeRoot(
if (!hasLogger) {
insertLogger(container);
}
if(conf.include?.includes('@sern/localizer')) {
insertLocalizer(container);
}
// if(conf.include?.includes('@sern/localizer')) {
// insertLocalizer(container);
// }
//Build the container based on the callback provided by the user
conf.build(container as CoreContainer<Omit<CoreDependencies, '@sern/client'>>);

Expand All @@ -147,10 +137,6 @@ export async function makeDependencies<const T extends Dependencies>
insertLogger(containerSubject);
}

if(included.includes('@sern/localizer')) {
insertLocalizer(containerSubject);
}

containerSubject.ready();
} else {
composeRoot(containerSubject, conf);
Expand Down
5 changes: 3 additions & 2 deletions src/core/ioc/container.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { Container } from 'iti';
import { Disposable, SernEmitter } from '../';
import { Disposable } from '../';
import * as assert from 'node:assert';
import { Subject } from 'rxjs';
import { DefaultServices, ModuleStore } from '../_internal';
import * as Hooks from './hooks';
import { EventEmitter } from 'node:events';


/**
Expand All @@ -23,7 +24,7 @@ export class CoreContainer<T extends Partial<Dependencies>> extends Container<T,

(this as Container<{}, {}>)
.add({ '@sern/errors': () => new DefaultServices.DefaultErrorHandling,
'@sern/emitter': () => new SernEmitter,
'@sern/emitter': () => new EventEmitter({ captureRejections: true }),
'@sern/store': () => new ModuleStore })
.add(ctx => {
return { '@sern/modules': () =>
Expand Down
26 changes: 25 additions & 1 deletion src/core/ioc/dependency-injection.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import assert from 'node:assert';
import type { IntoDependencies } from '../../types/ioc';
import { useContainerRaw } from './base';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
import { requir } from '../module-loading';
import type { Localizer } from '../contracts';

/**
* @__PURE__
Expand Down Expand Up @@ -54,11 +58,31 @@ export function useContainer<const T extends Dependencies>() {
keys.map(key => useContainerRaw().get(key as keyof Dependencies)) as IntoDependencies<V>;
}


/**
* Translates a string to its respective local
* @example
* ```ts
* assert.deepEqual(locals("salute.hello", "es"), "hola")
* ```
*/
export const local = (i: string, local: string) => {
return Service('@sern/localizer').translate(i, local)
}

/**
* Returns a record of locales to their respective translations.
* @example
* ```ts
* assert.deepEqual(localsFor("salute.hello"), { "en-US": "hello", "es": "hola" })
* ```
*/
export const localsFor = (path: string) => {
return Service('@sern/localizer').translationsFor(path)
}

export const Localization = () => {
const packageDirectory = fileURLToPath(import.meta.url);
const pathToLocalizer= path.resolve(packageDirectory, "../", "optional", "localizer");
const { ShrimpleLocalizer } = requir(pathToLocalizer);
return new ShrimpleLocalizer() as Localizer;
}
2 changes: 1 addition & 1 deletion src/core/ioc/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export { makeDependencies } from './base';
export { Service, Services, single, transient, local, localsFor } from './dependency-injection';
export { Service, Services, single, transient, local, localsFor, Localization } from './dependency-injection';
2 changes: 1 addition & 1 deletion src/core/structures/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export { CommandType, PluginType, PayloadType, EventType } from './enums';
export * from './context';
export * from './sern-emitter';
export * from './services';
export * from './module-store';

89 changes: 0 additions & 89 deletions src/core/structures/sern-emitter.ts

This file was deleted.

15 changes: 6 additions & 9 deletions src/handlers/event-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@ import {
handleError,
SernError,
VoidResult,
resultPayload,
} from '../core/_internal';
import { Emitter, ErrorHandling, Logging, ModuleManager } from '../core';
import { Emitter, ErrorHandling, Logging, ModuleManager, PayloadType } from '../core';
import { contextArgs, createDispatcher } from './dispatchers';
import { ObservableInput, pipe } from 'rxjs';
import { SernEmitter } from '../core';
import { Err, Ok, Result } from 'ts-results-es';
import type { Awaitable } from '../types/utility';
import type { ControlPlugin } from '../types/core-plugin';
Expand Down Expand Up @@ -168,10 +168,10 @@ export function executeModule(
concatMap(() => Result.wrapAsync(async () => task())),
concatMap(result => {
if (result.isOk()) {
emitter.emit('module.activate', SernEmitter.success(module));
emitter.emit('module.activate', resultPayload(PayloadType.Success, module));
return EMPTY;
}
return throwError(() => SernEmitter.failure(module, result.error));
return throwError(() => resultPayload(PayloadType.Failure, module, result.error));

}),
);
Expand Down Expand Up @@ -218,13 +218,10 @@ export function callInitPlugins<T extends Processed<AnyModule>>(sernEmitter: Emi
createResultResolver({
createStream: args => from(args.module.plugins).pipe(callPlugin(args)),
onStop: (module: T) => {
sernEmitter.emit(
'module.register',
SernEmitter.failure(module, SernError.PluginFailure),
);
sernEmitter.emit('module.register', resultPayload(PayloadType.Failure, module, SernError.PluginFailure));
},
onNext: ({ module }) => {
sernEmitter.emit('module.register', SernEmitter.success(module));
sernEmitter.emit('module.register', resultPayload(PayloadType.Success, module));
return { module };
},
}),
Expand Down
7 changes: 4 additions & 3 deletions src/handlers/interaction-event.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Interaction } from 'discord.js';
import { mergeMap, merge } from 'rxjs';
import { SernEmitter } from '../core';
import { PayloadType } from '../core';
import {
isAutocomplete,
isCommand,
Expand All @@ -9,6 +9,7 @@ import {
sharedEventStream,
SernError,
filterTap,
resultPayload,
} from '../core/_internal';
import { createInteractionHandler, executeModule, makeModuleExecutor } from './_internal';
import type { DependencyList } from '../types/ioc';
Expand All @@ -25,8 +26,8 @@ export function interactionHandler([emitter, err, log, modules, client]: Depende
);
return interactionHandler$
.pipe(
filterTap(e => emitter.emit('warning', SernEmitter.warning(e))),
filterTap(e => emitter.emit('warning', resultPayload(PayloadType.Warning, undefined, e))),
makeModuleExecutor(module =>
emitter.emit('module.activate', SernEmitter.failure(module, SernError.PluginFailure))),
emitter.emit('module.activate', resultPayload(PayloadType.Failure, module, SernError.PluginFailure))),
mergeMap(payload => executeModule(emitter, log, err, payload)));
}
9 changes: 5 additions & 4 deletions src/handlers/message-event.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { mergeMap, EMPTY } from 'rxjs';
import type { Message } from 'discord.js';
import { SernEmitter } from '../core';
import { sharedEventStream, SernError, filterTap } from '../core/_internal';
import { PayloadType, SernEmitter } from '../core';
import { sharedEventStream, SernError, filterTap, resultPayload } from '../core/_internal';
import { createMessageHandler, executeModule, makeModuleExecutor } from './_internal';
import type { DependencyList } from '../types/ioc';

Expand Down Expand Up @@ -38,9 +38,10 @@ export function messageHandler(
const msgCommands$ = handle(isNonBot(defaultPrefix));

return msgCommands$.pipe(
filterTap((e) => emitter.emit('warning', SernEmitter.warning(e))),
filterTap((e) => emitter.emit('warning', resultPayload(PayloadType.Warning, undefined, e))),
makeModuleExecutor(module => {
emitter.emit('module.activate', SernEmitter.failure(module, SernError.PluginFailure));
const result = resultPayload(PayloadType.Failure, module, SernError.PluginFailure);
emitter.emit('module.activate', result);
}),
mergeMap(payload => executeModule(emitter, log, err, payload)));
}
1 change: 0 additions & 1 deletion src/sern.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ import { Client } from 'discord.js';
* })
* ```
*/

export function init(maybeWrapper: Wrapper | 'file') {
const startTime = performance.now();
const wrapper = Files.loadConfig(maybeWrapper);
Expand Down
3 changes: 0 additions & 3 deletions src/types/ioc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,6 @@ export type IntoDependencies<Tuple extends [...any[]]> = {
export interface DependencyConfiguration {
//@deprecated. Loggers will always be included in the future
exclude?: Set<'@sern/logger'>;

//Extra modules that are preconfigured and ready to use! @sern/localizer is an example
include?: string[]
build: (
root: Container<Omit<CoreDependencies, '@sern/client'>, {}>,
) => Container<Dependencies, {}>;
Expand Down
1 change: 0 additions & 1 deletion src/types/utility.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,5 +29,4 @@ export type Payload =
| { type: PayloadType.Warning; reason: string };



export type ReplyOptions = string | Omit<InteractionReplyOptions, 'fetchReply'> | MessageReplyOptions;

0 comments on commit f020e78

Please sign in to comment.