Commit 6da18949 authored by nanahira's avatar nanahira

first

parent 5b71cccd
Pipeline #14648 failed with stages
in 1 minute and 56 seconds
# compiled output
/dist
/node_modules
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# OS
.DS_Store
# Tests
/coverage
/.nyc_output
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
/data
/output
/config.yaml
.git*
Dockerfile
.dockerignore
/tests
webpack.config.js
dist/*
build/*
*.js
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
],
root: true,
env: {
node: true,
jest: true,
},
ignorePatterns: ['.eslintrc.js'],
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-explicit-any': 'off',
},
};
# compiled output
/dist
/node_modules
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# OS
.DS_Store
# Tests
/coverage
/.nyc_output
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
/data
/output
/config.yaml
stages:
- build
- combine
- deploy
variables:
GIT_DEPTH: "1"
CONTAINER_TEST_IMAGE: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG
CONTAINER_TEST_ARM_IMAGE: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG-arm
CONTAINER_TEST_X86_IMAGE: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG-x86
CONTAINER_RELEASE_IMAGE: $CI_REGISTRY_IMAGE:latest
before_script:
- docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
build-x86:
stage: build
tags:
- docker
script:
- TARGET_IMAGE=$CONTAINER_TEST_X86_IMAGE
- docker build --pull -t $TARGET_IMAGE .
- docker push $TARGET_IMAGE
build-arm:
stage: build
tags:
- docker-arm
script:
- TARGET_IMAGE=$CONTAINER_TEST_ARM_IMAGE
- docker build --pull -t $TARGET_IMAGE .
- docker push $TARGET_IMAGE
combine:
stage: combine
tags:
- docker
script:
- TARGET_IMAGE=$CONTAINER_TEST_IMAGE
- SOURCE_IMAGE_2=$CONTAINER_TEST_ARM_IMAGE
- SOURCE_IMAGE_1=$CONTAINER_TEST_X86_IMAGE
- docker pull $SOURCE_IMAGE_1
- docker pull $SOURCE_IMAGE_2
- docker manifest create $TARGET_IMAGE --amend $SOURCE_IMAGE_1 --amend
$SOURCE_IMAGE_2
- docker manifest push $TARGET_IMAGE
deploy_latest:
stage: deploy
tags:
- docker
script:
- TARGET_IMAGE=$CONTAINER_RELEASE_IMAGE
- SOURCE_IMAGE=$CONTAINER_TEST_IMAGE
- docker pull $SOURCE_IMAGE
- docker tag $SOURCE_IMAGE $TARGET_IMAGE
- docker push $TARGET_IMAGE
only:
- master
deploy_tag:
stage: deploy
tags:
- docker
script:
- TARGET_IMAGE=$CI_REGISTRY_IMAGE:$CI_COMMIT_TAG
- SOURCE_IMAGE=$CONTAINER_TEST_IMAGE
- docker pull $SOURCE_IMAGE
- docker tag $SOURCE_IMAGE $TARGET_IMAGE
- docker push $TARGET_IMAGE
only:
- tags
stages:
- install
- build
- deploy
variables:
GIT_DEPTH: "1"
npm_ci:
stage: install
tags:
- linux
script:
- npm ci
artifacts:
paths:
- node_modules
.build_base:
stage: build
tags:
- linux
dependencies:
- npm_ci
build:
extends: .build_base
script: npm run build
artifacts:
paths:
- dist/
upload_to_minio:
stage: deploy
dependencies:
- build
tags:
- linux
script:
- aws s3 --endpoint=https://minio.momobako.com:9000 sync --delete dist/ s3://nanahira/path
only:
- master
stages:
- install
- build
- deploy
variables:
GIT_DEPTH: "1"
npm_ci:
stage: install
tags:
- linux
script:
- npm ci
artifacts:
paths:
- node_modules
.build_base:
stage: build
tags:
- linux
dependencies:
- npm_ci
build:
extends:
- .build_base
script:
- npm run build
artifacts:
paths:
- dist/
unit-test:
extends:
- .build_base
script:
- npm run test
deploy_npm:
stage: deploy
dependencies:
- build
tags:
- linux
script:
- apt update;apt -y install coreutils
- echo $NPMRC | base64 --decode > ~/.npmrc
- npm publish . || true
only:
- master
/install-npm.sh
.git*
/data
/output
/config.yaml
.idea
.dockerignore
Dockerfile
/src
/coverage
/tests
/dist/tests
{
"singleQuote": true,
"trailingComma": "all"
}
\ No newline at end of file
FROM node:lts-bullseye-slim as base
LABEL Author="Nanahira <nanahira@momobako.com>"
RUN apt update && apt -y install python3 build-essential && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* /var/log/*
WORKDIR /usr/src/app
COPY ./package*.json ./
FROM base as builder
RUN npm ci && npm cache clean --force
COPY . ./
RUN npm run build
FROM base
ENV NODE_ENV production
RUN npm ci && npm cache clean --force
COPY --from=builder /usr/src/app/dist ./dist
CMD [ "npm", "start" ]
The MIT License (MIT)
Copyright (c) 2021 Nanahira
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
export * from './src/registrar';
export * from './src/decorators';
export * from './src/utility/select-context';
export * from 'cordis-decorators';
#!/bin/bash
npm install --save-dev \
@types/node \
typescript \
'@typescript-eslint/eslint-plugin@^4.28.2' \
'@typescript-eslint/parser@^4.28.2 '\
'eslint@^7.30.0' \
'eslint-config-prettier@^8.3.0' \
'eslint-plugin-prettier@^3.4.0' \
prettier \
jest \
@types/jest \
ts-jest \
rimraf
This source diff could not be displayed because it is too large. You can view the blob instead.
{
"name": "satori-decorators",
"description": "[Satori](https://github.com/satorijs/satori) aspect of [cordis-decorators](https://code.mycard.moe/3rdeye/cordis-decorators)",
"version": "1.0.0",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"lint": "eslint --fix .",
"build": "rimraf dist && tsc",
"test": "jest --passWithNoTests",
"start": "node dist/index.js"
},
"repository": {
"type": "git",
"url": "https://code.mycard.moe/3rdeye/satori-decorators.git"
},
"author": "Nanahira <nanahira@momobako.com>",
"license": "MIT",
"keywords": [],
"bugs": {
"url": "https://code.mycard.moe/3rdeye/satori-decorators/issues"
},
"homepage": "https://code.mycard.moe/3rdeye/satori-decorators",
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "tests",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
},
"devDependencies": {
"@types/jest": "^28.1.6",
"@types/lodash": "^4.14.182",
"@types/node": "^18.0.6",
"@typescript-eslint/eslint-plugin": "^4.33.0",
"@typescript-eslint/parser": "^4.33.0",
"eslint": "^7.32.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-prettier": "^3.4.1",
"jest": "^28.1.3",
"prettier": "^2.7.1",
"rimraf": "^3.0.2",
"ts-jest": "^28.0.7",
"typescript": "^4.7.4"
},
"peerDependencies": {
"@satorijs/satori": "^1.0.3"
},
"dependencies": {
"cordis-decorators": "^1.0.6",
"lodash": "^4.17.21"
}
}
import { defaultRegistrarS } from './registrar';
export const {
OnAnywhere,
OnNowhere,
OnUser,
OnSelf,
OnGuild,
OnChannel,
OnPlatform,
OnPrivate,
OnSelection,
} = defaultRegistrarS.selectorDecorators();
export * from './map-plugin';
export * from './merge-plugin';
export * from './multi-plugin';
import {
MappingPluginBase,
MapPluginToConfig,
MapPluginToConfigWithSelection,
} from './mapping-base';
import {
ClassType,
CreatePluginFactory,
getPluginSchema,
PluginRegistrar,
SchemaProperty,
} from 'cordis-decorators';
import PluginClass = PluginRegistrar.PluginClass;
import { Context, Dict } from '@satorijs/satori';
function MappedConfig<
Ctx extends Context,
M extends Dict<PluginClass<Context>>,
>(dict: M): ClassType<MapPluginToConfigWithSelection<Ctx, M>> {
const PropertySchema = class SpecificPropertySchema {} as ClassType<
MapPluginToConfigWithSelection<Ctx, M>
>;
for (const [key, plugin] of Object.entries(dict)) {
SchemaProperty({
type: getPluginSchema(plugin),
})(PropertySchema.prototype, key);
}
return PropertySchema;
}
export function MapPlugin<
Ctx extends Context,
M extends Dict<PluginClass<Ctx>>,
OuterConfig,
>(dict: M, outerConfig?: ClassType<OuterConfig>) {
const basePlugin = class SpecificMapPlugin extends MappingPluginBase<
Ctx,
M,
MapPluginToConfig<Ctx, M>,
Partial<MapPluginToConfigWithSelection<Ctx, M>>
> {
_getDict() {
return dict;
}
_getPluginConfig(key: keyof M): any {
return this.config[key];
}
};
const schema = MappedConfig(dict);
const factory = CreatePluginFactory(basePlugin, schema);
return factory(outerConfig);
}
import {
BasePlugin,
PartialDeep,
Apply,
PluginRegistrar,
} from 'cordis-decorators';
import { selectContext, Selection } from '../utility/select-context';
import PluginClass = PluginRegistrar.PluginClass;
import { Context, Dict } from '@satorijs/satori';
import { defaultRegistrarS } from '../registrar';
import { ClonePlugin } from '../utility/clone-plugin';
export type ClassPluginConfig<
Ctx extends Context,
P extends PluginClass<Ctx>,
> = P extends PluginClass<Ctx, infer C> ? C : never;
export type ExactClassPluginConfig<
Ctx extends Context,
P extends PluginClass<Ctx>,
> = P extends PluginClass<Ctx, any, { config: infer IC }>
? IC
: ClassPluginConfig<Ctx, P>;
export type MapPluginToConfig<
Ctx extends Context,
M extends Dict<PluginClass<Ctx>>,
> = {
[K in keyof M]: ClassPluginConfig<Ctx, M[K]>;
};
export type MapPluginToConfigWithSelection<
Ctx extends Context,
M extends Dict<PluginClass<Ctx>>,
> = {
[K in keyof M]: ClassPluginConfig<Ctx, M[K]> & Selection;
};
export class MappingPluginBase<
Ctx extends Context,
M extends Dict<PluginClass<Ctx>>,
C,
PC = PartialDeep<C>,
> extends BasePlugin<Ctx, C, PC> {
_getDict(): M {
throw new Error('not implemented');
}
_instanceMap = new Map<string, PluginClass<Ctx>>();
getInstance<K extends keyof M>(key: K): M[K] {
return this._instanceMap?.get(key as string) as M[K];
}
_getPluginConfig(key: keyof M): any {
return {};
}
@Apply()
_registerInstances() {
const dict = this._getDict();
for (const [key, plugin] of Object.entries(dict)) {
const config = this._getPluginConfig(key);
if (config == null) continue;
const ctx =
typeof config === 'object' ? selectContext(this.ctx, config) : this.ctx;
const clonedPlugin = ClonePlugin(
plugin,
`${this.constructor.name}_${plugin.name}_dict_${key}`,
(o) => this._instanceMap.set(key, o),
);
ctx.plugin(clonedPlugin, config);
}
}
@defaultRegistrarS.methodDecorators().UseEvent('dispose')
_onThingsDispose() {
delete this._instanceMap;
}
}
import { MappingPluginBase, MapPluginToConfig } from './mapping-base';
import {
ClassType,
CreatePluginFactory,
getPluginSchema,
Mixin,
PluginRegistrar,
} from 'cordis-decorators';
import PluginClass = PluginRegistrar.PluginClass;
import { Context, Dict } from '@satorijs/satori';
import _ from 'lodash';
type UnionToIntersection<T> = (T extends any ? (x: T) => any : never) extends (
x: infer R,
) => any
? R
: never;
type MergePluginConfig<
Ctx extends Context,
M extends Dict<PluginClass<Ctx>>,
> = UnionToIntersection<MapPluginToConfig<Ctx, M>[keyof M]>;
export function MergePlugin<
Ctx extends Context,
M extends Dict<PluginClass<Ctx>>,
OuterConfig,
>(dict: M, outerConfig?: ClassType<OuterConfig>) {
const basePlugin = class SpecificMapPlugin extends MappingPluginBase<
Ctx,
M,
MergePluginConfig<Ctx, M>,
MergePluginConfig<Ctx, M>
> {
_getDict() {
return dict;
}
_getPluginConfig(key: keyof M): any {
return this.config;
}
};
const schemas = _.compact(
Object.values(dict).map((plugin) => getPluginSchema(plugin)),
);
const factory = CreatePluginFactory(basePlugin, Mixin(...schemas));
return factory(outerConfig);
}
import {
Apply,
BasePlugin,
ClassType,
CreatePluginFactory,
PluginRegistrar,
SchemaClass,
SchemaProperty,
TypeFromClass,
UsingService,
} from 'cordis-decorators';
import { selectContext, Selection } from '../utility/select-context';
import { ClonePlugin } from '../utility/clone-plugin';
import PluginClass = PluginRegistrar.PluginClass;
import { defaultRegistrarS } from '../registrar';
import { Context, Schema } from '@satorijs/satori';
import { ClassPluginConfig } from './mapping-base';
export interface Instances<T> {
instances: T[];
}
export function ToInstancesConfig<Inner extends new (...args: any[]) => any>(
instanceConfig: Inner,
): new () => Instances<TypeFromClass<Inner>> {
const instanceConfigClass = class InstancesConfig {
instances: TypeFromClass<Inner>[];
};
SchemaProperty({
type: SchemaClass(instanceConfig),
default: [],
array: true,
})(instanceConfigClass.prototype, 'instances');
return instanceConfigClass;
}
export class MultiInstancePluginFramework<
Ctx extends Context,
InnerPlugin extends PluginClass<Ctx>,
> extends BasePlugin<
Ctx,
Instances<ClassPluginConfig<Ctx, InnerPlugin>>,
Instances<ClassPluginConfig<Ctx, InnerPlugin> & Selection>
> {
instances: TypeFromClass<InnerPlugin>[] = [];
_getInnerPlugin(): InnerPlugin {
throw new Error(`Not implemented`);
}
@Apply()
_registerInstances() {
const innerPlugin = this._getInnerPlugin();
for (let i = 0; i < this.config.instances.length; i++) {
const clonedInnerPlugin = ClonePlugin(
innerPlugin,
`${this.constructor.name}_${innerPlugin.name}_instance_${i}`,
(instance) => this.instances.push(instance),
);
const instanceConfig = this.config.instances[i];
const instanceContext =
typeof instanceConfig === 'object'
? selectContext(this.ctx, instanceConfig)
: this.ctx;
instanceContext.plugin(clonedInnerPlugin, instanceConfig);
}
}
@defaultRegistrarS.methodDecorators().UseEvent('dispose')
_onThingsDispose() {
delete this.instances;
}
}
export function MultiInstancePlugin<
Ctx extends Context,
InnerPlugin extends PluginClass<Ctx>,
OuterConfig,
>(innerPlugin: InnerPlugin, outerConfig?: ClassType<OuterConfig>) {
const basePlugin = class SpecificMultiInstancePlugin extends MultiInstancePluginFramework<
Ctx,
InnerPlugin
> {
_getInnerPlugin() {
return innerPlugin;
}
};
const schema = ToInstancesConfig(
(innerPlugin['Config'] ||
innerPlugin['schema'] ||
Schema.any()) as ClassType<ClassPluginConfig<Ctx, InnerPlugin>>,
);
const factory = CreatePluginFactory(basePlugin, schema);
const plugin = factory(outerConfig);
if (innerPlugin['using']) {
UsingService(...(innerPlugin['using'] as string[]))(plugin);
}
return plugin;
}
import { Context } from '@satorijs/satori';
import { Registrar } from 'cordis-decorators';
import { selectContext, Selection } from './utility/select-context';
export class SatoriRegistrar<Ctx extends Context> extends Registrar<Ctx> {
selectorDecorators() {
return {
OnAnywhere: () => this.decorateTransformer((ctx, r) => ctx.any()),
OnNowhere: () => this.decorateTransformer((ctx, r) => ctx.never()),
OnUser: (...values: string[]) =>
this.decorateTransformer((ctx, r) => ctx.user(...r(values))),
OnSelf: (...values: string[]) =>
this.decorateTransformer((ctx, r) => ctx.self(...r(values))),
OnGuild: (...values: string[]) =>
this.decorateTransformer((ctx, r) => ctx.guild(...r(values))),
OnChannel: (...values: string[]) =>
this.decorateTransformer((ctx, r) => ctx.channel(...r(values))),
OnPlatform: (...values: string[]) =>
this.decorateTransformer((ctx, r) => ctx.platform(...r(values))),
OnPrivate: (...values: string[]) =>
this.decorateTransformer((ctx, r) => ctx.private(...r(values))),
OnSelection: (selection: Selection) =>
this.decorateTransformer((ctx, r) => selectContext(ctx, r(selection))),
};
}
scopeDecorators() {
return {
...super.scopeDecorators(),
...this.selectorDecorators(),
};
}
}
export const defaultRegistrarS = new SatoriRegistrar(Context);
import { TypeFromClass } from 'cordis-decorators';
export function ClonePlugin<P extends { new (...args: any[]): any }>(
target: P,
name: string,
callback?: (instance: TypeFromClass<P>) => void,
): P {
const clonedPlugin = class extends target {
constructor(...args: any[]) {
super(...args);
if (callback) {
callback(this as any);
}
}
};
for (const property of ['Config', 'schema', 'using']) {
Object.defineProperty(clonedPlugin, property, {
enumerable: true,
configurable: true,
writable: true,
value: target[property],
});
}
Object.defineProperty(clonedPlugin, 'name', {
enumerable: true,
configurable: true,
writable: true,
value: name,
});
return clonedPlugin;
}
import { Context, makeArray, MaybeArray } from '@satorijs/satori';
const selectors = [
'user',
'guild',
'channel',
'self',
'private',
'platform',
] as const;
export type SelectorType = typeof selectors[number];
export type SelectorValue = boolean | MaybeArray<string | number>;
export type BaseSelection = { [K in SelectorType]?: SelectorValue };
export interface Selection extends BaseSelection {
and?: Selection[];
or?: Selection[];
not?: Selection;
}
export function selectContext<Ctx extends Context>(
root: Ctx,
options: Selection,
) {
let ctx = root;
// basic selectors
for (const type of selectors) {
const value = options[type];
if (value === true) {
ctx = ctx[type]();
} else if (value === false) {
ctx = ctx.exclude(ctx[type]());
} else if (value !== undefined) {
// we turn everything into string
ctx = ctx[type](...makeArray(value).map((item) => '' + item));
}
}
// intersect
if (options.and) {
for (const selection of options.and) {
ctx = ctx.intersect(selectContext<Ctx>(root, selection));
}
}
// union
if (options.or) {
let ctx2: Context = ctx.never();
for (const selection of options.or) {
ctx2 = ctx2.union(selectContext<Ctx>(root, selection));
}
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
ctx = ctx.intersect(ctx2);
}
// exclude
if (options.not) {
ctx = ctx.exclude(selectContext<Ctx>(root, options.not));
}
return ctx;
}
import { Context } from '@satorijs/satori';
import { MapPlugin, MergePlugin } from '../src/plugin-operators';
import { SchemaProperty } from 'cordis-decorators';
import { DefinePlugin, StarterPlugin, UseEvent } from './utility/decorators';
declare module 'cordis' {
interface Events {
dressColor(): string;
skirtSize(): string;
wearingStrip(): string;
}
}
class DressConfig {
@SchemaProperty()
color: string;
}
@DefinePlugin()
class DressPlugin extends StarterPlugin(DressConfig) {
@UseEvent('dressColor')
dressColor() {
return this.config.color;
}
}
class SkirtConfig {
@SchemaProperty({ default: 'S' })
size: string;
}
@DefinePlugin()
class SkirtPlugin extends StarterPlugin(SkirtConfig) {
@UseEvent('skirtSize')
skirtSize() {
return this.config.size;
}
}
class WearingConfig {
@SchemaProperty()
strip: string;
}
@DefinePlugin()
class WearingPlugin extends MapPlugin(
{ dress: DressPlugin, skirt: SkirtPlugin },
WearingConfig,
) {
@UseEvent('wearingStrip')
wearingStrip() {
return this.config.strip;
}
}
@DefinePlugin()
class MergedWearingPlugin extends MergePlugin(
{ dress: DressPlugin, skirt: SkirtPlugin },
WearingConfig,
) {
@UseEvent('wearingStrip')
wearingStrip() {
return this.config.strip;
}
}
describe('register map plugin instance', () => {
it('should work on each level', async () => {
const app = new Context();
app.plugin(WearingPlugin, {
dress: { color: 'red' },
skirt: { size: 'XL' },
strip: 'pink',
});
await app.start();
expect(app.bail('dressColor')).toBe('red');
expect(app.bail('skirtSize')).toBe('XL');
expect(app.bail('wearingStrip')).toBe('pink');
});
it('should partial register', async () => {
const app = new Context();
app.plugin(WearingPlugin, {
dress: { color: 'red' },
strip: 'pink',
});
await app.start();
expect(app.bail('dressColor')).toBe('red');
expect(app.bail('wearingStrip')).toBe('pink');
expect(app.bail('skirtSize')).toBe('S');
});
it('should work on merge plugin', async () => {
const app = new Context();
app.plugin(MergedWearingPlugin, {
color: 'red',
size: 'XL',
strip: 'pink',
});
await app.start();
expect(app.bail('dressColor')).toBe('red');
expect(app.bail('skirtSize')).toBe('XL');
expect(app.bail('wearingStrip')).toBe('pink');
});
});
import { RegisterSchema, SchemaProperty } from 'cordis-decorators';
import { DefinePlugin, StarterPlugin, UseEvent } from './utility/decorators';
import { MultiInstancePlugin } from '../src/plugin-operators';
import { Context, Schema } from '@satorijs/satori';
declare module 'cordis' {
interface Events<C> {
message1: string;
message2: string;
message3: string;
}
}
class MessageConfig {
@SchemaProperty()
msg: string;
getMsg() {
return this.msg;
}
}
@RegisterSchema()
class InnerMessageConfig extends MessageConfig {}
@RegisterSchema()
class OuterMessageConfig extends MessageConfig {}
@DefinePlugin({ schema: InnerMessageConfig })
class Inner extends StarterPlugin(InnerMessageConfig) {
@UseEvent('message1')
onMessage() {
return this.config.getMsg();
}
}
@DefinePlugin({ schema: Schema.object({ msg: Schema.string() }) })
class Inner2 extends StarterPlugin(InnerMessageConfig) {
@UseEvent('message1')
onMessage() {
return this.config.msg;
}
}
@DefinePlugin()
class Outer extends MultiInstancePlugin(Inner, OuterMessageConfig) {
@UseEvent('message2')
onMessage() {
return this.config.getMsg();
}
@UseEvent('message3')
onInnerMessage() {
return this.instances[0].config.getMsg();
}
}
@DefinePlugin()
class Outer2 extends MultiInstancePlugin(Inner2, OuterMessageConfig) {
@UseEvent('message2')
onMessage() {
return this.config.getMsg();
}
@UseEvent('message3')
onInnerMessage() {
return this.instances[0].config.msg;
}
}
describe('register multi plugin instance', () => {
it('should work on schemastery-gen', async () => {
const app = new Context();
app.plugin(Outer, { msg: 'hello', instances: [{ msg: 'world' }] });
await app.start();
expect(app.bail('message1')).toBe('world');
expect(app.bail('message2')).toBe('hello');
expect(app.bail('message3')).toBe('world');
});
it('should work on common schemastery', async () => {
const app = new Context();
app.plugin(Outer2, { msg: 'hello', instances: [{ msg: 'world' }] });
await app.start();
expect(app.bail('message1')).toBe('world');
expect(app.bail('message2')).toBe('hello');
expect(app.bail('message3')).toBe('world');
});
});
import { OnGuild, OnPlatform } from '../src/decorators';
import { Context, Session } from '@satorijs/satori';
import { defaultRegistrarS } from '../src/registrar';
@OnPlatform('discord')
class MyClass {
@OnGuild('1111111111')
foo() {}
}
describe('Scope', () => {
let app: Context;
beforeEach(async () => {
app = new Context();
await app.start();
});
it('should check scope', () => {
const correctSession = {
guildId: '1111111111',
platform: 'discord',
} as Session;
const wrongSession1 = {
guildId: '2222222222',
platform: 'discord',
} as Session;
const wrongSession2 = {
guildId: '1111111111',
platform: 'telegram',
} as Session;
const registrar = defaultRegistrarS.aspect(new MyClass());
const globalCtx = registrar.getScopeContext(app);
const methodCtx = registrar.getScopeContext(app, 'foo', {}, true);
expect(globalCtx.filter(correctSession)).toBe(true);
expect(globalCtx.filter(wrongSession1)).toBe(true);
expect(globalCtx.filter(wrongSession2)).toBe(false);
expect(methodCtx.filter(correctSession)).toBe(true);
expect(methodCtx.filter(wrongSession1)).toBe(false);
expect(methodCtx.filter(wrongSession2)).toBe(false);
});
});
import { defaultRegistrarS } from '../../src/registrar';
export const { DefinePlugin } = defaultRegistrarS.pluginDecorators();
export const { UseEvent } = defaultRegistrarS.methodDecorators();
export const StarterPlugin = defaultRegistrarS.starterPluginFactory();
{
"compilerOptions": {
"outDir": "dist",
"module": "commonjs",
"target": "es2021",
"esModuleInterop": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"declaration": true,
"sourceMap": true
},
"compileOnSave": true,
"allowJs": true,
"include": [
"*.ts",
"src/**/*.ts",
"test/**/*.ts",
"tests/**/*.ts"
]
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment