Commit ed1d0de8 authored by nanahira's avatar nanahira

first

parent 2fad8436
# 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
/decks
webpack.config.js
dist/*
build/*
/decks
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
/decks
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/
test:
extends: .build_base
script: npm run test
upload_to_minio:
stage: deploy
dependencies:
- build
tags:
- linux
script:
- aws s3 --endpoint=https://minio.mycard.moe:9000 sync --delete dist/full/ s3://nanahira/koishi-plugin/draw
only:
- master
deploy_npm:
stage: deploy
dependencies:
- build
tags:
- linux
script:
- apt update;apt -y install coreutils
- echo $NPMRC | base64 --decode > ~/.npmrc
- npm publish . --access public
only:
- master
/install-npm.sh
.git*
/data
/output
/config.yaml
.idea
.dockerignore
Dockerfile
/src
/dist/full
/coverage
/tests
/dist/tests
/dev
/dist/dev
/webpack.config.js
/.eslint*
.*ignore
.prettierrc*
/decks
{
"singleQuote": true,
"trailingComma": "all"
}
\ No newline at end of file
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.
# koishi-plugin-draw
# koishi-plugin-myplugin
Draws from deck.
\ No newline at end of file
抽卡插件,格式为 Dice! 的格式。
## 安装
### npm
```bash
npm install koishi-plugin-draw
```
### 直接安装
在 https://cdn02.moecube.com:444/nanahira/koishi-plugin/draw/index.js 下载即可。
## 配置
详见 `config.ts` 部分,或详见 Schema 描述配置。
## 使用
按照 Dice! 的使用习惯即可。
import { Context } from 'koishi';
export default class ExtrasInDev {
constructor(ctx: Context) {}
}
import { App } from 'koishi';
import TargetPlugin from '../src';
import ConsolePlugin from '@koishijs/plugin-console';
import SandboxPlugin from '@koishijs/plugin-sandbox';
import DatabasePlugin from '@koishijs/plugin-database-memory';
import CachePlugin from '@koishijs/plugin-cache-lru';
import ExtrasInDev from './extras';
const app = new App({
port: 14514,
host: 'localhost',
prefix: '.',
});
// Console and sandbox
app.plugin(SandboxPlugin);
app.plugin(ConsolePlugin, {
open: false,
});
// Some services
app.plugin(CachePlugin);
app.plugin(DatabasePlugin);
// Some extras
app.plugin(ExtrasInDev);
// Target plugin
app.plugin(TargetPlugin, {});
app.start();
#!/bin/bash
npm install --save \
source-map-support \
koishi-thirdeye
npm install --save-peer \
koishi@latest
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 \
raw-loader \
ts-loader \
webpack \
webpack-cli \
ws \
ts-node \
@koishijs/plugin-console \
@koishijs/plugin-sandbox \
@koishijs/plugin-database-memory \
@koishijs/plugin-cache-lru \
jest \
ts-jest \
@types/jest
This diff is collapsed.
{
"name": "koishi-plugin-draw",
"description": "Draws from deck, with decks of Dice's format.",
"version": "1.0.0",
"main": "dist/index.js",
"types": "dist/src/index.d.ts",
"scripts": {
"lint": "eslint --fix .",
"build": "webpack && env PACK_ALL=1 webpack",
"start": "ts-node ./dev",
"test": "jest --passWithNoTests"
},
"repository": {
"type": "git",
"url": "https://code.mycard.moe/3rdeye/koishi-plugin-draw.git"
},
"author": "Nanahira <nanahira@momobako.com>",
"license": "MIT",
"keywords": [
"Koishi.js",
"qqbot",
"cqhttp",
"onebot"
],
"bugs": {
"url": "https://code.mycard.moe/3rdeye/koishi-plugin-draw/issues"
},
"homepage": "https://code.mycard.moe/3rdeye/koishi-plugin-draw",
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "tests",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
},
"dependencies": {
"koishi-thirdeye": "^9.2.9",
"leven": "^3.1.0",
"load-json-file": "^6.2.0",
"lodash": "^4.17.21",
"source-map-support": "^0.5.21"
},
"peerDependencies": {
"koishi": "^4.4.1"
},
"devDependencies": {
"@koishijs/plugin-cache-lru": "^1.0.0-rc.0",
"@koishijs/plugin-console": "^3.2.3",
"@koishijs/plugin-database-memory": "^1.0.2",
"@koishijs/plugin-sandbox": "^1.0.2",
"@types/jest": "^27.4.1",
"@types/lodash": "^4.14.179",
"@types/node": "^17.0.21",
"@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": "^27.5.1",
"prettier": "^2.5.1",
"raw-loader": "^4.0.2",
"ts-jest": "^27.1.3",
"ts-loader": "^9.2.8",
"ts-node": "^10.7.0",
"typescript": "^4.6.2",
"webpack": "^5.70.0",
"webpack-cli": "^4.9.2",
"ws": "^8.5.0"
}
}
import 'source-map-support/register';
import { DefineSchema, RegisterSchema } from 'koishi-thirdeye';
import * as fs from 'fs';
import path from 'path';
import _ from 'lodash';
@RegisterSchema()
export class MyPluginConfig {
constructor(config: MyPluginConfigLike) {}
@DefineSchema({
type: String,
description: 'Location of deck directory.',
default: ['./decks'],
})
deckPaths: string[];
@DefineSchema({
description: 'Max depth of recurse entry parsing.',
default: 10,
})
maxDepth: number;
async loadFileList() {
return _.flatten(
await Promise.all(
this.deckPaths.map(async (deckPath) => {
const files = await fs.promises.readdir(deckPath);
return files
.filter((file) => file.endsWith('.json'))
.map((file) => path.join(deckPath, file));
}),
),
);
}
}
export type MyPluginConfigLike = Partial<MyPluginConfig>;
import 'source-map-support/register';
import { MyPluginConfig } from './config';
import {
DefinePlugin,
BasePlugin,
InjectLogger,
LifecycleEvents,
UseCommand,
CommandLocale,
PutArg,
PutCommonRenderer,
CRenderer,
PutUserName,
Renderer,
PutRenderer,
} from 'koishi-thirdeye';
import { Logger, Random } from 'koishi';
import path from 'path';
import loadJsonFile from 'load-json-file';
import _ from 'lodash';
import * as localeZh from './locales/zh';
import * as localeEn from './locales/en';
import leven from 'leven';
export * from './config';
type Decks = Record<string, string[]>;
@DefinePlugin({ name: 'myplugin', schema: MyPluginConfig })
export default class MyPlugin
extends BasePlugin<MyPluginConfig>
implements LifecycleEvents
{
@InjectLogger()
private logger: Logger;
deckFiles = new Map<string, string[]>();
decks: Decks = {};
async loadDeck(file: string) {
const filename = path.basename(file);
if (this.deckFiles.has(filename)) return;
try {
const content: Decks = await loadJsonFile(file);
const deckTitles = Object.keys(content);
this.deckFiles.set(filename, deckTitles);
for (const key of deckTitles) {
if (this.decks[key]) {
this.logger.warn(`Duplicate deck ${key} in ${file}`);
}
this.decks[key] = content[key];
}
} catch (e) {
this.logger.error(`Load deck file ${file} failed: ${e.message}`);
}
}
async loadDecks() {
this.deckFiles.clear();
this.decks = {};
const files = await this.config.loadFileList();
await Promise.all(files.map((file) => this.loadDeck(file)));
const deckCount = _.sumBy(
Array.from(this.deckFiles.values()),
(v) => v.length,
);
const deckFileCount = this.deckFiles.size;
this.logger.info(
`Loaded ${deckCount} decks from ${deckFileCount} deck files.`,
);
return { deckCount, deckFileCount };
}
parseDicePattern(pattern: string) {
if (pattern.match(/^\d+$/)) {
return parseInt(pattern);
}
const match = pattern.match(/^(\d*)d(\d+)$/);
if (!match) {
return 0;
}
const [, _count, _sides] = match;
const count = _count ? parseInt(_count) : 1;
const sides = parseInt(_sides);
return _.sum(_.range(count).map(() => Random.int(1, sides + 1)));
}
parseDice(dice: string) {
const patterns = dice.split('+');
return _.sumBy(patterns, (pattern) => this.parseDicePattern(pattern));
}
parseEntry(entry: string, depth = 1) {
return entry
.replace(/\[[d\d\+]+\]/g, (dicePattern) =>
this.parseDice(dicePattern.slice(1, -1)).toString(),
)
.replace(
/\{[^\}]+\}/g,
(refPattern) =>
this.drawFromDeck(refPattern.slice(1, -1), depth + 1) || refPattern,
);
}
drawFromDeck(name: string, depth = 1) {
if (depth > this.config.maxDepth) {
this.logger.warn(
`Max depth ${this.config.maxDepth} reached in deck ${name}.`,
);
return null;
}
const deck = this.decks[name];
if (!deck) {
return null;
}
const entry = Random.pick(deck);
return this.parseEntry(entry, depth);
}
async onConnect() {
await this.loadDecks();
}
@UseCommand('draw <name:text>', { checkArgCount: true })
@CommandLocale('zh', localeZh.commands.draw)
@CommandLocale('en', localeEn.commands.draw)
drawCommand(
@PutArg(0) name: string,
@PutUserName() user: string,
@PutCommonRenderer() renderer: CRenderer,
) {
const result = this.drawFromDeck(name);
if (!result) {
return renderer('.notFound');
}
return (
renderer('.result', {
user,
}) +
'\n' +
result
);
}
@UseCommand('draw.list')
@CommandLocale('zh', localeZh.commands.list)
@CommandLocale('en', localeEn.commands.list)
onListCommand(@PutRenderer('.fileInfo') renderer: Renderer) {
const entries = Array.from(this.deckFiles.entries()).map(
([file, titles]) => ({
file,
count: titles.length,
}),
);
return entries.map((entry) => renderer(entry)).join('\n');
}
@UseCommand('draw.help')
@CommandLocale('zh', localeZh.commands.help)
@CommandLocale('en', localeEn.commands.help)
onHelpCommand(@PutRenderer('.fileInfo') renderer: Renderer) {
const entries = Array.from(this.deckFiles.entries()).map(
([file, titles]) => ({
file,
count: titles.length,
titles,
}),
);
return entries
.map(
(entry) =>
renderer(entry) +
'\n' +
entry.titles.map((title) => `draw ${title}`).join('\n'),
)
.join('\n');
}
@UseCommand('draw.reload')
@CommandLocale('zh', localeZh.commands.reload)
@CommandLocale('en', localeEn.commands.reload)
async onReloadCommand(@PutRenderer('.result') renderer: Renderer) {
const result = await this.loadDecks();
return renderer(result);
}
@UseCommand('draw.search <word:text>', { checkArgCount: true })
@CommandLocale('zh', localeZh.commands.search)
@CommandLocale('en', localeEn.commands.search)
async onSearchCommand(
@PutArg(0) word: string,
@PutRenderer('.result') renderer: Renderer,
@PutRenderer('.notFound') notFoundRenderer: Renderer,
) {
const allDecks = _.flatten(Array.from(this.deckFiles.values())).filter(
(d) => word.includes(d),
);
if (!allDecks.length) {
return notFoundRenderer(word);
}
_.sortBy(allDecks, (deck) => leven(deck, word));
return `${renderer()}\n${allDecks.join('|')}`;
}
}
import { Dict } from 'koishi';
import { CommandLocaleDef } from 'koishi-thirdeye';
export const fileInfo = 'File: {file} Count: {count}';
export const commands: Dict<CommandLocaleDef> = {
draw: {
description: 'Draw from deck.',
messages: {
result: '{user} got:',
notFound: 'The specified deck is not found.',
},
},
list: {
description: 'Check deck file list.',
messages: {
fileInfo,
},
},
help: {
description: 'Check deck list.',
messages: {
fileInfo,
},
},
reload: {
description: 'Reload deck files.',
messages: {
result: 'Loaded {deckCount} decks from {deckFileCount} deck files.',
},
},
search: {
description: 'Search for deck',
messages: {
result: 'Result:',
notFound: 'Deck with keyword "{keyword}" not found.',
},
},
};
import { CommandLocaleDef } from 'koishi-thirdeye';
import { Dict } from 'koishi';
export const fileInfo = '文件名: {file} 数量: {count}';
export const commands: Dict<CommandLocaleDef> = {
draw: {
description: '进行牌堆抽取',
messages: {
result: '{user} 抽到了这个:',
notFound: '找不到指定牌堆。',
},
},
list: {
description: '查看载入了哪些牌堆文件',
messages: {
fileInfo,
},
},
help: {
description: '查看有哪些牌堆名可以使用',
messages: {
fileInfo,
},
},
reload: {
description: '重新载入牌堆数据',
messages: {
result: '从 {deckFileCount} 个牌堆文件中重新载入了 {deckCount} 个牌堆。',
},
},
search: {
description: '搜索相关牌堆',
messages: {
result: '搜索结果:',
notFound: '没有找到关键词 [ {word} ]',
},
},
};
import { App } from 'koishi';
import TargetPlugin from '../src';
describe('Test of plugin.', () => {
let app: App;
beforeEach(async () => {
app = new App();
// app.plugin(TargetPlugin);
await app.start();
});
it('should pass', () => {
expect(true).toBe(true);
});
});
{
"compilerOptions": {
"outDir": "dist",
"module": "commonjs",
"target": "es2021",
"esModuleInterop": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"declaration": true,
"sourceMap": true,
"skipLibCheck": true
},
"compileOnSave": true,
"allowJs": true,
"include": [
"*.ts",
"src/**/*.ts",
"tests/**/*.ts",
"dev/**/*.ts"
]
}
const path = require('path');
const packgeInfo = require('./package.json');
function externalsFromDep() {
return Object.fromEntries(
[
...Object.keys(packgeInfo.dependencies || {}),
...Object.keys(packgeInfo.peerDependencies || {}),
]
.filter((dep) => dep !== 'source-map-support')
.map((dep) => [dep, dep]),
);
}
const packAll = !!process.env.PACK_ALL;
module.exports = {
entry: './src/index.ts',
mode: 'production',
target: 'node',
devtool: 'source-map',
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
{ test: /\.mustache$/, use: 'raw-loader' },
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
output: {
filename: 'index.js',
library: {
type: 'commonjs',
},
path: path.resolve(__dirname, packAll ? 'dist/full' : 'dist'),
},
externals: {
koishi: 'koishi',
...(packAll ? {} : externalsFromDep()),
},
};
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