mirror of
https://github.com/sern-handler/handler
synced 2026-06-06 01:16:55 +00:00
feat/abstractiti (#340)
* progress on better error handling * wiring onError callback through module loader and resolver * fix error callbacks not being stored * update onError to be record * type alias * wiring * seems to work * update error handling contract and wire more * add command error builder * fix merge * progress on error handling * naive onError handling, not tested * progres * proress * progress on abstracting away iti * seems to work * fix tests * better typings * add doc * abstracting iti * remove onerror for this pr * feat: better way to add dependencies * fix tests
This commit is contained in:
@@ -1,450 +0,0 @@
|
|||||||
/** @type {import('dependency-cruiser').IConfiguration} */
|
|
||||||
module.exports = {
|
|
||||||
forbidden: [
|
|
||||||
/* rules from the 'recommended' preset: */
|
|
||||||
{
|
|
||||||
name: 'no-circular',
|
|
||||||
severity: 'warn',
|
|
||||||
comment:
|
|
||||||
'This dependency is part of a circular relationship. You might want to revise ' +
|
|
||||||
'your solution (i.e. use dependency inversion, make sure the modules have a single responsibility) ',
|
|
||||||
from: {},
|
|
||||||
to: {
|
|
||||||
circular: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'no-orphans',
|
|
||||||
comment:
|
|
||||||
"This is an orphan module - it's likely not used (anymore?). Either use it or " +
|
|
||||||
"remove it. If it's logical this module is an orphan (i.e. it's a config file), " +
|
|
||||||
'add an exception for it in your dependency-cruiser configuration. By default ' +
|
|
||||||
'this rule does not scrutinize dot-files (e.g. .eslintrc.js), TypeScript declaration ' +
|
|
||||||
'files (.d.ts), tsconfig.json and some of the babel and webpack configs.',
|
|
||||||
severity: 'warn',
|
|
||||||
from: {
|
|
||||||
orphan: true,
|
|
||||||
pathNot: [
|
|
||||||
'(^|/)\\.[^/]+\\.(js|cjs|mjs|ts|json)$', // dot files
|
|
||||||
'\\.d\\.ts$', // TypeScript declaration files
|
|
||||||
'(^|/)tsconfig\\.json$', // TypeScript config
|
|
||||||
'(^|/)(babel|webpack)\\.config\\.(js|cjs|mjs|ts|json)$', // other configs
|
|
||||||
],
|
|
||||||
},
|
|
||||||
to: {},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'no-deprecated-core',
|
|
||||||
comment:
|
|
||||||
'A module depends on a node core module that has been deprecated. Find an alternative - these are ' +
|
|
||||||
"bound to exist - node doesn't deprecate lightly.",
|
|
||||||
severity: 'warn',
|
|
||||||
from: {},
|
|
||||||
to: {
|
|
||||||
dependencyTypes: ['core'],
|
|
||||||
path: [
|
|
||||||
'^(v8/tools/codemap)$',
|
|
||||||
'^(v8/tools/consarray)$',
|
|
||||||
'^(v8/tools/csvparser)$',
|
|
||||||
'^(v8/tools/logreader)$',
|
|
||||||
'^(v8/tools/profile_view)$',
|
|
||||||
'^(v8/tools/profile)$',
|
|
||||||
'^(v8/tools/SourceMap)$',
|
|
||||||
'^(v8/tools/splaytree)$',
|
|
||||||
'^(v8/tools/tickprocessor-driver)$',
|
|
||||||
'^(v8/tools/tickprocessor)$',
|
|
||||||
'^(node-inspect/lib/_inspect)$',
|
|
||||||
'^(node-inspect/lib/internal/inspect_client)$',
|
|
||||||
'^(node-inspect/lib/internal/inspect_repl)$',
|
|
||||||
'^(async_hooks)$',
|
|
||||||
'^(punycode)$',
|
|
||||||
'^(domain)$',
|
|
||||||
'^(constants)$',
|
|
||||||
'^(sys)$',
|
|
||||||
'^(_linklist)$',
|
|
||||||
'^(_stream_wrap)$',
|
|
||||||
],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'not-to-deprecated',
|
|
||||||
comment:
|
|
||||||
'This module uses a (version of an) npm module that has been deprecated. Either upgrade to a later ' +
|
|
||||||
'version of that module, or find an alternative. Deprecated modules are a security risk.',
|
|
||||||
severity: 'warn',
|
|
||||||
from: {},
|
|
||||||
to: {
|
|
||||||
dependencyTypes: ['deprecated'],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'no-non-package-json',
|
|
||||||
severity: 'error',
|
|
||||||
comment:
|
|
||||||
"This module depends on an npm package that isn't in the 'dependencies' section of your package.json. " +
|
|
||||||
"That's problematic as the package either (1) won't be available on live (2 - worse) will be " +
|
|
||||||
'available on live with an non-guaranteed version. Fix it by adding the package to the dependencies ' +
|
|
||||||
'in your package.json.',
|
|
||||||
from: {},
|
|
||||||
to: {
|
|
||||||
dependencyTypes: ['npm-no-pkg', 'npm-unknown'],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'not-to-unresolvable',
|
|
||||||
comment:
|
|
||||||
"This module depends on a module that cannot be found ('resolved to disk'). If it's an npm " +
|
|
||||||
'module: add it to your package.json. In all other cases you likely already know what to do.',
|
|
||||||
severity: 'error',
|
|
||||||
from: {},
|
|
||||||
to: {
|
|
||||||
couldNotResolve: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'no-duplicate-dep-types',
|
|
||||||
comment:
|
|
||||||
"Likely this module depends on an external ('npm') package that occurs more than once " +
|
|
||||||
'in your package.json i.e. bot as a devDependencies and in dependencies. This will cause ' +
|
|
||||||
'maintenance problems later on.',
|
|
||||||
severity: 'warn',
|
|
||||||
from: {},
|
|
||||||
to: {
|
|
||||||
moreThanOneDependencyType: true,
|
|
||||||
// as it's pretty common to have a type import be a type only import
|
|
||||||
// _and_ (e.g.) a devDependency - don't consider type-only dependency
|
|
||||||
// types for this rule
|
|
||||||
dependencyTypesNot: ['type-only'],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
|
|
||||||
/* rules you might want to tweak for your specific situation: */
|
|
||||||
{
|
|
||||||
name: 'not-to-test',
|
|
||||||
comment:
|
|
||||||
"This module depends on code within a folder that should only contain tests. As tests don't " +
|
|
||||||
"implement functionality this is odd. Either you're writing a test outside the test folder " +
|
|
||||||
"or there's something in the test folder that isn't a test.",
|
|
||||||
severity: 'error',
|
|
||||||
from: {
|
|
||||||
pathNot: '^(test)',
|
|
||||||
},
|
|
||||||
to: {
|
|
||||||
path: '^(test)',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'not-to-spec',
|
|
||||||
comment:
|
|
||||||
'This module depends on a spec (test) file. The sole responsibility of a spec file is to test code. ' +
|
|
||||||
"If there's something in a spec that's of use to other modules, it doesn't have that single " +
|
|
||||||
'responsibility anymore. Factor it out into (e.g.) a separate utility/ helper or a mock.',
|
|
||||||
severity: 'error',
|
|
||||||
from: {},
|
|
||||||
to: {
|
|
||||||
path: '\\.(spec|test)\\.(js|mjs|cjs|ts|ls|coffee|litcoffee|coffee\\.md)$',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'not-to-dev-dep',
|
|
||||||
severity: 'error',
|
|
||||||
comment:
|
|
||||||
"This module depends on an npm package from the 'devDependencies' section of your " +
|
|
||||||
'package.json. It looks like something that ships to production, though. To prevent problems ' +
|
|
||||||
"with npm packages that aren't there on production declare it (only!) in the 'dependencies'" +
|
|
||||||
'section of your package.json. If this module is development only - add it to the ' +
|
|
||||||
'from.pathNot re of the not-to-dev-dep rule in the dependency-cruiser configuration',
|
|
||||||
from: {
|
|
||||||
path: '^(src)',
|
|
||||||
pathNot: '\\.(spec|test)\\.(js|mjs|cjs|ts|ls|coffee|litcoffee|coffee\\.md)$',
|
|
||||||
},
|
|
||||||
to: {
|
|
||||||
dependencyTypes: ['npm-dev'],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'optional-deps-used',
|
|
||||||
severity: 'info',
|
|
||||||
comment:
|
|
||||||
'This module depends on an npm package that is declared as an optional dependency ' +
|
|
||||||
"in your package.json. As this makes sense in limited situations only, it's flagged here. " +
|
|
||||||
"If you're using an optional dependency here by design - add an exception to your" +
|
|
||||||
'dependency-cruiser configuration.',
|
|
||||||
from: {},
|
|
||||||
to: {
|
|
||||||
dependencyTypes: ['npm-optional'],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'peer-deps-used',
|
|
||||||
comment:
|
|
||||||
'This module depends on an npm package that is declared as a peer dependency ' +
|
|
||||||
'in your package.json. This makes sense if your package is e.g. a plugin, but in ' +
|
|
||||||
'other cases - maybe not so much. If the use of a peer dependency is intentional ' +
|
|
||||||
'add an exception to your dependency-cruiser configuration.',
|
|
||||||
severity: 'warn',
|
|
||||||
from: {},
|
|
||||||
to: {
|
|
||||||
dependencyTypes: ['npm-peer'],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
options: {
|
|
||||||
/* conditions specifying which files not to follow further when encountered:
|
|
||||||
- path: a regular expression to match
|
|
||||||
- dependencyTypes: see https://github.com/sverweij/dependency-cruiser/blob/main/doc/rules-reference.md#dependencytypes-and-dependencytypesnot
|
|
||||||
for a complete list
|
|
||||||
*/
|
|
||||||
doNotFollow: {
|
|
||||||
path: 'node_modules',
|
|
||||||
},
|
|
||||||
|
|
||||||
/* conditions specifying which dependencies to exclude
|
|
||||||
- path: a regular expression to match
|
|
||||||
- dynamic: a boolean indicating whether to ignore dynamic (true) or static (false) dependencies.
|
|
||||||
leave out if you want to exclude neither (recommended!)
|
|
||||||
*/
|
|
||||||
// exclude : {
|
|
||||||
// path: '',
|
|
||||||
// dynamic: true
|
|
||||||
// },
|
|
||||||
|
|
||||||
/* pattern specifying which files to include (regular expression)
|
|
||||||
dependency-cruiser will skip everything not matching this pattern
|
|
||||||
*/
|
|
||||||
// includeOnly : '',
|
|
||||||
|
|
||||||
/* dependency-cruiser will include modules matching against the focus
|
|
||||||
regular expression in its output, as well as their neighbours (direct
|
|
||||||
dependencies and dependents)
|
|
||||||
*/
|
|
||||||
// focus : '',
|
|
||||||
|
|
||||||
/* list of module systems to cruise */
|
|
||||||
// moduleSystems: ['amd', 'cjs', 'es6', 'tsd'],
|
|
||||||
|
|
||||||
/* prefix for links in html and svg output (e.g. 'https://github.com/you/yourrepo/blob/develop/'
|
|
||||||
to open it on your online repo or `vscode://file/${process.cwd()}/` to
|
|
||||||
open it in visual studio code),
|
|
||||||
*/
|
|
||||||
// prefix: '',
|
|
||||||
|
|
||||||
/* false (the default): ignore dependencies that only exist before typescript-to-javascript compilation
|
|
||||||
true: also detect dependencies that only exist before typescript-to-javascript compilation
|
|
||||||
"specify": for each dependency identify whether it only exists before compilation or also after
|
|
||||||
*/
|
|
||||||
tsPreCompilationDeps: true,
|
|
||||||
|
|
||||||
/*
|
|
||||||
list of extensions to scan that aren't javascript or compile-to-javascript.
|
|
||||||
Empty by default. Only put extensions in here that you want to take into
|
|
||||||
account that are _not_ parsable.
|
|
||||||
*/
|
|
||||||
// extraExtensionsToScan: [".json", ".jpg", ".png", ".svg", ".webp"],
|
|
||||||
|
|
||||||
/* if true combines the package.jsons found from the module up to the base
|
|
||||||
folder the cruise is initiated from. Useful for how (some) mono-repos
|
|
||||||
manage dependencies & dependency definitions.
|
|
||||||
*/
|
|
||||||
// combinedDependencies: false,
|
|
||||||
|
|
||||||
/* if true leave symlinks untouched, otherwise use the realpath */
|
|
||||||
// preserveSymlinks: false,
|
|
||||||
|
|
||||||
/* TypeScript project file ('tsconfig.json') to use for
|
|
||||||
(1) compilation and
|
|
||||||
(2) resolution (e.g. with the paths property)
|
|
||||||
|
|
||||||
The (optional) fileName attribute specifies which file to take (relative to
|
|
||||||
dependency-cruiser's current working directory). When not provided
|
|
||||||
defaults to './tsconfig.json'.
|
|
||||||
*/
|
|
||||||
tsConfig: {
|
|
||||||
fileName: 'tsconfig.json',
|
|
||||||
},
|
|
||||||
|
|
||||||
/* Webpack configuration to use to get resolve options from.
|
|
||||||
|
|
||||||
The (optional) fileName attribute specifies which file to take (relative
|
|
||||||
to dependency-cruiser's current working directory. When not provided defaults
|
|
||||||
to './webpack.conf.js'.
|
|
||||||
|
|
||||||
The (optional) `env` and `arguments` attributes contain the parameters to be passed if
|
|
||||||
your webpack config is a function and takes them (see webpack documentation
|
|
||||||
for details)
|
|
||||||
*/
|
|
||||||
// webpackConfig: {
|
|
||||||
// fileName: './webpack.config.js',
|
|
||||||
// env: {},
|
|
||||||
// arguments: {},
|
|
||||||
// },
|
|
||||||
|
|
||||||
/* Babel config ('.babelrc', '.babelrc.json', '.babelrc.json5', ...) to use
|
|
||||||
for compilation (and whatever other naughty things babel plugins do to
|
|
||||||
source code). This feature is well tested and usable, but might change
|
|
||||||
behavior a bit over time (e.g. more precise results for used module
|
|
||||||
systems) without dependency-cruiser getting a major version bump.
|
|
||||||
*/
|
|
||||||
// babelConfig: {
|
|
||||||
// fileName: './.babelrc'
|
|
||||||
// },
|
|
||||||
|
|
||||||
/* List of strings you have in use in addition to cjs/ es6 requires
|
|
||||||
& imports to declare module dependencies. Use this e.g. if you've
|
|
||||||
re-declared require, use a require-wrapper or use window.require as
|
|
||||||
a hack.
|
|
||||||
*/
|
|
||||||
// exoticRequireStrings: [],
|
|
||||||
/* options to pass on to enhanced-resolve, the package dependency-cruiser
|
|
||||||
uses to resolve module references to disk. You can set most of these
|
|
||||||
options in a webpack.conf.js - this section is here for those
|
|
||||||
projects that don't have a separate webpack config file.
|
|
||||||
|
|
||||||
Note: settings in webpack.conf.js override the ones specified here.
|
|
||||||
*/
|
|
||||||
enhancedResolveOptions: {
|
|
||||||
/* List of strings to consider as 'exports' fields in package.json. Use
|
|
||||||
['exports'] when you use packages that use such a field and your environment
|
|
||||||
supports it (e.g. node ^12.19 || >=14.7 or recent versions of webpack).
|
|
||||||
|
|
||||||
If you have an `exportsFields` attribute in your webpack config, that one
|
|
||||||
will have precedence over the one specified here.
|
|
||||||
*/
|
|
||||||
exportsFields: ['exports'],
|
|
||||||
/* List of conditions to check for in the exports field. e.g. use ['imports']
|
|
||||||
if you're only interested in exposed es6 modules, ['require'] for commonjs,
|
|
||||||
or all conditions at once `(['import', 'require', 'node', 'default']`)
|
|
||||||
if anything goes for you. Only works when the 'exportsFields' array is
|
|
||||||
non-empty.
|
|
||||||
|
|
||||||
If you have a 'conditionNames' attribute in your webpack config, that one will
|
|
||||||
have precedence over the one specified here.
|
|
||||||
*/
|
|
||||||
conditionNames: ['import', 'require', 'node', 'default'],
|
|
||||||
/*
|
|
||||||
The extensions, by default are the same as the ones dependency-cruiser
|
|
||||||
can access (run `npx depcruise --info` to see which ones that are in
|
|
||||||
_your_ environment. If that list is larger than what you need (e.g.
|
|
||||||
it contains .js, .jsx, .ts, .tsx, .cts, .mts - but you don't use
|
|
||||||
TypeScript you can pass just the extensions you actually use (e.g.
|
|
||||||
[".js", ".jsx"]). This can speed up the most expensive step in
|
|
||||||
dependency cruising (module resolution) quite a bit.
|
|
||||||
*/
|
|
||||||
// extensions: [".js", ".jsx", ".ts", ".tsx", ".d.ts"],
|
|
||||||
/*
|
|
||||||
If your TypeScript project makes use of types specified in 'types'
|
|
||||||
fields in package.jsons of external dependencies, specify "types"
|
|
||||||
in addition to "main" in here, so enhanced-resolve (the resolver
|
|
||||||
dependency-cruiser uses) knows to also look there. You can also do
|
|
||||||
this if you're not sure, but still use TypeScript. In a future version
|
|
||||||
of dependency-cruiser this will likely become the default.
|
|
||||||
*/
|
|
||||||
mainFields: ['main', 'types'],
|
|
||||||
},
|
|
||||||
reporterOptions: {
|
|
||||||
dot: {
|
|
||||||
/* pattern of modules that can be consolidated in the detailed
|
|
||||||
graphical dependency graph. The default pattern in this configuration
|
|
||||||
collapses everything in node_modules to one folder deep so you see
|
|
||||||
the external modules, but not the innards your app depends upon.
|
|
||||||
*/
|
|
||||||
collapsePattern: 'node_modules/(@[^/]+/[^/]+|[^/]+)',
|
|
||||||
|
|
||||||
/* Options to tweak the appearance of your graph.See
|
|
||||||
https://github.com/sverweij/dependency-cruiser/blob/main/doc/options-reference.md#reporteroptions
|
|
||||||
for details and some examples. If you don't specify a theme
|
|
||||||
don't worry - dependency-cruiser will fall back to the default one.
|
|
||||||
*/
|
|
||||||
// theme: {
|
|
||||||
// graph: {
|
|
||||||
// /* use splines: "ortho" for straight lines. Be aware though
|
|
||||||
// graphviz might take a long time calculating ortho(gonal)
|
|
||||||
// routings.
|
|
||||||
// */
|
|
||||||
// splines: "true"
|
|
||||||
// },
|
|
||||||
// modules: [
|
|
||||||
// {
|
|
||||||
// criteria: { matchesFocus: true },
|
|
||||||
// attributes: {
|
|
||||||
// fillcolor: "lime",
|
|
||||||
// penwidth: 2,
|
|
||||||
// },
|
|
||||||
// },
|
|
||||||
// {
|
|
||||||
// criteria: { matchesFocus: false },
|
|
||||||
// attributes: {
|
|
||||||
// fillcolor: "lightgrey",
|
|
||||||
// },
|
|
||||||
// },
|
|
||||||
// {
|
|
||||||
// criteria: { matchesReaches: true },
|
|
||||||
// attributes: {
|
|
||||||
// fillcolor: "lime",
|
|
||||||
// penwidth: 2,
|
|
||||||
// },
|
|
||||||
// },
|
|
||||||
// {
|
|
||||||
// criteria: { matchesReaches: false },
|
|
||||||
// attributes: {
|
|
||||||
// fillcolor: "lightgrey",
|
|
||||||
// },
|
|
||||||
// },
|
|
||||||
// {
|
|
||||||
// criteria: { source: "^src/model" },
|
|
||||||
// attributes: { fillcolor: "#ccccff" }
|
|
||||||
// },
|
|
||||||
// {
|
|
||||||
// criteria: { source: "^src/view" },
|
|
||||||
// attributes: { fillcolor: "#ccffcc" }
|
|
||||||
// },
|
|
||||||
// ],
|
|
||||||
// dependencies: [
|
|
||||||
// {
|
|
||||||
// criteria: { "rules[0].severity": "error" },
|
|
||||||
// attributes: { fontcolor: "red", color: "red" }
|
|
||||||
// },
|
|
||||||
// {
|
|
||||||
// criteria: { "rules[0].severity": "warn" },
|
|
||||||
// attributes: { fontcolor: "orange", color: "orange" }
|
|
||||||
// },
|
|
||||||
// {
|
|
||||||
// criteria: { "rules[0].severity": "info" },
|
|
||||||
// attributes: { fontcolor: "blue", color: "blue" }
|
|
||||||
// },
|
|
||||||
// {
|
|
||||||
// criteria: { resolved: "^src/model" },
|
|
||||||
// attributes: { color: "#0000ff77" }
|
|
||||||
// },
|
|
||||||
// {
|
|
||||||
// criteria: { resolved: "^src/view" },
|
|
||||||
// attributes: { color: "#00770077" }
|
|
||||||
// }
|
|
||||||
// ]
|
|
||||||
// }
|
|
||||||
},
|
|
||||||
archi: {
|
|
||||||
/* pattern of modules that can be consolidated in the high level
|
|
||||||
graphical dependency graph. If you use the high level graphical
|
|
||||||
dependency graph reporter (`archi`) you probably want to tweak
|
|
||||||
this collapsePattern to your situation.
|
|
||||||
*/
|
|
||||||
collapsePattern:
|
|
||||||
'^(packages|src|lib|app|bin|test(s?)|spec(s?))/[^/]+|node_modules/(@[^/]+/[^/]+|[^/]+)',
|
|
||||||
|
|
||||||
/* Options to tweak the appearance of your graph.See
|
|
||||||
https://github.com/sverweij/dependency-cruiser/blob/main/doc/options-reference.md#reporteroptions
|
|
||||||
for details and some examples. If you don't specify a theme
|
|
||||||
for 'archi' dependency-cruiser will use the one specified in the
|
|
||||||
dot section (see above), if any, and otherwise use the default one.
|
|
||||||
*/
|
|
||||||
// theme: {
|
|
||||||
// },
|
|
||||||
},
|
|
||||||
text: {
|
|
||||||
highlightFocused: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
};
|
|
||||||
// generated: dependency-cruiser@13.0.5 on 2023-07-08T03:48:00.632Z
|
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "@sern/handler",
|
"name": "@sern/handler",
|
||||||
"packageManager": "yarn@3.5.0",
|
"packageManager": "yarn@3.5.0",
|
||||||
"version": "3.1.1",
|
"version": "3.2.0",
|
||||||
"description": "A complete, customizable, typesafe, & reactive framework for discord bots.",
|
"description": "A complete, customizable, typesafe, & reactive framework for discord bots.",
|
||||||
"main": "./dist/index.js",
|
"main": "./dist/index.js",
|
||||||
"module": "./dist/index.mjs",
|
"module": "./dist/index.mjs",
|
||||||
@@ -15,7 +15,6 @@
|
|||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"watch": "tsup --watch",
|
"watch": "tsup --watch",
|
||||||
"clean-modules": "rimraf node_modules/ && npm install",
|
|
||||||
"lint": "eslint src/**/*.ts",
|
"lint": "eslint src/**/*.ts",
|
||||||
"format": "eslint src/**/*.ts --fix",
|
"format": "eslint src/**/*.ts --fix",
|
||||||
"build:dev": "tsup --metafile",
|
"build:dev": "tsup --metafile",
|
||||||
@@ -47,8 +46,7 @@
|
|||||||
"@types/node": "^18.15.11",
|
"@types/node": "^18.15.11",
|
||||||
"@typescript-eslint/eslint-plugin": "5.58.0",
|
"@typescript-eslint/eslint-plugin": "5.58.0",
|
||||||
"@typescript-eslint/parser": "5.59.1",
|
"@typescript-eslint/parser": "5.59.1",
|
||||||
"dependency-cruiser": "^13.0.5",
|
"discord.js": "^14.11.0",
|
||||||
"discord.js": "14.11.0",
|
|
||||||
"esbuild": "^0.17.0",
|
"esbuild": "^0.17.0",
|
||||||
"eslint": "8.39.0",
|
"eslint": "8.39.0",
|
||||||
"prettier": "2.8.8",
|
"prettier": "2.8.8",
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
{
|
{
|
||||||
"extends": ["config:base", "helpers:pinGitHubActionDigests", "group:allNonMajor"],
|
"extends": [
|
||||||
|
"config:base",
|
||||||
|
"helpers:pinGitHubActionDigests",
|
||||||
|
"group:allNonMajor"
|
||||||
|
],
|
||||||
"major": {
|
"major": {
|
||||||
"dependencyDashboardApproval": true,
|
"dependencyDashboardApproval": true,
|
||||||
"reviewers": ["EvolutionX-10", "jacoobes", "Murtatrxx"]
|
"reviewers": ["EvolutionX-10", "jacoobes", "Murtatrxx"]
|
||||||
|
|||||||
@@ -1,21 +1,18 @@
|
|||||||
|
import type { CommandModule,Processed, EventModule } from "../../types/core-modules";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @since 2.0.0
|
* @since 2.0.0
|
||||||
*/
|
*/
|
||||||
export interface ErrorHandling {
|
export interface ErrorHandling {
|
||||||
/**
|
|
||||||
* Number of times the process should throw an error until crashing and exiting
|
|
||||||
*/
|
|
||||||
keepAlive: number;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @deprecated
|
* @deprecated
|
||||||
* Version 4 will remove this method
|
* Version 4 will remove this method
|
||||||
*/
|
*/
|
||||||
crash(err: Error): never;
|
crash(err: Error): never;
|
||||||
/**
|
/**
|
||||||
* A function that is called on every crash. Updates keepAlive.
|
* A function that is called on every throw.
|
||||||
* If keepAlive is 0, the process crashes.
|
|
||||||
* @param error
|
* @param error
|
||||||
*/
|
*/
|
||||||
updateAlive(error: Error): void;
|
updateAlive(error: Error): void;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,13 +6,18 @@ import type {
|
|||||||
} from '../../types/core-modules';
|
} from '../../types/core-modules';
|
||||||
import { CommandType } from '../structures';
|
import { CommandType } from '../structures';
|
||||||
|
|
||||||
/**
|
interface MetadataAccess {
|
||||||
* @since 2.0.0
|
|
||||||
*/
|
|
||||||
export interface ModuleManager {
|
|
||||||
get(id: string): string | undefined;
|
|
||||||
getMetadata(m: Module): CommandMeta | undefined;
|
getMetadata(m: Module): CommandMeta | undefined;
|
||||||
setMetadata(m: Module, c: CommandMeta): void;
|
setMetadata(m: Module, c: CommandMeta): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @since 2.0.0
|
||||||
|
* @internal - direct access to the module manager will be removed in version 4
|
||||||
|
*/
|
||||||
|
export interface ModuleManager extends MetadataAccess {
|
||||||
|
get(id: string): string | undefined;
|
||||||
|
|
||||||
set(id: string, path: string): void;
|
set(id: string, path: string): void;
|
||||||
getPublishableCommands(): Promise<CommandModule[]>;
|
getPublishableCommands(): Promise<CommandModule[]>;
|
||||||
getByNameCommandType<T extends CommandType>(
|
getByNameCommandType<T extends CommandType>(
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ export function partitionPlugins(
|
|||||||
export function treeSearch(
|
export function treeSearch(
|
||||||
iAutocomplete: AutocompleteInteraction,
|
iAutocomplete: AutocompleteInteraction,
|
||||||
options: SernOptionsData[] | undefined,
|
options: SernOptionsData[] | undefined,
|
||||||
): SernAutocompleteData | undefined {
|
): SernAutocompleteData & { parent?: string } | undefined {
|
||||||
if (options === undefined) return undefined;
|
if (options === undefined) return undefined;
|
||||||
//clone to prevent mutation of original command module
|
//clone to prevent mutation of original command module
|
||||||
const _options = options.map(a => ({ ...a }));
|
const _options = options.map(a => ({ ...a }));
|
||||||
@@ -68,11 +68,11 @@ export function treeSearch(
|
|||||||
const parentAndOptionMatches =
|
const parentAndOptionMatches =
|
||||||
subcommands.has(parent) && cur.name === choice.name;
|
subcommands.has(parent) && cur.name === choice.name;
|
||||||
if (parentAndOptionMatches) {
|
if (parentAndOptionMatches) {
|
||||||
return cur;
|
return { ...cur, parent };
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (cur.name === choice.name) {
|
if (cur.name === choice.name) {
|
||||||
return cur;
|
return { ...cur, parent: undefined };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,9 @@ import * as assert from 'assert';
|
|||||||
import { composeRoot, useContainer } from './dependency-injection';
|
import { composeRoot, useContainer } from './dependency-injection';
|
||||||
import type { DependencyConfiguration } from '../../types/ioc';
|
import type { DependencyConfiguration } from '../../types/ioc';
|
||||||
import { CoreContainer } from './container';
|
import { CoreContainer } from './container';
|
||||||
|
import { Result } from 'ts-results-es'
|
||||||
|
import { DefaultServices } from '../_internal';
|
||||||
|
import { AnyFunction } from '../../types/utility';
|
||||||
//SIDE EFFECT: GLOBAL DI
|
//SIDE EFFECT: GLOBAL DI
|
||||||
let containerSubject: CoreContainer<Partial<Dependencies>>;
|
let containerSubject: CoreContainer<Partial<Dependencies>>;
|
||||||
|
|
||||||
@@ -20,17 +22,83 @@ export function useContainerRaw() {
|
|||||||
return containerSubject;
|
return containerSubject;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const dependencyBuilder = (container: any, excluded: string[]) => {
|
||||||
|
type Insertable =
|
||||||
|
| ((container: CoreContainer<Dependencies>) => unknown )
|
||||||
|
| Record<PropertyKey, unknown>
|
||||||
|
return {
|
||||||
/**
|
/**
|
||||||
* @since 2.0.0
|
* Insert a dependency into your container.
|
||||||
* @param conf a configuration for creating your project dependencies
|
* Supply the correct key and dependency
|
||||||
*/
|
*/
|
||||||
export async function makeDependencies<const T extends Dependencies>(
|
add(key: keyof Dependencies, v: Insertable) {
|
||||||
conf: DependencyConfiguration,
|
Result
|
||||||
) {
|
.wrap(() => container.add({ [key]: v}))
|
||||||
|
.expect("Failed to add " + key);
|
||||||
|
},
|
||||||
|
/**
|
||||||
|
* Exclude any dependencies from being added.
|
||||||
|
* Warning: this could lead to bad errors if not used correctly
|
||||||
|
*/
|
||||||
|
exclude(...keys: (keyof Dependencies)[]) {
|
||||||
|
keys.forEach(key => excluded.push(key));
|
||||||
|
},
|
||||||
|
/**
|
||||||
|
* @param key the key of the dependency
|
||||||
|
* @param v The dependency to swap out.
|
||||||
|
* Swap out a preexisting dependency.
|
||||||
|
*/
|
||||||
|
swap(key: keyof Dependencies, v: Insertable) {
|
||||||
|
Result
|
||||||
|
.wrap(() => container.upsert({ [key]: v }))
|
||||||
|
.expect("Failed to update " + key);
|
||||||
|
},
|
||||||
|
/**
|
||||||
|
* @param key the key of the dependency
|
||||||
|
* @param cleanup Provide cleanup for the dependency at key. First parameter is the dependency itself
|
||||||
|
* @example
|
||||||
|
* ```ts
|
||||||
|
* addDisposer('dbConnection', (dbConnection) => dbConnection.end())
|
||||||
|
* ```
|
||||||
|
* Swap out a preexisting dependency.
|
||||||
|
*/
|
||||||
|
addDisposer(key: keyof Dependencies, cleanup: AnyFunction) {
|
||||||
|
Result
|
||||||
|
.wrap(() => container.addDisposer({ [key] : cleanup }))
|
||||||
|
.expect("Failed to addDisposer for" + key);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
type CallbackBuilder = (c: ReturnType<typeof dependencyBuilder>) => any
|
||||||
|
|
||||||
|
type ValidDependencyConfig =
|
||||||
|
| CallbackBuilder
|
||||||
|
| DependencyConfiguration;
|
||||||
|
|
||||||
|
export const insertLogger = (containerSubject: CoreContainer<any>) => {
|
||||||
|
containerSubject
|
||||||
|
.upsert({'@sern/logger': () => new DefaultServices.DefaultLogging});
|
||||||
|
}
|
||||||
|
export async function makeDependencies<const T extends Dependencies>
|
||||||
|
(conf: ValidDependencyConfig) {
|
||||||
//Until there are more optional dependencies, just check if the logger exists
|
//Until there are more optional dependencies, just check if the logger exists
|
||||||
//SIDE EFFECT
|
//SIDE EFFECT
|
||||||
containerSubject = new CoreContainer();
|
containerSubject = new CoreContainer();
|
||||||
await composeRoot(containerSubject, conf);
|
if(typeof conf === 'function') {
|
||||||
|
const excluded: string[] = [];
|
||||||
|
conf(dependencyBuilder(containerSubject, excluded));
|
||||||
|
if(!excluded.includes('@sern/logger')) {
|
||||||
|
assert.ok(!containerSubject.getTokens()['@sern/logger'])
|
||||||
|
insertLogger(containerSubject);
|
||||||
|
}
|
||||||
|
containerSubject.ready();
|
||||||
|
} else {
|
||||||
|
composeRoot(containerSubject, conf);
|
||||||
|
}
|
||||||
|
|
||||||
return useContainer<T>();
|
return useContainer<T>();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -21,11 +21,9 @@ export class CoreContainer<T extends Partial<Dependencies>> extends Container<T,
|
|||||||
.subscribe({ complete: unsubscribe });
|
.subscribe({ complete: unsubscribe });
|
||||||
|
|
||||||
(this as Container<{}, {}>)
|
(this as Container<{}, {}>)
|
||||||
.add({
|
.add({ '@sern/errors': () => new DefaultServices.DefaultErrorHandling(),
|
||||||
'@sern/errors': () => new DefaultServices.DefaultErrorHandling(),
|
|
||||||
'@sern/emitter': () => new SernEmitter(),
|
'@sern/emitter': () => new SernEmitter(),
|
||||||
'@sern/store': () => new ModuleStore(),
|
'@sern/store': () => new ModuleStore() })
|
||||||
})
|
|
||||||
.add(ctx => {
|
.add(ctx => {
|
||||||
return {
|
return {
|
||||||
'@sern/modules': () =>
|
'@sern/modules': () =>
|
||||||
@@ -34,9 +32,7 @@ export class CoreContainer<T extends Partial<Dependencies>> extends Container<T,
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
isReady() {
|
isReady() {
|
||||||
|
|
||||||
return this.ready$.closed;
|
return this.ready$.closed;
|
||||||
}
|
}
|
||||||
override async disposeAll() {
|
override async disposeAll() {
|
||||||
@@ -44,9 +40,7 @@ export class CoreContainer<T extends Partial<Dependencies>> extends Container<T,
|
|||||||
const otherDisposables = Object
|
const otherDisposables = Object
|
||||||
.entries(this._context)
|
.entries(this._context)
|
||||||
.flatMap(([key, value]) =>
|
.flatMap(([key, value]) =>
|
||||||
'dispose' in value
|
'dispose' in value ? [key] : []);
|
||||||
? [key]
|
|
||||||
: []);
|
|
||||||
|
|
||||||
for(const key of otherDisposables) {
|
for(const key of otherDisposables) {
|
||||||
this.addDisposer({ [key]: (dep: Disposable) => dep.dispose() } as never);
|
this.addDisposer({ [key]: (dep: Disposable) => dep.dispose() } as never);
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import type { CoreDependencies, DependencyConfiguration, IntoDependencies } from '../../types/ioc';
|
import type { CoreDependencies, DependencyConfiguration, IntoDependencies } from '../../types/ioc';
|
||||||
import { DefaultServices } from '../_internal';
|
import { insertLogger, useContainerRaw } from './base';
|
||||||
import { useContainerRaw } from './base';
|
|
||||||
import { CoreContainer } from './container';
|
import { CoreContainer } from './container';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -53,16 +52,14 @@ export function Services<const T extends (keyof Dependencies)[]>(...keys: [...T]
|
|||||||
* Finally, update the containerSubject with the new container state
|
* Finally, update the containerSubject with the new container state
|
||||||
* @param conf
|
* @param conf
|
||||||
*/
|
*/
|
||||||
export async function composeRoot(
|
export function composeRoot(
|
||||||
container: CoreContainer<Partial<Dependencies>>,
|
container: CoreContainer<Partial<Dependencies>>,
|
||||||
conf: DependencyConfiguration,
|
conf: DependencyConfiguration,
|
||||||
) {
|
) {
|
||||||
//container should have no client or logger yet.
|
//container should have no client or logger yet.
|
||||||
const hasLogger = conf.exclude?.has('@sern/logger');
|
const hasLogger = conf.exclude?.has('@sern/logger');
|
||||||
if (!hasLogger) {
|
if (!hasLogger) {
|
||||||
container.upsert({
|
insertLogger(container);
|
||||||
'@sern/logger': () => new DefaultServices.DefaultLogging(),
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
//Build the container based on the callback provided by the user
|
//Build the container based on the callback provided by the user
|
||||||
conf.build(container as CoreContainer<Omit<CoreDependencies, '@sern/client'>>);
|
conf.build(container as CoreContainer<Omit<CoreDependencies, '@sern/client'>>);
|
||||||
|
|||||||
@@ -23,19 +23,21 @@ export type ModuleResult<T> = Promise<ImportPayload<T>>;
|
|||||||
* export default commandModule({})
|
* export default commandModule({})
|
||||||
*/
|
*/
|
||||||
export async function importModule<T>(absPath: string) {
|
export async function importModule<T>(absPath: string) {
|
||||||
let module = await import(absPath).then(esm => esm.default);
|
let fileModule = await import(absPath);
|
||||||
|
|
||||||
assert(module, `Found no export for module at ${absPath}. Forgot to ignore with "!"? (!${basename(absPath)})?`);
|
let commandModule = fileModule.default;
|
||||||
if ('default' in module) {
|
|
||||||
module = module.default;
|
assert(commandModule , `Found no export @ ${absPath}. Forgot to ignore with "!"? (!${basename(absPath)})?`);
|
||||||
|
if ('default' in commandModule ) {
|
||||||
|
commandModule = commandModule.default;
|
||||||
}
|
}
|
||||||
return Result
|
return Result
|
||||||
.wrap(() => module.getInstance())
|
.wrap(() => ({ module: commandModule.getInstance() }))
|
||||||
.unwrapOr(module) as T;
|
.unwrapOr({ module: commandModule }) as T;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function defaultModuleLoader<T extends Module>(absPath: string): ModuleResult<T> {
|
export async function defaultModuleLoader<T extends Module>(absPath: string): ModuleResult<T> {
|
||||||
let module = await importModule<T>(absPath);
|
let { module } = await importModule<{ module: T }>(absPath);
|
||||||
assert(module, `Found an undefined module: ${absPath}`);
|
assert(module, `Found an undefined module: ${absPath}`);
|
||||||
return { module, absPath };
|
return { module, absPath };
|
||||||
}
|
}
|
||||||
@@ -51,7 +53,8 @@ export const fmtFileName = (fileName: string) => parse(fileName).name;
|
|||||||
export function buildModuleStream<T extends Module>(
|
export function buildModuleStream<T extends Module>(
|
||||||
input: ObservableInput<string>,
|
input: ObservableInput<string>,
|
||||||
): Observable<ImportPayload<T>> {
|
): Observable<ImportPayload<T>> {
|
||||||
return from(input).pipe(mergeMap(defaultModuleLoader<T>));
|
return from(input)
|
||||||
|
.pipe(mergeMap(defaultModuleLoader<T>));
|
||||||
}
|
}
|
||||||
|
|
||||||
export const getFullPathTree = (dir: string) => readPaths(resolve(dir));
|
export const getFullPathTree = (dir: string) => readPaths(resolve(dir));
|
||||||
|
|||||||
41
src/core/structures/command-error.ts
Normal file
41
src/core/structures/command-error.ts
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
import type { ReplyOptions } from "../../types/utility";
|
||||||
|
import type { Logging } from "../contracts";
|
||||||
|
|
||||||
|
export interface Response {
|
||||||
|
type: 'fail' | 'continue';
|
||||||
|
body?: ReplyOptions;
|
||||||
|
log?: { type: keyof Logging; message: unknown }
|
||||||
|
}
|
||||||
|
|
||||||
|
export const of = () => {
|
||||||
|
const payload = {
|
||||||
|
type: 'fail',
|
||||||
|
body: undefined,
|
||||||
|
log : undefined
|
||||||
|
} as Record<PropertyKey, unknown>
|
||||||
|
|
||||||
|
return {
|
||||||
|
/**
|
||||||
|
* @param {'fail' | 'continue'} p a status to determine if the error will
|
||||||
|
* terminate your application or continue. Warning and
|
||||||
|
*/
|
||||||
|
status: (p: 'fail' | 'continue') => {
|
||||||
|
payload.type = p;
|
||||||
|
return payload;
|
||||||
|
},
|
||||||
|
/**
|
||||||
|
* @param {keyof Logging} type Determine to log to logger[type].
|
||||||
|
* @param {T} message the message to log
|
||||||
|
*
|
||||||
|
* Log this error with the logger.
|
||||||
|
*/
|
||||||
|
log: <T=string>(type: keyof Logging, message: T) => {
|
||||||
|
payload.log = { type, message };
|
||||||
|
return payload;
|
||||||
|
},
|
||||||
|
reply: (bodyContent: ReplyOptions) => {
|
||||||
|
payload.body = bodyContent;
|
||||||
|
return payload;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -11,8 +11,8 @@ import {
|
|||||||
import { CoreContext } from '../structures/core-context';
|
import { CoreContext } from '../structures/core-context';
|
||||||
import { Result, Ok, Err } from 'ts-results-es';
|
import { Result, Ok, Err } from 'ts-results-es';
|
||||||
import * as assert from 'assert';
|
import * as assert from 'assert';
|
||||||
|
import { ReplyOptions } from '../../types/utility';
|
||||||
|
|
||||||
type ReplyOptions = string | Omit<InteractionReplyOptions, 'fetchReply'> | MessageReplyOptions;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @since 1.0.0
|
* @since 1.0.0
|
||||||
@@ -103,9 +103,9 @@ export class Context extends CoreContext<Message, ChatInputCommandInteraction> {
|
|||||||
public async reply(content: ReplyOptions) {
|
public async reply(content: ReplyOptions) {
|
||||||
return safeUnwrap(
|
return safeUnwrap(
|
||||||
this.ctx
|
this.ctx
|
||||||
.map(m => m.reply(content as string | MessageReplyOptions))
|
.map(m => m.reply(content as MessageReplyOptions))
|
||||||
.mapErr(i =>
|
.mapErr(i =>
|
||||||
i.reply(content as string | InteractionReplyOptions).then(() => i.fetchReply()),
|
i.reply(content as InteractionReplyOptions).then(() => i.fetchReply()),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,3 +3,4 @@ export * from './context';
|
|||||||
export * from './sern-emitter';
|
export * from './sern-emitter';
|
||||||
export * from './services';
|
export * from './services';
|
||||||
export * from './module-store';
|
export * from './module-store';
|
||||||
|
export * as CommandError from './command-error';
|
||||||
|
|||||||
@@ -3,18 +3,18 @@ import { ErrorHandling } from '../../contracts';
|
|||||||
/**
|
/**
|
||||||
* @internal
|
* @internal
|
||||||
* @since 2.0.0
|
* @since 2.0.0
|
||||||
* Version 4.0.0 will internalize this api. Please refrain from using ModuleStore!
|
* Version 4.0.0 will internalize this api. Please refrain from using the defaults!
|
||||||
*/
|
*/
|
||||||
export class DefaultErrorHandling implements ErrorHandling {
|
export class DefaultErrorHandling implements ErrorHandling {
|
||||||
crash(err: Error): never {
|
crash(err: Error): never {
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
|
|
||||||
keepAlive = 5;
|
#keepAlive = 5;
|
||||||
|
|
||||||
updateAlive(err: Error) {
|
updateAlive(err: Error) {
|
||||||
this.keepAlive--;
|
this.#keepAlive--;
|
||||||
if (this.keepAlive === 0) {
|
if (this.#keepAlive === 0) {
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import { CommandType } from '../enums';
|
|||||||
export class DefaultModuleManager implements ModuleManager {
|
export class DefaultModuleManager implements ModuleManager {
|
||||||
constructor(private moduleStore: CoreModuleStore) {}
|
constructor(private moduleStore: CoreModuleStore) {}
|
||||||
|
|
||||||
|
|
||||||
getByNameCommandType<T extends CommandType>(name: string, commandType: T) {
|
getByNameCommandType<T extends CommandType>(name: string, commandType: T) {
|
||||||
const id = this.get(Id.create(name, commandType));
|
const id = this.get(Id.create(name, commandType));
|
||||||
if (!id) {
|
if (!id) {
|
||||||
|
|||||||
@@ -9,23 +9,16 @@ import {
|
|||||||
SernError,
|
SernError,
|
||||||
} from '../core/_internal';
|
} from '../core/_internal';
|
||||||
import { createResultResolver } from './event-utils';
|
import { createResultResolver } from './event-utils';
|
||||||
import { AutocompleteInteraction, BaseInteraction, Message } from 'discord.js';
|
import { BaseInteraction, Message } from 'discord.js';
|
||||||
import { CommandType, Context } from '../core';
|
import { CommandType, Context } from '../core';
|
||||||
import type { Args } from '../types/utility';
|
import type { AnyFunction, Args } from '../types/utility';
|
||||||
import type { BothCommand, CommandModule, Module, Processed } from '../types/core-modules';
|
import type { CommandModule, Module, Processed } from '../types/core-modules';
|
||||||
|
|
||||||
function dispatchAutocomplete(payload: {
|
//TODO: refactor dispatchers so that it implements a strategy for each different type of payload?
|
||||||
module: Processed<BothCommand>;
|
export function dispatchMessage(module: Processed<CommandModule>, args: [Context, Args]) {
|
||||||
event: AutocompleteInteraction;
|
|
||||||
}) {
|
|
||||||
const option = treeSearch(payload.event, payload.module.options);
|
|
||||||
assert.ok(
|
|
||||||
option,
|
|
||||||
Error(SernError.NotSupportedInteraction + ` There is no autocomplete tag for this option`),
|
|
||||||
);
|
|
||||||
return {
|
return {
|
||||||
module: option.command as Processed<Module>, //autocomplete is not a true "module" warning cast!
|
module,
|
||||||
args: [payload.event],
|
args,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -36,10 +29,10 @@ export function contextArgs(wrappable: Message | BaseInteraction, messageArgs?:
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
function intoPayload(module: Processed<Module>) {
|
function intoPayload(module: Processed<Module>, ) {
|
||||||
return pipe(
|
return pipe(
|
||||||
arrayifySource,
|
arrayifySource,
|
||||||
map(args => ({ module, args })),
|
map(args => ({ module, args, })),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -81,13 +74,18 @@ export function createDispatcher(payload: {
|
|||||||
case CommandType.Slash:
|
case CommandType.Slash:
|
||||||
case CommandType.Both: {
|
case CommandType.Both: {
|
||||||
if (isAutocomplete(payload.event)) {
|
if (isAutocomplete(payload.event)) {
|
||||||
/**
|
const option = treeSearch(payload.event, payload.module.options);
|
||||||
* Autocomplete is a special case that
|
assert.ok(
|
||||||
* must be handled separately, since it's
|
option,
|
||||||
* too different from regular command modules
|
Error(SernError.NotSupportedInteraction + ` There is no autocomplete tag for this option`),
|
||||||
* CAST SAFETY: payload is already guaranteed to be a slash command or both command
|
);
|
||||||
*/
|
const { command, name, parent } = option;
|
||||||
return dispatchAutocomplete(payload as never);
|
|
||||||
|
return {
|
||||||
|
...payload,
|
||||||
|
module: command as Processed<Module>, //autocomplete is not a true "module" warning cast!
|
||||||
|
args: [payload.event],
|
||||||
|
};
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
module: payload.module,
|
module: payload.module,
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ import { contextArgs, createDispatcher } from './dispatchers';
|
|||||||
import { ObservableInput, pipe } from 'rxjs';
|
import { ObservableInput, pipe } from 'rxjs';
|
||||||
import { SernEmitter } from '../core';
|
import { SernEmitter } from '../core';
|
||||||
import { Err, Ok, Result } from 'ts-results-es';
|
import { Err, Ok, Result } from 'ts-results-es';
|
||||||
import type { Awaitable } from '../types/utility';
|
import type { AnyFunction, Awaitable } from '../types/utility';
|
||||||
import type { ControlPlugin } from '../types/core-plugin';
|
import type { ControlPlugin } from '../types/core-plugin';
|
||||||
import type { AnyModule, CommandModule, Module, Processed } from '../types/core-modules';
|
import type { AnyModule, CommandModule, Module, Processed } from '../types/core-modules';
|
||||||
import type { ImportPayload } from '../types/core';
|
import type { ImportPayload } from '../types/core';
|
||||||
@@ -78,7 +78,10 @@ export function createInteractionHandler<T extends Interaction>(
|
|||||||
return Files
|
return Files
|
||||||
.defaultModuleLoader<Processed<CommandModule>>(fullPath)
|
.defaultModuleLoader<Processed<CommandModule>>(fullPath)
|
||||||
.then(payload =>
|
.then(payload =>
|
||||||
Ok(createDispatcher({ module: payload.module, event })));
|
Ok(createDispatcher({
|
||||||
|
module: payload.module,
|
||||||
|
event,
|
||||||
|
})));
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -97,9 +100,10 @@ export function createMessageHandler(
|
|||||||
}
|
}
|
||||||
return Files
|
return Files
|
||||||
.defaultModuleLoader<Processed<CommandModule>>(fullPath)
|
.defaultModuleLoader<Processed<CommandModule>>(fullPath)
|
||||||
.then(({ module })=> {
|
.then((payload)=> {
|
||||||
const args = contextArgs(event, rest);
|
const args = contextArgs(event, rest);
|
||||||
return Ok({ module, args });
|
return Ok({ args, ...payload });
|
||||||
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -130,6 +134,12 @@ export function buildModules<T extends AnyModule>(
|
|||||||
.pipe(assignDefaults(moduleManager));
|
.pipe(assignDefaults(moduleManager));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
interface ExecutePayload {
|
||||||
|
module: Processed<Module>;
|
||||||
|
task: () => Awaitable<unknown>;
|
||||||
|
args: unknown[]
|
||||||
|
}
|
||||||
/**
|
/**
|
||||||
* Wraps the task in a Result as a try / catch.
|
* Wraps the task in a Result as a try / catch.
|
||||||
* if the task is ok, an event is emitted and the stream becomes empty
|
* if the task is ok, an event is emitted and the stream becomes empty
|
||||||
@@ -140,13 +150,13 @@ export function buildModules<T extends AnyModule>(
|
|||||||
*/
|
*/
|
||||||
export function executeModule(
|
export function executeModule(
|
||||||
emitter: Emitter,
|
emitter: Emitter,
|
||||||
|
logger: Logging|undefined,
|
||||||
|
errHandler: ErrorHandling,
|
||||||
{
|
{
|
||||||
module,
|
module,
|
||||||
task,
|
task,
|
||||||
}: {
|
args
|
||||||
module: Processed<Module>;
|
}: ExecutePayload,
|
||||||
task: () => Awaitable<unknown>;
|
|
||||||
},
|
|
||||||
) {
|
) {
|
||||||
return of(module).pipe(
|
return of(module).pipe(
|
||||||
//converting the task into a promise so rxjs can resolve the Awaitable properly
|
//converting the task into a promise so rxjs can resolve the Awaitable properly
|
||||||
@@ -155,9 +165,9 @@ export function executeModule(
|
|||||||
if (result.isOk()) {
|
if (result.isOk()) {
|
||||||
emitter.emit('module.activate', SernEmitter.success(module));
|
emitter.emit('module.activate', SernEmitter.success(module));
|
||||||
return EMPTY;
|
return EMPTY;
|
||||||
} else {
|
|
||||||
return throwError(() => SernEmitter.failure(module, result.error));
|
|
||||||
}
|
}
|
||||||
|
return throwError(() => SernEmitter.failure(module, result.error));
|
||||||
|
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -208,7 +218,7 @@ export function callInitPlugins<T extends Processed<AnyModule>>(sernEmitter: Emi
|
|||||||
},
|
},
|
||||||
onNext: ({ module }) => {
|
onNext: ({ module }) => {
|
||||||
sernEmitter.emit('module.register', SernEmitter.success(module));
|
sernEmitter.emit('module.register', SernEmitter.success(module));
|
||||||
return module;
|
return { module };
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -220,16 +230,22 @@ export function callInitPlugins<T extends Processed<AnyModule>>(sernEmitter: Emi
|
|||||||
*/
|
*/
|
||||||
export function makeModuleExecutor<
|
export function makeModuleExecutor<
|
||||||
M extends Processed<Module>,
|
M extends Processed<Module>,
|
||||||
Args extends { module: M; args: unknown[] },
|
Args extends {
|
||||||
|
module: M;
|
||||||
|
args: unknown[];
|
||||||
|
},
|
||||||
>(onStop: (m: M) => unknown) {
|
>(onStop: (m: M) => unknown) {
|
||||||
const onNext = ({ args, module }: Args) => ({
|
const onNext = ({ args, module }: Args) => ({
|
||||||
task: () => module.execute(...args),
|
task: () => module.execute(...args),
|
||||||
module,
|
module,
|
||||||
|
args
|
||||||
});
|
});
|
||||||
return concatMap(
|
return concatMap(
|
||||||
createResultResolver({
|
createResultResolver({
|
||||||
onStop,
|
onStop,
|
||||||
createStream: ({ args, module }) => from(module.onEvent).pipe(callPlugin(args)),
|
createStream: ({ args, module }) =>
|
||||||
|
from(module.onEvent)
|
||||||
|
.pipe(callPlugin(args)),
|
||||||
onNext,
|
onNext,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import {
|
|||||||
import { createInteractionHandler, executeModule, makeModuleExecutor } from './_internal';
|
import { createInteractionHandler, executeModule, makeModuleExecutor } from './_internal';
|
||||||
import type { DependencyList } from '../types/ioc';
|
import type { DependencyList } from '../types/ioc';
|
||||||
|
|
||||||
export function interactionHandler([emitter, , , modules, client]: DependencyList) {
|
export function interactionHandler([emitter, err, log, modules, client]: DependencyList) {
|
||||||
const interactionStream$ = sharedEventStream<Interaction>(client, 'interactionCreate');
|
const interactionStream$ = sharedEventStream<Interaction>(client, 'interactionCreate');
|
||||||
const handle = createInteractionHandler(interactionStream$, modules);
|
const handle = createInteractionHandler(interactionStream$, modules);
|
||||||
|
|
||||||
@@ -28,6 +28,6 @@ export function interactionHandler([emitter, , , modules, client]: DependencyLis
|
|||||||
filterTap(e => emitter.emit('warning', SernEmitter.warning(e))),
|
filterTap(e => emitter.emit('warning', SernEmitter.warning(e))),
|
||||||
makeModuleExecutor(module =>
|
makeModuleExecutor(module =>
|
||||||
emitter.emit('module.activate', SernEmitter.failure(module, SernError.PluginFailure))),
|
emitter.emit('module.activate', SernEmitter.failure(module, SernError.PluginFailure))),
|
||||||
mergeMap(payload => executeModule(emitter, payload)),
|
mergeMap(payload => executeModule(emitter, log, err, payload)),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ function hasPrefix(prefix: string, content: string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function messageHandler(
|
export function messageHandler(
|
||||||
[emitter, , log, modules, client]: DependencyList,
|
[emitter, err, log, modules, client]: DependencyList,
|
||||||
defaultPrefix: string | undefined,
|
defaultPrefix: string | undefined,
|
||||||
) {
|
) {
|
||||||
if (!defaultPrefix) {
|
if (!defaultPrefix) {
|
||||||
@@ -42,6 +42,6 @@ export function messageHandler(
|
|||||||
makeModuleExecutor(module => {
|
makeModuleExecutor(module => {
|
||||||
emitter.emit('module.activate', SernEmitter.failure(module, SernError.PluginFailure));
|
emitter.emit('module.activate', SernEmitter.failure(module, SernError.PluginFailure));
|
||||||
}),
|
}),
|
||||||
mergeMap(payload => executeModule(emitter, payload)),
|
mergeMap(payload => executeModule(emitter, log, err, payload)),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,10 +17,9 @@ export function startReadyEvent(
|
|||||||
|
|
||||||
return concat(ready$, buildModules<AnyModule>(allPaths, moduleManager))
|
return concat(ready$, buildModules<AnyModule>(allPaths, moduleManager))
|
||||||
.pipe(callInitPlugins(sEmitter))
|
.pipe(callInitPlugins(sEmitter))
|
||||||
.subscribe(module => {
|
.subscribe(({ module }) => {
|
||||||
register(moduleManager, module).expect(
|
register(moduleManager, module)
|
||||||
SernError.InvalidModuleType + ' ' + util.inspect(module),
|
.expect(SernError.InvalidModuleType + ' ' + util.inspect(module));
|
||||||
);
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,27 +4,28 @@ import { SernError } from '../core/_internal';
|
|||||||
import { buildModules, callInitPlugins, handleCrash, eventDispatcher } from './_internal';
|
import { buildModules, callInitPlugins, handleCrash, eventDispatcher } from './_internal';
|
||||||
import { Service } from '../core/ioc';
|
import { Service } from '../core/ioc';
|
||||||
import type { DependencyList } from '../types/ioc';
|
import type { DependencyList } from '../types/ioc';
|
||||||
import type { CommandModule, EventModule, Processed } from '../types/core-modules';
|
import type { EventModule, Processed } from '../types/core-modules';
|
||||||
|
|
||||||
export function eventsHandler(
|
export function eventsHandler(
|
||||||
[emitter, err, log, moduleManager, client]: DependencyList,
|
[emitter, err, log, moduleManager, client]: DependencyList,
|
||||||
allPaths: ObservableInput<string>,
|
allPaths: ObservableInput<string>,
|
||||||
) {
|
) {
|
||||||
//code smell
|
//code smell
|
||||||
const intoDispatcher = (e: Processed<EventModule | CommandModule>) => {
|
const intoDispatcher = (e: { module: Processed<EventModule> }) => {
|
||||||
switch (e.type) {
|
switch (e.module.type) {
|
||||||
case EventType.Sern:
|
case EventType.Sern:
|
||||||
return eventDispatcher(e, emitter);
|
return eventDispatcher(e.module, emitter);
|
||||||
case EventType.Discord:
|
case EventType.Discord:
|
||||||
return eventDispatcher(e, client);
|
return eventDispatcher(e.module, client);
|
||||||
case EventType.External:
|
case EventType.External:
|
||||||
return eventDispatcher(e, Service(e.emitter));
|
return eventDispatcher(e.module, Service(e.module.emitter));
|
||||||
default:
|
default:
|
||||||
throw Error(SernError.InvalidModuleType + ' while creating event handler');
|
throw Error(SernError.InvalidModuleType + ' while creating event handler');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
buildModules<EventModule>(allPaths, moduleManager)
|
buildModules<EventModule>(allPaths, moduleManager)
|
||||||
.pipe(callInitPlugins(emitter),
|
.pipe(
|
||||||
|
callInitPlugins(emitter),
|
||||||
map(intoDispatcher),
|
map(intoDispatcher),
|
||||||
/**
|
/**
|
||||||
* Where all events are turned on
|
* Where all events are turned on
|
||||||
|
|||||||
@@ -19,6 +19,8 @@ import { CommandType, Context, EventType } from '../../src/core';
|
|||||||
import { AnyCommandPlugin, AnyEventPlugin, ControlPlugin, InitPlugin } from './core-plugin';
|
import { AnyCommandPlugin, AnyEventPlugin, ControlPlugin, InitPlugin } from './core-plugin';
|
||||||
import { Awaitable, Args, SlashOptions, SernEventsMapping } from './utility';
|
import { Awaitable, Args, SlashOptions, SernEventsMapping } from './utility';
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
export interface CommandMeta {
|
export interface CommandMeta {
|
||||||
fullPath: string;
|
fullPath: string;
|
||||||
id: string;
|
id: string;
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
|
||||||
export interface ImportPayload<T> {
|
export interface ImportPayload<T> {
|
||||||
module: T;
|
module: T;
|
||||||
absPath: string;
|
absPath: string;
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { CommandInteractionOptionResolver } from 'discord.js';
|
import type { CommandInteractionOptionResolver, InteractionReplyOptions, MessageReplyOptions } from 'discord.js';
|
||||||
import { PayloadType } from '../core';
|
import type { PayloadType } from '../core';
|
||||||
import { AnyModule } from './core-modules';
|
import type { AnyModule } from './core-modules';
|
||||||
|
|
||||||
export type Awaitable<T> = PromiseLike<T> | T;
|
export type Awaitable<T> = PromiseLike<T> | T;
|
||||||
|
|
||||||
@@ -27,3 +27,7 @@ export type Payload =
|
|||||||
| { type: PayloadType.Success; module: AnyModule }
|
| { type: PayloadType.Success; module: AnyModule }
|
||||||
| { type: PayloadType.Failure; module?: AnyModule; reason: string | Error }
|
| { type: PayloadType.Failure; module?: AnyModule; reason: string | Error }
|
||||||
| { type: PayloadType.Warning; reason: string };
|
| { type: PayloadType.Warning; reason: string };
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
export type ReplyOptions = string | Omit<InteractionReplyOptions, 'fetchReply'> | MessageReplyOptions;
|
||||||
|
|||||||
@@ -3,8 +3,6 @@
|
|||||||
"rootDir": "src",
|
"rootDir": "src",
|
||||||
"strict": true,
|
"strict": true,
|
||||||
"esModuleInterop": true,
|
"esModuleInterop": true,
|
||||||
"noImplicitAny": true,
|
|
||||||
"experimentalDecorators": true,
|
|
||||||
"strictNullChecks": true,
|
"strictNullChecks": true,
|
||||||
"moduleResolution": "node",
|
"moduleResolution": "node",
|
||||||
"skipLibCheck": true,
|
"skipLibCheck": true,
|
||||||
|
|||||||
Reference in New Issue
Block a user