mirror of
https://github.com/sern-handler/handler
synced 2026-06-07 16:32:14 +00:00
Compare commits
39 Commits
feat/error
...
version/3
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a19edaf883 | ||
|
|
90e55dfa14 | ||
|
|
2106522812 | ||
|
|
ce8c4bf649 | ||
|
|
e89b918390 | ||
|
|
f8b69ae542 | ||
|
|
48f9f6ec16 | ||
|
|
86ebb221ed | ||
|
|
4efdbb21fb | ||
|
|
07b11b357b | ||
|
|
ac7f47c590 | ||
| 45cbda7b42 | |||
|
|
5cad432589 | ||
|
|
044a10dace | ||
|
|
9d5c6c714f | ||
|
|
4f2387119a | ||
|
|
a6fa4e3dcb | ||
|
|
c281832db2 | ||
|
|
a359f73fa2 | ||
| 655bb8d358 | |||
| e8d5029834 | |||
|
|
b0399f9507 | ||
|
|
b962dae36c | ||
|
|
c73cf96cb2 | ||
|
|
7458befe8a | ||
|
|
efe49391e8 | ||
|
|
3140f80c10 | ||
|
|
504cdee7b2 | ||
|
|
c7661f272c | ||
|
|
daac37c288 | ||
|
|
a579e272d0 | ||
|
|
2051aa1ac0 | ||
|
|
237c8537c6 | ||
|
|
77fb00d386 | ||
|
|
89f6bbb975 | ||
|
|
8ef4ee87e9 | ||
|
|
fd39858636 | ||
|
|
132b625070 | ||
|
|
03439fec43 |
@@ -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
|
|
||||||
2
.github/workflows/continuous-integration.yml
vendored
2
.github/workflows/continuous-integration.yml
vendored
@@ -23,7 +23,7 @@ jobs:
|
|||||||
uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3
|
uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3
|
||||||
|
|
||||||
- name: Set up Node.js
|
- name: Set up Node.js
|
||||||
uses: actions/setup-node@64ed1c7eab4cce3362f8c340dee64e5eaeef8f7c # v3
|
uses: actions/setup-node@1a4442cacd436585916779262731d5b162bc6ec7 # v3
|
||||||
with:
|
with:
|
||||||
node-version: 17
|
node-version: 17
|
||||||
|
|
||||||
|
|||||||
34
.github/workflows/npm-publish-dev.yml
vendored
Normal file
34
.github/workflows/npm-publish-dev.yml
vendored
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
name: Continuous Delivery
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- main
|
||||||
|
paths:
|
||||||
|
- 'src/**'
|
||||||
|
- 'package.json'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
Publish:
|
||||||
|
name: Publishing Dev
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Check out Git repository
|
||||||
|
uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3
|
||||||
|
|
||||||
|
- name: Set up Node.js
|
||||||
|
uses: actions/setup-node@64ed1c7eab4cce3362f8c340dee64e5eaeef8f7c # v3
|
||||||
|
with:
|
||||||
|
node-version: 18
|
||||||
|
registry-url: 'https://registry.npmjs.org'
|
||||||
|
|
||||||
|
- name: Install Node.js dependencies
|
||||||
|
run: npm i && npm run build:dev
|
||||||
|
|
||||||
|
- name: Publish to npm
|
||||||
|
run: |
|
||||||
|
npm version premajor --preid "dev.$(git rev-parse --verify --short HEAD)" --git-tag-version=false
|
||||||
|
npm publish --tag dev
|
||||||
|
env:
|
||||||
|
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||||
2
.github/workflows/npm-publish.yml
vendored
2
.github/workflows/npm-publish.yml
vendored
@@ -11,7 +11,7 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3
|
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3
|
||||||
- uses: actions/setup-node@5e21ff4d9bc1a8cf6de233a3057d20ec6b3fb69d # v3
|
- uses: actions/setup-node@1a4442cacd436585916779262731d5b162bc6ec7 # v3
|
||||||
with:
|
with:
|
||||||
node-version: 17
|
node-version: 17
|
||||||
- run: yarn --immutable
|
- run: yarn --immutable
|
||||||
|
|||||||
2
.github/workflows/release-please.yml
vendored
2
.github/workflows/release-please.yml
vendored
@@ -6,7 +6,7 @@ jobs:
|
|||||||
release-please:
|
release-please:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: google-github-actions/release-please-action@ca6063f4ed81b55db15b8c42d1b6f7925866342d # v3
|
- uses: google-github-actions/release-please-action@db8f2c60ee802b3748b512940dde88eabd7b7e01 # v3
|
||||||
with:
|
with:
|
||||||
release-type: node
|
release-type: node
|
||||||
package-name: release-please-action
|
package-name: release-please-action
|
||||||
|
|||||||
2
.github/workflows/test.yml
vendored
2
.github/workflows/test.yml
vendored
@@ -20,7 +20,7 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3
|
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3
|
||||||
- name: Use Node.js ${{ matrix.node-version }}
|
- name: Use Node.js ${{ matrix.node-version }}
|
||||||
uses: actions/setup-node@5e21ff4d9bc1a8cf6de233a3057d20ec6b3fb69d # v3
|
uses: actions/setup-node@1a4442cacd436585916779262731d5b162bc6ec7 # v3
|
||||||
with:
|
with:
|
||||||
node-version: ${{ matrix.node-version }}
|
node-version: ${{ matrix.node-version }}
|
||||||
cache: 'npm'
|
cache: 'npm'
|
||||||
|
|||||||
64
CHANGELOG.md
64
CHANGELOG.md
@@ -1,5 +1,69 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## [3.3.4](https://github.com/sern-handler/handler/compare/v3.3.3...v3.3.4) (2024-03-18)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* sern emitter err ([#358](https://github.com/sern-handler/handler/issues/358)) ([90e55df](https://github.com/sern-handler/handler/commit/90e55dfa1466c91e5da48922251309331921b1ef))
|
||||||
|
|
||||||
|
## [3.3.3](https://github.com/sern-handler/handler/compare/v3.3.2...v3.3.3) (2024-02-25)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* rm deprecated class modules, clean up, rm indirection ([#355](https://github.com/sern-handler/handler/issues/355)) ([48f9f6e](https://github.com/sern-handler/handler/commit/48f9f6ec16e650d574bd24dcbb0ed176933bfe17))
|
||||||
|
* singleton init not being fired when inserting function ([07b11b3](https://github.com/sern-handler/handler/commit/07b11b357baac0c3c7055c022bc353995c80f766))
|
||||||
|
* typings and cleanup ([#356](https://github.com/sern-handler/handler/issues/356)) ([ce8c4bf](https://github.com/sern-handler/handler/commit/ce8c4bf6492b9680fb1c1a530d3e0028f214ad2f))
|
||||||
|
|
||||||
|
## [3.3.2](https://github.com/sern-handler/handler/compare/v3.3.1...v3.3.2) (2024-01-08)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* presence feature not working on cjs applications ([#351](https://github.com/sern-handler/handler/issues/351)) ([4f23871](https://github.com/sern-handler/handler/commit/4f2387119acfde036d0d1626553e9050f55627d1))
|
||||||
|
|
||||||
|
## [3.3.1](https://github.com/sern-handler/handler/compare/v3.3.0...v3.3.1) (2024-01-07)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* crashing when slash command is used as text command ([#349](https://github.com/sern-handler/handler/issues/349)) ([a359f73](https://github.com/sern-handler/handler/commit/a359f73fa24127a4964d411c8c1c0dfea5edc0f1))
|
||||||
|
|
||||||
|
|
||||||
|
### Reverts
|
||||||
|
|
||||||
|
* the last commit ([655bb8d](https://github.com/sern-handler/handler/commit/655bb8d35815fe0ce9797d8b169310a07b284ae0))
|
||||||
|
|
||||||
|
## [3.3.0](https://github.com/sern-handler/handler/compare/v3.2.1...v3.3.0) (2023-12-27)
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
* presence ([#345](https://github.com/sern-handler/handler/issues/345)) ([7458bef](https://github.com/sern-handler/handler/commit/7458befe8a5900480cd71900df02a8364837dc00))
|
||||||
|
|
||||||
|
## [3.2.1](https://github.com/sern-handler/handler/compare/v3.2.0...v3.2.1) (2023-12-21)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* logger swap failing ([daac37c](https://github.com/sern-handler/handler/commit/daac37c28858c42b21042bdcb8141239db634e7d))
|
||||||
|
|
||||||
|
## [3.2.0](https://github.com/sern-handler/handler/compare/v3.1.1...v3.2.0) (2023-12-15)
|
||||||
|
|
||||||
|
|
||||||
|
### Miscellaneous Chores
|
||||||
|
|
||||||
|
* release 3.2.0 ([237c853](https://github.com/sern-handler/handler/commit/237c8537c66052309d7e13a7e6e0a4f7995c2558))
|
||||||
|
|
||||||
|
## [3.1.1](https://github.com/sern-handler/handler/compare/v3.1.0...v3.1.1) (2023-11-06)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* queuing events ([fd39858](https://github.com/sern-handler/handler/commit/fd39858636d3038abb6d91021b65c99c488a3d6e))
|
||||||
|
* queuing events ([#332](https://github.com/sern-handler/handler/issues/332)) @Benzo-Fury ([#333](https://github.com/sern-handler/handler/issues/333)) ([fd39858](https://github.com/sern-handler/handler/commit/fd39858636d3038abb6d91021b65c99c488a3d6e))
|
||||||
|
|
||||||
## [3.1.0](https://github.com/sern-handler/handler/compare/v3.0.2...v3.1.0) (2023-09-04)
|
## [3.1.0](https://github.com/sern-handler/handler/compare/v3.0.2...v3.1.0) (2023-09-04)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
62
README.md
62
README.md
@@ -19,28 +19,16 @@
|
|||||||
- Lightweight. Does a lot while being small.
|
- Lightweight. Does a lot while being small.
|
||||||
- Latest features. Support for discord.js v14 and all of its interactions.
|
- Latest features. Support for discord.js v14 and all of its interactions.
|
||||||
- Start quickly. Plug and play or customize to your liking.
|
- Start quickly. Plug and play or customize to your liking.
|
||||||
- Switch and customize how errors are handled, logging, and more.
|
|
||||||
- works with [bun](https://bun.sh/) and [node](https://nodejs.org/en) out the box!
|
- works with [bun](https://bun.sh/) and [node](https://nodejs.org/en) out the box!
|
||||||
- Use it with TypeScript or JavaScript. CommonJS and ESM supported.
|
- Use it with TypeScript or JavaScript. CommonJS and ESM supported.
|
||||||
- Active and growing community, always here to help. [Join us](https://sern.dev/discord)
|
- Active and growing community, always here to help. [Join us](https://sern.dev/discord)
|
||||||
- Unleash its full potential with a powerful CLI and awesome plugins.
|
- Unleash its full potential with a powerful CLI and awesome plugins.
|
||||||
|
|
||||||
## 📜 Installation
|
## 📜 Installation
|
||||||
|
[Start here!!](https://sern.dev/docs/guide/walkthrough/new-project)
|
||||||
```sh
|
|
||||||
npm install @sern/handler
|
|
||||||
```
|
|
||||||
|
|
||||||
```sh
|
|
||||||
yarn add @sern/handler
|
|
||||||
```
|
|
||||||
|
|
||||||
```sh
|
|
||||||
pnpm add @sern/handler
|
|
||||||
```
|
|
||||||
|
|
||||||
## 👶 Basic Usage
|
## 👶 Basic Usage
|
||||||
<details open><summary>ping.ts</summary>
|
<details><summary>ping.ts</summary>
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
export default commandModule({
|
export default commandModule({
|
||||||
@@ -54,50 +42,7 @@ export default commandModule({
|
|||||||
});
|
});
|
||||||
```
|
```
|
||||||
</details>
|
</details>
|
||||||
<details open><summary>modal.ts</summary>
|
|
||||||
|
|
||||||
```ts
|
|
||||||
export default commandModule({
|
|
||||||
type: CommandType.Modal,
|
|
||||||
//Installed a plugin to make sure modal fields pass a validation.
|
|
||||||
plugins : [
|
|
||||||
assertFields({
|
|
||||||
fields: {
|
|
||||||
name: /^([^0-9]*)$/
|
|
||||||
},
|
|
||||||
failure: (errors, modal) => modal.reply('your submission did not pass the validations')
|
|
||||||
})
|
|
||||||
],
|
|
||||||
execute : (modal) => {
|
|
||||||
modal.reply('thanks for the submission!');
|
|
||||||
}
|
|
||||||
})
|
|
||||||
```
|
|
||||||
</details>
|
|
||||||
<details open><summary>index.ts</summary>
|
|
||||||
|
|
||||||
|
|
||||||
```ts
|
|
||||||
import { Client, GatewayIntentBits } from 'discord.js';
|
|
||||||
import { Sern, single } from '@sern/handler';
|
|
||||||
|
|
||||||
//client has been declared previously
|
|
||||||
//Version 3
|
|
||||||
await makeDependencies({
|
|
||||||
build: root => root
|
|
||||||
.add({ '@sern/client': single(() => client) })
|
|
||||||
});
|
|
||||||
|
|
||||||
//View docs for all options
|
|
||||||
Sern.init({
|
|
||||||
defaultPrefix: '!', // removing defaultPrefix will shut down text commands
|
|
||||||
commands: 'src/commands',
|
|
||||||
// events: 'src/events' (optional),
|
|
||||||
});
|
|
||||||
|
|
||||||
client.login("YOUR_BOT_TOKEN_HERE");
|
|
||||||
```
|
|
||||||
</details>
|
|
||||||
|
|
||||||
## 🤖 Bots Using sern
|
## 🤖 Bots Using sern
|
||||||
- [Community Bot](https://github.com/sern-handler/sern-community), the community bot for our [discord server](https://sern.dev/discord).
|
- [Community Bot](https://github.com/sern-handler/sern-community), the community bot for our [discord server](https://sern.dev/discord).
|
||||||
@@ -107,7 +52,8 @@ client.login("YOUR_BOT_TOKEN_HERE");
|
|||||||
- [Murayama](https://github.com/murayamabot/murayama), :pepega:
|
- [Murayama](https://github.com/murayamabot/murayama), :pepega:
|
||||||
- [Protector (WIP)](https://github.com/needhamgary/Protector), Just a simple bot to help enhance a private minecraft server.
|
- [Protector (WIP)](https://github.com/needhamgary/Protector), Just a simple bot to help enhance a private minecraft server.
|
||||||
- [SmokinWeed 💨](https://github.com/Peter-MJ-Parker/sern-bud), A fun bot for a small - but growing - server.
|
- [SmokinWeed 💨](https://github.com/Peter-MJ-Parker/sern-bud), A fun bot for a small - but growing - server.
|
||||||
|
- [Man Nomic](https://github.com/jacoobes/man-nomic), A simple information bot to provide information to the nomic-ai discord community.
|
||||||
|
- [Linear-Discord](https://github.com/sern-handler/linear-discord) Display and manage a linear dashboard.
|
||||||
## 💻 CLI
|
## 💻 CLI
|
||||||
|
|
||||||
It is **highly encouraged** to use the [command line interface](https://github.com/sern-handler/cli) for your project. Don't forget to view it.
|
It is **highly encouraged** to use the [command line interface](https://github.com/sern-handler/cli) for your project. Don't forget to view it.
|
||||||
|
|||||||
11
package.json
11
package.json
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "@sern/handler",
|
"name": "@sern/handler",
|
||||||
"packageManager": "yarn@3.5.0",
|
"packageManager": "yarn@3.5.0",
|
||||||
"version": "3.1.0",
|
"version": "3.3.4",
|
||||||
"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",
|
||||||
@@ -38,6 +37,7 @@
|
|||||||
"author": "SernDevs",
|
"author": "SernDevs",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"callsites": "^3.1.0",
|
||||||
"iti": "^0.6.0",
|
"iti": "^0.6.0",
|
||||||
"rxjs": "^7.8.0",
|
"rxjs": "^7.8.0",
|
||||||
"ts-results-es": "^4.0.0"
|
"ts-results-es": "^4.0.0"
|
||||||
@@ -47,9 +47,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",
|
|
||||||
"eslint": "8.39.0",
|
"eslint": "8.39.0",
|
||||||
"prettier": "2.8.8",
|
"prettier": "2.8.8",
|
||||||
"tsup": "^6.7.0",
|
"tsup": "^6.7.0",
|
||||||
@@ -96,5 +94,8 @@
|
|||||||
"type": "git",
|
"type": "git",
|
||||||
"url": "git+https://github.com/sern-handler/handler.git"
|
"url": "git+https://github.com/sern-handler/handler.git"
|
||||||
},
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 18.16.x"
|
||||||
|
},
|
||||||
"homepage": "https://sern.dev"
|
"homepage": "https://sern.dev"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,10 +1,10 @@
|
|||||||
export * as Id from './id';
|
export * as Id from './id';
|
||||||
export * from './operators';
|
export * from './operators';
|
||||||
export * from './predicates';
|
|
||||||
export * as Files from './module-loading';
|
export * as Files from './module-loading';
|
||||||
export * from './functions';
|
export * from './functions';
|
||||||
export type { VoidResult } from '../types/core-plugin';
|
export type { VoidResult } from '../types/core-plugin';
|
||||||
export { SernError } from './structures/enums';
|
export { SernError } from './structures/enums';
|
||||||
export { ModuleStore } from './structures/module-store';
|
export { ModuleStore } from './structures/module-store';
|
||||||
export * as DefaultServices from './structures/services';
|
export * as __Services from './structures/services';
|
||||||
export { useContainerRaw } from './ioc/base'
|
export { useContainerRaw } from './ioc/base';
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +0,0 @@
|
|||||||
import type { Awaitable } from '../../types/utility';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Represents a Disposable contract.
|
|
||||||
* Let dependencies implement this to dispose and cleanup.
|
|
||||||
*/
|
|
||||||
export interface Disposable {
|
|
||||||
dispose(): Awaitable<unknown>;
|
|
||||||
}
|
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
//i deleted it, hmm so how should we allow users to enable localization?
|
||||||
|
// a
|
||||||
import type { AnyFunction } from '../../types/utility';
|
import type { AnyFunction } from '../../types/utility';
|
||||||
|
|
||||||
export interface Emitter {
|
export interface Emitter {
|
||||||
|
|||||||
@@ -2,20 +2,15 @@
|
|||||||
* @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;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
16
src/core/contracts/hooks.ts
Normal file
16
src/core/contracts/hooks.ts
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
|
||||||
|
/**
|
||||||
|
* Represents an initialization contract.
|
||||||
|
* Let dependencies implement this to initiate some logic.
|
||||||
|
*/
|
||||||
|
export interface Init {
|
||||||
|
init(): unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Represents a Disposable contract.
|
||||||
|
* Let dependencies implement this to dispose and cleanup.
|
||||||
|
*/
|
||||||
|
export interface Disposable {
|
||||||
|
dispose(): unknown;
|
||||||
|
}
|
||||||
@@ -2,6 +2,5 @@ export * from './error-handling';
|
|||||||
export * from './logging';
|
export * from './logging';
|
||||||
export * from './module-manager';
|
export * from './module-manager';
|
||||||
export * from './module-store';
|
export * from './module-store';
|
||||||
export * from './init';
|
export * from './hooks';
|
||||||
export * from './emitter';
|
export * from './emitter';
|
||||||
export * from './disposable'
|
|
||||||
|
|||||||
@@ -1,9 +0,0 @@
|
|||||||
import type { Awaitable } from '../../types/utility';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Represents an initialization contract.
|
|
||||||
* Let dependencies implement this to initiate some logic.
|
|
||||||
*/
|
|
||||||
export interface Init {
|
|
||||||
init(): Awaitable<unknown>;
|
|
||||||
}
|
|
||||||
@@ -6,17 +6,29 @@ 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;
|
||||||
set(id: string, path: string): void;
|
}
|
||||||
getPublishableCommands(): Promise<CommandModule[]>;
|
|
||||||
|
/**
|
||||||
|
* @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): Module | undefined;
|
||||||
|
|
||||||
|
set(id: string, path: Module): void;
|
||||||
|
/**
|
||||||
|
* @deprecated
|
||||||
|
*/
|
||||||
|
getPublishableCommands(): CommandModule[];
|
||||||
|
|
||||||
|
/*
|
||||||
|
* @deprecated
|
||||||
|
*/
|
||||||
getByNameCommandType<T extends CommandType>(
|
getByNameCommandType<T extends CommandType>(
|
||||||
name: string,
|
name: string,
|
||||||
commandType: T,
|
commandType: T,
|
||||||
): Promise<CommandModuleDefs[T]> | undefined;
|
): CommandModuleDefs[T] | undefined;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,6 @@ import type { CommandMeta, Module } from '../../types/core-modules';
|
|||||||
* Represents a core module store that stores IDs mapped to file paths.
|
* Represents a core module store that stores IDs mapped to file paths.
|
||||||
*/
|
*/
|
||||||
export interface CoreModuleStore {
|
export interface CoreModuleStore {
|
||||||
commands: Map<string, string>;
|
commands: Map<string, Module>;
|
||||||
metadata: WeakMap<Module, CommandMeta>;
|
metadata: WeakMap<Module, CommandMeta>;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { CommandType, EventType, PluginType } from './structures';
|
import { CommandType, EventType, PluginType } from './structures';
|
||||||
import type { Plugin, PluginResult, EventArgs, CommandArgs } from '../types/core-plugin';
|
import type { Plugin, PluginResult, EventArgs, CommandArgs } from '../types/core-plugin';
|
||||||
import type { ClientEvents } from 'discord.js';
|
import type { ClientEvents } from 'discord.js';
|
||||||
|
import { err, ok } from './functions';
|
||||||
|
|
||||||
export function makePlugin<V extends unknown[]>(
|
export function makePlugin<V extends unknown[]>(
|
||||||
type: PluginType,
|
type: PluginType,
|
||||||
@@ -60,3 +61,12 @@ export function DiscordEventControlPlugin<T extends keyof ClientEvents>(
|
|||||||
) {
|
) {
|
||||||
return makePlugin(PluginType.Control, execute);
|
return makePlugin(PluginType.Control, execute);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @since 1.0.0
|
||||||
|
* The object passed into every plugin to control a command's behavior
|
||||||
|
*/
|
||||||
|
export const controller = {
|
||||||
|
next: ok,
|
||||||
|
stop: err,
|
||||||
|
};
|
||||||
|
|||||||
@@ -1,9 +1,19 @@
|
|||||||
import { Err, Ok } from 'ts-results-es';
|
import { Err, Ok } from 'ts-results-es';
|
||||||
import { ApplicationCommandOptionType, AutocompleteInteraction } from 'discord.js';
|
import type { Module, SernAutocompleteData, SernOptionsData } from '../types/core-modules';
|
||||||
import type { SernAutocompleteData, SernOptionsData } from '../types/core-modules';
|
|
||||||
import type { AnyCommandPlugin, AnyEventPlugin, Plugin } from '../types/core-plugin';
|
import type { AnyCommandPlugin, AnyEventPlugin, Plugin } from '../types/core-plugin';
|
||||||
import { PluginType } from './structures';
|
import type {
|
||||||
|
AnySelectMenuInteraction,
|
||||||
|
ButtonInteraction,
|
||||||
|
ChatInputCommandInteraction,
|
||||||
|
MessageContextMenuCommandInteraction,
|
||||||
|
ModalSubmitInteraction,
|
||||||
|
UserContextMenuCommandInteraction,
|
||||||
|
AutocompleteInteraction
|
||||||
|
} from 'discord.js';
|
||||||
|
import { ApplicationCommandOptionType, InteractionType } from 'discord.js';
|
||||||
|
import { PayloadType, PluginType } from './structures';
|
||||||
import assert from 'assert';
|
import assert from 'assert';
|
||||||
|
import type { Payload } from '../types/utility';
|
||||||
|
|
||||||
//function wrappers for empty ok / err
|
//function wrappers for empty ok / err
|
||||||
export const ok = /* @__PURE__*/ () => Ok.EMPTY;
|
export const ok = /* @__PURE__*/ () => Ok.EMPTY;
|
||||||
@@ -36,11 +46,11 @@ 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 }));
|
||||||
let subcommands = new Set();
|
const subcommands = new Set();
|
||||||
while (_options.length > 0) {
|
while (_options.length > 0) {
|
||||||
const cur = _options.pop()!;
|
const cur = _options.pop()!;
|
||||||
switch (cur.type) {
|
switch (cur.type) {
|
||||||
@@ -61,18 +71,18 @@ export function treeSearch(
|
|||||||
const choice = iAutocomplete.options.getFocused(true);
|
const choice = iAutocomplete.options.getFocused(true);
|
||||||
assert(
|
assert(
|
||||||
'command' in cur,
|
'command' in cur,
|
||||||
'No command property found for autocomplete option',
|
'No `command` property found for autocomplete option',
|
||||||
);
|
);
|
||||||
if (subcommands.size > 0) {
|
if (subcommands.size > 0) {
|
||||||
const parent = iAutocomplete.options.getSubcommand();
|
const parent = iAutocomplete.options.getSubcommand();
|
||||||
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 };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -81,3 +91,33 @@ export function treeSearch(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
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: InteractionTypable): i is AnyCommandInteraction {
|
||||||
|
return i.type === InteractionType.ApplicationCommand;
|
||||||
|
}
|
||||||
|
export function isAutocomplete(i: InteractionTypable): i is AutocompleteInteraction {
|
||||||
|
return i.type === InteractionType.ApplicationCommandAutocomplete;
|
||||||
|
}
|
||||||
|
|
||||||
|
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 };
|
||||||
|
}
|
||||||
|
|||||||
@@ -4,20 +4,20 @@ import { CommandType, EventType } from './structures';
|
|||||||
/**
|
/**
|
||||||
* Construct unique ID for a given interaction object.
|
* Construct unique ID for a given interaction object.
|
||||||
* @param event The interaction object for which to create an ID.
|
* @param event The interaction object for which to create an ID.
|
||||||
* @returns A unique string ID based on the type and properties of the interaction object.
|
* @returns An array of unique string IDs based on the type and properties of the interaction object.
|
||||||
*/
|
*/
|
||||||
export function reconstruct<T extends Interaction>(event: T) {
|
export function reconstruct<T extends Interaction>(event: T) {
|
||||||
switch (event.type) {
|
switch (event.type) {
|
||||||
case InteractionType.MessageComponent: {
|
case InteractionType.MessageComponent: {
|
||||||
return `${event.customId}_C${event.componentType}`;
|
return [`${event.customId}_C${event.componentType}`];
|
||||||
}
|
}
|
||||||
case InteractionType.ApplicationCommand:
|
case InteractionType.ApplicationCommand:
|
||||||
case InteractionType.ApplicationCommandAutocomplete: {
|
case InteractionType.ApplicationCommandAutocomplete: {
|
||||||
return `${event.commandName}_A${event.commandType}`;
|
return [`${event.commandName}_A${event.commandType}`, `${event.commandName}_B`];
|
||||||
}
|
}
|
||||||
//Modal interactions are classified as components for sern
|
//Modal interactions are classified as components for sern
|
||||||
case InteractionType.ModalSubmit: {
|
case InteractionType.ModalSubmit: {
|
||||||
return `${event.customId}_C1`;
|
return [`${event.customId}_M`];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -27,37 +27,39 @@ export function reconstruct<T extends Interaction>(event: T) {
|
|||||||
*/
|
*/
|
||||||
const appBitField = 0b000000001111;
|
const appBitField = 0b000000001111;
|
||||||
|
|
||||||
// Each index represents the exponent of a CommandType.
|
|
||||||
// Every CommandType is a power of two.
|
const TypeMap = new Map<number, number>([
|
||||||
export const CommandTypeDiscordApi = [
|
[CommandType.Text, 0],
|
||||||
1, // CommandType.Text
|
[CommandType.Both, 0],
|
||||||
ApplicationCommandType.ChatInput,
|
[CommandType.Slash, ApplicationCommandType.ChatInput],
|
||||||
ApplicationCommandType.User,
|
[CommandType.CtxUser, ApplicationCommandType.User],
|
||||||
ApplicationCommandType.Message,
|
[CommandType.CtxMsg, ApplicationCommandType.Message],
|
||||||
ComponentType.Button,
|
[CommandType.Button, ComponentType.Button],
|
||||||
ComponentType.StringSelect,
|
[CommandType.Modal, InteractionType.ModalSubmit],
|
||||||
1, // CommandType.Modal
|
[CommandType.StringSelect, ComponentType.StringSelect],
|
||||||
ComponentType.UserSelect,
|
[CommandType.UserSelect, ComponentType.UserSelect],
|
||||||
ComponentType.RoleSelect,
|
[CommandType.MentionableSelect, ComponentType.MentionableSelect],
|
||||||
ComponentType.MentionableSelect,
|
[CommandType.RoleSelect, ComponentType.RoleSelect],
|
||||||
ComponentType.ChannelSelect,
|
[CommandType.ChannelSelect, ComponentType.ChannelSelect]]);
|
||||||
];
|
|
||||||
/*
|
|
||||||
* Generates a number based on CommandType.
|
|
||||||
* This corresponds to an ApplicationCommandType or ComponentType
|
|
||||||
* TextCommands are 0 as they aren't either or.
|
|
||||||
*/
|
|
||||||
function apiType(t: CommandType | EventType) {
|
|
||||||
if (t === CommandType.Both || t === CommandType.Modal) return 1;
|
|
||||||
return CommandTypeDiscordApi[Math.log2(t)];
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Generates an id based on name and CommandType.
|
* Generates an id based on name and CommandType.
|
||||||
* A is for any ApplicationCommand. C is for any ComponentCommand
|
* A is for any ApplicationCommand. C is for any ComponentCommand
|
||||||
* Then, another number generated by apiType function is appended
|
* Then, another number fetched from TypeMap
|
||||||
*/
|
*/
|
||||||
export function create(name: string, type: CommandType | EventType) {
|
export function create(name: string, type: CommandType | EventType) {
|
||||||
|
if(type == CommandType.Text) {
|
||||||
|
return `${name}_T`;
|
||||||
|
}
|
||||||
|
if(type == CommandType.Both) {
|
||||||
|
return `${name}_B`;
|
||||||
|
}
|
||||||
|
if(type == CommandType.Modal) {
|
||||||
|
return `${name}_M`;
|
||||||
|
}
|
||||||
const am = (appBitField & type) !== 0 ? 'A' : 'C';
|
const am = (appBitField & type) !== 0 ? 'A' : 'C';
|
||||||
return name + '_' + am + apiType(type);
|
return `${name}_${am}${TypeMap.get(type)!}`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,16 +1,40 @@
|
|||||||
import * as assert from 'assert';
|
import * as assert from 'assert';
|
||||||
import { composeRoot, useContainer } from './dependency-injection';
|
import { useContainer } from './dependency-injection';
|
||||||
import type { DependencyConfiguration } from '../../types/ioc';
|
import type { CoreDependencies, DependencyConfiguration } from '../../types/ioc';
|
||||||
import { CoreContainer } from './container';
|
import { CoreContainer } from './container';
|
||||||
|
import { Result } from 'ts-results-es';
|
||||||
|
import { __Services } from '../_internal';
|
||||||
|
import { AnyFunction } from '../../types/utility';
|
||||||
|
import type { Logging } from '../contracts/logging';
|
||||||
|
import type { UnpackFunction } from 'iti';
|
||||||
//SIDE EFFECT: GLOBAL DI
|
//SIDE EFFECT: GLOBAL DI
|
||||||
let containerSubject: CoreContainer<Partial<Dependencies>>;
|
let containerSubject: CoreContainer<Partial<Dependencies>>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @deprecated
|
* @internal
|
||||||
|
* Don't use this unless you know what you're doing. Destroys old containerSubject if it exists and disposes everything
|
||||||
|
* then it will swap
|
||||||
|
*/
|
||||||
|
export async function __swap_container(c: CoreContainer<Partial<Dependencies>>) {
|
||||||
|
if(containerSubject) {
|
||||||
|
await containerSubject.disposeAll()
|
||||||
|
}
|
||||||
|
containerSubject = c;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @internal
|
||||||
|
* Don't use this unless you know what you're doing. Destroys old containerSubject if it exists and disposes everything
|
||||||
|
* then it will swap
|
||||||
|
*/
|
||||||
|
export function __add_container(key: string,v : Insertable) {
|
||||||
|
containerSubject.add({ [key]: v });
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
* Returns the underlying data structure holding all dependencies.
|
* Returns the underlying data structure holding all dependencies.
|
||||||
* Exposes methods from iti
|
* Exposes methods from iti
|
||||||
* Use the Service API. The container should be readonly
|
* Use the Service API. The container should be readonly from the consumer side
|
||||||
*/
|
*/
|
||||||
export function useContainerRaw() {
|
export function useContainerRaw() {
|
||||||
assert.ok(
|
assert.ok(
|
||||||
@@ -20,17 +44,123 @@ export function useContainerRaw() {
|
|||||||
return containerSubject;
|
return containerSubject;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function disposeAll(logger: Logging|undefined) {
|
||||||
|
containerSubject
|
||||||
|
?.disposeAll()
|
||||||
|
.then(() => logger?.info({ message: 'Cleaning container and crashing' }));
|
||||||
|
}
|
||||||
|
type UnpackedDependencies = {
|
||||||
|
[K in keyof Dependencies]: UnpackFunction<Dependencies[K]>
|
||||||
|
}
|
||||||
|
type Insertable =
|
||||||
|
| ((container: UnpackedDependencies) => unknown)
|
||||||
|
| object
|
||||||
|
const dependencyBuilder = (container: any, excluded: string[] ) => {
|
||||||
|
return {
|
||||||
|
/**
|
||||||
|
* Insert a dependency into your container.
|
||||||
|
* Supply the correct key and dependency
|
||||||
|
*/
|
||||||
|
add(key: keyof Dependencies, v: Insertable) {
|
||||||
|
if(typeof v !== 'function') {
|
||||||
|
Result.wrap(() => container.add({ [key]: v}))
|
||||||
|
.expect("Failed to add " + key);
|
||||||
|
} else {
|
||||||
|
Result.wrap(() =>
|
||||||
|
container.add((cntr: UnpackedDependencies) => ({ [key]: v(cntr)} )))
|
||||||
|
.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) {
|
||||||
|
if(typeof v !== 'function') {
|
||||||
|
Result.wrap(() => container.upsert({ [key]: v}))
|
||||||
|
.expect("Failed to update " + key);
|
||||||
|
} else {
|
||||||
|
Result.wrap(() =>
|
||||||
|
container.upsert((cntr: UnpackedDependencies) => ({ [key]: v(cntr)})))
|
||||||
|
.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 ValidDependencyConfig =
|
||||||
|
| ((c: ReturnType<typeof dependencyBuilder>) => any)
|
||||||
|
| DependencyConfiguration;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @since 2.0.0
|
* Given the user's conf, check for any excluded/included dependency keys.
|
||||||
* @param conf a configuration for creating your project dependencies
|
* Then, call conf.build to get the rest of the users' dependencies.
|
||||||
|
* Finally, update the containerSubject with the new container state
|
||||||
|
* @param conf
|
||||||
*/
|
*/
|
||||||
export async function makeDependencies<const T extends Dependencies>(
|
function composeRoot(
|
||||||
|
container: CoreContainer<Partial<Dependencies>>,
|
||||||
conf: DependencyConfiguration,
|
conf: DependencyConfiguration,
|
||||||
) {
|
) {
|
||||||
//Until there are more optional dependencies, just check if the logger exists
|
//container should have no client or logger yet.
|
||||||
//SIDE EFFECT
|
const hasLogger = conf.exclude?.has('@sern/logger');
|
||||||
|
if (!hasLogger) {
|
||||||
|
__add_container('@sern/logger', new __Services.DefaultLogging);
|
||||||
|
}
|
||||||
|
//Build the container based on the callback provided by the user
|
||||||
|
conf.build(container as CoreContainer<Omit<CoreDependencies, '@sern/client'>>);
|
||||||
|
|
||||||
|
if (!hasLogger) {
|
||||||
|
container.get('@sern/logger')?.info({ message: 'All dependencies loaded successfully.' });
|
||||||
|
}
|
||||||
|
|
||||||
|
container.ready();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function makeDependencies<const T extends Dependencies>
|
||||||
|
(conf: ValidDependencyConfig) {
|
||||||
containerSubject = new CoreContainer();
|
containerSubject = new CoreContainer();
|
||||||
await composeRoot(containerSubject, conf);
|
if(typeof conf === 'function') {
|
||||||
|
const excluded: string[] = [];
|
||||||
|
conf(dependencyBuilder(containerSubject, excluded));
|
||||||
|
//We only include logger if it does not exist
|
||||||
|
const includeLogger =
|
||||||
|
!excluded.includes('@sern/logger')
|
||||||
|
&& !containerSubject.hasKey('@sern/logger');
|
||||||
|
|
||||||
|
if(includeLogger) {
|
||||||
|
__add_container('@sern/logger', new __Services.DefaultLogging);
|
||||||
|
}
|
||||||
|
|
||||||
|
containerSubject.ready();
|
||||||
|
} else {
|
||||||
|
composeRoot(containerSubject, conf);
|
||||||
|
}
|
||||||
|
|
||||||
return useContainer<T>();
|
return useContainer<T>();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
import { Container } from 'iti';
|
import { Container } from 'iti';
|
||||||
import { Disposable, SernEmitter } from '../';
|
import { Disposable } from '../';
|
||||||
import * as assert from 'node:assert';
|
import * as assert from 'node:assert';
|
||||||
import { Subject } from 'rxjs';
|
import { Subject } from 'rxjs';
|
||||||
import { DefaultServices, ModuleStore } from '../_internal';
|
import { __Services, ModuleStore } from '../_internal';
|
||||||
import * as Hooks from './hooks'
|
import * as Hooks from './hooks';
|
||||||
|
import { EventEmitter } from 'node:events';
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -17,42 +18,39 @@ export class CoreContainer<T extends Partial<Dependencies>> extends Container<T,
|
|||||||
assert.ok(!this.isReady(), 'Listening for dispose & init should occur prior to sern being ready.');
|
assert.ok(!this.isReady(), 'Listening for dispose & init should occur prior to sern being ready.');
|
||||||
|
|
||||||
const { unsubscribe } = Hooks.createInitListener(this);
|
const { unsubscribe } = Hooks.createInitListener(this);
|
||||||
|
|
||||||
this.ready$
|
this.ready$
|
||||||
.subscribe({ complete: unsubscribe });
|
.subscribe({ complete: unsubscribe });
|
||||||
|
|
||||||
(this as Container<{}, {}>)
|
(this as Container<{}, {}>)
|
||||||
.add({
|
.add({ '@sern/errors': () => new __Services.DefaultErrorHandling,
|
||||||
'@sern/errors': () => new DefaultServices.DefaultErrorHandling(),
|
'@sern/emitter': () => new EventEmitter({ captureRejections: true }),
|
||||||
'@sern/emitter': () => new SernEmitter(),
|
'@sern/store': () => new ModuleStore })
|
||||||
'@sern/store': () => new ModuleStore(),
|
|
||||||
})
|
|
||||||
.add(ctx => {
|
.add(ctx => {
|
||||||
return {
|
return { '@sern/modules': new __Services.DefaultModuleManager(ctx['@sern/store'])};
|
||||||
'@sern/modules': () =>
|
|
||||||
new DefaultServices.DefaultModuleManager(ctx['@sern/store']),
|
|
||||||
};
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
isReady() {
|
isReady() {
|
||||||
|
|
||||||
return this.ready$.closed;
|
return this.ready$.closed;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
hasKey(key: string): boolean {
|
||||||
|
return Boolean((this as Container<any,any>)._context[key]);
|
||||||
|
}
|
||||||
|
|
||||||
override async disposeAll() {
|
override async disposeAll() {
|
||||||
|
|
||||||
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]
|
otherDisposables.forEach(key => {
|
||||||
: []);
|
//possible source of bug: dispose is a property.
|
||||||
|
|
||||||
for(const key of otherDisposables) {
|
|
||||||
this.addDisposer({ [key]: (dep: Disposable) => dep.dispose() } as never);
|
this.addDisposer({ [key]: (dep: Disposable) => dep.dispose() } as never);
|
||||||
}
|
})
|
||||||
await super.disposeAll()
|
await super.disposeAll();
|
||||||
}
|
}
|
||||||
|
|
||||||
ready() {
|
ready() {
|
||||||
this.ready$.complete();
|
this.ready$.complete();
|
||||||
this.ready$.unsubscribe();
|
this.ready$.unsubscribe();
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import type { CoreDependencies, DependencyConfiguration, IntoDependencies } from '../../types/ioc';
|
import assert from 'node:assert';
|
||||||
import { DefaultServices } from '../_internal';
|
import type { IntoDependencies } from '../../types/ioc';
|
||||||
import { useContainerRaw } from './base';
|
import { useContainerRaw } from './base';
|
||||||
import { CoreContainer } from './container';
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @__PURE__
|
* @__PURE__
|
||||||
@@ -26,6 +25,7 @@ export function transient<T>(cb: () => () => T) {
|
|||||||
* The new Service api, a cleaner alternative to useContainer
|
* The new Service api, a cleaner alternative to useContainer
|
||||||
* To obtain intellisense, ensure a .d.ts file exists in the root of compilation.
|
* To obtain intellisense, ensure a .d.ts file exists in the root of compilation.
|
||||||
* Usually our scaffolding tool takes care of this.
|
* Usually our scaffolding tool takes care of this.
|
||||||
|
* Note: this method only works AFTER your container has been initiated
|
||||||
* @since 3.0.0
|
* @since 3.0.0
|
||||||
* @example
|
* @example
|
||||||
* ```ts
|
* ```ts
|
||||||
@@ -35,7 +35,9 @@ export function transient<T>(cb: () => () => T) {
|
|||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
export function Service<const T extends keyof Dependencies>(key: T) {
|
export function Service<const T extends keyof Dependencies>(key: T) {
|
||||||
return useContainerRaw().get(key)!;
|
const dep = useContainerRaw().get(key)!;
|
||||||
|
assert(dep, "Requested key " + key + " returned undefined");
|
||||||
|
return dep;
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* @since 3.0.0
|
* @since 3.0.0
|
||||||
@@ -47,34 +49,9 @@ export function Services<const T extends (keyof Dependencies)[]>(...keys: [...T]
|
|||||||
return keys.map(k => container.get(k)!) as IntoDependencies<T>;
|
return keys.map(k => container.get(k)!) as IntoDependencies<T>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Given the user's conf, check for any excluded dependency keys.
|
|
||||||
* Then, call conf.build to get the rest of the users' dependencies.
|
|
||||||
* Finally, update the containerSubject with the new container state
|
|
||||||
* @param conf
|
|
||||||
*/
|
|
||||||
export async function composeRoot(
|
|
||||||
container: CoreContainer<Partial<Dependencies>>,
|
|
||||||
conf: DependencyConfiguration,
|
|
||||||
) {
|
|
||||||
//container should have no client or logger yet.
|
|
||||||
const hasLogger = conf.exclude?.has('@sern/logger');
|
|
||||||
if (!hasLogger) {
|
|
||||||
container.upsert({
|
|
||||||
'@sern/logger': () => new DefaultServices.DefaultLogging(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
//Build the container based on the callback provided by the user
|
|
||||||
conf.build(container as CoreContainer<Omit<CoreDependencies, '@sern/client'>>);
|
|
||||||
|
|
||||||
if (!hasLogger) {
|
|
||||||
container.get('@sern/logger')?.info({ message: 'All dependencies loaded successfully.' });
|
|
||||||
}
|
|
||||||
|
|
||||||
container.ready();
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useContainer<const T extends Dependencies>() {
|
export function useContainer<const T extends Dependencies>() {
|
||||||
return <V extends (keyof T)[]>(...keys: [...V]) =>
|
return <V extends (keyof T)[]>(...keys: [...V]) =>
|
||||||
keys.map(key => useContainerRaw().get(key as keyof Dependencies)) as IntoDependencies<V>;
|
keys.map(key => useContainerRaw().get(key as keyof Dependencies)) as IntoDependencies<V>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ type HookName = 'init';
|
|||||||
export const createInitListener = (coreContainer : CoreContainer<any>) => {
|
export const createInitListener = (coreContainer : CoreContainer<any>) => {
|
||||||
const initCalled = new Set<PropertyKey>();
|
const initCalled = new Set<PropertyKey>();
|
||||||
const hasCallableMethod = createPredicate(initCalled);
|
const hasCallableMethod = createPredicate(initCalled);
|
||||||
const unsubscribe = coreContainer.on('containerUpserted', async (event) => {
|
const unsubscribe = coreContainer.on('containerUpserted', async event => {
|
||||||
|
|
||||||
if(isNotHookable(event)) {
|
if(isNotHookable(event)) {
|
||||||
return;
|
return;
|
||||||
@@ -21,6 +21,7 @@ export const createInitListener = (coreContainer : CoreContainer<any>) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
return { unsubscribe };
|
return { unsubscribe };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,11 +1,21 @@
|
|||||||
import { Result } from 'ts-results-es';
|
|
||||||
import { type Observable, from, mergeMap, ObservableInput } from 'rxjs';
|
import { type Observable, from, mergeMap, ObservableInput } from 'rxjs';
|
||||||
import { readdir, stat } from 'fs/promises';
|
import { readdir, stat } from 'fs/promises';
|
||||||
import { basename, extname, join, resolve, parse } from 'path';
|
import { basename, extname, join, resolve, parse, dirname } from 'path';
|
||||||
import assert from 'assert';
|
import assert from 'assert';
|
||||||
import { createRequire } from 'node:module';
|
import { createRequire } from 'node:module';
|
||||||
import type { ImportPayload, Wrapper } from '../types/core';
|
import type { ImportPayload, Wrapper } from '../types/core';
|
||||||
import type { Module } from '../types/core-modules';
|
import type { Module } from '../types/core-modules';
|
||||||
|
import { existsSync } from 'fs';
|
||||||
|
import type { Logging } from './contracts/logging';
|
||||||
|
|
||||||
|
export const shouldHandle = (path: string, fpath: string) => {
|
||||||
|
const file_name = fpath+extname(path);
|
||||||
|
let newPath = join(dirname(path), file_name)
|
||||||
|
.replace(/file:\\?/, "");
|
||||||
|
return { exists: existsSync(newPath),
|
||||||
|
path: 'file:///'+newPath };
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
export type ModuleResult<T> = Promise<ImportPayload<T>>;
|
export type ModuleResult<T> = Promise<ImportPayload<T>>;
|
||||||
|
|
||||||
@@ -23,19 +33,19 @@ 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 { module: commandModule } as T;
|
||||||
.wrap(() => module.getInstance())
|
|
||||||
.unwrapOr(module) 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 +61,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));
|
||||||
@@ -63,14 +74,14 @@ const isSkippable = (filename: string) => {
|
|||||||
const validExtensions = ['.js', '.cjs', '.mts', '.mjs', '.cts', '.ts', ''];
|
const validExtensions = ['.js', '.cjs', '.mts', '.mjs', '.cts', '.ts', ''];
|
||||||
return filename[0] === '!' || !validExtensions.includes(extname(filename));
|
return filename[0] === '!' || !validExtensions.includes(extname(filename));
|
||||||
};
|
};
|
||||||
|
|
||||||
async function deriveFileInfo(dir: string, file: string) {
|
async function deriveFileInfo(dir: string, file: string) {
|
||||||
const fullPath = join(dir, file);
|
const fullPath = join(dir, file);
|
||||||
return {
|
return { fullPath,
|
||||||
fullPath,
|
fileStats: await stat(fullPath),
|
||||||
fileStats: await stat(fullPath),
|
base: basename(file) };
|
||||||
base: basename(file),
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function* readPaths(dir: string): AsyncGenerator<string> {
|
async function* readPaths(dir: string): AsyncGenerator<string> {
|
||||||
try {
|
try {
|
||||||
const files = await readdir(dir);
|
const files = await readdir(dir);
|
||||||
@@ -94,11 +105,11 @@ async function* readPaths(dir: string): AsyncGenerator<string> {
|
|||||||
|
|
||||||
const requir = createRequire(import.meta.url);
|
const requir = createRequire(import.meta.url);
|
||||||
|
|
||||||
export function loadConfig(wrapper: Wrapper | 'file'): Wrapper {
|
export function loadConfig(wrapper: Wrapper | 'file', log: Logging | undefined): Wrapper {
|
||||||
if (wrapper !== 'file') {
|
if (wrapper !== 'file') {
|
||||||
return wrapper;
|
return wrapper;
|
||||||
}
|
}
|
||||||
console.log('Experimental loading of sern.config.json');
|
log?.info({ message: 'Experimental loading of sern.config.json'});
|
||||||
const config = requir(resolve('sern.config.json'));
|
const config = requir(resolve('sern.config.json'));
|
||||||
|
|
||||||
const makePath = (dir: PropertyKey) =>
|
const makePath = (dir: PropertyKey) =>
|
||||||
@@ -106,19 +117,18 @@ export function loadConfig(wrapper: Wrapper | 'file'): Wrapper {
|
|||||||
? join('dist', config.paths[dir]!)
|
? join('dist', config.paths[dir]!)
|
||||||
: join(config.paths[dir]!);
|
: join(config.paths[dir]!);
|
||||||
|
|
||||||
console.log('Loading config: ', config);
|
log?.info({ message: 'Loading config: ' + JSON.stringify(config, null, 4) });
|
||||||
const commandsPath = makePath('commands');
|
const commandsPath = makePath('commands');
|
||||||
|
|
||||||
console.log('Commands path is set to', commandsPath);
|
log?.info({ message: `Commands path is set to ${commandsPath}` });
|
||||||
let eventsPath: string | undefined;
|
let eventsPath: string | undefined;
|
||||||
if (config.paths.events) {
|
if (config.paths.events) {
|
||||||
eventsPath = makePath('events');
|
eventsPath = makePath('events');
|
||||||
console.log('Events path is set to', eventsPath);
|
log?.info({ message: `Events path is set to ${eventsPath} `});
|
||||||
}
|
}
|
||||||
return {
|
|
||||||
defaultPrefix: config.defaultPrefix,
|
return { defaultPrefix: config.defaultPrefix,
|
||||||
commands: commandsPath,
|
commands: commandsPath,
|
||||||
events: eventsPath,
|
events: eventsPath };
|
||||||
};
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,19 +1,13 @@
|
|||||||
import { ClientEvents } from 'discord.js';
|
import { ClientEvents } from 'discord.js';
|
||||||
import { CommandType, EventType, PluginType } from '../core/structures';
|
import { EventType } from '../core/structures';
|
||||||
import type {
|
import type {
|
||||||
AnyCommandPlugin,
|
|
||||||
AnyEventPlugin,
|
AnyEventPlugin,
|
||||||
CommandArgs,
|
|
||||||
ControlPlugin,
|
|
||||||
EventArgs,
|
|
||||||
InitPlugin,
|
|
||||||
} from '../types/core-plugin';
|
} from '../types/core-plugin';
|
||||||
import type {
|
import type {
|
||||||
CommandModule,
|
CommandModule,
|
||||||
EventModule,
|
EventModule,
|
||||||
InputCommand,
|
InputCommand,
|
||||||
InputEvent,
|
InputEvent,
|
||||||
Module,
|
|
||||||
} from '../types/core-modules';
|
} from '../types/core-modules';
|
||||||
import { partitionPlugins } from './_internal';
|
import { partitionPlugins } from './_internal';
|
||||||
import type { Awaitable } from '../types/utility';
|
import type { Awaitable } from '../types/utility';
|
||||||
@@ -61,52 +55,3 @@ export function discordEvent<T extends keyof ClientEvents>(mod: {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function prepareClassPlugins(c: Module) {
|
|
||||||
const [onEvent, initPlugins] = partitionPlugins(c.plugins);
|
|
||||||
c.plugins = initPlugins as InitPlugin[];
|
|
||||||
c.onEvent = onEvent as ControlPlugin[];
|
|
||||||
}
|
|
||||||
//
|
|
||||||
// Class modules:
|
|
||||||
// Can be refactored.
|
|
||||||
// Both implement singleton, could I make them inherit a singleton parent class?
|
|
||||||
/**
|
|
||||||
* @Experimental
|
|
||||||
* Will be refactored / changed in future
|
|
||||||
*/
|
|
||||||
export abstract class CommandExecutable<const Type extends CommandType = CommandType> {
|
|
||||||
abstract type: Type;
|
|
||||||
plugins: AnyCommandPlugin[] = [];
|
|
||||||
private static _instance: CommandModule;
|
|
||||||
|
|
||||||
static getInstance() {
|
|
||||||
if (!CommandExecutable._instance) {
|
|
||||||
//@ts-ignore
|
|
||||||
CommandExecutable._instance = new this();
|
|
||||||
prepareClassPlugins(CommandExecutable._instance);
|
|
||||||
}
|
|
||||||
return CommandExecutable._instance;
|
|
||||||
}
|
|
||||||
|
|
||||||
abstract execute(...args: CommandArgs<Type, PluginType.Control>): Awaitable<unknown>;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @Experimental
|
|
||||||
* Will be refactored in future
|
|
||||||
*/
|
|
||||||
export abstract class EventExecutable<Type extends EventType> {
|
|
||||||
abstract type: Type;
|
|
||||||
plugins: AnyEventPlugin[] = [];
|
|
||||||
|
|
||||||
private static _instance: EventModule;
|
|
||||||
static getInstance() {
|
|
||||||
if (!EventExecutable._instance) {
|
|
||||||
//@ts-ignore
|
|
||||||
EventExecutable._instance = new this();
|
|
||||||
prepareClassPlugins(EventExecutable._instance);
|
|
||||||
}
|
|
||||||
return EventExecutable._instance;
|
|
||||||
}
|
|
||||||
abstract execute(...args: EventArgs<Type, PluginType.Control>): Awaitable<unknown>;
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -28,16 +28,15 @@ export function filterMapTo<V>(item: () => V): OperatorFunction<boolean, V> {
|
|||||||
return concatMap(shouldKeep => (shouldKeep ? of(item()) : EMPTY));
|
return concatMap(shouldKeep => (shouldKeep ? of(item()) : EMPTY));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface PluginExecutable {
|
||||||
|
execute: (...args: unknown[]) => PluginResult;
|
||||||
|
};
|
||||||
/**
|
/**
|
||||||
* Calls any plugin with {args}.
|
* Calls any plugin with {args}.
|
||||||
* @param args if an array, its spread and plugin called.
|
* @param args if an array, its spread and plugin called.
|
||||||
*/
|
*/
|
||||||
export function callPlugin(args: unknown): OperatorFunction<
|
export function callPlugin(args: unknown): OperatorFunction<PluginExecutable, VoidResult>
|
||||||
{
|
{
|
||||||
execute: (...args: unknown[]) => PluginResult;
|
|
||||||
},
|
|
||||||
VoidResult
|
|
||||||
> {
|
|
||||||
return concatMap(async plugin => {
|
return concatMap(async plugin => {
|
||||||
if (Array.isArray(args)) {
|
if (Array.isArray(args)) {
|
||||||
return plugin.execute(...args);
|
return plugin.execute(...args);
|
||||||
@@ -60,27 +59,25 @@ export const sharedEventStream = <T>(e: Emitter, eventName: string) => {
|
|||||||
return (fromEvent(e, eventName) as Observable<T>).pipe(share());
|
return (fromEvent(e, eventName) as Observable<T>).pipe(share());
|
||||||
};
|
};
|
||||||
|
|
||||||
export function handleError<C>(crashHandler: ErrorHandling, logging?: Logging) {
|
export function handleError<C>(crashHandler: ErrorHandling, emitter: Emitter, logging?: Logging) {
|
||||||
return (pload: unknown, caught: Observable<C>) => {
|
return (pload: unknown, caught: Observable<C>) => {
|
||||||
// This is done to fit the ErrorHandling contract
|
// This is done to fit the ErrorHandling contract
|
||||||
const err = pload instanceof Error ? pload : Error(util.inspect(pload, { colors: true }));
|
if(!emitter.emit('error', pload)) {
|
||||||
//formatted payload
|
const err = pload instanceof Error ? pload : Error(util.inspect(pload, { colors: true }));
|
||||||
logging?.error({ message: util.inspect(pload) });
|
logging?.error({ message: util.inspect(pload) });
|
||||||
crashHandler.updateAlive(err);
|
crashHandler.updateAlive(err);
|
||||||
|
}
|
||||||
return caught;
|
return caught;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
// Temporary until i get rxjs operators working on ts-results-es
|
// Temporary until i get rxjs operators working on ts-results-es
|
||||||
export const filterTap = <K, R>(onErr: (e: R) => void): OperatorFunction<Result<K, R>, K> =>
|
export const filterTap = <K, R>(onErr: (e: R) => void): OperatorFunction<Result<K, R>, K> =>
|
||||||
pipe(
|
pipe(concatMap(result => {
|
||||||
concatMap(result => {
|
|
||||||
if(result.isOk()) {
|
if(result.isOk()) {
|
||||||
return of(result.value)
|
return of(result.value)
|
||||||
}
|
}
|
||||||
onErr(result.error);
|
onErr(result.error);
|
||||||
return EMPTY
|
return EMPTY
|
||||||
|
}))
|
||||||
})
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,34 +0,0 @@
|
|||||||
import type {
|
|
||||||
AnySelectMenuInteraction,
|
|
||||||
AutocompleteInteraction,
|
|
||||||
ButtonInteraction,
|
|
||||||
ChatInputCommandInteraction,
|
|
||||||
MessageContextMenuCommandInteraction,
|
|
||||||
ModalSubmitInteraction,
|
|
||||||
UserContextMenuCommandInteraction,
|
|
||||||
} from 'discord.js';
|
|
||||||
import { InteractionType } from 'discord.js';
|
|
||||||
|
|
||||||
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: InteractionTypable): i is AnyCommandInteraction {
|
|
||||||
return i.type === InteractionType.ApplicationCommand;
|
|
||||||
}
|
|
||||||
export function isAutocomplete(i: InteractionTypable): i is AutocompleteInteraction {
|
|
||||||
return i.type === InteractionType.ApplicationCommandAutocomplete;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function isModal(i: InteractionTypable): i is ModalSubmitInteraction {
|
|
||||||
return i.type === InteractionType.ModalSubmit;
|
|
||||||
}
|
|
||||||
68
src/core/presences.ts
Normal file
68
src/core/presences.ts
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
import type { ActivitiesOptions } from "discord.js";
|
||||||
|
import type { IntoDependencies } from "../types/ioc";
|
||||||
|
import type { Emitter } from "./contracts/emitter";
|
||||||
|
|
||||||
|
type Status = 'online' | 'idle' | 'invisible' | 'dnd'
|
||||||
|
type PresenceReduce = (previous: Result) => Result;
|
||||||
|
|
||||||
|
export interface Result {
|
||||||
|
status?: Status;
|
||||||
|
afk?: boolean;
|
||||||
|
activities?: ActivitiesOptions[];
|
||||||
|
shardId?: number[];
|
||||||
|
repeat?: number | [Emitter, string];
|
||||||
|
onRepeat?: (previous: Result) => Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Config <T extends (keyof Dependencies)[]> =
|
||||||
|
{
|
||||||
|
inject?: [...T]
|
||||||
|
execute: (...v: IntoDependencies<T>) => Result;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A small wrapper to provide type inference.
|
||||||
|
* Create a Presence module which **MUST** be put in a file called presence.(language-extension)
|
||||||
|
* adjacent to the file where **Sern.init** is CALLED.
|
||||||
|
*/
|
||||||
|
export function module<T extends (keyof Dependencies)[]>(conf: Config<T>)
|
||||||
|
{ return conf; }
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a Presence body which can be either:
|
||||||
|
* - once, the presence is activated only once.
|
||||||
|
* - repeated, per cycle or event, the presence can be changed.
|
||||||
|
*/
|
||||||
|
export function of(root: Omit<Result, 'repeat' | 'onRepeat'>) {
|
||||||
|
return {
|
||||||
|
/**
|
||||||
|
* @example
|
||||||
|
* Presence
|
||||||
|
* .of({
|
||||||
|
* activities: [{ name: "deez nuts" }]
|
||||||
|
* }) //starts the presence with "deez nuts".
|
||||||
|
* .repeated(prev => {
|
||||||
|
* return {
|
||||||
|
* afk: true,
|
||||||
|
* activities: prev.activities?.map(s => ({ ...s, name: s.name+"s" }))
|
||||||
|
* };
|
||||||
|
* }, 10000)) //every 10 s, the callback sets the presence to the returned one.
|
||||||
|
*/
|
||||||
|
repeated: (onRepeat: PresenceReduce, repeat: number | [Emitter, string]) => {
|
||||||
|
return { repeat, onRepeat, ...root }
|
||||||
|
},
|
||||||
|
/**
|
||||||
|
* @example
|
||||||
|
* Presence
|
||||||
|
* .of({
|
||||||
|
* activities: [
|
||||||
|
* { name: "Chilling out" }
|
||||||
|
* ]
|
||||||
|
* })
|
||||||
|
* .once() // Sets the presence once, with what's provided in '.of()'
|
||||||
|
*/
|
||||||
|
once: () => root
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import {
|
import type {
|
||||||
BaseInteraction,
|
BaseInteraction,
|
||||||
ChatInputCommandInteraction,
|
ChatInputCommandInteraction,
|
||||||
Client,
|
Client,
|
||||||
@@ -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()),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -114,7 +114,7 @@ export class Context extends CoreContext<Message, ChatInputCommandInteraction> {
|
|||||||
if ('interaction' in wrappable) {
|
if ('interaction' in wrappable) {
|
||||||
return new Context(Ok(wrappable));
|
return new Context(Ok(wrappable));
|
||||||
}
|
}
|
||||||
assert.ok(wrappable.isChatInputCommand());
|
assert.ok(wrappable.isChatInputCommand(), "Context created with bad interaction.");
|
||||||
return new Context(Err(wrappable));
|
return new Context(Err(wrappable));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import * as assert from 'node:assert';
|
|||||||
*/
|
*/
|
||||||
export abstract class CoreContext<M, I> {
|
export abstract class CoreContext<M, I> {
|
||||||
protected constructor(protected ctx: Either<M, I>) {
|
protected constructor(protected ctx: Either<M, I>) {
|
||||||
assert.ok(typeof ctx === 'object' && ctx != null);
|
assert.ok(typeof ctx === 'object' && ctx != null, "Context was nonobject or null");
|
||||||
}
|
}
|
||||||
get message(): M {
|
get message(): M {
|
||||||
return this.ctx.expect(SernError.MismatchEvent);
|
return this.ctx.expect(SernError.MismatchEvent);
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
export { CommandType, PluginType, PayloadType, EventType } from './enums';
|
export { CommandType, PluginType, PayloadType, EventType } from './enums';
|
||||||
export * from './context';
|
export * from './context';
|
||||||
export * from './sern-emitter';
|
|
||||||
export * from './services';
|
export * from './services';
|
||||||
export * from './module-store';
|
export * from './module-store';
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,11 @@
|
|||||||
import { CommandMeta, Module } from '../../types/core-modules';
|
import { CommandMeta, Module } from '../../types/core-modules';
|
||||||
import { CoreModuleStore } from '../contracts';
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* @internal
|
* @deprecated
|
||||||
* 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 ModuleStore!
|
||||||
* For interacting with modules, use the ModuleManager instead.
|
* For interacting with modules, use the ModuleManager instead.
|
||||||
*/
|
*/
|
||||||
export class ModuleStore implements CoreModuleStore {
|
export class ModuleStore {
|
||||||
metadata = new WeakMap<Module, CommandMeta>();
|
metadata = new WeakMap<Module, CommandMeta>();
|
||||||
commands = new Map<string, string>();
|
commands = new Map<string, Module>();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,89 +0,0 @@
|
|||||||
import { EventEmitter } from 'node:events';
|
|
||||||
import { PayloadType } from '../../core/structures';
|
|
||||||
import { Module } from '../../types/core-modules';
|
|
||||||
import { SernEventsMapping, Payload } from '../../types/utility';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @since 1.0.0
|
|
||||||
*/
|
|
||||||
export class SernEmitter extends EventEmitter {
|
|
||||||
constructor() {
|
|
||||||
super({ captureRejections: true });
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Listening to sern events with on. This event stays on until a crash or a normal exit
|
|
||||||
* @param eventName
|
|
||||||
* @param listener what to do with the data
|
|
||||||
*/
|
|
||||||
public override on<T extends keyof SernEventsMapping>(
|
|
||||||
eventName: T,
|
|
||||||
listener: (...args: SernEventsMapping[T][]) => void,
|
|
||||||
): this {
|
|
||||||
return super.on(eventName, listener);
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Listening to sern events with on. This event stays on until a crash or a normal exit
|
|
||||||
* @param eventName
|
|
||||||
* @param listener what to do with the data
|
|
||||||
*/
|
|
||||||
public override once<T extends keyof SernEventsMapping>(
|
|
||||||
eventName: T,
|
|
||||||
listener: (...args: SernEventsMapping[T][]) => void,
|
|
||||||
): this {
|
|
||||||
return super.once(eventName, listener);
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Listening to sern events with on. This event stays on until a crash or a normal exit
|
|
||||||
* @param eventName
|
|
||||||
* @param args the arguments for emitting the eventName
|
|
||||||
*/
|
|
||||||
public override emit<T extends keyof SernEventsMapping>(
|
|
||||||
eventName: T,
|
|
||||||
...args: SernEventsMapping[T]
|
|
||||||
): boolean {
|
|
||||||
return super.emit(eventName, ...args);
|
|
||||||
}
|
|
||||||
private static payload<T extends Payload>(
|
|
||||||
type: PayloadType,
|
|
||||||
module?: Module,
|
|
||||||
reason?: unknown,
|
|
||||||
) {
|
|
||||||
return { type, module, reason } as T;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Creates a compliant SernEmitter failure payload
|
|
||||||
* @param module
|
|
||||||
* @param reason
|
|
||||||
*/
|
|
||||||
static failure(module?: Module, reason?: unknown) {
|
|
||||||
//The generic cast Payload & { type : PayloadType.* } coerces the type to be a failure payload
|
|
||||||
// same goes to the other methods below
|
|
||||||
return SernEmitter.payload<Payload & { type: PayloadType.Failure }>(
|
|
||||||
PayloadType.Failure,
|
|
||||||
module,
|
|
||||||
reason,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Creates a compliant SernEmitter module success payload
|
|
||||||
* @param module
|
|
||||||
*/
|
|
||||||
static success(module: Module) {
|
|
||||||
return SernEmitter.payload<Payload & { type: PayloadType.Success }>(
|
|
||||||
PayloadType.Success,
|
|
||||||
module,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Creates a compliant SernEmitter module warning payload
|
|
||||||
* @param reason
|
|
||||||
*/
|
|
||||||
static warning(reason: unknown) {
|
|
||||||
return SernEmitter.payload<Payload & { type: PayloadType.Warning }>(
|
|
||||||
PayloadType.Warning,
|
|
||||||
undefined,
|
|
||||||
reason,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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 = 1;
|
||||||
|
|
||||||
updateAlive(err: Error) {
|
updateAlive(err: Error) {
|
||||||
this.keepAlive--;
|
this.#keepAlive--;
|
||||||
if (this.keepAlive === 0) {
|
if (this.#keepAlive === 0) {
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import * as Id from '../../../core/id';
|
import * as Id from '../../../core/id';
|
||||||
import { CoreModuleStore, ModuleManager } from '../../contracts';
|
import { CoreModuleStore, ModuleManager } from '../../contracts';
|
||||||
import { Files } from '../../_internal';
|
|
||||||
import { CommandMeta, CommandModule, CommandModuleDefs, Module } from '../../../types/core-modules';
|
import { CommandMeta, CommandModule, CommandModuleDefs, Module } from '../../../types/core-modules';
|
||||||
import { CommandType } from '../enums';
|
import { CommandType } from '../enums';
|
||||||
/**
|
/**
|
||||||
@@ -11,12 +10,13 @@ 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 module = this.get(Id.create(name, commandType));
|
||||||
if (!id) {
|
if (!module) {
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
return Files.importModule<CommandModuleDefs[T]>(id);
|
return module as CommandModuleDefs[T];
|
||||||
}
|
}
|
||||||
|
|
||||||
setMetadata(m: Module, c: CommandMeta): void {
|
setMetadata(m: Module, c: CommandMeta): void {
|
||||||
@@ -34,17 +34,18 @@ export class DefaultModuleManager implements ModuleManager {
|
|||||||
get(id: string) {
|
get(id: string) {
|
||||||
return this.moduleStore.commands.get(id);
|
return this.moduleStore.commands.get(id);
|
||||||
}
|
}
|
||||||
set(id: string, path: string): void {
|
set(id: string, path: CommandModule): void {
|
||||||
this.moduleStore.commands.set(id, path);
|
this.moduleStore.commands.set(id, path);
|
||||||
}
|
}
|
||||||
//not tested
|
//not tested
|
||||||
getPublishableCommands(): Promise<CommandModule[]> {
|
getPublishableCommands(): CommandModule[] {
|
||||||
const entries = this.moduleStore.commands.entries();
|
const entries = this.moduleStore.commands.entries();
|
||||||
const publishable = 0b000000110;
|
const publishable = 0b000000110;
|
||||||
return Promise.all(
|
return Array.from(entries)
|
||||||
Array.from(entries)
|
.filter(([id]) => {
|
||||||
.filter(([id]) => !(Number.parseInt(id.at(-1)!) & publishable))
|
const last_entry = id.at(-1);
|
||||||
.map(([, path]) => Files.importModule<CommandModule>(path)),
|
return last_entry == 'B' || !(publishable & Number.parseInt(last_entry!));
|
||||||
);
|
})
|
||||||
|
.map(([, path]) => path as CommandModule);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,41 +9,15 @@ 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 { Args } from '../types/utility';
|
||||||
import type { BothCommand, CommandModule, Module, Processed } from '../types/core-modules';
|
import { inspect } from 'node:util'
|
||||||
|
import type { CommandModule, Module, Processed } from '../types/core-modules';
|
||||||
|
|
||||||
function dispatchInteraction<T extends CommandModule, V extends BaseInteraction | Message>(
|
|
||||||
payload: { module: Processed<T>; event: V },
|
|
||||||
createArgs: (m: typeof payload.event) => unknown[],
|
|
||||||
) {
|
|
||||||
return {
|
|
||||||
module: payload.module,
|
|
||||||
args: createArgs(payload.event),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
//TODO: refactor dispatchers so that it implements a strategy for each different type of payload?
|
//TODO: refactor dispatchers so that it implements a strategy for each different type of payload?
|
||||||
export function dispatchMessage(module: Processed<CommandModule>, args: [Context, Args]) {
|
export function dispatchMessage(module: Processed<CommandModule>, args: [Context, Args]) {
|
||||||
return {
|
return { module, args };
|
||||||
module,
|
|
||||||
args,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function dispatchAutocomplete(payload: {
|
|
||||||
module: Processed<BothCommand>;
|
|
||||||
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 {
|
|
||||||
module: option.command as Processed<Module>, //autocomplete is not a true "module" warning cast!
|
|
||||||
args: [payload.event],
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function contextArgs(wrappable: Message | BaseInteraction, messageArgs?: string[]) {
|
export function contextArgs(wrappable: Message | BaseInteraction, messageArgs?: string[]) {
|
||||||
@@ -52,20 +26,17 @@ export function contextArgs(wrappable: Message | BaseInteraction, messageArgs?:
|
|||||||
return [ctx, args] as [Context, Args];
|
return [ctx, args] as [Context, Args];
|
||||||
}
|
}
|
||||||
|
|
||||||
function interactionArg<T extends BaseInteraction>(interaction: T) {
|
|
||||||
return [interaction] as [T];
|
|
||||||
}
|
|
||||||
|
|
||||||
function intoPayload(module: Processed<Module>) {
|
function intoPayload(module: Processed<Module>, ) {
|
||||||
return pipe(
|
return pipe(
|
||||||
arrayifySource,
|
arrayifySource,
|
||||||
map(args => ({ module, args })),
|
map(args => ({ module, args, })),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const createResult = createResultResolver<
|
const createResult = createResultResolver<
|
||||||
Processed<Module>,
|
Processed<Module>,
|
||||||
{ module: Processed<Module>; args: unknown[] },
|
{ module: Processed<Module>; args: unknown[] },
|
||||||
unknown[]
|
unknown[]
|
||||||
>({
|
>({
|
||||||
createStream: ({ module, args }) => from(module.onEvent).pipe(callPlugin(args)),
|
createStream: ({ module, args }) => from(module.onEvent).pipe(callPlugin(args)),
|
||||||
@@ -76,7 +47,7 @@ const createResult = createResultResolver<
|
|||||||
* @param module
|
* @param module
|
||||||
* @param source
|
* @param source
|
||||||
*/
|
*/
|
||||||
export function eventDispatcher(module: Processed<Module>, source: unknown) {
|
export function eventDispatcher(module: Processed<Module>, source: unknown) {
|
||||||
assert.ok(source instanceof EventEmitter, `${source} is not an EventEmitter`);
|
assert.ok(source instanceof EventEmitter, `${source} is not an EventEmitter`);
|
||||||
|
|
||||||
const execute: OperatorFunction<unknown[], unknown> = concatMap(async args =>
|
const execute: OperatorFunction<unknown[], unknown> = concatMap(async args =>
|
||||||
@@ -101,17 +72,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(option, SernError.NotSupportedInteraction + ` There is no autocomplete tag for ` + inspect(payload.module));
|
||||||
* must be handled separately, since it's
|
const { command } = option;
|
||||||
* too different from regular command modules
|
|
||||||
* CAST SAFETY: payload is already guaranteed to be a slash command or both command
|
return {
|
||||||
*/
|
...payload,
|
||||||
return dispatchAutocomplete(payload as never);
|
module: command as Processed<Module>, //autocomplete is not a true "module" warning cast!
|
||||||
|
args: [payload.event],
|
||||||
|
};
|
||||||
}
|
}
|
||||||
return dispatchInteraction(payload, contextArgs);
|
return { module: payload.module, args: contextArgs(payload.event) };
|
||||||
}
|
}
|
||||||
default:
|
default: return { module: payload.module, args: [payload.event] };
|
||||||
return dispatchInteraction(payload, interactionArg);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,9 +8,9 @@ import {
|
|||||||
of,
|
of,
|
||||||
throwError,
|
throwError,
|
||||||
tap,
|
tap,
|
||||||
MonoTypeOperatorFunction,
|
|
||||||
catchError,
|
catchError,
|
||||||
finalize,
|
finalize,
|
||||||
|
map,
|
||||||
} from 'rxjs';
|
} from 'rxjs';
|
||||||
import {
|
import {
|
||||||
Files,
|
Files,
|
||||||
@@ -21,17 +21,16 @@ import {
|
|||||||
handleError,
|
handleError,
|
||||||
SernError,
|
SernError,
|
||||||
VoidResult,
|
VoidResult,
|
||||||
useContainerRaw,
|
resultPayload,
|
||||||
} from '../core/_internal';
|
} from '../core/_internal';
|
||||||
import { Emitter, ErrorHandling, Logging, ModuleManager } from '../core';
|
import { Emitter, ErrorHandling, Logging, ModuleManager, PayloadType } from '../core';
|
||||||
import { contextArgs, createDispatcher, dispatchMessage } from './dispatchers';
|
import { contextArgs, createDispatcher } from './dispatchers';
|
||||||
import { ObservableInput, pipe } from 'rxjs';
|
import { ObservableInput, pipe } from 'rxjs';
|
||||||
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 { 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, CommandMeta, CommandModule, Module, Processed } from '../types/core-modules';
|
||||||
import type { ImportPayload } from '../types/core';
|
import { disposeAll } from '../core/ioc/base';
|
||||||
|
|
||||||
function createGenericHandler<Source, Narrowed extends Source, Output>(
|
function createGenericHandler<Source, Narrowed extends Source, Output>(
|
||||||
source: Observable<Source>,
|
source: Observable<Source>,
|
||||||
@@ -71,17 +70,17 @@ export function createInteractionHandler<T extends Interaction>(
|
|||||||
return createGenericHandler<Interaction, T, Result<ReturnType<typeof createDispatcher>, void>>(
|
return createGenericHandler<Interaction, T, Result<ReturnType<typeof createDispatcher>, void>>(
|
||||||
source,
|
source,
|
||||||
async event => {
|
async event => {
|
||||||
const fullPath = mg.get(Id.reconstruct(event));
|
const possibleIds = Id.reconstruct(event);
|
||||||
if(!fullPath) {
|
let fullPaths= possibleIds
|
||||||
return Err.EMPTY
|
.map(id => mg.get(id))
|
||||||
|
.filter((id): id is Module => id !== undefined);
|
||||||
|
|
||||||
|
if(fullPaths.length == 0) {
|
||||||
|
return Err.EMPTY;
|
||||||
}
|
}
|
||||||
return Files
|
const [ path ] = fullPaths;
|
||||||
.defaultModuleLoader<Processed<CommandModule>>(fullPath)
|
return Ok(createDispatcher({ module: path as Processed<CommandModule>, event }));
|
||||||
.then(payload =>
|
});
|
||||||
Ok(createDispatcher({ module: payload.module, event }))
|
|
||||||
);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createMessageHandler(
|
export function createMessageHandler(
|
||||||
@@ -91,44 +90,52 @@ export function createMessageHandler(
|
|||||||
) {
|
) {
|
||||||
return createGenericHandler(source, async event => {
|
return createGenericHandler(source, async event => {
|
||||||
const [prefix, ...rest] = fmt(event.content, defaultPrefix);
|
const [prefix, ...rest] = fmt(event.content, defaultPrefix);
|
||||||
const fullPath = mg.get(`${prefix}_A1`);
|
let fullPath = mg.get(`${prefix}_T`);
|
||||||
|
|
||||||
if(!fullPath) {
|
if(!fullPath) {
|
||||||
return Err('Possibly undefined behavior: could not find a static id to resolve ')
|
fullPath = mg.get(`${prefix}_B`);
|
||||||
|
if(!fullPath) {
|
||||||
|
return Err('Possibly undefined behavior: could not find a static id to resolve');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return Files
|
return Ok({ args: contextArgs(event, rest), module: fullPath as Processed<CommandModule> })
|
||||||
.defaultModuleLoader<Processed<CommandModule>>(fullPath)
|
|
||||||
.then(payload => {
|
|
||||||
const args = contextArgs(event, rest);
|
|
||||||
return Ok(dispatchMessage(payload.module, args));
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* IMPURE SIDE EFFECT
|
|
||||||
* This function assigns remaining, incomplete data to each imported module.
|
* This function assigns remaining, incomplete data to each imported module.
|
||||||
*/
|
*/
|
||||||
function assignDefaults<T extends Module>(
|
function assignDefaults() {
|
||||||
moduleManager: ModuleManager,
|
return map(({ module, absPath }) => {
|
||||||
): MonoTypeOperatorFunction<ImportPayload<T>> {
|
const processed = {
|
||||||
return tap(({ module, absPath }) => {
|
name: module.name ?? Files.filename(absPath),
|
||||||
module.name ??= Files.filename(absPath);
|
description: module.description ?? '...',
|
||||||
module.description ??= '...';
|
...module
|
||||||
moduleManager.setMetadata(module, {
|
}
|
||||||
isClass: module.constructor.name === 'Function',
|
return {
|
||||||
fullPath: absPath,
|
module: processed,
|
||||||
id: Id.create(module.name, module.type),
|
absPath,
|
||||||
});
|
metadata: {
|
||||||
|
isClass: module.constructor.name === 'Function',
|
||||||
|
fullPath: absPath,
|
||||||
|
id: Id.create(processed.name, module.type),
|
||||||
|
}
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function buildModules<T extends AnyModule>(
|
export function buildModules<T extends AnyModule>(
|
||||||
input: ObservableInput<string>,
|
input: ObservableInput<string>,
|
||||||
moduleManager: ModuleManager,
|
|
||||||
) {
|
) {
|
||||||
return Files.buildModuleStream<Processed<T>>(input).pipe(assignDefaults(moduleManager));
|
return Files
|
||||||
|
.buildModuleStream<Processed<T>>(input)
|
||||||
|
.pipe(assignDefaults());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
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
|
||||||
@@ -139,28 +146,30 @@ 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
|
||||||
concatMap(() => Result.wrapAsync(async () => task())),
|
concatMap(() => Result.wrapAsync(async () => task())),
|
||||||
concatMap(result => {
|
concatMap(result => {
|
||||||
if (result.isOk()) {
|
if (result.isOk()) {
|
||||||
emitter.emit('module.activate', SernEmitter.success(module));
|
emitter.emit('module.activate', resultPayload(PayloadType.Success, module));
|
||||||
return EMPTY;
|
return EMPTY;
|
||||||
} else {
|
}
|
||||||
return throwError(() => SernEmitter.failure(module, result.error));
|
return throwError(() => resultPayload(PayloadType.Failure, module, result.error));
|
||||||
}
|
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A higher order function that
|
* A higher order function that
|
||||||
* - creates a stream of {@link VoidResult} { config.createStream }
|
* - creates a stream of {@link VoidResult} { config.createStream }
|
||||||
@@ -200,14 +209,11 @@ export function callInitPlugins<T extends Processed<AnyModule>>(sernEmitter: Emi
|
|||||||
createResultResolver({
|
createResultResolver({
|
||||||
createStream: args => from(args.module.plugins).pipe(callPlugin(args)),
|
createStream: args => from(args.module.plugins).pipe(callPlugin(args)),
|
||||||
onStop: (module: T) => {
|
onStop: (module: T) => {
|
||||||
sernEmitter.emit(
|
sernEmitter.emit('module.register', resultPayload(PayloadType.Failure, module, SernError.PluginFailure));
|
||||||
'module.register',
|
|
||||||
SernEmitter.failure(module, SernError.PluginFailure),
|
|
||||||
);
|
|
||||||
},
|
},
|
||||||
onNext: ({ module }) => {
|
onNext: (payload) => {
|
||||||
sernEmitter.emit('module.register', SernEmitter.success(module));
|
sernEmitter.emit('module.register', resultPayload(PayloadType.Success, payload.module));
|
||||||
return module;
|
return payload as { module: T; metadata: CommandMeta };
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -219,30 +225,33 @@ 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,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export const handleCrash = (err: ErrorHandling, log?: Logging) =>
|
export const handleCrash = (err: ErrorHandling,sernemitter: Emitter, log?: Logging) =>
|
||||||
pipe(
|
pipe(
|
||||||
catchError(handleError(err, log)),
|
catchError(handleError(err, sernemitter, log)),
|
||||||
finalize(() => {
|
finalize(() => {
|
||||||
log?.info({
|
log?.info({
|
||||||
message: 'A stream closed or reached end of lifetime',
|
message: 'A stream closed or reached end of lifetime',
|
||||||
});
|
});
|
||||||
useContainerRaw()
|
disposeAll(log);
|
||||||
?.disposeAll()
|
}));
|
||||||
.then(() => log?.info({ message: 'Cleaning container and crashing' }));
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { Interaction } from 'discord.js';
|
import { Interaction } from 'discord.js';
|
||||||
import { concatMap, merge } from 'rxjs';
|
import { mergeMap, merge } from 'rxjs';
|
||||||
import { SernEmitter } from '../core';
|
import { PayloadType } from '../core';
|
||||||
import {
|
import {
|
||||||
isAutocomplete,
|
isAutocomplete,
|
||||||
isCommand,
|
isCommand,
|
||||||
@@ -9,11 +9,12 @@ import {
|
|||||||
sharedEventStream,
|
sharedEventStream,
|
||||||
SernError,
|
SernError,
|
||||||
filterTap,
|
filterTap,
|
||||||
|
resultPayload,
|
||||||
} from '../core/_internal';
|
} from '../core/_internal';
|
||||||
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);
|
||||||
|
|
||||||
@@ -25,9 +26,8 @@ export function interactionHandler([emitter, , , modules, client]: DependencyLis
|
|||||||
);
|
);
|
||||||
return interactionHandler$
|
return interactionHandler$
|
||||||
.pipe(
|
.pipe(
|
||||||
filterTap(e => emitter.emit('warning', SernEmitter.warning(e))),
|
filterTap(e => emitter.emit('warning', resultPayload(PayloadType.Warning, undefined, e))),
|
||||||
makeModuleExecutor(module =>
|
makeModuleExecutor(module =>
|
||||||
emitter.emit('module.activate', SernEmitter.failure(module, SernError.PluginFailure))),
|
emitter.emit('module.activate', resultPayload(PayloadType.Failure, module, SernError.PluginFailure))),
|
||||||
concatMap(payload => executeModule(emitter, payload)),
|
mergeMap(payload => executeModule(emitter, log, err, payload)));
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { concatMap, EMPTY } from 'rxjs';
|
import { mergeMap, EMPTY } from 'rxjs';
|
||||||
import type { Message } from 'discord.js';
|
import type { Message } from 'discord.js';
|
||||||
import { SernEmitter } from '../core';
|
import { PayloadType } from '../core';
|
||||||
import { sharedEventStream, SernError, filterTap } from '../core/_internal';
|
import { sharedEventStream, SernError, filterTap, resultPayload } from '../core/_internal';
|
||||||
import { createMessageHandler, executeModule, makeModuleExecutor } from './_internal';
|
import { createMessageHandler, executeModule, makeModuleExecutor } from './_internal';
|
||||||
import type { DependencyList } from '../types/ioc';
|
import type { DependencyList } from '../types/ioc';
|
||||||
|
|
||||||
@@ -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) {
|
||||||
@@ -38,10 +38,10 @@ export function messageHandler(
|
|||||||
const msgCommands$ = handle(isNonBot(defaultPrefix));
|
const msgCommands$ = handle(isNonBot(defaultPrefix));
|
||||||
|
|
||||||
return msgCommands$.pipe(
|
return msgCommands$.pipe(
|
||||||
filterTap((e) => emitter.emit('warning', SernEmitter.warning(e))),
|
filterTap((e) => emitter.emit('warning', resultPayload(PayloadType.Warning, undefined, e))),
|
||||||
makeModuleExecutor(module => {
|
makeModuleExecutor(module => {
|
||||||
emitter.emit('module.activate', SernEmitter.failure(module, SernError.PluginFailure));
|
const result = resultPayload(PayloadType.Failure, module, SernError.PluginFailure);
|
||||||
|
emitter.emit('module.activate', result);
|
||||||
}),
|
}),
|
||||||
concatMap(payload => executeModule(emitter, payload)),
|
mergeMap(payload => executeModule(emitter, log, err, payload)));
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|||||||
45
src/handlers/presence.ts
Normal file
45
src/handlers/presence.ts
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
import { concatMap, from, interval, of, map, scan, startWith, fromEvent, take } from "rxjs"
|
||||||
|
import { Files } from "../core/_internal";
|
||||||
|
import * as Presence from "../core/presences";
|
||||||
|
import { Services } from "../core/ioc";
|
||||||
|
import assert from "node:assert";
|
||||||
|
|
||||||
|
type SetPresence = (conf: Presence.Result) => Promise<unknown>
|
||||||
|
|
||||||
|
const parseConfig = async (conf: Promise<Presence.Result>) => {
|
||||||
|
return conf.then(s => {
|
||||||
|
if('repeat' in s) {
|
||||||
|
const { onRepeat, repeat } = s;
|
||||||
|
assert(repeat !== undefined, "repeat option is undefined");
|
||||||
|
assert(onRepeat !== undefined, "onRepeat callback is undefined, but repeat exists");
|
||||||
|
const src$ = typeof repeat === 'number'
|
||||||
|
? interval(repeat)
|
||||||
|
: fromEvent(...repeat);
|
||||||
|
return src$
|
||||||
|
.pipe(scan(onRepeat, s),
|
||||||
|
startWith(s));
|
||||||
|
}
|
||||||
|
return of(s).pipe(take(1));
|
||||||
|
})
|
||||||
|
};
|
||||||
|
|
||||||
|
export const presenceHandler = (path: string, setPresence: SetPresence) => {
|
||||||
|
interface PresenceModule {
|
||||||
|
module: Presence.Config<(keyof Dependencies)[]>
|
||||||
|
}
|
||||||
|
const presence = Files
|
||||||
|
.importModule<PresenceModule>(path)
|
||||||
|
.then(({ module }) => {
|
||||||
|
//fetch services with the order preserved, passing it to the execute fn
|
||||||
|
const fetchedServices = Services(...module.inject ?? []);
|
||||||
|
return async () => module.execute(...fetchedServices);
|
||||||
|
})
|
||||||
|
const module$ = from(presence);
|
||||||
|
return module$.pipe(
|
||||||
|
//compose:
|
||||||
|
//call the execute function, passing that result into parseConfig.
|
||||||
|
//concatMap resolves the promise, and passes it to the next concatMap.
|
||||||
|
concatMap(fn => parseConfig(fn())),
|
||||||
|
// subscribe to the observable parseConfig yields, and set the presence.
|
||||||
|
concatMap(conf => conf.pipe(map(setPresence))));
|
||||||
|
}
|
||||||
@@ -1,48 +1,54 @@
|
|||||||
import { ObservableInput, concat, first, fromEvent, ignoreElements, pipe } from 'rxjs';
|
import { ObservableInput, concat, first, fromEvent, ignoreElements, pipe, tap } from 'rxjs';
|
||||||
import { CommandType } from '../core/structures';
|
import { CommandType } from '../core/structures';
|
||||||
import { SernError } from '../core/_internal';
|
import { SernError } from '../core/_internal';
|
||||||
import { Result } from 'ts-results-es';
|
import { Result } from 'ts-results-es';
|
||||||
import { ModuleManager } from '../core/contracts';
|
import { Logging, ModuleManager } from '../core/contracts';
|
||||||
import { buildModules, callInitPlugins } from './_internal';
|
import { buildModules, callInitPlugins } from './_internal';
|
||||||
import * as assert from 'node:assert';
|
import * as assert from 'node:assert';
|
||||||
import * as util from 'node:util';
|
import * as util from 'node:util';
|
||||||
import type { DependencyList } from '../types/ioc';
|
import type { DependencyList } from '../types/ioc';
|
||||||
import type { AnyModule, Processed } from '../types/core-modules';
|
import type { AnyModule, CommandMeta, Processed } from '../types/core-modules';
|
||||||
|
|
||||||
export function startReadyEvent(
|
export function readyHandler(
|
||||||
[sEmitter, , , moduleManager, client]: DependencyList,
|
[sEmitter, , log , moduleManager, client]: DependencyList,
|
||||||
allPaths: ObservableInput<string>,
|
allPaths: ObservableInput<string>,
|
||||||
) {
|
) {
|
||||||
const ready$ = fromEvent(client!, 'ready').pipe(once());
|
//Todo: add module manager on on ready
|
||||||
|
const ready$ = fromEvent(client!, 'ready').pipe(once(log));
|
||||||
return concat(ready$, buildModules<AnyModule>(allPaths, moduleManager))
|
|
||||||
|
return concat(ready$, buildModules<AnyModule>(allPaths))
|
||||||
.pipe(callInitPlugins(sEmitter))
|
.pipe(callInitPlugins(sEmitter))
|
||||||
.subscribe(module => {
|
.subscribe(({ module, metadata }) => {
|
||||||
register(moduleManager, module).expect(
|
register(moduleManager, module, metadata)
|
||||||
SernError.InvalidModuleType + ' ' + util.inspect(module),
|
.expect(SernError.InvalidModuleType + ' ' + util.inspect(module));
|
||||||
);
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const once = () => pipe(
|
const once = (log: Logging | undefined) => pipe(
|
||||||
|
tap(() => { log?.info({ message: "Waiting on discord client to be ready..." }) }),
|
||||||
first(),
|
first(),
|
||||||
ignoreElements()
|
ignoreElements())
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
function register<T extends Processed<AnyModule>>(
|
function register<T extends Processed<AnyModule>>(
|
||||||
manager: ModuleManager,
|
manager: ModuleManager,
|
||||||
module: T,
|
module: T,
|
||||||
|
metadata:CommandMeta
|
||||||
): Result<void, void> {
|
): Result<void, void> {
|
||||||
const { id, fullPath } = manager.getMetadata(module)!;
|
manager.setMetadata(module, metadata)!;
|
||||||
|
|
||||||
const validModuleType = module.type >= 0 && module.type <= 1 << 10;
|
const validModuleType = module.type >= 0 && module.type <= 1 << 10;
|
||||||
assert.ok(
|
assert.ok(
|
||||||
validModuleType,
|
validModuleType,
|
||||||
`Found ${module.name} at ${fullPath}, which does not have a valid type`,
|
//@ts-ignore
|
||||||
|
`Found ${module.name} at ${metadata.fullPath}, which does not have a valid type`,
|
||||||
);
|
);
|
||||||
if (module.type === CommandType.Both || module.type === CommandType.Text) {
|
if (module.type === CommandType.Both) {
|
||||||
module.alias?.forEach(a => manager.set(`${a}_A1`, fullPath));
|
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(id, fullPath));
|
return Result.wrap(() => manager.set(metadata.id, module));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,26 +4,26 @@ 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)
|
||||||
.pipe(
|
.pipe(
|
||||||
callInitPlugins(emitter),
|
callInitPlugins(emitter),
|
||||||
map(intoDispatcher),
|
map(intoDispatcher),
|
||||||
@@ -31,7 +31,6 @@ export function eventsHandler(
|
|||||||
* Where all events are turned on
|
* Where all events are turned on
|
||||||
*/
|
*/
|
||||||
mergeAll(),
|
mergeAll(),
|
||||||
handleCrash(err, log),
|
handleCrash(err, emitter, log))
|
||||||
)
|
|
||||||
.subscribe();
|
.subscribe();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -46,11 +46,8 @@ export {
|
|||||||
commandModule,
|
commandModule,
|
||||||
eventModule,
|
eventModule,
|
||||||
discordEvent,
|
discordEvent,
|
||||||
EventExecutable,
|
|
||||||
CommandExecutable,
|
|
||||||
} from './core/modules';
|
} from './core/modules';
|
||||||
|
|
||||||
export {
|
export * as Presence from './core/presences'
|
||||||
useContainerRaw
|
|
||||||
} from './core/_internal'
|
|
||||||
export { controller } from './sern';
|
|
||||||
|
|||||||
58
src/sern.ts
58
src/sern.ts
@@ -1,12 +1,15 @@
|
|||||||
import { handleCrash } from './handlers/_internal';
|
import { handleCrash } from './handlers/_internal';
|
||||||
import { err, ok, Files } from './core/_internal';
|
import callsites from 'callsites';
|
||||||
|
import { Files } from './core/_internal';
|
||||||
import { merge } from 'rxjs';
|
import { merge } from 'rxjs';
|
||||||
import { Services } from './core/ioc';
|
import { Services } from './core/ioc';
|
||||||
import { Wrapper } from './types/core';
|
import { Wrapper } from './types/core';
|
||||||
import { eventsHandler } from './handlers/user-defined-events';
|
import { eventsHandler } from './handlers/user-defined-events';
|
||||||
import { startReadyEvent } from './handlers/ready-event';
|
import { readyHandler } from './handlers/ready-event';
|
||||||
import { messageHandler } from './handlers/message-event';
|
import { messageHandler } from './handlers/message-event';
|
||||||
import { interactionHandler } from './handlers/interaction-event';
|
import { interactionHandler } from './handlers/interaction-event';
|
||||||
|
import { presenceHandler } from './handlers/presence';
|
||||||
|
import { Client } from 'discord.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @since 1.0.0
|
* @since 1.0.0
|
||||||
@@ -20,47 +23,40 @@ import { interactionHandler } from './handlers/interaction-event';
|
|||||||
* })
|
* })
|
||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
|
|
||||||
export function init(maybeWrapper: Wrapper | 'file') {
|
export function init(maybeWrapper: Wrapper | 'file') {
|
||||||
const startTime = performance.now();
|
const startTime = performance.now();
|
||||||
const wrapper = Files.loadConfig(maybeWrapper);
|
const dependencies = Services('@sern/emitter',
|
||||||
const dependencies = useDependencies();
|
'@sern/errors',
|
||||||
|
'@sern/logger',
|
||||||
|
'@sern/modules',
|
||||||
|
'@sern/client');
|
||||||
const logger = dependencies[2],
|
const logger = dependencies[2],
|
||||||
errorHandler = dependencies[1];
|
errorHandler = dependencies[1];
|
||||||
|
|
||||||
|
const wrapper = Files.loadConfig(maybeWrapper, logger);
|
||||||
if (wrapper.events !== undefined) {
|
if (wrapper.events !== undefined) {
|
||||||
eventsHandler(dependencies, Files.getFullPathTree(wrapper.events));
|
eventsHandler(dependencies, Files.getFullPathTree(wrapper.events));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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
|
//Ready event: load all modules and when finished, time should be taken and logged
|
||||||
startReadyEvent(dependencies, Files.getFullPathTree(wrapper.commands)).add(() => {
|
readyHandler(dependencies, Files.getFullPathTree(wrapper.commands))
|
||||||
const time = ((performance.now() - startTime) / 1000).toFixed(2);
|
.add(() => {
|
||||||
dependencies[0].emit('modulesLoaded');
|
logger?.info({ message: "Client signaled ready, registering modules" });
|
||||||
logger?.info({
|
const time = ((performance.now() - startTime) / 1000).toFixed(2);
|
||||||
message: `sern: registered all modules in ${time} s`,
|
dependencies[0].emit('modulesLoaded');
|
||||||
|
logger?.info({ message: `sern: registered in ${time} s`, });
|
||||||
|
if(presencePath.exists) {
|
||||||
|
const setPresence = async (p: any) => {
|
||||||
|
return (dependencies[4] as Client).user?.setPresence(p);
|
||||||
|
}
|
||||||
|
presenceHandler(presencePath.path, setPresence).subscribe();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
});
|
|
||||||
|
|
||||||
const messages$ = messageHandler(dependencies, wrapper.defaultPrefix);
|
const messages$ = messageHandler(dependencies, wrapper.defaultPrefix);
|
||||||
const interactions$ = interactionHandler(dependencies);
|
const interactions$ = interactionHandler(dependencies);
|
||||||
// listening to the message stream and interaction stream
|
// listening to the message stream and interaction stream
|
||||||
merge(messages$, interactions$).pipe(handleCrash(errorHandler, logger)).subscribe();
|
merge(messages$, interactions$).pipe(handleCrash(errorHandler, dependencies[0], logger)).subscribe();
|
||||||
}
|
}
|
||||||
|
|
||||||
function useDependencies() {
|
|
||||||
return Services(
|
|
||||||
'@sern/emitter',
|
|
||||||
'@sern/errors',
|
|
||||||
'@sern/logger',
|
|
||||||
'@sern/modules',
|
|
||||||
'@sern/client',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @since 1.0.0
|
|
||||||
* The object passed into every plugin to control a command's behavior
|
|
||||||
*/
|
|
||||||
export const controller = {
|
|
||||||
next: ok,
|
|
||||||
stop: err,
|
|
||||||
};
|
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ 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;
|
||||||
|
|||||||
@@ -33,9 +33,9 @@ import type {
|
|||||||
TextCommand,
|
TextCommand,
|
||||||
UserSelectCommand,
|
UserSelectCommand,
|
||||||
} from './core-modules';
|
} from './core-modules';
|
||||||
import { Args, Awaitable, Payload, SlashOptions } from './utility';
|
import type { Args, Awaitable, Payload, SlashOptions } from './utility';
|
||||||
import { CommandType, Context, EventType, PluginType } from '../core';
|
import type { CommandType, Context, EventType, PluginType } from '../core';
|
||||||
import {
|
import type {
|
||||||
ButtonInteraction,
|
ButtonInteraction,
|
||||||
ChannelSelectMenuInteraction,
|
ChannelSelectMenuInteraction,
|
||||||
ClientEvents,
|
ClientEvents,
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
|
||||||
export interface ImportPayload<T> {
|
export interface ImportPayload<T> {
|
||||||
module: T;
|
module: T;
|
||||||
absPath: string;
|
absPath: string;
|
||||||
|
|||||||
@@ -26,11 +26,15 @@ export type DependencyList = [
|
|||||||
|
|
||||||
export interface CoreDependencies {
|
export interface CoreDependencies {
|
||||||
'@sern/client': () => Contracts.Emitter;
|
'@sern/client': () => Contracts.Emitter;
|
||||||
'@sern/logger'?: () => Contracts.Logging;
|
|
||||||
'@sern/emitter': () => Contracts.Emitter;
|
'@sern/emitter': () => Contracts.Emitter;
|
||||||
|
/**
|
||||||
|
* @deprecated
|
||||||
|
* Will be removed and turned internal
|
||||||
|
*/
|
||||||
'@sern/store': () => Contracts.CoreModuleStore;
|
'@sern/store': () => Contracts.CoreModuleStore;
|
||||||
'@sern/modules': () => Contracts.ModuleManager;
|
'@sern/modules': () => Contracts.ModuleManager;
|
||||||
'@sern/errors': () => Contracts.ErrorHandling;
|
'@sern/errors': () => Contracts.ErrorHandling;
|
||||||
|
'@sern/logger'?: () => Contracts.Logging;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type DependencyFromKey<T extends keyof Dependencies> = Dependencies[T];
|
export type DependencyFromKey<T extends keyof Dependencies> = Dependencies[T];
|
||||||
@@ -39,8 +43,13 @@ export type IntoDependencies<Tuple extends [...any[]]> = {
|
|||||||
[Index in keyof Tuple]: UnpackFunction<NonNullable<DependencyFromKey<Tuple[Index]>>>; //Unpack and make NonNullable
|
[Index in keyof Tuple]: UnpackFunction<NonNullable<DependencyFromKey<Tuple[Index]>>>; //Unpack and make NonNullable
|
||||||
} & { length: Tuple['length'] };
|
} & { length: Tuple['length'] };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @deprecated This old signature will be incompatible with future versions of sern.
|
||||||
|
*/
|
||||||
export interface DependencyConfiguration {
|
export interface DependencyConfiguration {
|
||||||
//@deprecated. Loggers will always be included in the future
|
/*
|
||||||
|
* @deprecated. Loggers will be opt-in the future
|
||||||
|
*/
|
||||||
exclude?: Set<'@sern/logger'>;
|
exclude?: Set<'@sern/logger'>;
|
||||||
build: (
|
build: (
|
||||||
root: Container<Omit<CoreDependencies, '@sern/client'>, {}>,
|
root: Container<Omit<CoreDependencies, '@sern/client'>, {}>,
|
||||||
|
|||||||
@@ -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;
|
||||||
|
|
||||||
@@ -18,7 +18,7 @@ export type Args = ParseType<{ text: string[]; slash: SlashOptions }>;
|
|||||||
export interface SernEventsMapping {
|
export interface SernEventsMapping {
|
||||||
'module.register': [Payload];
|
'module.register': [Payload];
|
||||||
'module.activate': [Payload];
|
'module.activate': [Payload];
|
||||||
error: [Payload];
|
error: [{ type: PayloadType.Failure; module?: AnyModule; reason: string | Error }];
|
||||||
warning: [Payload];
|
warning: [Payload];
|
||||||
modulesLoaded: [never?];
|
modulesLoaded: [never?];
|
||||||
}
|
}
|
||||||
@@ -26,4 +26,7 @@ export interface SernEventsMapping {
|
|||||||
export type Payload =
|
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; module: undefined; reason: string };
|
||||||
|
|
||||||
|
|
||||||
|
export type ReplyOptions = string | Omit<InteractionReplyOptions, 'fetchReply'> | MessageReplyOptions;
|
||||||
|
|||||||
64
test/core/id.test.ts
Normal file
64
test/core/id.test.ts
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
import { CommandType } from '../../src/core';
|
||||||
|
import * as Id from '../../src/core/id'
|
||||||
|
import { expect, test } from 'vitest'
|
||||||
|
|
||||||
|
test('id -> Text', () => {
|
||||||
|
const bothCmdId = Id.create("ping", CommandType.Text)
|
||||||
|
expect(bothCmdId).toBe("ping_T")
|
||||||
|
})
|
||||||
|
|
||||||
|
test('id -> Both', () => {
|
||||||
|
const bothCmdId = Id.create("ping", CommandType.Both)
|
||||||
|
expect(bothCmdId).toBe("ping_B")
|
||||||
|
})
|
||||||
|
|
||||||
|
test('id -> CtxMsg', () => {
|
||||||
|
const bothCmdId = Id.create("ping", CommandType.CtxMsg)
|
||||||
|
expect(bothCmdId).toBe("ping_A3")
|
||||||
|
})
|
||||||
|
test('id -> CtxUsr', () => {
|
||||||
|
const bothCmdId = Id.create("ping", CommandType.CtxUser)
|
||||||
|
expect(bothCmdId).toBe("ping_A2")
|
||||||
|
})
|
||||||
|
test('id -> Modal', () => {
|
||||||
|
const modal = Id.create("my-modal", CommandType.Modal)
|
||||||
|
expect(modal).toBe("my-modal_M");
|
||||||
|
})
|
||||||
|
|
||||||
|
test('id -> Button', () => {
|
||||||
|
const modal = Id.create("my-button", CommandType.Button)
|
||||||
|
expect(modal).toBe("my-button_C2");
|
||||||
|
})
|
||||||
|
|
||||||
|
test('id -> Slash', () => {
|
||||||
|
const modal = Id.create("myslash", CommandType.Slash)
|
||||||
|
expect(modal).toBe("myslash_A1");
|
||||||
|
})
|
||||||
|
|
||||||
|
test('id -> StringSelect', () => {
|
||||||
|
const modal = Id.create("mystringselect", CommandType.StringSelect)
|
||||||
|
expect(modal).toBe("mystringselect_C3");
|
||||||
|
})
|
||||||
|
|
||||||
|
test('id -> UserSelect', () => {
|
||||||
|
const modal = Id.create("myuserselect", CommandType.UserSelect)
|
||||||
|
expect(modal).toBe("myuserselect_C5");
|
||||||
|
})
|
||||||
|
|
||||||
|
test('id -> RoleSelect', () => {
|
||||||
|
const modal = Id.create("myroleselect", CommandType.RoleSelect)
|
||||||
|
expect(modal).toBe("myroleselect_C6");
|
||||||
|
})
|
||||||
|
|
||||||
|
test('id -> MentionSelect', () => {
|
||||||
|
const modal = Id.create("mymentionselect", CommandType.MentionableSelect)
|
||||||
|
expect(modal).toBe("mymentionselect_C7");
|
||||||
|
})
|
||||||
|
|
||||||
|
test('id -> ChannelSelect', () => {
|
||||||
|
const modal = Id.create("mychannelselect", CommandType.ChannelSelect)
|
||||||
|
expect(modal).toBe("mychannelselect_C8");
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -1,12 +1,13 @@
|
|||||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
import { CoreContainer } from '../../src/core/ioc/container';
|
import { CoreContainer } from '../../src/core/ioc/container';
|
||||||
import { EventEmitter } from 'events';
|
import { EventEmitter } from 'events';
|
||||||
import { DefaultLogging, Disposable, Init, Logging } from '../../src/core';
|
import { DefaultLogging, Disposable, Emitter, Init, Logging } from '../../src/core';
|
||||||
import { CoreDependencies } from '../../src/types/ioc';
|
import { CoreDependencies } from '../../src/types/ioc';
|
||||||
|
|
||||||
describe('ioc container', () => {
|
describe('ioc container', () => {
|
||||||
let container: CoreContainer<{}> = new CoreContainer();
|
let container: CoreContainer<{}> = new CoreContainer();
|
||||||
let dependency: Logging & Init & Disposable;
|
let dependency: Logging & Init & Disposable;
|
||||||
|
let dependency2: Emitter
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
dependency = {
|
dependency = {
|
||||||
init: vi.fn(),
|
init: vi.fn(),
|
||||||
@@ -16,6 +17,11 @@ describe('ioc container', () => {
|
|||||||
debug(): void {},
|
debug(): void {},
|
||||||
dispose: vi.fn()
|
dispose: vi.fn()
|
||||||
};
|
};
|
||||||
|
dependency2 = {
|
||||||
|
addListener: vi.fn(),
|
||||||
|
removeListener: vi.fn(),
|
||||||
|
emit: vi.fn()
|
||||||
|
};
|
||||||
container = new CoreContainer();
|
container = new CoreContainer();
|
||||||
});
|
});
|
||||||
const wait = (seconds: number) => new Promise((resolve) => setTimeout(resolve, seconds));
|
const wait = (seconds: number) => new Promise((resolve) => setTimeout(resolve, seconds));
|
||||||
@@ -83,4 +89,25 @@ describe('ioc container', () => {
|
|||||||
container.ready();
|
container.ready();
|
||||||
expect(dependency.init).toHaveBeenCalledTimes(0);
|
expect(dependency.init).toHaveBeenCalledTimes(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('should init dependency depending on something else', () => {
|
||||||
|
container.add({ '@sern/client': dependency2 });
|
||||||
|
container.upsert((cntr) => ({
|
||||||
|
'@sern/logger': dependency
|
||||||
|
}));
|
||||||
|
container.ready();
|
||||||
|
expect(dependency.init).toHaveBeenCalledTimes(1);
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should detect a key already exists', () => {
|
||||||
|
container.add({ '@sern/client': dependency2 });
|
||||||
|
expect(container.hasKey('@sern/client')).toBeTruthy()
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
it('should detect a key already exists', () => {
|
||||||
|
container.add({ '@sern/client': () => dependency2 });
|
||||||
|
expect(container.hasKey('@sern/client')).toBeTruthy()
|
||||||
|
})
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|||||||
57
test/core/presence.test.ts
Normal file
57
test/core/presence.test.ts
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
import { describe, expect, it, vi } from 'vitest';
|
||||||
|
import { Presence } from '../../src';
|
||||||
|
|
||||||
|
|
||||||
|
// Example test suite for the module function
|
||||||
|
describe('module function', () => {
|
||||||
|
it('should return a valid configuration', () => {
|
||||||
|
const config: Presence.Config<['dependency1', 'dependency2']> = Presence.module({
|
||||||
|
inject: ['dependency1', 'dependency2'],
|
||||||
|
execute: vi.fn(),
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(config).toBeDefined();
|
||||||
|
expect(config.inject).toEqual(['dependency1', 'dependency2']);
|
||||||
|
expect(typeof config.execute).toBe('function');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
describe('of function', () => {
|
||||||
|
it('should return a valid presence configuration without repeat and onRepeat', () => {
|
||||||
|
const presenceConfig = Presence.of({
|
||||||
|
status: 'online',
|
||||||
|
afk: false,
|
||||||
|
activities: [{ name: 'Test Activity' }],
|
||||||
|
shardId: [1, 2, 3],
|
||||||
|
}).once();
|
||||||
|
|
||||||
|
expect(presenceConfig).toBeDefined();
|
||||||
|
//@ts-ignore Maybe fix?
|
||||||
|
expect(presenceConfig.repeat).toBeUndefined();
|
||||||
|
//@ts-ignore Maybe fix?
|
||||||
|
expect(presenceConfig.onRepeat).toBeUndefined();
|
||||||
|
expect(presenceConfig).toMatchObject({
|
||||||
|
status: 'online',
|
||||||
|
afk: false,
|
||||||
|
activities: [{ name: 'Test Activity' }],
|
||||||
|
shardId: [1, 2, 3],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return a valid presence configuration with repeat and onRepeat', () => {
|
||||||
|
const onRepeatCallback = vi.fn();
|
||||||
|
const presenceConfig = Presence.of({
|
||||||
|
status: 'idle',
|
||||||
|
activities: [{ name: 'Another Test Activity' }],
|
||||||
|
}).repeated(onRepeatCallback, 5000);
|
||||||
|
|
||||||
|
expect(presenceConfig).toBeDefined();
|
||||||
|
expect(presenceConfig.repeat).toBe(5000);
|
||||||
|
expect(presenceConfig.onRepeat).toBe(onRepeatCallback);
|
||||||
|
expect(presenceConfig).toMatchObject({
|
||||||
|
status: 'idle',
|
||||||
|
activities: [{ name: 'Another Test Activity' }],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
})
|
||||||
@@ -74,4 +74,7 @@ describe('services', () => {
|
|||||||
expect(consoleMock).toHaveBeenCalledOnce();
|
expect(consoleMock).toHaveBeenCalledOnce();
|
||||||
expect(consoleMock).toHaveBeenLastCalledWith({ message: 'error' });
|
expect(consoleMock).toHaveBeenLastCalledWith({ message: 'error' });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -29,14 +29,14 @@ describe('eventDispatcher standard', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should throw', () => {
|
it('should throw', () => {
|
||||||
expect(() => eventDispatcher(m, 'not event emitter')).toThrowError();
|
expect(() => eventDispatcher(m, 'not event emitter')).toThrowError();
|
||||||
});
|
});
|
||||||
it("Shouldn't throw", () => {
|
it("Shouldn't throw", () => {
|
||||||
expect(() => eventDispatcher(m, ee)).not.toThrowError();
|
expect(() => eventDispatcher(m, ee)).not.toThrowError();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('Should be called once', () => {
|
it('Should be called once', () => {
|
||||||
const s = eventDispatcher(m, ee);
|
const s = eventDispatcher(m, ee);
|
||||||
s.subscribe();
|
s.subscribe();
|
||||||
ee.emit(m.name, faker.string.alpha());
|
ee.emit(m.name, faker.string.alpha());
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import { describe, expect, it, vi } from 'vitest';
|
|||||||
import * as Id from '../../src/core/id';
|
import * as Id from '../../src/core/id';
|
||||||
import { faker } from '@faker-js/faker';
|
import { faker } from '@faker-js/faker';
|
||||||
import { CommandModule, CommandType, commandModule } from '../../src';
|
import { CommandModule, CommandType, commandModule } from '../../src';
|
||||||
import { CommandTypeDiscordApi } from '../../src/core/id';
|
|
||||||
|
|
||||||
function createRandomCommandModules() {
|
function createRandomCommandModules() {
|
||||||
const randomCommandType = [
|
const randomCommandType = [
|
||||||
@@ -41,32 +40,8 @@ describe('id resolution', () => {
|
|||||||
const metadata = modules.map(createMetadata);
|
const metadata = modules.map(createMetadata);
|
||||||
metadata.forEach((meta, idx) => {
|
metadata.forEach((meta, idx) => {
|
||||||
const associatedModule = modules[idx];
|
const associatedModule = modules[idx];
|
||||||
const am = (appBitField & associatedModule.type) !== 0 ? 'A' : 'C';
|
const uid = Id.create(associatedModule.name!, associatedModule.type!);
|
||||||
let uid = 0;
|
expect(meta.id).toBe(uid);
|
||||||
if (
|
|
||||||
associatedModule.type === CommandType.Both ||
|
|
||||||
associatedModule.type === CommandType.Modal
|
|
||||||
) {
|
|
||||||
uid = 1;
|
|
||||||
} else {
|
|
||||||
uid = CommandTypeDiscordApi[Math.log2(associatedModule.type)];
|
|
||||||
}
|
|
||||||
expect(meta.id).toBe(associatedModule.name + '_' + am + uid);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('maps commands type to discord components or application commands', () => {
|
|
||||||
expect(CommandTypeDiscordApi[Math.log2(CommandType.Text)]).toBe(1);
|
|
||||||
|
|
||||||
expect(CommandTypeDiscordApi[1]).toBe(1);
|
|
||||||
expect(CommandTypeDiscordApi[Math.log2(CommandType.CtxUser)]).toBe(2);
|
|
||||||
expect(CommandTypeDiscordApi[Math.log2(CommandType.CtxMsg)]).toBe(3);
|
|
||||||
expect(CommandTypeDiscordApi[Math.log2(CommandType.Button)]).toBe(2);
|
|
||||||
expect(CommandTypeDiscordApi[Math.log2(CommandType.StringSelect)]).toBe(3);
|
|
||||||
expect(CommandTypeDiscordApi[Math.log2(CommandType.UserSelect)]).toBe(5);
|
|
||||||
expect(CommandTypeDiscordApi[Math.log2(CommandType.RoleSelect)]).toBe(6);
|
|
||||||
expect(CommandTypeDiscordApi[Math.log2(CommandType.MentionableSelect)]).toBe(7);
|
|
||||||
expect(CommandTypeDiscordApi[Math.log2(CommandType.ChannelSelect)]).toBe(8);
|
|
||||||
expect(CommandTypeDiscordApi[6]).toBe(1);
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -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