Compare commits
116 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| cf9508ba31 | |||
| e0f4c5e77d | |||
| e4a87095ce | |||
| 950575edbc | |||
| c2a71b9a7a | |||
| 068ac7b76e | |||
| 05cbd85828 | |||
| ea28d20aa1 | |||
| d3f33f50e0 | |||
| d004ba17e6 | |||
| 7a25dd8b3b | |||
| dedc8393da | |||
| 8d344492d9 | |||
| 81a76af7be | |||
| b458da7a6e | |||
| 45cb6fa667 | |||
| 9c4543df30 | |||
| 512bdb22c5 | |||
| f6e39c131c | |||
| 73d4dad7f6 | |||
| de4a22362f | |||
| 5fde2e5554 | |||
| 6a6765e5c3 | |||
| 4a1f25ee6a | |||
| 5999567ee3 | |||
| fad4e27a7f | |||
| b477938e4f | |||
| 7cbd91826a | |||
| 6797761a2f | |||
| be114e6d1b | |||
| 3e40934339 | |||
| 3e6c7b2d8c | |||
| 6c0bb75561 | |||
| a47896a97f | |||
| 1d97bbc9ce | |||
| b1f1f9837e | |||
| 99dee28fd4 | |||
| c7f66d8252 | |||
| 8c4f266356 | |||
| 39e899211b | |||
| da72a0dac6 | |||
| 9984787202 | |||
| 4493d35786 | |||
| e1aad59eeb | |||
| 849393492f | |||
| 1ff33702d8 | |||
| e68005fd6f | |||
| 17269b50f4 | |||
| 363d0c164a | |||
| 13a0b62103 | |||
| cb4e152800 | |||
| fb83acfcc8 | |||
| 7263fbb437 | |||
| 23868a58b9 | |||
| effa7f70ec | |||
| eef0baa740 | |||
| 4d0c0122c7 | |||
| aa581afbe5 | |||
| 1425c473fd | |||
| 53e4f6c658 | |||
| 73db4a9169 | |||
| a2efd878db | |||
| 4e6cda0545 | |||
| 859a3a9171 | |||
| 96481032c5 | |||
| f950c3dae8 | |||
| 9248294cb3 | |||
| 53873d7b63 | |||
| be59ae480b | |||
| 9fa3ed704a | |||
| a76858d626 | |||
| 55a6b33110 | |||
| b87b94aade | |||
| 4110ed2c20 | |||
| 3cbc101eff | |||
| 221b821085 | |||
| 7331cfaa55 | |||
| 40d020ef67 | |||
| eea2a225e8 | |||
| 48f7f0fdbb | |||
| 99ed76f9bb | |||
| 7f21fa67ee | |||
| 8584709828 | |||
| d1f58e7482 | |||
| 1bd35aef6d | |||
| fdf1088564 | |||
| 7bb4d1f6a3 | |||
| b8c3d0d19d | |||
| a616a07553 | |||
| 781524f83e | |||
| c7a812c003 | |||
| 325f2c8cf9 | |||
| 562e2d0017 | |||
| b7871e8d33 | |||
| 060cffd8e7 | |||
| 4b1fb07cc9 | |||
| 0931d69188 | |||
| 7d33368ebd | |||
| c95fc5fcff | |||
| a7479f60c8 | |||
| ac75356778 | |||
| 7f32382dbc | |||
| b3c2def36d | |||
| 1ea93dfb9f | |||
| e5ffa70ed9 | |||
| 2a60b36e23 | |||
| c4c2c0ab0f | |||
| bf5628a646 | |||
| 13e9f0a5af | |||
| cdd5f2d250 | |||
| dfd7182008 | |||
| 533859808f | |||
| 15cea1dfc8 | |||
| dfa43d58f0 | |||
| 2bf239d8ea | |||
| cbe87cc378 |
2
.gitignore
vendored
2
.gitignore
vendored
@@ -2,3 +2,5 @@ node_modules
|
||||
dist
|
||||
package-lock.json
|
||||
yarn.lock
|
||||
packages/nashorn/docs
|
||||
!packages/types/dist
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
src
|
||||
test
|
||||
typings
|
||||
bundled
|
||||
@@ -19,4 +18,5 @@ wallaby.js
|
||||
.travis.yml
|
||||
.gitignore
|
||||
.vscode
|
||||
.theia
|
||||
type_definitions
|
||||
29
README.MD
Normal file
29
README.MD
Normal file
@@ -0,0 +1,29 @@
|
||||
# MiaoScript implement
|
||||
|
||||
## MiaoScript JS 实现
|
||||
|
||||
项目 由 TypeScript 进行编写 然后编译至 `es5` 用于兼容 Java8 的 `Nashorn`
|
||||
|
||||
### Project Path
|
||||
|
||||
```txt
|
||||
└─packages
|
||||
├─api 全平台兼容的接口
|
||||
├─core 核心代码 用于引导加载
|
||||
├─common 公共类库代码 例如 http reflect 模块
|
||||
├─compile 实时编译模块 自动编译TS文件为js
|
||||
├─container IOC容器 用于注入具体实现
|
||||
├─nashorn Nashorn 的类型定义
|
||||
├─ployfill Java Nashorn的补丁
|
||||
├─bungee BungeeCordAPI内部实现
|
||||
├─bukkit BukkitAPI内部实现
|
||||
├─sponge SpongeAPI内部实现
|
||||
├─plugin 插件管理器
|
||||
├─manager 插件管理中心后端服务
|
||||
├─types Java在TypeScript的类型定义文件
|
||||
├─websocket Netty的WebSocket的MiaoScript实现(兼容socket.io)
|
||||
└─plugins 这里当然是插件啦
|
||||
├─bungee 只兼容BungeeCord的插件
|
||||
├─bukkit 只兼容Bukkit的插件
|
||||
└─sponge 只兼容Sponge的插件
|
||||
```
|
||||
62
cli.sh
Executable file
62
cli.sh
Executable file
@@ -0,0 +1,62 @@
|
||||
#!/bin/bash
|
||||
SHELL_PREFIX="[FAAS-CLI]"
|
||||
# Shell Base Script
|
||||
set -e
|
||||
|
||||
c_red="\033[38;5;1m"
|
||||
c_blue="\033[38;5;4m"
|
||||
c_green="\033[38;5;2m"
|
||||
c_reset="\033[0m"
|
||||
c_yellow="\033[38;5;3m"
|
||||
|
||||
c_prefix="${c_blue}${SHELL_PREFIX}>>${c_reset}"
|
||||
|
||||
dateStr() {
|
||||
echo -e "[$(date '+%H:%M:%S')]"
|
||||
}
|
||||
|
||||
info() {
|
||||
echo -e "${c_prefix}$(dateStr) ${*}"
|
||||
}
|
||||
|
||||
warn() {
|
||||
echo -e "${c_prefix}$(dateStr) ${c_yellow}${*}${c_reset}"
|
||||
}
|
||||
|
||||
error() {
|
||||
echo -e "${c_prefix}$(dateStr) ${c_red}${*}${c_reset}"
|
||||
}
|
||||
#====================
|
||||
cd $(dirname $0)
|
||||
|
||||
# User Input Variable
|
||||
action=
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
-a)
|
||||
action="$2"
|
||||
shift
|
||||
;;
|
||||
-*)
|
||||
echo "Illegal option $1"
|
||||
;;
|
||||
esac
|
||||
shift $(( $# > 0 ? 1 : 0 ))
|
||||
done
|
||||
|
||||
case "${action}" in
|
||||
undo)
|
||||
hash=$(git log -n 1 --format=format:%H)
|
||||
tag=$(git tag -l --contains=${hash})
|
||||
if [[ -z "${tag}" ]]; then
|
||||
error "last commit not have tag exit..."
|
||||
exit 0
|
||||
fi
|
||||
git reset HEAD^
|
||||
git tag -d ${tag}
|
||||
git push origin master -f
|
||||
git push origin :${tag}
|
||||
;;
|
||||
esac
|
||||
|
||||
391
doc/MCBBS.MD
Normal file
391
doc/MCBBS.MD
Normal file
@@ -0,0 +1,391 @@
|
||||
- 构建状态 [](https://ci.yumc.pw/job/Minecraft/job/MiaoScript/)
|
||||
- 当前版本 
|
||||
- 下载地址 [](http://w.yumc.pw/free.html#MiaoScript-download)
|
||||
- 为了方便阅读 我对帖子进行了分页 请点击目录阅读!
|
||||
|
||||
### 更新日志
|
||||
|
||||
- 2019-09-25
|
||||
- 完善 `Sponge` 类型自动补全
|
||||
- 2019-09-24
|
||||
- 完善 `Bukkit` 类型自动补全
|
||||
|
||||
## 插件简介
|
||||
|
||||
- 此插件可以实现跨端使用 `TypeScript` 开发 脚本插件
|
||||
- 目前已经兼容 `Spigot` `Sponge`
|
||||
- 后续计划兼容 `BungeeCord` `Nukkit`
|
||||
|
||||
## 起源 (可以略过)
|
||||
|
||||
### 简介
|
||||
|
||||
> 这个坑是我自己刨的 但是发现坑太大 需要更多的人一起填
|
||||
|
||||
### 起源
|
||||
|
||||
- 诞生于 `2016年08月25日` 这是 Git 上的第一个提交 具体啥时候我也忘了
|
||||
- 起初 `MiaoScript` 只是用于服务器其他插件的变量执行 并且依赖于PAPI(不知道是啥的自己百度)
|
||||
- 比如 [`MiaoMenu`](http://w.yumc.pw/zc/MiaoMenu.html) 的部分复杂脚本
|
||||
- 比如 [`MiaoChat`](http://mcbbs.net/thread-631240-1-1.html) 的聊天变量
|
||||
- 突然有一天 圈内的大佬 `QSB` @qiu1995 过来找我 说能不能用脚本监听玩家的事件
|
||||
- PS: 这货自从用过 `DeluxeMenu` 之后就喜欢上了用JS写菜单
|
||||
- 当初感觉没啥问题 就出了第一个简易的 `MiaoScript` 版本 还是用 yml 做的配置文件
|
||||
- 但是由于设计 BukkitAPI 等内容 对Java要求太高 后来 邱也弃坑了 我也弃坑了
|
||||
|
||||
### 刨坑
|
||||
|
||||
- 时隔多年(也就一年) 看到了Sponge的兴起 (估摸着是MCPC系列的MOD端都弃坑了)
|
||||
- 同时 这期间 收到很多腐竹的单子 但是又是非常基础的东西
|
||||
- 比如 开服给玩家发一条消息啦
|
||||
- 比如 修改玩家某些数据啦
|
||||
- 这些东西实际上也就几行代码的事情
|
||||
- 同时 很多想入坑 插件开发 但是又有一些被卡死在环境搭建上
|
||||
- 比如 `Bukkit` 需要 `BukkitAPI`
|
||||
- `Sponge` 需要 `SpongeAPI` 如果涉及 `MOD` 还要 `Forge` 环境
|
||||
- 再或者 BungeeCord 的插件开发 我也是经常懒得搞
|
||||
- 当然 最主要的是 某个 咕咕咕的群 天天有人问我 喵系插件能不能支持 Sponge
|
||||
- 内心当然是拒绝的 现在要上班养老婆孩子(咳咳 不要以为我是大叔 我也才刚毕业而已) 那里还有时间免费给你们写插件
|
||||
- 于是乎 我又想起了当初的 `MiaoScript`
|
||||
- 突发奇想 一个插件的雏形出现在我的脑海中
|
||||
- 可以兼容多种服务器
|
||||
- 不需要开发环境 有记事本就可以开发
|
||||
- 语法要简单 比如 JavaScript
|
||||
- 能够自动搜索安装依赖(毕竟很多人天天问我为何喵系插件跑不起来 都是缺少PAPI)
|
||||
- 能够不重启更新插件(当然得保证代码安全的前提下)
|
||||
- 在 2017年9月14号(距离 第一个版本正式版发布(2016-09-21) 相差一年整)
|
||||
- 一个全新的 `MiaoScript` 诞生了
|
||||
- Java部分代码 只有一个启动类
|
||||
- 核心全部由 JS 编写
|
||||
- 兼容 `CommonJS` 规范
|
||||
- 实时重载
|
||||
- 2019年9月14号 emm 咸鱼2年之后
|
||||
- TypeScript 重构版本横空出世
|
||||
- 只保留 基础Java启动类 三个环境初始化js
|
||||
- 完整的服务端Java类自动补全
|
||||
- 全新的 IOC容器 注入功能
|
||||
- 注解式 注册命令 注册事件
|
||||
|
||||
### 进展
|
||||
|
||||
- [项目发布](https://git.yumc.pw/502647092/MiaoScript/releases)
|
||||
- [项目代码](https://git.yumc.pw/502647092/MiaoScript)
|
||||
- [项目脑图](http://naotu.baidu.com/file/293b9a0fc7cef23c69de81c55e3617d5?token=1eee8fd759198eb7)
|
||||
|
||||
### 规划
|
||||
|
||||
- 初期只会支持JS类型的插件开发
|
||||
- 二期会出一个建议版本的MS脚本 可以用简单的语法实现简单的功能
|
||||
- 各个层级会有依赖控制 比如 `MS脚本 => JS脚本 => 调用Java原生API`
|
||||
|
||||
## 框架设计
|
||||
|
||||
### MiaoScript TS 实现
|
||||
|
||||
项目具体实现 由 TypeScript 进行编写 然后编译至 `es5` 用于兼容 Java8 的 `Nashorn`
|
||||
|
||||
### Project Structure
|
||||
|
||||
```txt
|
||||
└─packages
|
||||
├─api 全平台兼容的接口
|
||||
├─core 核心代码 用于引导加载
|
||||
├─common 公共类库代码 例如 http reflect 模块
|
||||
├─client NodeJS的Minecraft客户端 用于调试插件
|
||||
├─container IOC容器 用于注入具体实现
|
||||
├─ployfill Nashorn 的一些自定义增强
|
||||
├─nashorn Nashorn 的类型定义
|
||||
├─bungee BungeeCordAPI内部实现
|
||||
├─bukkit BukkitAPI内部实现
|
||||
├─sponge SpongeAPI内部实现
|
||||
├─ployfill JS环境的相关环境补全
|
||||
├─plugin 插件管理器
|
||||
├─type Java的类型定义
|
||||
| ├─bungee BungeeCord类型定义
|
||||
| ├─bukkit Bukkit类型定义
|
||||
| └─sponge Sponge类型定义
|
||||
├─websocket Netty的WebSocket注入
|
||||
└─plugins 这里当然是插件啦
|
||||
├─bungee 只兼容BungeeCord的插件
|
||||
├─bukkit 只兼容Bukkit的插件
|
||||
└─sponge 只兼容Sponge的插件
|
||||
```
|
||||
|
||||
详细的内容就不逼逼了 自己看代码吧
|
||||
|
||||
Github: https://github.com/circlecloud/ms
|
||||
|
||||
## 插件开发基础
|
||||
|
||||
### 开发IDE (推荐VSCode或者MiaoScrit在线IDE)
|
||||
|
||||
如果只是简单的开发 你可用记事本 (但是没有任何补全和错误提示)
|
||||
|
||||
### 开发环境准备(针对高级用户)
|
||||
|
||||
- 安装 `NodeJS` 和 `Yarn`
|
||||
- 拉取代码
|
||||
- `git clone https://github.com/circlecloud/ms.git`
|
||||
- 进入目录 `ms`
|
||||
- 安装 npm 包
|
||||
- `yarn`
|
||||
- 编译一次生成对应的类库
|
||||
- `yarn build`
|
||||
|
||||
### 直接在 MiaoScript Online WebIDE 开发
|
||||
|
||||
填坑中...
|
||||
|
||||
## 基本插件框架
|
||||
|
||||
### HelloWorld 示例插件
|
||||
|
||||
先来一个 `HelloWorld.ts` 插件示范!
|
||||
|
||||
```ts
|
||||
/// <reference types="@ms/types/dist/typings/bukkit" />
|
||||
/// <reference types="@ms/types/dist/typings/sponge" />
|
||||
/// <reference types="@ms/types/dist/typings/bungee" />
|
||||
|
||||
import { server } from '@ms/api';
|
||||
import { inject } from '@ms/container';
|
||||
import { plugin, interfaces, cmd, listener, tab } from '@ms/plugin'
|
||||
|
||||
@plugin({ name: 'HelloWorld', version: '1.0.0', author: 'MiaoWoo', source: __filename })
|
||||
export class HelloWorld extends interfaces.Plugin {
|
||||
@inject(server.Server)
|
||||
private Server: server.Server
|
||||
|
||||
load() {
|
||||
this.logger.log('Plugin load from MiaoScript Plugin System...');
|
||||
}
|
||||
enable() {
|
||||
this.logger.log('Plugin enable from MiaoScript Plugin System...');
|
||||
}
|
||||
disable() {
|
||||
this.logger.log('Plugin disable from MiaoScript Plugin System...');
|
||||
}
|
||||
|
||||
bukkitload() {
|
||||
this.logger.log('Load When ServerType is Bukkit!')
|
||||
}
|
||||
bukkitenable() {
|
||||
this.logger.log('Enable When ServerType is Bukkit!')
|
||||
}
|
||||
bukkitdisable() {
|
||||
this.logger.log('Disable When ServerType is Bukkit!')
|
||||
}
|
||||
|
||||
spongeload() {
|
||||
this.logger.log('Load When ServerType is Sponge!')
|
||||
}
|
||||
spongeenable() {
|
||||
this.logger.log('Enable When ServerType is Sponge!')
|
||||
}
|
||||
spongedisable() {
|
||||
this.logger.log('Disable When ServerType is Sponge!')
|
||||
}
|
||||
|
||||
bungeeload() {
|
||||
this.logger.log('Load When ServerType is BungeeCord!')
|
||||
}
|
||||
bungeeenable() {
|
||||
this.logger.log('Enable When ServerType is BungeeCord!')
|
||||
}
|
||||
bungeedisable() {
|
||||
this.logger.log('Disable When ServerType is BungeeCord!')
|
||||
}
|
||||
|
||||
@cmd()
|
||||
hello(sender: any, command: string, args: string[]) {
|
||||
this.logger.log(sender, command, args);
|
||||
sender.sendMessage(JSON.stringify({ command, ...args }))
|
||||
}
|
||||
|
||||
@tab()
|
||||
tabhello(_sender: any, _command: string, _args: string[]) {
|
||||
return ['world']
|
||||
}
|
||||
|
||||
@listener({ servers: ['bukkit'] })
|
||||
PlayerJoin(event: org.bukkit.event.player.PlayerJoinEvent) {
|
||||
let plyaer = event.getPlayer();
|
||||
this.logger.console(`§cBukkit §aPlayerJoinEvent: §b${plyaer.getName()}`)
|
||||
setTimeout(() => this.sendWelcome(plyaer), 10);
|
||||
}
|
||||
|
||||
@listener({ servers: ['sponge'] })
|
||||
ClientConnectionEvent$Join(event: org.spongepowered.api.event.network.ClientConnectionEvent.Join) {
|
||||
this.logger.console(`§cSponge §aClientConnectionEvent.Join: §b${event.getTargetEntity().getName()}`)
|
||||
setTimeout(() => this.sendWelcome(event.getTargetEntity()), 10);
|
||||
}
|
||||
|
||||
private sendWelcome(player: any) {
|
||||
this.logger.sender(player, `§a欢迎来到 §bMiaoScript §a的世界!`)
|
||||
this.logger.sender(player, `§6当前版本: §c${this.Server.getVersion()}`)
|
||||
}
|
||||
|
||||
@listener({ servers: ['bungee'] })
|
||||
ServerConnected(e: any) {
|
||||
let event = e as net.md_5.bungee.api.event.ServerConnectedEvent
|
||||
this.logger.console(`§cBungeeCord §aServerConnectedEvent: §b${event.getPlayer().getDisplayName()}`)
|
||||
setTimeout(() => this.logger.sender(event.getPlayer(), `§a欢迎来到 §bMiaoScript §a的世界 §6来自 §cBungeeCord §6的问候!`), 10);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- 进入 `ms`目录
|
||||
- 执行编译 `yarn build:plugins`
|
||||
- 从 `packages/plugins/dist` 中复制 `HelloWorld.js` 文件 到对应的插件目录
|
||||
- Bungee: plugins/MiaoScript/plugins/
|
||||
- Bukkit: plugins/MiaoScript/plugins/
|
||||
- Sponge: config/miaoscript/plugins/
|
||||
- 重载 `MiaoScript`
|
||||
- 打开客户端进入游戏 预览一下效果
|
||||
- 从 Spigot 服务端进入
|
||||

|
||||

|
||||
- 从 Sponge 服务端进入
|
||||

|
||||

|
||||
|
||||
## 注册插件
|
||||
|
||||
- 从上面的示例可以看到 一个插件 通过注解 `@plugin` 即可启动
|
||||
- 此注解接受一个 `PluginMetadata` 对象 定义如下
|
||||
```ts
|
||||
export interface PluginMetadata {
|
||||
/**
|
||||
* 插件名称
|
||||
*/
|
||||
name: string;
|
||||
/**
|
||||
* 前缀
|
||||
*/
|
||||
prefix?: string;
|
||||
/**
|
||||
* 插件版本
|
||||
*/
|
||||
version: string;
|
||||
/**
|
||||
* 插件版本
|
||||
*/
|
||||
author: string | string[];
|
||||
/**
|
||||
* 插件源文件 必须指定为 __filename
|
||||
*/
|
||||
source: string;
|
||||
/**
|
||||
* 插件本体
|
||||
*/
|
||||
target?: any;
|
||||
}
|
||||
```
|
||||
|
||||
### 插件生命周期
|
||||
|
||||
MiaoScript的生命周期遵循了 Bukkit 的生命周期
|
||||
|
||||
MiaoScript针对不同的服务端 提供了扩展的周期
|
||||
以服务端类型开头阶段名结束 例如 `bukkitload` `spongeenbale`
|
||||
扩展的生命周期只会在特定的服务器执行
|
||||
|
||||
### load 加载阶段
|
||||
|
||||
此阶段通常用于初始化基础配置 数据库链接等
|
||||
某些对外提供功能的插件 需要在此阶段初始化完成
|
||||
|
||||
### enable 启动阶段
|
||||
|
||||
此阶段通常用于注册命令 注册事件等
|
||||
由于命令和事件 MiaoScript 已经托管了 所以开发者可以直接用注解实现
|
||||
|
||||
### disable 关闭阶段
|
||||
|
||||
此阶段通常用于注销命令 注销事件等
|
||||
由于命令和事件 MiaoScript 已经托管了 所以开发者可以直接用注解实现
|
||||
|
||||
## 注册命令/补全
|
||||
|
||||
### cmd 命令
|
||||
|
||||
命令 就是玩家在Minecraft中执行命令 下面是一个示例的命令
|
||||
|
||||
- 命令是一个 `function` 通过 `@cmd` 注解注册
|
||||
- 由于不同的服务端有不同的逻辑 所以支持通过 `servers` 指定注册的类型 加上 `!` 代表不注册 不指定 `servers` 则注册所有的类型
|
||||
- 命令注册时默认使用方法名称为命令名称 当前你可以传入 name 参数指定命令名称 例如 `{name: 'test'}`
|
||||
- 接受三个参数 `sender: any, command: string, args: string[]`
|
||||
- 分别代表 命令发送者 命令名称 命令参数
|
||||
|
||||
```ts
|
||||
@cmd({ servers: ["bukkit", "sponge", "!bungee"] })
|
||||
hello(sender: any, command: string, args: string[]) {
|
||||
this.logger.log(sender, command, args);
|
||||
this.logger.sender(sender, JSON.stringify({ command, args }));
|
||||
}
|
||||
```
|
||||
|
||||
### tab 补全
|
||||
|
||||
补全就是 玩家在Minecraft执行命令时 使用 Tab键 补全
|
||||
|
||||
- 补全是一个 `function` 一般以 `tab` 开头 需要补全的命令结尾 通过 `@tab` 注解注册
|
||||
- 补全注册时默认使用方法名称为补全名称 当前你可以传入 name 参数指定命令名称 例如 `{name: 'test'}`
|
||||
- 接受三个参数 `sender: any, command: string, args: string[]`
|
||||
- 分别代表 命令发送者 命令名称 命令参数
|
||||
|
||||
_注意: 当补全命令未注册时 补全无效! 且补全和命令必须在同一个Class内!_
|
||||
|
||||
```ts
|
||||
@tab()
|
||||
tabhello(_sender: any, _command: string, _args: string[]) {
|
||||
return ['world']
|
||||
}
|
||||
```
|
||||
|
||||
## 监听事件
|
||||
|
||||
事件是指 Minecraft 中发生的各种事情
|
||||
|
||||
- 监听事件是一个 `function` 通过 `@listener` 注册
|
||||
- 由于不同的服务端有不同的逻辑 所以支持通过 `servers` 指定注册的类型 加上 `!` 代表不注册 不指定 `servers` 则注册所有的类型
|
||||
- 事件名称默认为方法名称
|
||||
- 所有类型服务端的事件 MiaoScript 都会进行一次映射 方便使用
|
||||
- 例如 `PlayerJoinEvent` 会映射为 `PlayerJoinEvent, playerjoinevent, playerjoin` 等
|
||||
- 一般规则就是 类名直接小写 如果遇到子类 则保留 `$`
|
||||
- 例如 `ClientConnectionEvent.Join` 会映射为 `clientconnectionevent$join`
|
||||
- 事件的注可以传入 `servertype` 来指定这个事件类型的服务端加载 默认是所有服务端都加载
|
||||
- 事件监听方法的第一个参数就是本次事件的具体内容 (这里就需要自己去查询对应的JavaDoc了)
|
||||
|
||||
```ts
|
||||
@listener({ servers: ['bukkit'] })
|
||||
PlayerJoin(event: org.bukkit.event.player.PlayerJoinEvent) {
|
||||
let plyaer = event.getPlayer();
|
||||
this.logger.console(`§cBukkit §aPlayerJoinEvent: §b${plyaer.getName()}`)
|
||||
setTimeout(() => this.sendWelcome(plyaer), 10);
|
||||
}
|
||||
|
||||
@listener({ servers: ['sponge'] })
|
||||
ClientConnectionEvent$Join(event: org.spongepowered.api.event.network.ClientConnectionEvent.Join) {
|
||||
this.logger.console(`§cSponge §aClientConnectionEvent.Join: §b${event.getTargetEntity().getName()}`)
|
||||
setTimeout(() => this.sendWelcome(event.getTargetEntity()), 10);
|
||||
}
|
||||
|
||||
private sendWelcome(player: any) {
|
||||
this.logger.sender(player, `§a欢迎来到 §bMiaoScript §a的世界!`)
|
||||
this.logger.sender(player, `§6当前版本: §c${this.Server.getVersion()}`)
|
||||
}
|
||||
|
||||
@listener({ servers: ['bungee'] })
|
||||
ServerConnected(e: any) {
|
||||
let event = e as net.md_5.bungee.api.event.ServerConnectedEvent
|
||||
this.logger.console(`§cBungeeCord §aServerConnectedEvent: §b${event.getPlayer().getDisplayName()}`)
|
||||
setTimeout(() => this.logger.sender(event.getPlayer(), `§a欢迎来到 §bMiaoScript §a的世界 §6来自 §cBungeeCord §6的问候!`), 10);
|
||||
}
|
||||
```
|
||||
|
||||
## 插件列表
|
||||
|
||||
暂无
|
||||
|
||||
> 注意: 一楼的列表是老版本的 新版本无法加载!
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"version": "0.0.0",
|
||||
"version": "0.2.1",
|
||||
"useWorkspaces": true,
|
||||
"npmClient": "yarn",
|
||||
"packages": [
|
||||
|
||||
13
package.json
13
package.json
@@ -6,15 +6,18 @@
|
||||
"author": "MiaoWoo <admin@yumc.pw>",
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
"clean": "npx lerna run clean",
|
||||
"watch": "npx lerna run watch --parallel",
|
||||
"build": "npx lerna run build",
|
||||
"lp": "npx lerna publish"
|
||||
"bs": "lerna bootstrap",
|
||||
"clean": "lerna run clean",
|
||||
"watch": "lerna run watch --parallel --scope=\"@ms/!(manager)\"",
|
||||
"build": "lerna run build --scope=\"@ms/!(plugins|manager)\"",
|
||||
"build:plugins": "lerna run build --scope=\"@ms/plugins\"",
|
||||
"ug": "yarn upgrade-interactive --latest",
|
||||
"lp": "lerna publish"
|
||||
},
|
||||
"workspaces": [
|
||||
"packages/*"
|
||||
],
|
||||
"devDependencies": {
|
||||
"lerna": "^3.16.4"
|
||||
"lerna": "^3.20.2"
|
||||
}
|
||||
}
|
||||
4
packages/api/.gitignore
vendored
4
packages/api/.gitignore
vendored
@@ -1,4 +0,0 @@
|
||||
/node_modules
|
||||
/dist
|
||||
/package-lock.json
|
||||
/yarn.lock
|
||||
@@ -1,22 +0,0 @@
|
||||
src
|
||||
test
|
||||
typings
|
||||
bundled
|
||||
build
|
||||
coverage
|
||||
docs
|
||||
wiki
|
||||
gulpfile.js
|
||||
bower.json
|
||||
karma.conf.js
|
||||
tsconfig.json
|
||||
typings.json
|
||||
CONTRIBUTING.md
|
||||
ISSUE_TEMPLATE.md
|
||||
PULL_REQUEST_TEMPLATE.md
|
||||
tslint.json
|
||||
wallaby.js
|
||||
.travis.yml
|
||||
.gitignore
|
||||
.vscode
|
||||
type_definitions
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ms/api",
|
||||
"version": "0.0.0",
|
||||
"version": "0.2.1",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -13,21 +13,22 @@
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"publishConfig": {
|
||||
"registry": "https://repo.yumc.pw/repository/npm/"
|
||||
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
|
||||
},
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "npx tsc --watch",
|
||||
"build": "yarn clean && npx tsc",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ms/common": "^0.0.0",
|
||||
"@ms/container": "^0.0.0"
|
||||
"@ms/container": "^0.2.1",
|
||||
"@ms/ployfill": "^0.2.1",
|
||||
"source-map-builder": "^0.0.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.0",
|
||||
"typescript": "^3.6.2"
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.8.2"
|
||||
}
|
||||
}
|
||||
@@ -4,22 +4,65 @@ export namespace command {
|
||||
@injectable()
|
||||
export abstract class Command {
|
||||
on(plugin: any, name: string, exec: { cmd: Function, tab?: Function }) {
|
||||
var cmd = this.create(plugin, { name: name });
|
||||
console.debug(`插件 ${plugin.description.name} 创建命令 ${name}(${cmd})...`)
|
||||
var cmd = this.create(plugin, name);
|
||||
console.debug(`[${plugin.description.name}] register command ${name}(${cmd})...`)
|
||||
if (exec.cmd && typeof exec.cmd === "function") {
|
||||
this.onCommand(plugin, cmd, exec.cmd)
|
||||
this.onCommand(plugin, cmd, exec.cmd);
|
||||
} else {
|
||||
throw Error("CommandExec Must be a function... Input: " + exec.cmd)
|
||||
}
|
||||
if (exec.tab && typeof exec.tab === "function") {
|
||||
this.onTabComplete(plugin, cmd, exec.tab)
|
||||
this.onTabComplete(plugin, cmd, exec.tab);
|
||||
}
|
||||
}
|
||||
off(plugin: any, name: string) {
|
||||
console.debug(`[${plugin.description.name}] unregister command ${name}...`)
|
||||
this.remove(plugin, name);
|
||||
}
|
||||
/**
|
||||
* Create Server Command Object
|
||||
*/
|
||||
abstract create(plugin: object, opts: { name: string });
|
||||
abstract onCommand(plugin: object, command: any, opts: { name: string });
|
||||
abstract onTabComplete(plugin: object, command: any, opts: { name: string });
|
||||
protected abstract create(plugin: any, command: string);
|
||||
protected abstract remove(plugin: any, command: string);
|
||||
protected abstract onCommand(plugin: any, command: any, executor: Function);
|
||||
protected abstract onTabComplete(plugin: any, command: any, tabCompleter: Function);
|
||||
|
||||
protected setExecutor(plugin: any, command: any, executor: Function) {
|
||||
return (sender: any, _: any, command: string, args: string[]) => {
|
||||
try {
|
||||
return executor(sender, command, Java.from(args));
|
||||
} catch (ex) {
|
||||
console.console(`§6玩家 §a${sender.name} §6执行 §b${plugin.description.name} §6插件 §d${command} ${Java.from(args).join(' ')} §6命令时发生异常 §4${ex}`);
|
||||
console.ex(ex);
|
||||
console.sender(sender, [`§6执行 §b${plugin.description.name} §6插件 §d${command} ${Java.from(args).join(' ')} §6命令时发生异常`, ...console.stack(ex)])
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected setTabCompleter(plugin: any, command: any, tabCompleter: Function) {
|
||||
return (sender: any, _: any, command: string, args: string[]) => {
|
||||
try {
|
||||
var token = args[args.length - 1];
|
||||
var complete = tabCompleter(sender, command, Java.from(args)) || [];
|
||||
return this.copyPartialMatches(complete, token);
|
||||
} catch (ex) {
|
||||
console.console(`§6玩家 §a${sender.name} §6执行 §b${plugin.description.name} §6插件 §d${command} ${Java.from(args).join(' ')} §6补全时发生异常 §4${ex}`);
|
||||
console.ex(ex);
|
||||
console.sender(sender, [`§6执行 §b${plugin.description.name} §6插件 §d${command} ${Java.from(args).join(' ')} §6补全时发生异常 §4${ex}`, ...console.stack(ex)]);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected copyPartialMatches(complete: string[], token: string, array: string[] = []): string[] {
|
||||
if (!token) { return complete }
|
||||
complete.forEach(function(e) {
|
||||
if (typeof e === "string" && e.toLowerCase().startsWith(token.toLowerCase())) {
|
||||
array.push(e)
|
||||
}
|
||||
});
|
||||
return array
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,29 @@
|
||||
let Arrays = Java.type('java.util.Arrays');
|
||||
let Level = Java.type('java.util.logging.Level');
|
||||
let ignoreLogPrefix = ['java.', 'net.minecraft.', 'org.bukkit.', 'jdk.nashorn.'];
|
||||
import { SourceMapBuilder } from 'source-map-builder'
|
||||
|
||||
const Arrays = Java.type('java.util.Arrays');
|
||||
const Level = Java.type('java.util.logging.Level');
|
||||
const JavaString = Java.type('java.lang.String');
|
||||
const Files = Java.type('java.nio.file.Files');
|
||||
const Paths = Java.type('java.nio.file.Paths');
|
||||
const ignoreLogPrefix = ['java.', 'net.minecraft.', 'org.bukkit.', 'jdk.nashorn.', 'io.netty.', 'org.spongepowered.'];
|
||||
|
||||
enum LogLevel {
|
||||
ALL,
|
||||
TRACE,
|
||||
DEBUG,
|
||||
INFO,
|
||||
WARN,
|
||||
ERROR,
|
||||
FATAL,
|
||||
OFF
|
||||
}
|
||||
|
||||
export class MiaoScriptConsole implements Console {
|
||||
Console: NodeJS.ConsoleConstructor;
|
||||
|
||||
private sourceMaps: { [key: string]: SourceMapBuilder } = {};
|
||||
private _name: string = '';
|
||||
private _level: LogLevel = LogLevel.INFO;
|
||||
|
||||
protected logger: any;
|
||||
protected prefix: string = '§6[§bMiaoScript§6]§r ';
|
||||
@@ -13,6 +31,12 @@ export class MiaoScriptConsole implements Console {
|
||||
constructor(name?: string) {
|
||||
this.name = name;
|
||||
this.logger = global.logger;
|
||||
if (global.debug) {
|
||||
this._level = LogLevel.DEBUG
|
||||
}
|
||||
if (global.level?.toUpperCase() === "TRACE") {
|
||||
this._level = LogLevel.TRACE
|
||||
}
|
||||
}
|
||||
|
||||
get name() {
|
||||
@@ -26,23 +50,28 @@ export class MiaoScriptConsole implements Console {
|
||||
this.prefix = `§6[§cMS§6][§b${name}§6]§r `;
|
||||
}
|
||||
}
|
||||
log(...args): void {
|
||||
log(...args: any[]): void {
|
||||
this.logger.info(this.name + args.join(' '));
|
||||
}
|
||||
info(...args) {
|
||||
info(...args: any[]) {
|
||||
this.logger.info(this.name + args.join(' '));
|
||||
};
|
||||
warn(...args) {
|
||||
}
|
||||
warn(...args: any[]) {
|
||||
this.logger.warning(this.name + args.join(' '));
|
||||
};
|
||||
error(...args) {
|
||||
}
|
||||
error(...args: any[]) {
|
||||
this.logger.log(Level.SEVERE, this.name + args.join(' '));
|
||||
};
|
||||
debug(...args) {
|
||||
}
|
||||
debug(...args: any[]) {
|
||||
if (global.debug) {
|
||||
this.logger.info(this.name + '[DEBUG] ' + args.join(' '));
|
||||
}
|
||||
};
|
||||
}
|
||||
trace(...args: any[]): void {
|
||||
if (this._level <= LogLevel.TRACE) {
|
||||
this.logger.info(this.name + '[TRACE] ' + args.join(' '));
|
||||
}
|
||||
}
|
||||
sender(...args) {
|
||||
this.info(args)
|
||||
}
|
||||
@@ -51,28 +80,57 @@ export class MiaoScriptConsole implements Console {
|
||||
}
|
||||
object(obj) {
|
||||
for (var i in obj) {
|
||||
this.logger(i, '=>', obj[i])
|
||||
this.info(i, '=>', obj[i])
|
||||
}
|
||||
};
|
||||
}
|
||||
ex(ex: Error) {
|
||||
this.stack(ex).forEach(line => this.console(line))
|
||||
};
|
||||
stack(ex: Error | any): string[] {
|
||||
}
|
||||
readSourceMap(fileName: string, lineNumber: number) {
|
||||
try {
|
||||
if (fileName.endsWith('js')) {
|
||||
var file = Paths.get(fileName + '.map');
|
||||
if (!this.sourceMaps[fileName]) {
|
||||
if (file.toFile().exists()) {
|
||||
var sourceMapObj = JSON.parse(new JavaString(Files.readAllBytes(file), "UTF-8"))
|
||||
this.sourceMaps[fileName] = new SourceMapBuilder(sourceMapObj)
|
||||
}
|
||||
}
|
||||
if (this.sourceMaps[fileName]) {
|
||||
var sourceMapping = this.sourceMaps[fileName].getSource(lineNumber, lineNumber);
|
||||
if (sourceMapping) {
|
||||
fileName = fileName.replace(".js", ".ts");
|
||||
lineNumber = sourceMapping.mapping.sourceLine;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.debug('search source map', fileName, 'line', lineNumber, 'error:', error)
|
||||
}
|
||||
return {
|
||||
fileName,
|
||||
lineNumber
|
||||
}
|
||||
}
|
||||
stack(ex: Error): string[] {
|
||||
var stack = ex.getStackTrace();
|
||||
var cache = ['§4' + ex];
|
||||
//@ts-ignore
|
||||
if (stack.class) {
|
||||
stack = Arrays.asList(stack)
|
||||
}
|
||||
stack.forEach(function(trace) {
|
||||
stack.forEach(trace => {
|
||||
if (trace.className.startsWith('<')) {
|
||||
var fileName = trace.fileName
|
||||
var { fileName, lineNumber } = this.readSourceMap(trace.fileName, trace.lineNumber)
|
||||
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
|
||||
if (fileName.startsWith('/runtime')) { fileName = fileName.split('/runtime')[1] }
|
||||
cache.push(` §e->§c ${fileName} => §4${trace.methodName}:${trace.lineNumber}`)
|
||||
cache.push(` §e->§c ${fileName} => §4${trace.methodName}:${lineNumber}`)
|
||||
} else {
|
||||
var className = trace.className;
|
||||
var fileName = trace.fileName as string;
|
||||
if (className.startsWith('jdk.nashorn.internal.scripts')) {
|
||||
className = className.substr(className.lastIndexOf('$') + 1)
|
||||
var { fileName, lineNumber } = this.readSourceMap(trace.fileName, trace.lineNumber)
|
||||
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
|
||||
} else {
|
||||
for (var prefix in ignoreLogPrefix) {
|
||||
if (className.startsWith(ignoreLogPrefix[prefix])) {
|
||||
@@ -80,7 +138,7 @@ export class MiaoScriptConsole implements Console {
|
||||
}
|
||||
}
|
||||
}
|
||||
cache.push(` §e->§c ${className}.${trace.methodName}(§4${trace.fileName}:${trace.lineNumber}§c)`);
|
||||
cache.push(` §e->§c ${className}.${trace.methodName}(§4${fileName}:${trace.lineNumber}§c)`);
|
||||
}
|
||||
});
|
||||
return cache;
|
||||
@@ -124,9 +182,6 @@ export class MiaoScriptConsole implements Console {
|
||||
timeLog(label?: string, ...data: any[]): void {
|
||||
throw new Error("Method not implemented.");
|
||||
}
|
||||
trace(message?: any, ...optionalParams: any[]): void {
|
||||
throw new Error("Method not implemented.");
|
||||
}
|
||||
markTimeline(label?: string): void {
|
||||
throw new Error("Method not implemented.");
|
||||
}
|
||||
|
||||
@@ -6,66 +6,77 @@ import '@ms/core'
|
||||
import '@ms/nashorn'
|
||||
import { injectable } from '@ms/container'
|
||||
|
||||
const Thread = Java.type("java.lang.Thread");
|
||||
const Thread = Java.type('java.lang.Thread');
|
||||
|
||||
export namespace event {
|
||||
export enum EventPriority {
|
||||
LOWEST = "LOWEST",
|
||||
LOW = "LOW",
|
||||
NORMAL = "NORMAL",
|
||||
HIGH = "HIGH",
|
||||
HIGHEST = "HIGHEST",
|
||||
MONITOR = "MONITOR",
|
||||
}
|
||||
|
||||
@injectable()
|
||||
export abstract class Event {
|
||||
private mapEvent = [];
|
||||
private listenerMap = [];
|
||||
private baseEventDir = '';
|
||||
|
||||
protected baseEventDir = '';
|
||||
|
||||
constructor(baseEventDir: string) {
|
||||
this.baseEventDir = baseEventDir;
|
||||
}
|
||||
|
||||
/**
|
||||
* 扫描包 org.bukkit.event 下的所有事件
|
||||
* 映射简写名称 org.bukkit.event.player.PlayerLoginEvent => playerloginevent
|
||||
* abstract event map function
|
||||
* ig: org.bukkit.event.player.PlayerLoginEvent => playerloginevent
|
||||
* org.spongepowered.api.event.game.GameRegistryEvent.Register => gameregistryevent$register
|
||||
*/
|
||||
mapEventName() {
|
||||
if (this.baseEventDir === "") {
|
||||
throw new Error("事件基础包名为空 无法进行事件映射!");
|
||||
throw new Error("base event dir is empty, can't map event name !");
|
||||
}
|
||||
var count = 0;
|
||||
var dirs = Thread.currentThread().getContextClassLoader().getResources(this.baseEventDir);
|
||||
while (dirs.hasMoreElements()) {
|
||||
var url = dirs.nextElement();
|
||||
var protocol = url.protocol;
|
||||
if (protocol === "jar") {
|
||||
// noinspection JSUnresolvedVariable
|
||||
var jar = url.openConnection().jarFile;
|
||||
var entries = jar.entries();
|
||||
while (entries.hasMoreElements()) {
|
||||
var entry = entries.nextElement();
|
||||
var name = entry.name;
|
||||
// 以 org/bukkit/event 开头 并且以 .class 结尾
|
||||
if (name.startsWith(this.baseEventDir) && name.endsWith(".class")) {
|
||||
var i = name.replaceAll('/', '.');
|
||||
try {
|
||||
var clz = base.getClass(i.substring(0, i.length - 6));
|
||||
// 继承于 org.bukkit.event.Event 访问符为Public
|
||||
if (this.isValidEvent(clz)) {
|
||||
var simpleName = this.class2Name(clz).toLowerCase();
|
||||
console.debug(`Mapping Event [${clz.canonicalName}] => ${simpleName}`);
|
||||
this.mapEvent[simpleName] = clz;
|
||||
count++;
|
||||
}
|
||||
} catch (ex) {
|
||||
//ignore already loaded class
|
||||
}
|
||||
let count = 0;
|
||||
let jar = this.getJarFile(this.baseEventDir);
|
||||
let entries = jar.entries();
|
||||
while (entries.hasMoreElements()) {
|
||||
let entry = entries.nextElement();
|
||||
let name = entry.name;
|
||||
if (name.startsWith(this.baseEventDir) && name.endsWith(".class")) {
|
||||
// replace name to qualifiedName
|
||||
let qualifiedName = name.replaceAll('/', '.');
|
||||
try {
|
||||
let clazz = base.getClass(qualifiedName.substring(0, qualifiedName.length - 6));
|
||||
if (this.isValidEvent(clazz)) {
|
||||
let simpleName = this.class2Name(clazz).toLowerCase();
|
||||
console.trace(`Mapping Event [${clazz.canonicalName}] => ${simpleName}`);
|
||||
this.mapEvent[simpleName] = clazz;
|
||||
count++;
|
||||
}
|
||||
} catch (ex) {
|
||||
//ignore already loaded class
|
||||
}
|
||||
}
|
||||
}
|
||||
return count;
|
||||
};
|
||||
}
|
||||
|
||||
class2Name(clazz) {
|
||||
getJarFile(resource: string) {
|
||||
let dirs = Thread.currentThread().getContextClassLoader().getResources(resource);
|
||||
if (dirs.hasMoreElements()) {
|
||||
let url = dirs.nextElement();
|
||||
if (url.protocol === "jar") { return url.openConnection().jarFile; }
|
||||
}
|
||||
throw new Error(`Can't Mapping Event Because not found Resources ${resource}!`)
|
||||
}
|
||||
|
||||
class2Name(clazz: any) {
|
||||
return clazz.simpleName;
|
||||
};
|
||||
}
|
||||
|
||||
name2Class(name, event) {
|
||||
name2Class(name: any, event: string) {
|
||||
var eventCls = this.mapEvent[event.toLowerCase()] || this.mapEvent[event.toLowerCase() + 'event'];
|
||||
if (!eventCls) {
|
||||
try {
|
||||
@@ -73,15 +84,15 @@ export namespace event {
|
||||
this.mapEvent[event] = eventCls;
|
||||
} catch (ex) {
|
||||
console.console(`§6插件 §b${name} §6注册事件 §c${event} §6失败 §4事件未找到!`);
|
||||
console.ex(new Error(`插件 ${name} 注册事件 ${event} 失败 事件未找到!`));
|
||||
console.ex(new Error(`Plugin ${name} register event error ${event} not found!`));
|
||||
return;
|
||||
}
|
||||
}
|
||||
return eventCls;
|
||||
};
|
||||
}
|
||||
|
||||
execute(name, exec, eventCls) {
|
||||
return (...args) => {
|
||||
return (...args: any[]) => {
|
||||
try {
|
||||
var time = new Date().getTime()
|
||||
exec(args[args.length - 1]);
|
||||
@@ -93,36 +104,36 @@ export namespace event {
|
||||
console.console(`§6插件 §b${name} §6处理 §d${this.class2Name(eventCls)} §6事件时发生异常 §4${ex}`);
|
||||
console.ex(ex);
|
||||
}
|
||||
};
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加事件监听
|
||||
* @param jsp
|
||||
* @param event
|
||||
* @param plugin {any}
|
||||
* @param event {string}
|
||||
* @param exec {function}
|
||||
* @param priority [LOWEST,LOW,NORMAL,HIGH,HIGHEST,MONITOR]
|
||||
* @param priority {string} [LOWEST,LOW,NORMAL,HIGH,HIGHEST,MONITOR]
|
||||
* @param ignoreCancel
|
||||
*/
|
||||
listen(jsp, event, exec, priority, ignoreCancel) {
|
||||
if (!jsp || !jsp.description || !jsp.description.name) throw new TypeError('插件名称为空 请检查传入参数!');
|
||||
var name = jsp.description.name;
|
||||
listen(plugin: any, event: string, exec: () => void, priority: EventPriority = EventPriority.NORMAL, ignoreCancel = false) {
|
||||
if (!plugin || !plugin.description || !plugin.description.name) throw new TypeError('插件名称为空 请检查传入参数!');
|
||||
var name = plugin.description.name;
|
||||
var eventCls = this.name2Class(name, event);
|
||||
if (!eventCls) { return; }
|
||||
if (typeof priority === 'boolean') {
|
||||
ignoreCancel = priority;
|
||||
priority = 'NORMAL';
|
||||
priority = EventPriority.NORMAL;
|
||||
}
|
||||
priority = priority || 'NORMAL';
|
||||
priority = priority || EventPriority.NORMAL;
|
||||
ignoreCancel = ignoreCancel || false;
|
||||
// noinspection JSUnusedGlobalSymbols
|
||||
var listener = this.register(eventCls, this.execute(name, exec, eventCls), priority, ignoreCancel);
|
||||
var listenerMap = this.listenerMap;
|
||||
// 添加到缓存 用于关闭插件的时候关闭事件
|
||||
// add to cache Be used for close plugin to close event
|
||||
if (!listenerMap[name]) listenerMap[name] = [];
|
||||
var offExec = () => {
|
||||
this.unregister(eventCls, listener);
|
||||
console.debug(`插件 ${name} 注销事件 ${this.class2Name(eventCls)}`);
|
||||
console.debug(`[${name}] unregister event ${this.class2Name(eventCls)}`);
|
||||
};
|
||||
var off = {
|
||||
event: eventCls,
|
||||
@@ -131,7 +142,7 @@ export namespace event {
|
||||
};
|
||||
listenerMap[name].push(off);
|
||||
// noinspection JSUnresolvedVariable
|
||||
console.debug(`插件 ${name} 注册事件 ${this.class2Name(eventCls)} => ${exec.name || '匿名方法'}`);
|
||||
console.debug(`[${name}] register event ${this.class2Name(eventCls)} => ${exec.name || '[anonymous]'}`);
|
||||
return off;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import './typings/global'
|
||||
|
||||
/// <reference types='@ms/ployfill' />
|
||||
export * from './task'
|
||||
export * from './event'
|
||||
export * from './console'
|
||||
export * from './command'
|
||||
|
||||
@@ -1,25 +1,30 @@
|
||||
import { Container } from "inversify";
|
||||
|
||||
export namespace plugin {
|
||||
/**
|
||||
* MiaoScript Plugin
|
||||
*/
|
||||
export const Plugin = Symbol("Plugin");
|
||||
/**
|
||||
* MiaoScript Plugin
|
||||
*/
|
||||
export const PluginFolder = Symbol("PluginFolder");
|
||||
/**
|
||||
* Runtime Plugin Instance
|
||||
*/
|
||||
export const PluginInstance = Symbol("PluginInstance");
|
||||
/**
|
||||
* MiaoScript Plugin Manager
|
||||
* MiaoScript Plugin Manager Symbol
|
||||
*/
|
||||
export const PluginManager = Symbol("PluginManager");
|
||||
/**
|
||||
* MiaoScript Plugin Manager
|
||||
* MiaoScript Plugin Manager Interface
|
||||
*/
|
||||
export interface PluginManager {
|
||||
scan(folder: string): void;
|
||||
load(container: Container): void;
|
||||
enable(): void;
|
||||
disable(): void;
|
||||
build(): void;
|
||||
load(...args: any[]): void;
|
||||
enable(...args: any[]): void;
|
||||
disable(...args: any[]): void;
|
||||
reload(...args: any[]): void;
|
||||
getPlugins(): Map<string, any>;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,31 @@
|
||||
export namespace server {
|
||||
/**
|
||||
* Runtime ServerType
|
||||
*/
|
||||
export const ServerType = Symbol("ServerType");
|
||||
/**
|
||||
* Runtime Console
|
||||
*/
|
||||
export const Console = Symbol("Console");
|
||||
/**
|
||||
* MiaoScript Server
|
||||
*/
|
||||
export const Server = Symbol("Server");
|
||||
/**
|
||||
* Runtime Server Instance
|
||||
*/
|
||||
export const ServerInstance = Symbol("ServerInstance");
|
||||
/**
|
||||
* MiaoScript Server
|
||||
*/
|
||||
export interface Server {
|
||||
getVersion(): string;
|
||||
getPlayer(name: string): any;
|
||||
getOnlinePlayers(): any[];
|
||||
getConsoleSender(): any;
|
||||
getService(service: string): any;
|
||||
dispatchCommand(sender: string | any, command: string): boolean;
|
||||
dispatchConsoleCommand(command: string): boolean;
|
||||
sendJson(sender: string | any, json: object | string): void;
|
||||
}
|
||||
}
|
||||
|
||||
56
packages/api/src/task.ts
Normal file
56
packages/api/src/task.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
import { injectable, DefaultContainer as container } from "@ms/container";
|
||||
|
||||
export namespace task {
|
||||
export const TaskManager = Symbol('TaskManager')
|
||||
export interface TaskManager {
|
||||
create(func: Function): task.Task;
|
||||
callSyncMethod(func: Function): any;
|
||||
}
|
||||
/**
|
||||
* 任务抽象
|
||||
*/
|
||||
export abstract class Task {
|
||||
protected plugin: any;
|
||||
protected func: Function;
|
||||
protected isAsync: boolean = false;
|
||||
protected laterTime: number = 0;
|
||||
protected interval: number = 0;
|
||||
|
||||
constructor(plugin: any, func: Function) {
|
||||
this.plugin = plugin;
|
||||
this.func = func;
|
||||
}
|
||||
|
||||
async(isAsync: boolean = true): task.Task {
|
||||
this.isAsync = isAsync;
|
||||
return this;
|
||||
}
|
||||
|
||||
later(tick: number): task.Task {
|
||||
this.laterTime = tick;
|
||||
return this;
|
||||
}
|
||||
|
||||
timer(tick: number): task.Task {
|
||||
this.interval = tick;
|
||||
return this;
|
||||
}
|
||||
|
||||
protected run(): void {
|
||||
try {
|
||||
this.func();
|
||||
} catch (ex) {
|
||||
console.console('§4插件执行任务时发生错误', ex)
|
||||
console.ex(ex);
|
||||
}
|
||||
}
|
||||
|
||||
abstract submit(): Cancelable;
|
||||
}
|
||||
/**
|
||||
* 返可取消的对象
|
||||
*/
|
||||
export interface Cancelable {
|
||||
cancel(): boolean;
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
export interface CommandInfo {
|
||||
aliases: string[];
|
||||
description: string;
|
||||
}
|
||||
export interface PluginInfo {
|
||||
description: PluginDescription;
|
||||
}
|
||||
export interface PluginDescription {
|
||||
name: string;
|
||||
version: string;
|
||||
author: string;
|
||||
commands: { [key: string]: CommandInfo };
|
||||
}
|
||||
4
packages/bukkit/.gitignore
vendored
4
packages/bukkit/.gitignore
vendored
@@ -1,4 +0,0 @@
|
||||
/node_modules
|
||||
/dist
|
||||
/package-lock.json
|
||||
/yarn.lock
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@ms/bukkit",
|
||||
"version": "0.0.0",
|
||||
"description": "MiaoScript api package",
|
||||
"version": "0.2.1",
|
||||
"description": "MiaoScript bukkit package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
"minecraft",
|
||||
@@ -13,22 +13,23 @@
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"publishConfig": {
|
||||
"registry": "https://repo.yumc.pw/repository/npm/"
|
||||
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
|
||||
},
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "npx tsc --watch",
|
||||
"build": "yarn clean && npx tsc",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.0",
|
||||
"typescript": "^3.6.2"
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.8.2"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ms/api": "^0.0.0",
|
||||
"@ms/common": "^0.0.0",
|
||||
"@ms/container": "^0.0.0"
|
||||
"@ms/api": "^0.2.1",
|
||||
"@ms/common": "^0.2.1",
|
||||
"@ms/container": "^0.2.1",
|
||||
"@ms/types": "^0.2.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,8 +4,7 @@ import { command, plugin } from '@ms/api'
|
||||
import * as reflect from '@ms/common/dist/reflect'
|
||||
import { injectable, postConstruct, inject } from '@ms/container'
|
||||
|
||||
let Bukkit = Java.type("org.bukkit.Bukkit");
|
||||
let Arrays = Java.type('java.util.Arrays');
|
||||
let Bukkit = org.bukkit.Bukkit;
|
||||
let TabCompleter = Java.type('org.bukkit.command.TabCompleter');
|
||||
let PluginCommand = Java.type('org.bukkit.command.PluginCommand');
|
||||
let CommandExecutor = Java.type('org.bukkit.command.CommandExecutor');
|
||||
@@ -18,75 +17,31 @@ export class BukkitCommand extends command.Command {
|
||||
|
||||
@postConstruct()
|
||||
init() {
|
||||
this.commandMap = reflect.on(Bukkit.pluginManager).get('commandMap').get();
|
||||
this.commandMap = reflect.on(Bukkit.getPluginManager()).get('commandMap').get();
|
||||
}
|
||||
|
||||
enable(jsp) {
|
||||
var commands = jsp.description.commands;
|
||||
if (commands) {
|
||||
var pluginCommands = [];
|
||||
for (var name in commands) {
|
||||
var command = commands[name];
|
||||
if (typeof command !== 'object') continue;
|
||||
command.name = name;
|
||||
var newCmd = this.create(jsp, command);
|
||||
if (command.description) newCmd.setDescription(command.description);
|
||||
if (command.usage) newCmd.setUsage(command.usage);
|
||||
if (command.aliases) newCmd.setAliases(Arrays.asList(command.aliases));
|
||||
if (command.permission) newCmd.setPermission(command.permission);
|
||||
if (command['permission-message']) newCmd.setPermissionMessage(command['permission-message']);
|
||||
pluginCommands.push(newCmd);
|
||||
console.debug(`插件 ${jsp.description.name} 注册命令 ${name} ...`);
|
||||
}
|
||||
this.commandMap.registerAll(jsp.description.name, Arrays.asList(pluginCommands));
|
||||
}
|
||||
}
|
||||
|
||||
disable(jsp) {
|
||||
var commands = jsp.description.commands;
|
||||
if (commands) {
|
||||
for (var name in commands) {
|
||||
//TODO 删除插件命令
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
create(jsp, command) {
|
||||
var cmd = this.commandMap.getCommand(command.name)
|
||||
create(plugin: any, command: string) {
|
||||
var cmd = this.commandMap.getCommand(command)
|
||||
if (cmd && cmd instanceof PluginCommand) { return cmd };
|
||||
cmd = reflect.on(PluginCommand).create(command.name, this.pluginInstance).get();
|
||||
this.commandMap.register(jsp.description.name, cmd);
|
||||
cmd = reflect.on(PluginCommand).create(command, this.pluginInstance).get();
|
||||
this.commandMap.register(plugin.description.name, cmd);
|
||||
return cmd;
|
||||
}
|
||||
|
||||
onCommand(jsp, c, cmd) {
|
||||
remove(plugin: any, command: string) {
|
||||
var cmd = this.commandMap.getCommand(command)
|
||||
if (cmd && cmd instanceof PluginCommand) {
|
||||
cmd.unregister(this.commandMap);
|
||||
}
|
||||
}
|
||||
onCommand(plugin: any, command: any, executor: Function) {
|
||||
// 必须指定需要实现的接口类型 否则MOD服会报错
|
||||
c.setExecutor(new CommandExecutor({
|
||||
onCommand: function(sender, _, command, args) {
|
||||
try {
|
||||
return cmd(sender, command, Java.from(args));
|
||||
} catch (ex) {
|
||||
console.console(`§6玩家 §a${sender.name} §6执行 §b${jsp.description.name} §6插件 §d${command} ${Java.from(args).join(' ')} §6命令时发生异常 §4${ex}`);
|
||||
console.ex(ex);
|
||||
}
|
||||
}
|
||||
command.setExecutor(new CommandExecutor({
|
||||
onCommand: super.setExecutor(plugin, command, executor)
|
||||
}));
|
||||
}
|
||||
|
||||
onTabComplete(jsp, c, tab) {
|
||||
onTabComplete(plugin: any, command: any, tabCompleter: Function) {
|
||||
// 必须指定需要实现的接口类型 否则MOD服会报错
|
||||
// noinspection JSUnusedGlobalSymbols
|
||||
c.setTabCompleter(new TabCompleter({
|
||||
onTabComplete: function(sender, _, command, args) {
|
||||
try {
|
||||
var token = args[args.length - 1];
|
||||
var complete = tab(sender, command, Java.from(args)) || [];
|
||||
return Arrays.asList(complete.copyPartialMatches(token, []));
|
||||
} catch (ex) {
|
||||
console.console(`§6玩家 §a${sender.name} §6执行 §b${jsp.description.name} §6插件 §d${command} ${Java.from(args).join(' ')} §6补全时发生异常 §4${ex}`);
|
||||
console.ex(ex);
|
||||
}
|
||||
}
|
||||
command.setTabCompleter(new TabCompleter({
|
||||
onTabComplete: super.setTabCompleter(plugin, command, tabCompleter)
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -1,21 +1,20 @@
|
||||
import { MiaoScriptConsole } from '@ms/api'
|
||||
|
||||
let Bukkit = Java.type("org.bukkit.Bukkit");
|
||||
let CommandSender = Java.type("org.bukkit.command.CommandSender");
|
||||
let Bukkit = org.bukkit.Bukkit;
|
||||
|
||||
export class BukkitConsole extends MiaoScriptConsole {
|
||||
sender(sender, ...args) {
|
||||
if (!(sender instanceof CommandSender)) {
|
||||
this.error("第一个参数未实现 org.bukkit.command.CommandSender 无法发送消息!")
|
||||
if (!(sender instanceof Java.type('org.bukkit.command.CommandSender'))) {
|
||||
this.error(`First parameter ${sender} not instanceof org.bukkit.command.CommandSender can't send message!`)
|
||||
return;
|
||||
}
|
||||
if (args[0].toString() === "[object Array]") {
|
||||
if (Object.prototype.toString.call(args[0]) === "[object Array]") {
|
||||
args[0].forEach(line => sender.sendMessage(this.prefix + line))
|
||||
} else {
|
||||
sender.sendMessage(this.prefix + args.join(' '));
|
||||
}
|
||||
}
|
||||
console(...args): void {
|
||||
this.sender(Bukkit.consoleSender, args.join(' '));
|
||||
console(...args: string[]): void {
|
||||
this.sender(Bukkit.getConsoleSender(), args.join(' '));
|
||||
}
|
||||
}
|
||||
|
||||
114
packages/bukkit/src/enhance/chat.ts
Normal file
114
packages/bukkit/src/enhance/chat.ts
Normal file
@@ -0,0 +1,114 @@
|
||||
/*global Java, base, module, exports, require*/
|
||||
var nmsChatSerializerClass;
|
||||
var nmsChatSerializerMethod;
|
||||
var packetTypeConstructor;
|
||||
var nmsChatMessageTypeClass;
|
||||
var chatMessageTypes;
|
||||
|
||||
var RemapUtils;
|
||||
|
||||
var playerConnectionFieldName;
|
||||
var sendPacketMethod;
|
||||
|
||||
var downgrade = false;
|
||||
/**
|
||||
* 获取NMS版本
|
||||
*/
|
||||
//@ts-ignore
|
||||
var nmsVersion = org.bukkit.Bukkit.server.class.name.split('.')[3];
|
||||
/**
|
||||
* 获取NMS类
|
||||
*/
|
||||
function nmsCls(name) {
|
||||
return base.getClass(['net.minecraft.server', nmsVersion, name].join('.'))
|
||||
}
|
||||
|
||||
function remapMethod(clazz: any, origin: string, test: string, params) {
|
||||
try {
|
||||
return clazz.getMethod(origin, params)
|
||||
} catch (ex) {
|
||||
if (RemapUtils) {
|
||||
return clazz.getMethod(RemapUtils.mapMethod(clazz, origin, params), params)
|
||||
} else {
|
||||
return clazz.getMethod(test, params)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function remapFieldName(clazz: any, origin: string, test: string) {
|
||||
try {
|
||||
return clazz.getField(origin)
|
||||
} catch (ex) {
|
||||
if (RemapUtils) {
|
||||
return clazz.getField(RemapUtils.mapFieldName(clazz, origin))
|
||||
} else {
|
||||
return clazz.getField(test)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function init() {
|
||||
try {
|
||||
RemapUtils = Java.type('catserver.server.remapper.RemapUtils');
|
||||
} catch (ex) {
|
||||
}
|
||||
nmsChatSerializerClass = nmsCls(nmsVersion.split("_")[1] > 7 ? "IChatBaseComponent$ChatSerializer" : "ChatSerializer");
|
||||
nmsChatSerializerMethod = remapMethod(nmsChatSerializerClass, 'a', 'func_150699_a', base.getClass('java.lang.String'))
|
||||
var packetTypeClass = nmsCls("PacketPlayOutChat");
|
||||
Java.from(packetTypeClass.constructors).forEach(function(c) {
|
||||
if (c.parameterTypes.length === 2) {
|
||||
packetTypeConstructor = c
|
||||
}
|
||||
});
|
||||
nmsChatMessageTypeClass = packetTypeConstructor.parameterTypes[1];
|
||||
if (nmsChatMessageTypeClass.isEnum()) {
|
||||
chatMessageTypes = nmsChatMessageTypeClass.getEnumConstants();
|
||||
} else {
|
||||
switch (nmsChatMessageTypeClass.name) {
|
||||
case "int":
|
||||
//@ts-ignore
|
||||
nmsChatMessageTypeClass = java.lang.Integer;
|
||||
break;
|
||||
case "byte":
|
||||
//@ts-ignore
|
||||
nmsChatMessageTypeClass = java.lang.Byte;
|
||||
break;
|
||||
}
|
||||
}
|
||||
var entityPlayerClass = nmsCls('EntityPlayer');
|
||||
var packetClass = nmsCls('Packet');
|
||||
var playerConnectionField = remapFieldName(entityPlayerClass, 'playerConnection', 'field_71135_a')
|
||||
playerConnectionFieldName = playerConnectionField.getName()
|
||||
sendPacketMethod = remapMethod(playerConnectionField.getType(), 'sendPacket', 'func_179290_a', packetClass)
|
||||
}
|
||||
|
||||
function json(sender, json) {
|
||||
if (downgrade) {
|
||||
return '/tellraw ' + sender.name + ' ' + json
|
||||
} else {
|
||||
send(sender, json, 0);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function send(sender, json, type) {
|
||||
//@ts-ignore
|
||||
sendPacket(sender, packetTypeConstructor.newInstance(nmsChatSerializerMethod.invoke(null, json), chatMessageTypes == null ? nmsChatMessageTypeClass.valueOf(java.lang.String.valueOf(type)) : chatMessageTypes[type]))
|
||||
}
|
||||
|
||||
function sendPacket(player, p) {
|
||||
sendPacketMethod.invoke(player.handle[playerConnectionFieldName], p)
|
||||
}
|
||||
|
||||
try {
|
||||
init();
|
||||
} catch (ex) {
|
||||
org.bukkit.Bukkit.getConsoleSender().sendMessage(`§6[§cMS§6][§bbukkit§6][§achat§6] §cNMS Inject Error §4${ex} §cDowngrade to Command Mode...`)
|
||||
downgrade = true;
|
||||
}
|
||||
|
||||
let chat = {
|
||||
json
|
||||
}
|
||||
|
||||
export default chat
|
||||
48
packages/bukkit/src/event.ts
Normal file
48
packages/bukkit/src/event.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import { event, server, plugin } from '@ms/api'
|
||||
import { injectable, inject } from '@ms/container';
|
||||
import * as reflect from '@ms/common/dist/reflect'
|
||||
|
||||
const Bukkit = Java.type("org.bukkit.Bukkit");
|
||||
const Event = Java.type("org.bukkit.event.Event");
|
||||
const Modifier = Java.type("java.lang.reflect.Modifier");
|
||||
const Listener = Java.type("org.bukkit.event.Listener");
|
||||
const EventPriority = Java.type("org.bukkit.event.EventPriority");
|
||||
const EventExecutor = Java.type("org.bukkit.plugin.EventExecutor");
|
||||
|
||||
@injectable()
|
||||
export class BukkitEvent extends event.Event {
|
||||
@inject(plugin.PluginInstance)
|
||||
private pluginInstance: any
|
||||
|
||||
constructor() {
|
||||
super('org/bukkit/event');
|
||||
}
|
||||
|
||||
getJarFile(resource: string) {
|
||||
return super.getJarFile('org/bukkit/Bukkit.class')
|
||||
}
|
||||
isValidEvent(clazz: any): boolean {
|
||||
// 继承于 org.bukkit.event.Event
|
||||
return Event.class.isAssignableFrom(clazz) &&
|
||||
// 访问符为Public
|
||||
Modifier.isPublic(clazz.getModifiers()) &&
|
||||
// 不是抽象类
|
||||
!Modifier.isAbstract(clazz.getModifiers());
|
||||
}
|
||||
register(eventCls: any, exec: Function, priority: event.EventPriority, ignoreCancel: boolean) {
|
||||
let listener = new Listener({});
|
||||
Bukkit.pluginManager.registerEvent(
|
||||
eventCls,
|
||||
listener,
|
||||
EventPriority[priority],
|
||||
new EventExecutor({
|
||||
execute: exec
|
||||
}),
|
||||
this.pluginInstance,
|
||||
ignoreCancel);
|
||||
return listener;
|
||||
}
|
||||
unregister(event: any, listener: any): void {
|
||||
reflect.on(event).call('getHandlerList').get().unregister(listener);
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,18 @@
|
||||
import { server, plugin, command } from '@ms/api'
|
||||
import { DefaultContainer as container } from '@ms/container'
|
||||
/// <reference types="@ms/types/dist/typings/bukkit" />
|
||||
|
||||
import { BukkitConsole } from './console'
|
||||
import { server, command, event, task } from '@ms/api'
|
||||
import { Container } from '@ms/container'
|
||||
|
||||
import { BukkitConsole } from './console';
|
||||
import { BukkitEvent } from './event';
|
||||
import { BukkitServer } from './server';
|
||||
import { BukkitCommand } from './command';
|
||||
import { BukkitTaskManager } from './task';
|
||||
|
||||
let BukkitServerType = 'bukkit';
|
||||
let Bukkit = Java.type("org.bukkit.Bukkit");
|
||||
|
||||
container.bind(server.Console).toConstantValue(BukkitConsole);
|
||||
container.bind(server.ServerType).toConstantValue(BukkitServerType);
|
||||
container.bind(plugin.PluginInstance).toConstantValue(Bukkit.pluginManager.getPlugin('MiaoScript'));
|
||||
|
||||
container.bind(command.Command).to(BukkitCommand).inSingletonScope();
|
||||
export default function BukkitImpl(container: Container) {
|
||||
container.bind(server.Console).toConstantValue(BukkitConsole);
|
||||
container.bind(event.Event).to(BukkitEvent).inSingletonScope();
|
||||
container.bind(server.Server).to(BukkitServer).inSingletonScope();
|
||||
container.bind(command.Command).to(BukkitCommand).inSingletonScope();
|
||||
container.bind(task.TaskManager).to(BukkitTaskManager).inSingletonScope();
|
||||
}
|
||||
|
||||
43
packages/bukkit/src/server.ts
Normal file
43
packages/bukkit/src/server.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import { server } from '@ms/api'
|
||||
import { injectable } from '@ms/container';
|
||||
|
||||
import chat from './enhance/chat'
|
||||
|
||||
let Bukkit = org.bukkit.Bukkit;
|
||||
|
||||
@injectable()
|
||||
export class BukkitServer implements server.Server {
|
||||
getPlayer(name: string) {
|
||||
return Bukkit.getPlayer(name)
|
||||
}
|
||||
getVersion(): string {
|
||||
return Bukkit.getVersion()
|
||||
}
|
||||
getOnlinePlayers() {
|
||||
return Bukkit.getOnlinePlayers() as unknown as any[]
|
||||
}
|
||||
getConsoleSender() {
|
||||
return Bukkit.getConsoleSender()
|
||||
}
|
||||
getService(service: string) {
|
||||
return Bukkit.getServicesManager().getRegistration(base.getClass(service))?.getProvider()
|
||||
}
|
||||
dispatchCommand(sender: string | any, command: string): boolean {
|
||||
if (typeof sender === 'string') {
|
||||
sender = this.getPlayer(sender)
|
||||
}
|
||||
return Bukkit.dispatchCommand(sender, command)
|
||||
}
|
||||
dispatchConsoleCommand(command: string): boolean {
|
||||
return Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command)
|
||||
}
|
||||
sendJson(sender: string | any, json: object | string): void {
|
||||
if (typeof sender === "string") {
|
||||
sender = this.getPlayer(sender)
|
||||
}
|
||||
let result = chat.json(sender, json)
|
||||
if (result !== false) {
|
||||
this.dispatchConsoleCommand(result)
|
||||
}
|
||||
}
|
||||
}
|
||||
34
packages/bukkit/src/task.ts
Normal file
34
packages/bukkit/src/task.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { task, plugin } from '@ms/api'
|
||||
import { injectable, inject } from '@ms/container';
|
||||
|
||||
const Bukkit = Java.type('org.bukkit.Bukkit');
|
||||
const BukkitRunnable = Java.type('org.bukkit.scheduler.BukkitRunnable');
|
||||
const Callable = Java.type('java.util.concurrent.Callable')
|
||||
|
||||
@injectable()
|
||||
export class BukkitTaskManager implements task.TaskManager {
|
||||
@inject(plugin.PluginInstance)
|
||||
private pluginInstance: any;
|
||||
|
||||
create(func: Function): task.Task {
|
||||
if (Object.prototype.toString.call(func) !== "[object Function]") { throw TypeError('第一个参数 Task 必须为 function !'); };
|
||||
return new BukkitTask(this.pluginInstance, func);
|
||||
}
|
||||
callSyncMethod(func: Function): any {
|
||||
return Bukkit.getScheduler().callSyncMethod(this.pluginInstance, new Callable({ call: () => func() })).get()
|
||||
}
|
||||
}
|
||||
|
||||
export class BukkitTask extends task.Task {
|
||||
submit(): task.Cancelable {
|
||||
let run = new BukkitRunnable({
|
||||
run: () => this.run()
|
||||
})
|
||||
let funcName = `runTask${this.interval ? 'Timer' : 'Later'}${this.isAsync ? 'Asynchronously' : ''}`
|
||||
if (this.interval) {
|
||||
return run[funcName](this.plugin, this.laterTime, this.interval)
|
||||
} else {
|
||||
return run[funcName](this.plugin, this.laterTime)
|
||||
}
|
||||
}
|
||||
}
|
||||
35
packages/bungee/package.json
Normal file
35
packages/bungee/package.json
Normal file
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"name": "@ms/bungee",
|
||||
"version": "0.2.1",
|
||||
"description": "MiaoScript bungee package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
"minecraft",
|
||||
"bukkit",
|
||||
"sponge"
|
||||
],
|
||||
"author": "MiaoWoo <admin@yumc.pw>",
|
||||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"publishConfig": {
|
||||
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
|
||||
},
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.8.2"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ms/api": "^0.2.1",
|
||||
"@ms/common": "^0.2.1",
|
||||
"@ms/container": "^0.2.1",
|
||||
"@ms/types": "^0.2.1"
|
||||
}
|
||||
}
|
||||
66
packages/bungee/src/command.ts
Normal file
66
packages/bungee/src/command.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
import { command, plugin } from "@ms/api";
|
||||
import { inject, injectable } from "@ms/container";
|
||||
import * as ref from '@ms/common/dist/reflect'
|
||||
|
||||
const Arrays = Java.type('java.util.Arrays')
|
||||
const Command = Java.extend(Java.type('net.md_5.bungee.api.plugin.Command'), Java.type('net.md_5.bungee.api.plugin.TabExecutor'));
|
||||
const createCommand = eval(`
|
||||
function(cls, name, exec, tab){
|
||||
return new cls(name) {
|
||||
execute: exec,
|
||||
onTabComplete: tab
|
||||
}
|
||||
}
|
||||
`)
|
||||
|
||||
class SimpleCommand {
|
||||
public callable: any;
|
||||
private name: string;
|
||||
private executor: Function;
|
||||
private tabComplete: Function = () => [];
|
||||
|
||||
constructor(command: string) {
|
||||
this.name = command;
|
||||
this.callable = createCommand(Command, command,
|
||||
(sender, args) => this.executor(sender, '', command, args),
|
||||
(sender, args) => Arrays.asList(this.tabComplete(sender, '', command, args))
|
||||
);
|
||||
}
|
||||
|
||||
setExecutor = (executor: Function) => this.executor = executor;
|
||||
setTabComplete = (tabComplete: Function) => this.tabComplete = tabComplete;
|
||||
toString = () => `Bungee SimpleCommand(${this.name})`
|
||||
}
|
||||
|
||||
@injectable()
|
||||
export class BungeeCommand extends command.Command {
|
||||
@inject(plugin.PluginInstance)
|
||||
private pluginInstance: any;
|
||||
private pluginManager: net.md_5.bungee.api.plugin.PluginManager = base.getInstance().getProxy().getPluginManager();
|
||||
private commandMapping: any[] = [];
|
||||
|
||||
create(plugin: any, command: string) {
|
||||
let commandKey = this.getCommandKey(plugin, command);
|
||||
let commandCallable = new SimpleCommand(command);
|
||||
this.pluginManager.registerCommand(this.pluginInstance, commandCallable.callable)
|
||||
this.commandMapping[commandKey] = commandCallable.callable;
|
||||
return commandCallable;
|
||||
}
|
||||
remove(plugin: any, command: string) {
|
||||
var commandKey = this.getCommandKey(plugin, command);
|
||||
if (this.commandMapping[commandKey]) {
|
||||
this.pluginManager.unregisterCommand(this.commandMapping[commandKey])
|
||||
delete this.commandMapping[commandKey];
|
||||
}
|
||||
}
|
||||
onCommand(plugin: any, command: any, executor: Function) {
|
||||
command.setExecutor(super.setExecutor(plugin, command, executor));
|
||||
}
|
||||
onTabComplete(plugin: any, command: any, tabCompleter: Function) {
|
||||
command.setTabComplete(super.setTabCompleter(plugin, command, tabCompleter))
|
||||
}
|
||||
|
||||
private getCommandKey(plugin: any, command: string) {
|
||||
return plugin.description.name.toLowerCase() + ":" + command;
|
||||
}
|
||||
}
|
||||
27
packages/bungee/src/console.ts
Normal file
27
packages/bungee/src/console.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import '@ms/nashorn'
|
||||
import { plugin, MiaoScriptConsole } from '@ms/api'
|
||||
import { inject, injectable } from "@ms/container";
|
||||
|
||||
let CommandSender = Java.type("net.md_5.bungee.api.CommandSender")
|
||||
|
||||
@injectable()
|
||||
export class BungeeConsole extends MiaoScriptConsole {
|
||||
@inject(plugin.PluginInstance)
|
||||
private pluginInstance: any
|
||||
private proxyServer: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy();
|
||||
|
||||
sender(sender, ...args) {
|
||||
if (!(sender instanceof CommandSender)) {
|
||||
this.error('第一个参数未实现 net.md_5.bungee.api.CommandSender 无法发送消息!')
|
||||
return
|
||||
}
|
||||
if (Object.prototype.toString.call(args[0]) === '[object Array]') {
|
||||
args[0].forEach(line => sender.sendMessage(this.prefix + line))
|
||||
} else {
|
||||
sender.sendMessage(this.prefix + args.join(' '));
|
||||
}
|
||||
}
|
||||
console(...args): void {
|
||||
this.sender(this.proxyServer.getConsole(), args.join(' '));
|
||||
}
|
||||
}
|
||||
119
packages/bungee/src/event.ts
Normal file
119
packages/bungee/src/event.ts
Normal file
@@ -0,0 +1,119 @@
|
||||
import { event, plugin } from '@ms/api'
|
||||
import { injectable, inject, postConstruct } from '@ms/container'
|
||||
import * as reflect from '@ms/common/dist/reflect'
|
||||
|
||||
const Bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy();
|
||||
const Event = Java.type("net.md_5.bungee.api.plugin.Event");
|
||||
const Modifier = Java.type("java.lang.reflect.Modifier");
|
||||
const ProxyClass = Java.type(base.getProxyClass().name);
|
||||
const ProxyMethod = reflect.on(base.getProxyClass()).method("method");
|
||||
const HashMap = Java.type('java.util.HashMap');
|
||||
const ReflectMethodArray = Java.type('java.lang.reflect.Method[]');
|
||||
|
||||
const Byte = Java.type('java.lang.Byte');
|
||||
const EventPriority = [];
|
||||
EventPriority[event.EventPriority.LOWEST] = Byte.valueOf(-64);
|
||||
EventPriority[event.EventPriority.LOW] = -Byte.valueOf(32);
|
||||
EventPriority[event.EventPriority.NORMAL] = Byte.valueOf(0);
|
||||
EventPriority[event.EventPriority.HIGH] = Byte.valueOf(32);
|
||||
EventPriority[event.EventPriority.HIGHEST] = Byte.valueOf(64);
|
||||
|
||||
/**
|
||||
* Bungee Event Impl
|
||||
*/
|
||||
@injectable()
|
||||
export class BungeeEvent extends event.Event {
|
||||
@inject(plugin.PluginInstance)
|
||||
private pluginInstance: any;
|
||||
private pluginManager = Bungee.getPluginManager()
|
||||
|
||||
// EventBus
|
||||
private eventBus: any;
|
||||
// private final Lock lock = new ReentrantLock();
|
||||
private lock: any;
|
||||
// private final Map<Class<?>, Map<Byte, Map<Object, Method[]>>> byListenerAndPriority = new HashMap<>();
|
||||
private byListenerAndPriority: any;
|
||||
// bakeHandlers(Class<?> eventClass)
|
||||
private bakeHandlers: any;
|
||||
|
||||
constructor() {
|
||||
super('net/md_5/bungee/api/event');
|
||||
}
|
||||
|
||||
@postConstruct()
|
||||
init() {
|
||||
this.eventBus = reflect.on(this.pluginManager).get('eventBus').get();
|
||||
this.lock = reflect.on(this.eventBus).get('lock').get()
|
||||
this.byListenerAndPriority = reflect.on(this.eventBus).get('byListenerAndPriority').get();
|
||||
this.bakeHandlers = reflect.accessible(reflect.on(this.eventBus).method("bakeHandlers"));
|
||||
}
|
||||
|
||||
isValidEvent(clazz: any): boolean {
|
||||
//继承于 net.md_5.bungee.api.plugin.Event
|
||||
return Event.class.isAssignableFrom(clazz) &&
|
||||
// 访问符为Public
|
||||
Modifier.isPublic(clazz.getModifiers()) &&
|
||||
// 不是抽象类
|
||||
!Modifier.isAbstract(clazz.getModifiers());
|
||||
}
|
||||
|
||||
register(eventCls: any, exec: Function, priority: event.EventPriority = event.EventPriority.NORMAL, ignoreCancel: boolean = true) {
|
||||
this.lock.lock()
|
||||
try {
|
||||
// private final Map<类, Map<优先级, Map<监听器, 方法[]>>> byListenerAndPriority = new HashMap<>();
|
||||
// this.byListenerAndPriority.put(eventCls)
|
||||
// Map<优先级, Map<监听器, 方法[]>>
|
||||
let prioritiesMap = this.byListenerAndPriority.get(eventCls);
|
||||
if (prioritiesMap == null) {
|
||||
prioritiesMap = new HashMap();
|
||||
this.byListenerAndPriority.put(eventCls, prioritiesMap);
|
||||
}
|
||||
// Map<监听器, 方法[]>
|
||||
let currentPriorityMap = prioritiesMap.get(EventPriority[priority]);
|
||||
if (currentPriorityMap == null) {
|
||||
currentPriorityMap = new HashMap();
|
||||
prioritiesMap.put(EventPriority[priority], currentPriorityMap);
|
||||
}
|
||||
let listener = new ProxyClass(ScriptEngineContextHolder.getEngine(), "exec(args)", { exec, priority: EventPriority[priority] })
|
||||
// 方法[]
|
||||
let methods = new ReflectMethodArray(1);
|
||||
methods[0] = ProxyMethod;
|
||||
currentPriorityMap.put(listener, methods);
|
||||
this.bakeHandlers.invoke(this.eventBus, eventCls);
|
||||
return listener;
|
||||
} catch (ex) {
|
||||
console.ex(ex)
|
||||
} finally {
|
||||
this.lock.unlock()
|
||||
}
|
||||
}
|
||||
|
||||
unregister(eventCls: any, listener: any): void {
|
||||
this.lock.lock()
|
||||
try {
|
||||
// private final Map<类, Map<优先级, Map<监听器, 方法[]>>> byListenerAndPriority = new HashMap<>();
|
||||
// Map<优先级, Map<监听器, 方法[]>>
|
||||
let prioritiesMap = this.byListenerAndPriority.get(eventCls);
|
||||
if (prioritiesMap != null) {
|
||||
let bindings = reflect.on(listener).get("bindings").get();
|
||||
let priority = bindings["priority"];
|
||||
// Map<监听器, 方法[]>
|
||||
let currentPriorityMap = prioritiesMap.get(priority);
|
||||
if (currentPriorityMap != null) {
|
||||
currentPriorityMap.remove(listener);
|
||||
if (currentPriorityMap.isEmpty()) {
|
||||
prioritiesMap.remove(priority);
|
||||
}
|
||||
}
|
||||
if (prioritiesMap.isEmpty()) {
|
||||
this.byListenerAndPriority.remove(eventCls);
|
||||
}
|
||||
this.bakeHandlers.invoke(this.eventBus, eventCls);
|
||||
}
|
||||
} catch (ex) {
|
||||
console.ex(ex)
|
||||
} finally {
|
||||
this.lock.unlock()
|
||||
}
|
||||
}
|
||||
}
|
||||
18
packages/bungee/src/index.ts
Normal file
18
packages/bungee/src/index.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
/// <reference types="@ms/types/dist/typings/bungee" />
|
||||
|
||||
import { server, command, event, task } from '@ms/api'
|
||||
import { Container } from '@ms/container'
|
||||
|
||||
import { BungeeConsole } from './console';
|
||||
import { BungeeEvent } from './event';
|
||||
import { BungeeServer } from './server';
|
||||
import { BungeeCommand } from './command';
|
||||
import { BungeeTaskManager } from './task';
|
||||
|
||||
export default function BungeeImpl(container: Container) {
|
||||
container.bind(server.Console).toConstantValue(BungeeConsole);
|
||||
container.bind(event.Event).to(BungeeEvent).inSingletonScope();
|
||||
container.bind(server.Server).to(BungeeServer).inSingletonScope();
|
||||
container.bind(command.Command).to(BungeeCommand).inSingletonScope();
|
||||
container.bind(task.TaskManager).to(BungeeTaskManager).inSingletonScope();
|
||||
}
|
||||
35
packages/bungee/src/server.ts
Normal file
35
packages/bungee/src/server.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import { server } from '@ms/api'
|
||||
import { injectable } from '@ms/container';
|
||||
|
||||
let Bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy();
|
||||
|
||||
@injectable()
|
||||
export class BungeeServer implements server.Server {
|
||||
getPlayer(name: string) {
|
||||
return Bungee.getPlayer(name);
|
||||
}
|
||||
getVersion(): string {
|
||||
return Bungee.getVersion()
|
||||
}
|
||||
getOnlinePlayers() {
|
||||
return Bungee.getPlayers()
|
||||
}
|
||||
getConsoleSender() {
|
||||
return Bungee.getConsole()
|
||||
}
|
||||
getService(service: string) {
|
||||
throw new Error("Method not implemented.");
|
||||
}
|
||||
dispatchCommand(sender: string | any, command: string): boolean {
|
||||
if (typeof sender === 'string') {
|
||||
sender = this.getPlayer(sender)
|
||||
}
|
||||
return Bungee.getPluginManager().dispatchCommand(sender, command)
|
||||
}
|
||||
dispatchConsoleCommand(command: string): boolean {
|
||||
return Bungee.getPluginManager().dispatchCommand(Bungee.getConsole(), command)
|
||||
}
|
||||
sendJson(sender: string | any, json: string): void {
|
||||
throw new Error("Method not implemented.");
|
||||
}
|
||||
}
|
||||
33
packages/bungee/src/task.ts
Normal file
33
packages/bungee/src/task.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { task, plugin } from '@ms/api'
|
||||
import { injectable, inject } from '@ms/container';
|
||||
|
||||
var Runnable = Java.type('java.lang.Runnable')
|
||||
let TimeUnit = Java.type('java.util.concurrent.TimeUnit')
|
||||
|
||||
@injectable()
|
||||
export class BungeeTaskManager implements task.TaskManager {
|
||||
@inject(plugin.PluginInstance)
|
||||
private pluginInstance: any;
|
||||
|
||||
create(func: Function): task.Task {
|
||||
if (Object.prototype.toString.call(func) !== "[object Function]") { throw TypeError('第一个参数 Task 必须为 function !'); };
|
||||
return new BungeeTask(this.pluginInstance, func);
|
||||
}
|
||||
callSyncMethod(func: Function): any {
|
||||
return func();
|
||||
}
|
||||
}
|
||||
|
||||
export class BungeeTask extends task.Task {
|
||||
submit(): task.Cancelable {
|
||||
let run = new Runnable({ run: () => this.run() })
|
||||
if (this.isAsync) {
|
||||
return this.plugin.getProxy().getScheduler().runAsync(this.plugin, run)
|
||||
}
|
||||
if (this.interval) {
|
||||
return this.plugin.getProxy().getScheduler().schedule(this.plugin, run, this.laterTime, this.interval, TimeUnit.MILLISECONDS)
|
||||
} else {
|
||||
return this.plugin.getProxy().getScheduler().schedule(this.plugin, run, this.laterTime, TimeUnit.MILLISECONDS)
|
||||
}
|
||||
}
|
||||
}
|
||||
8
packages/bungee/tsconfig.json
Normal file
8
packages/bungee/tsconfig.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"baseUrl": "src",
|
||||
"outDir": "dist",
|
||||
"allowJs": true
|
||||
}
|
||||
}
|
||||
35
packages/client/package.json
Normal file
35
packages/client/package.json
Normal file
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"private": true,
|
||||
"name": "@ms/client",
|
||||
"version": "0.2.1",
|
||||
"description": "MiaoScript client package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
"minecraft",
|
||||
"bukkit",
|
||||
"sponge"
|
||||
],
|
||||
"author": "MiaoWoo <admin@yumc.pw>",
|
||||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"publishConfig": {
|
||||
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "ts-node-dev --respawn --debounce=1500 src/index.ts",
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"start": "node dist/index.js",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"minecraft-protocol": "^1.11.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@nestjs/cli": "^6.14.2",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.8.2"
|
||||
}
|
||||
}
|
||||
101
packages/client/src/color.ts
Normal file
101
packages/client/src/color.ts
Normal file
@@ -0,0 +1,101 @@
|
||||
class MessagePart {
|
||||
text: string
|
||||
color: string
|
||||
clickEvent: MessagePartEvent
|
||||
hoverEvent: MessagePartEvent
|
||||
translate: string
|
||||
with: MessagePart[]
|
||||
extra: MessagePart[]
|
||||
}
|
||||
|
||||
class MessagePartEvent {
|
||||
action: string
|
||||
value: string
|
||||
}
|
||||
|
||||
var colorMap = []
|
||||
colorMap['0'] = '38;5;0'
|
||||
colorMap['1'] = '38;5;4'
|
||||
colorMap['2'] = '38;5;2'
|
||||
colorMap['3'] = '38;5;6'
|
||||
colorMap['4'] = '38;5;1'
|
||||
colorMap['5'] = '38;5;5'
|
||||
colorMap['6'] = '38;5;3'
|
||||
colorMap['7'] = '38;5;7'
|
||||
colorMap['8'] = '38;5;8'
|
||||
colorMap['9'] = '38;5;12'
|
||||
colorMap['a'] = '38;5;10'
|
||||
colorMap['b'] = '38;5;14'
|
||||
colorMap['c'] = '38;5;9'
|
||||
colorMap['d'] = '38;5;13'
|
||||
colorMap['e'] = '38;5;11'
|
||||
colorMap['f'] = '38;5;15'
|
||||
colorMap['r'] = '0'
|
||||
colorMap['l'] = '1'
|
||||
colorMap['n'] = '4'
|
||||
var regexMap = []
|
||||
for (const c in colorMap) {
|
||||
regexMap[colorMap[c]] = new RegExp(`§${c}`, "g")
|
||||
}
|
||||
function mcColor2ANSI(str) {
|
||||
for (const regex in regexMap) {
|
||||
str = str.replace(regexMap[regex], `\u001b[${regex}m`)
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
let jsonColorMap = {
|
||||
"black": '0',
|
||||
"dark_blue": '1',
|
||||
"dark_green": '2',
|
||||
"dark_aqua": '3',
|
||||
"dark_red": '4',
|
||||
"dark_purple": '5',
|
||||
"gold": '6',
|
||||
"gray": '7',
|
||||
"dark_gray": '8',
|
||||
"blue": '9',
|
||||
"green": 'a',
|
||||
"aqua": 'b',
|
||||
"red": 'c',
|
||||
"light_purple": 'd',
|
||||
"yellow": 'e',
|
||||
"white": 'f',
|
||||
"obfuscated": 'k',
|
||||
"bold": 'l',
|
||||
"strikethrough": 'm',
|
||||
"underline": 'n',
|
||||
"italic": 'o',
|
||||
"reset": 'r',
|
||||
};
|
||||
|
||||
function json2text(json: MessagePart): string {
|
||||
let temp = "";
|
||||
if (json.color) {
|
||||
temp += `§${jsonColorMap[json.color]}`
|
||||
}
|
||||
temp += json.text || json.translate || ''
|
||||
if (json.extra) {
|
||||
json.extra.forEach((ext) => {
|
||||
temp += json2text(ext)
|
||||
})
|
||||
}
|
||||
return temp += '§r'
|
||||
}
|
||||
|
||||
function $(input: any) {
|
||||
if (typeof input === "string") {
|
||||
input = JSON.parse(input)
|
||||
}
|
||||
input = json2text(input) + '§r'
|
||||
if (input.startsWith('§卐')) {
|
||||
input = input.substring(2)
|
||||
}
|
||||
return mcColor2ANSI(input)
|
||||
}
|
||||
|
||||
export {
|
||||
json2text,
|
||||
mcColor2ANSI,
|
||||
$
|
||||
}
|
||||
27
packages/client/src/event.ts
Normal file
27
packages/client/src/event.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { $ } from './color'
|
||||
|
||||
export function attachEvents(client) {
|
||||
client.on('chat', (packet) => {
|
||||
// Listen for chat messages and echo them back.
|
||||
var jsonMsg = JSON.parse(packet.message);
|
||||
console.log($(jsonMsg))
|
||||
})
|
||||
client.on('state', (newState, oldState) => {
|
||||
console.log('Client Change State', oldState, 'to', newState)
|
||||
let targetServer = process.argv[3]
|
||||
if (newState == "play" && targetServer) {
|
||||
setTimeout(() => {
|
||||
client.write('chat', {
|
||||
message: '/server ' + targetServer
|
||||
})
|
||||
}, 3000)
|
||||
}
|
||||
})
|
||||
client.on('update_health', (packet) => {
|
||||
if (packet.health <= 0) {
|
||||
console.log("Player Dead Auto Respawn...")
|
||||
client.write('client_command', { payload: 0 })
|
||||
} else if (packet.health > 0) {
|
||||
}
|
||||
})
|
||||
}
|
||||
14
packages/client/src/forge.ts
Normal file
14
packages/client/src/forge.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
export function attachForge(client) {
|
||||
client.on('custom_payload', function(packet) {
|
||||
if (packet.channel === 'FML|HS') {
|
||||
client.write('custom_payload', {
|
||||
channel: 'FML|HS',
|
||||
data: Buffer.of(0x01, 0x02)
|
||||
});
|
||||
client.write('custom_payload', {
|
||||
channel: 'FML|HS',
|
||||
data: Buffer.of(0x02, 0x00)
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
61
packages/client/src/index.ts
Normal file
61
packages/client/src/index.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import { createInterface } from 'readline'
|
||||
import { createClient } from 'minecraft-protocol'
|
||||
|
||||
import { attachForge } from './forge'
|
||||
import { attachEvents } from './event'
|
||||
|
||||
let username = process.argv[2] || 'Mr_jtb'
|
||||
let client = createConnection('192.168.2.5', 25577, username)
|
||||
|
||||
function createConnection(host: string, port: number, username: string) {
|
||||
let client = createClient({
|
||||
version: '1.12.2',
|
||||
host,
|
||||
port,
|
||||
username,
|
||||
skipValidation: true
|
||||
})
|
||||
|
||||
attachForge(client)
|
||||
attachEvents(client)
|
||||
return client;
|
||||
}
|
||||
|
||||
client.on('end', (resone) => {
|
||||
console.log("Client End Resone:", resone)
|
||||
client = createConnection('192.168.2.5', 25577, username)
|
||||
})
|
||||
|
||||
const rl = createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stdout,
|
||||
terminal: true,
|
||||
prompt: ''
|
||||
})
|
||||
|
||||
rl.on('line', function(line) {
|
||||
switch (line) {
|
||||
case "":
|
||||
break;
|
||||
case "/respawn":
|
||||
client.write('client_command', { payload: 0 })
|
||||
// client.write("respawn", {
|
||||
|
||||
// })
|
||||
break;
|
||||
case "//reco":
|
||||
client.end("")
|
||||
client = createConnection('192.168.2.5', 25577, username)
|
||||
break;
|
||||
case "//quit":
|
||||
console.info('Disconnected')
|
||||
client.end("")
|
||||
break;
|
||||
case "//end":
|
||||
console.info('Forcibly ended client')
|
||||
process.exit(0)
|
||||
default:
|
||||
client.write('chat', { message: line })
|
||||
}
|
||||
rl.prompt()
|
||||
})
|
||||
7
packages/client/tsconfig.json
Normal file
7
packages/client/tsconfig.json
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"baseUrl": "src",
|
||||
"outDir": "dist"
|
||||
}
|
||||
}
|
||||
4
packages/common/.gitignore
vendored
4
packages/common/.gitignore
vendored
@@ -1,4 +0,0 @@
|
||||
/node_modules
|
||||
/dist
|
||||
/package-lock.json
|
||||
/yarn.lock
|
||||
@@ -1,22 +0,0 @@
|
||||
src
|
||||
test
|
||||
typings
|
||||
bundled
|
||||
build
|
||||
coverage
|
||||
docs
|
||||
wiki
|
||||
gulpfile.js
|
||||
bower.json
|
||||
karma.conf.js
|
||||
tsconfig.json
|
||||
typings.json
|
||||
CONTRIBUTING.md
|
||||
ISSUE_TEMPLATE.md
|
||||
PULL_REQUEST_TEMPLATE.md
|
||||
tslint.json
|
||||
wallaby.js
|
||||
.travis.yml
|
||||
.gitignore
|
||||
.vscode
|
||||
type_definitions
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ms/common",
|
||||
"version": "0.0.0",
|
||||
"version": "0.2.1",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -13,20 +13,22 @@
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"publishConfig": {
|
||||
"registry": "https://repo.yumc.pw/repository/npm/"
|
||||
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
|
||||
},
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "npx tsc --watch",
|
||||
"build": "yarn clean && npx tsc",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.0",
|
||||
"typescript": "^3.6.2"
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.8.2"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ms/nashorn": "^0.0.0"
|
||||
}
|
||||
"@ms/nashorn": "^0.2.1",
|
||||
"@ms/ployfill": "^0.2.1"
|
||||
},
|
||||
"gitHead": "562e2d00175c9d3a99c8b672aa07e6d92706a027"
|
||||
}
|
||||
|
||||
@@ -12,8 +12,8 @@ const StandardCopyOption = Java.type("java.nio.file.StandardCopyOption");
|
||||
/**
|
||||
* 用文件分割符合并路径
|
||||
*/
|
||||
export function concat() {
|
||||
return Array.prototype.join.call(arguments, separatorChar);
|
||||
export function concat(...args: string[]) {
|
||||
return args.join(separatorChar);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -23,12 +23,12 @@ export function concat() {
|
||||
* @returns {*}
|
||||
*/
|
||||
export function file(...opts: any[]): any {
|
||||
if (!arguments[0]) {
|
||||
if (!opts[0]) {
|
||||
console.warn("文件名称不得为 undefined 或者 null !");
|
||||
}
|
||||
switch (arguments.length) {
|
||||
switch (opts.length) {
|
||||
case 1:
|
||||
var f = arguments[0];
|
||||
var f = opts[0];
|
||||
if (f instanceof File) {
|
||||
return f;
|
||||
}
|
||||
@@ -40,7 +40,7 @@ export function file(...opts: any[]): any {
|
||||
}
|
||||
break;
|
||||
default:
|
||||
return new File(file(arguments[0]), arguments[1]);
|
||||
return new File(file(opts[0]), opts[1]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,7 +48,7 @@ export function file(...opts: any[]): any {
|
||||
* 创建目录
|
||||
* @param path
|
||||
*/
|
||||
export function mkdirs(path) {
|
||||
export function mkdirs(path: any) {
|
||||
// noinspection JSUnresolvedVariable
|
||||
file(path).parentFile.mkdirs();
|
||||
}
|
||||
@@ -57,7 +57,7 @@ export function mkdirs(path) {
|
||||
* 创建文件
|
||||
* @param file
|
||||
*/
|
||||
export function create(path) {
|
||||
export function create(path: any) {
|
||||
var f = file(path);
|
||||
if (!f.exists()) {
|
||||
mkdirs(f);
|
||||
@@ -70,7 +70,7 @@ export function create(path) {
|
||||
* @param file
|
||||
* @returns {*}
|
||||
*/
|
||||
export function path(f) {
|
||||
export function path(f: any) {
|
||||
return file(f).canonicalPath;
|
||||
}
|
||||
|
||||
@@ -80,7 +80,7 @@ export function path(f) {
|
||||
* @param target 目标文件
|
||||
* @param override 是否覆盖
|
||||
*/
|
||||
export function copy(inputStream, target, override) {
|
||||
export function copy(inputStream: any, target: any, override: any) {
|
||||
Files.copy(inputStream, target.toPath(), StandardCopyOption[override ? 'REPLACE_EXISTING' : 'ATOMIC_MOVE']);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,155 +1,44 @@
|
||||
'use strict';
|
||||
/**
|
||||
* HTTP 网络类
|
||||
* Created by 蒋天蓓 on 2017/2/9 0009.
|
||||
*/
|
||||
import '@ms/api'
|
||||
|
||||
/*global Java, base, module, exports, require, __FILE__*/
|
||||
export type Method =
|
||||
| 'get' | 'GET'
|
||||
| 'delete' | 'DELETE'
|
||||
| 'head' | 'HEAD'
|
||||
| 'options' | 'OPTIONS'
|
||||
| 'post' | 'POST'
|
||||
| 'put' | 'PUT'
|
||||
| 'patch' | 'PATCH'
|
||||
|
||||
var URL = Java.type("java.net.URL");
|
||||
var UUID = Java.type("java.util.UUID");
|
||||
var System = Java.type("java.lang.System");
|
||||
var Files = Java.type("java.nio.file.Files");
|
||||
var Paths = Java.type("java.nio.file.Paths");
|
||||
var JavaString = Java.type("java.lang.String");
|
||||
var SecureRandom = Java.type("java.security.SecureRandom");
|
||||
|
||||
var SSLContext = Java.type("javax.net.ssl.SSLContext");
|
||||
var HttpsURLConnection = Java.type("javax.net.ssl.HttpsURLConnection");
|
||||
|
||||
var HostnameVerifier = Java.type("javax.net.ssl.HostnameVerifier");
|
||||
var X509TrustManager = Java.type("javax.net.ssl.X509TrustManager");
|
||||
|
||||
// noinspection JSUnusedGlobalSymbols,JSUnusedLocalSymbols
|
||||
var TrustAnyHostnameVerifier = new HostnameVerifier({
|
||||
verify: function(hostname, session) {
|
||||
return true;
|
||||
}
|
||||
});
|
||||
|
||||
var SSLSocketFactory = function initSSLSocketFactory() {
|
||||
var sslContext = SSLContext.getInstance("TLS");
|
||||
// noinspection JSUnusedGlobalSymbols
|
||||
sslContext.init(null, [new X509TrustManager({
|
||||
getAcceptedIssuers: function() {
|
||||
return null;
|
||||
},
|
||||
checkClientTrusted: function(chain, authType) {
|
||||
},
|
||||
checkServerTrusted: function(chain, authType) {
|
||||
}
|
||||
})], new SecureRandom());
|
||||
return sslContext.getSocketFactory();
|
||||
}();
|
||||
|
||||
var config = {
|
||||
Charset: 'UTF-8',
|
||||
ConnectTimeout: 10000,
|
||||
ReadTimeout: 10000,
|
||||
Debug: false
|
||||
};
|
||||
|
||||
function open(url, method, header) {
|
||||
// conn.setRequestProperty
|
||||
var conn = new URL(url).openConnection();
|
||||
if (conn instanceof HttpsURLConnection) {
|
||||
conn.setHostnameVerifier(TrustAnyHostnameVerifier);
|
||||
conn.setSSLSocketFactory(SSLSocketFactory);
|
||||
}
|
||||
conn.setRequestMethod(method);
|
||||
conn.setDoOutput(true);
|
||||
conn.setDoInput(true);
|
||||
conn.setConnectTimeout(config.ConnectTimeout);
|
||||
conn.setReadTimeout(config.ReadTimeout);
|
||||
if (header) {
|
||||
for (var key in header) {
|
||||
// noinspection JSUnfilteredForInLoop
|
||||
conn.setRequestProperty(key, header[key]);
|
||||
}
|
||||
}
|
||||
return conn;
|
||||
interface RequestConfig {
|
||||
url?: string;
|
||||
method?: Method;
|
||||
headers?: { [key: string]: string };
|
||||
params?: { [key: string]: string };
|
||||
data?: any;
|
||||
}
|
||||
|
||||
function buildUrl(url, params) {
|
||||
if (params && Object.keys(params).length > 0) {
|
||||
var queryStart = url.indexOf('?');
|
||||
if (queryStart === -1) {
|
||||
url += '?';
|
||||
}
|
||||
return url += object2URLSearchParams(params);
|
||||
function request(config: RequestConfig) {
|
||||
// @ts-ignore
|
||||
let xhr = new XMLHttpRequest();
|
||||
xhr.open(config.method, config.url, false);
|
||||
for (const header in config.headers) {
|
||||
xhr.setRequestHeader(header, config.headers[header]);
|
||||
}
|
||||
return url;
|
||||
xhr.send(config.data);
|
||||
if ((xhr.getResponseHeader("Content-Type") + '').indexOf('application/json') != -1) {
|
||||
xhr.responseType = "json"
|
||||
}
|
||||
return xhr.get();
|
||||
}
|
||||
|
||||
function request(config) {
|
||||
var conn = open(buildUrl(config.url, config.query), config.method, config.header);
|
||||
try {
|
||||
conn.connect();
|
||||
var data = config.data;
|
||||
if (data) {
|
||||
var out = conn.getOutputStream();
|
||||
if (typeof data === "object") {
|
||||
var type = config.header['Content-Type'];
|
||||
switch (type) {
|
||||
case "application/x-www-form-urlencoded":
|
||||
data = object2URLSearchParams(data);
|
||||
break;
|
||||
default:
|
||||
data = JSON.stringify(data)
|
||||
}
|
||||
}
|
||||
out.write(new JavaString(data).getBytes(config.Charset));
|
||||
out.flush();
|
||||
out.close();
|
||||
}
|
||||
return response(conn);
|
||||
} finally {
|
||||
conn.disconnect();
|
||||
function _proxy(method: Method) {
|
||||
return function(url: string, data?: any, config?: RequestConfig) {
|
||||
return request({ url, method, data, ...config });
|
||||
}
|
||||
}
|
||||
|
||||
function response(conn) {
|
||||
var temp = Paths.get(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
|
||||
Files.copy(conn.getInputStream(), temp);
|
||||
var result = new JavaString(Files.readAllBytes(temp), config.Charset);
|
||||
var tempFile = temp.toFile();
|
||||
tempFile.delete() || tempFile.deleteOnExit();
|
||||
return result;
|
||||
export default {
|
||||
get: _proxy('GET'),
|
||||
post: _proxy('POST'),
|
||||
request
|
||||
}
|
||||
|
||||
function object2URLSearchParams(params) {
|
||||
var temp: string[] = [];
|
||||
for (var key in params) {
|
||||
temp.push(`${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
|
||||
}
|
||||
return temp.join('&')
|
||||
}
|
||||
|
||||
var http = {
|
||||
config: config,
|
||||
request: request
|
||||
};
|
||||
|
||||
['GET', 'DELETE', 'HEAD', 'OPTIONS'].forEach(function(method) {
|
||||
http[method.toLowerCase()] = function __likeGet__(url, data, config = {}) {
|
||||
return this.request({
|
||||
...config,
|
||||
url: url,
|
||||
method: method,
|
||||
query: data
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
['POST', 'PUT', 'PATCH'].forEach(function(method) {
|
||||
http[method.toLowerCase()] = function __likePost__(url, data, config) {
|
||||
return this.request({
|
||||
...config,
|
||||
url: url,
|
||||
method: method,
|
||||
data: data
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export = http;
|
||||
|
||||
@@ -1,24 +1,27 @@
|
||||
import '@ms/core'
|
||||
/**
|
||||
* 反射工具类
|
||||
* Created by 蒋天蓓 on 2017/2/9 0009.
|
||||
* Created by MiaoWoo on 2017/2/9 0009.
|
||||
*/
|
||||
var JavaClass = Java.type('java.lang.Class');
|
||||
var JavaObject = Java.type('java.lang.Object')
|
||||
var NoSuchFieldException = Java.type('java.lang.NoSuchFieldException');
|
||||
var methodCache = [];
|
||||
const JavaClass = Java.type('java.lang.Class');
|
||||
const JavaObject = Java.type('java.lang.Object')
|
||||
const NoSuchFieldException = Java.type('java.lang.NoSuchFieldException');
|
||||
const methodCache = [];
|
||||
|
||||
class Reflect {
|
||||
private obj: any;
|
||||
private class: any
|
||||
|
||||
constructor(obj: any) {
|
||||
// if (obj === undefined || obj === null) { throw Error(`reflect object can't be ${obj}!`) }
|
||||
if (obj instanceof JavaClass) {
|
||||
this.obj = null;
|
||||
this.class = obj;
|
||||
} else {
|
||||
this.obj = obj;
|
||||
this.class = obj.class;
|
||||
if (obj !== null && obj !== undefined && obj.class) {
|
||||
this.class = obj.class;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,10 +33,10 @@ class Reflect {
|
||||
return Java.from(declaredMethods(this.class));
|
||||
}
|
||||
|
||||
field(name) {
|
||||
field(name): Reflect {
|
||||
try {
|
||||
// Try getting a public field
|
||||
var field = this.class.field(name);
|
||||
let field = this.class.field(name);
|
||||
return on(field.get(this.obj));
|
||||
} catch (ex) {
|
||||
// Try again, getting a non-public field
|
||||
@@ -41,36 +44,34 @@ class Reflect {
|
||||
}
|
||||
};
|
||||
|
||||
fields(declared) {
|
||||
fields(declared = false) {
|
||||
return Java.from(declared ? this.class.declaredFields : this.class.fields);
|
||||
}
|
||||
|
||||
values(declared) {
|
||||
var cache = {};
|
||||
var feds = declared ? this.class.declaredFields : this.class.fields;
|
||||
Java.from(feds).forEach(function(fed) {
|
||||
cache[fed.name] = this.field(fed.name).get();
|
||||
}.bind(this))
|
||||
values(declared = false) {
|
||||
let cache = {};
|
||||
this.fields(declared).forEach(fed => cache[fed.name] = this.field(fed.name).get())
|
||||
return cache;
|
||||
}
|
||||
|
||||
call(...args) {
|
||||
var params = args.slice(1);
|
||||
var method = declaredMethod(this.class, args[0], types(params));
|
||||
return on(method.invoke(this.get(), params));
|
||||
call(...args): Reflect {
|
||||
let params = args.slice(1);
|
||||
let method = accessible(declaredMethod(this.class, args[0], types(params)));
|
||||
let result = method.invoke(this.get(), params);
|
||||
return result && on(result);
|
||||
};
|
||||
|
||||
get(...args) {
|
||||
get(...args): Reflect | any {
|
||||
return args.length === 1 ? this.field(args[0]) : this.obj;
|
||||
};
|
||||
|
||||
// noinspection JSUnusedGlobalSymbols
|
||||
set(name, value) {
|
||||
set(name, value): Reflect {
|
||||
accessible(declaredField(this.class, name)).set(this.obj, value);
|
||||
return this;
|
||||
};
|
||||
|
||||
create(...args) {
|
||||
create(...args): Reflect {
|
||||
return on(declaredConstructor(this.class, args).newInstance(args));
|
||||
};
|
||||
}
|
||||
@@ -82,7 +83,7 @@ function types(values, def?) {
|
||||
if (values === null) {
|
||||
return [];
|
||||
}
|
||||
var result = [];
|
||||
let result: any[] = [];
|
||||
values.forEach(t => result.push((t || def) ? JavaObject.class : t instanceof JavaClass ? t : t.class));
|
||||
return result;
|
||||
}
|
||||
@@ -98,7 +99,7 @@ function accessible(accessible) {
|
||||
}
|
||||
|
||||
function declaredConstructor(clazz, param) {
|
||||
var constructor;
|
||||
let constructor;
|
||||
try {
|
||||
constructor = clazz.getDeclaredConstructor(types(param));
|
||||
} catch (ex) {
|
||||
@@ -112,16 +113,17 @@ function declaredConstructor(clazz, param) {
|
||||
}
|
||||
|
||||
function declaredField(clazz, name) {
|
||||
var field = null;
|
||||
if (!clazz) { throw Error(`target class can't be ${clazz}!`) }
|
||||
let target = clazz;
|
||||
let field = null;
|
||||
// noinspection JSUnresolvedVariable
|
||||
while (clazz !== JavaObject.class) {
|
||||
while (target !== JavaObject.class) {
|
||||
try {
|
||||
field = clazz.getDeclaredField(name);
|
||||
if (field !== null) {
|
||||
break;
|
||||
}
|
||||
field = target.getDeclaredField(name);
|
||||
if (field !== null) { break; }
|
||||
} catch (e) {
|
||||
clazz = clazz.getSuperclass();
|
||||
if (target === undefined) { break; }
|
||||
target = target.getSuperclass();
|
||||
}
|
||||
}
|
||||
if (field === null) {
|
||||
@@ -131,12 +133,21 @@ function declaredField(clazz, name) {
|
||||
}
|
||||
|
||||
function declaredMethod(clazz, name, clazzs) {
|
||||
var key = clazz.name + '.' + name + ':' + (clazzs || []).join(':');
|
||||
let key = clazz.name + '.' + name + ':' + (clazzs || []).join(':');
|
||||
if (!methodCache[key]) {
|
||||
try {
|
||||
methodCache[key] = clazz.getMethod(name, clazzs);
|
||||
} catch (ex) {
|
||||
methodCache[key] = clazz.getDeclaredMethod(name, clazzs);
|
||||
try {
|
||||
methodCache[key] = clazz.getDeclaredMethod(name, clazzs);
|
||||
} catch (ex) {
|
||||
for (const m of Java.from(declaredMethods(clazz))) {
|
||||
if (m.name == name) {
|
||||
methodCache[key] = m;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return methodCache[key];
|
||||
@@ -146,21 +157,21 @@ function declaredMethods(clazz) {
|
||||
return clazz.declaredMethods;
|
||||
}
|
||||
|
||||
var classMethodsCache = [];
|
||||
let classMethodsCache: any[] = [];
|
||||
|
||||
function mapToObject(javaObj) {
|
||||
if (!javaObj || !javaObj.class) { throw new TypeError(`参数 ${javaObj} 不是一个Java对象!`) }
|
||||
var target = {};
|
||||
let target = {};
|
||||
getJavaObjectMethods(javaObj).forEach(t => mapMethod(target, javaObj, t));
|
||||
return target;
|
||||
}
|
||||
|
||||
function getJavaObjectMethods(javaObj) {
|
||||
var className = javaObj.class.name;
|
||||
let className = javaObj.class.name;
|
||||
if (!classMethodsCache[className]) {
|
||||
var names = [];
|
||||
var methods = javaObj.class.methods;
|
||||
for (var i in methods) {
|
||||
let names: any[] = [];
|
||||
let methods = javaObj.class.methods;
|
||||
for (let i in methods) {
|
||||
names.push(methods[i].name);
|
||||
}
|
||||
classMethodsCache[className] = names;
|
||||
@@ -179,7 +190,7 @@ function mapMethod(target, source, name) {
|
||||
}
|
||||
|
||||
function on(obj) {
|
||||
if (!obj || !obj.class) { throw new TypeError(`参数 ${obj} 不是一个Java对象!`) }
|
||||
// if (!obj || !obj.class) { throw new TypeError(`参数 ${obj} 不是一个Java对象!`) }
|
||||
return new Reflect(obj);
|
||||
}
|
||||
|
||||
|
||||
109
packages/common/src/tellraw.ts
Normal file
109
packages/common/src/tellraw.ts
Normal file
@@ -0,0 +1,109 @@
|
||||
class ChatMessagePart {
|
||||
private internal: any = {}
|
||||
|
||||
get text() {
|
||||
return this.internal.text
|
||||
}
|
||||
set text(text: string) {
|
||||
this.internal.text = text
|
||||
}
|
||||
|
||||
click(action: string, value: string) {
|
||||
this.internal.clickEvent = { action, value }
|
||||
}
|
||||
|
||||
hover(action: string, value: string) {
|
||||
this.internal.hoverEvent = { action, value }
|
||||
}
|
||||
|
||||
convert() {
|
||||
return this.internal;
|
||||
}
|
||||
}
|
||||
|
||||
class Tellraw {
|
||||
static duplicateChar = '§卐'
|
||||
static create() {
|
||||
return new Tellraw().then(Tellraw.duplicateChar);
|
||||
}
|
||||
|
||||
private cache: string = '';
|
||||
private parts = [new ChatMessagePart()];
|
||||
|
||||
then(part: ChatMessagePart | string) {
|
||||
if (typeof part === "string") {
|
||||
var newPart = new ChatMessagePart();
|
||||
newPart.text = part
|
||||
this.then(newPart);
|
||||
return this;
|
||||
}
|
||||
var last = this.latest();
|
||||
if (!last.text) {
|
||||
last.text = part.text;
|
||||
} else {
|
||||
this.parts.push(part);
|
||||
}
|
||||
this.cache = null;
|
||||
}
|
||||
|
||||
text(text: string) {
|
||||
this.latest().text = text;
|
||||
return this;
|
||||
}
|
||||
|
||||
tip(text: string) {
|
||||
this.latest().hover("show_text", text);
|
||||
return this;
|
||||
}
|
||||
|
||||
item(text: string) {
|
||||
this.latest().hover("show_item", text);
|
||||
return this;
|
||||
}
|
||||
|
||||
command(command: string) {
|
||||
this.latest().click("run_command", command);
|
||||
return this;
|
||||
}
|
||||
|
||||
suggest(url: string) {
|
||||
this.latest().click("suggest_command", url);
|
||||
return this;
|
||||
}
|
||||
|
||||
file(path: string) {
|
||||
this.latest().click("open_file", path);
|
||||
return this;
|
||||
}
|
||||
|
||||
link(url: string) {
|
||||
this.latest().click("open_url", url);
|
||||
return this;
|
||||
}
|
||||
|
||||
latest() {
|
||||
return this.parts[this.parts.length - 1];
|
||||
}
|
||||
|
||||
json() {
|
||||
if (!this.cache) {
|
||||
var temp = [];
|
||||
this.parts.forEach(t => {
|
||||
temp.push(t.convert());
|
||||
});
|
||||
this.cache = JSON.stringify(temp);
|
||||
console.trace(this.cache);
|
||||
}
|
||||
return this.cache;
|
||||
}
|
||||
|
||||
string() {
|
||||
var temp = '';
|
||||
this.parts.forEach(t => {
|
||||
temp += t.text
|
||||
});
|
||||
return temp;
|
||||
}
|
||||
}
|
||||
|
||||
export default Tellraw
|
||||
@@ -1,25 +1,30 @@
|
||||
function Template(tpl: string) {
|
||||
var match: RegExpExecArray;
|
||||
var code = ['var r=[];'];
|
||||
var re = /\{\{\s*([a-zA-Z\.\_0-9()]+)\s*\}\}/m;
|
||||
function addLine(text: string) {
|
||||
code.push('r.push(\'' + text.replace(/\'/g, '\\\'').replace(/\n/g, '\\n').replace(/\r/g, '\\r') + '\');');
|
||||
};
|
||||
while (match = re.exec(tpl)) {
|
||||
if (match.index > 0) {
|
||||
addLine(tpl.slice(0, match.index));
|
||||
class Template {
|
||||
private renderFunc: Function;
|
||||
|
||||
constructor(tpl: string) {
|
||||
var match: RegExpExecArray;
|
||||
var code = ['var r=[];'];
|
||||
var re = /\{\{\s*([a-zA-Z\.\_0-9()]+)\s*\}\}/m;
|
||||
|
||||
while (match = re.exec(tpl)) {
|
||||
if (match.index > 0) {
|
||||
this.addLine(code, tpl.slice(0, match.index));
|
||||
}
|
||||
code.push('r.push(this.' + match[1] + ');');
|
||||
tpl = tpl.substring(match.index + match[0].length);
|
||||
}
|
||||
code.push('r.push(this.' + match[1] + ');');
|
||||
tpl = tpl.substring(match.index + match[0].length);
|
||||
this.addLine(code, tpl);
|
||||
code.push('return r.join(\'\');');
|
||||
// 创建函数:
|
||||
this.renderFunc = new Function(code.join('\n'));
|
||||
}
|
||||
addLine(code: string[], text: string) {
|
||||
code.push('r.push(\'' + text.replace(/\'/g, '\\\'').replace(/\n/g, '\\n').replace(/\r/g, '\\r') + '\');');
|
||||
}
|
||||
addLine(tpl);
|
||||
code.push('return r.join(\'\');');
|
||||
// 创建函数:
|
||||
var fn = new Function(code.join('\n'));
|
||||
// 用render()调用函数并绑定this参数:
|
||||
this.render = function(model) {
|
||||
return fn.apply(model);
|
||||
};
|
||||
render(model: object) {
|
||||
return this.renderFunc.apply(model);
|
||||
}
|
||||
}
|
||||
|
||||
export = {
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"baseUrl": "src",
|
||||
"outDir": "dist",
|
||||
"declaration": true
|
||||
"outDir": "dist"
|
||||
}
|
||||
}
|
||||
29
packages/compile/package.json
Normal file
29
packages/compile/package.json
Normal file
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"name": "@ms/compile",
|
||||
"version": "0.2.1",
|
||||
"description": "MiaoScript compile package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
"minecraft",
|
||||
"bukkit",
|
||||
"sponge"
|
||||
],
|
||||
"author": "MiaoWoo <admin@yumc.pw>",
|
||||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"publishConfig": {
|
||||
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
|
||||
},
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.8.2"
|
||||
}
|
||||
}
|
||||
5
packages/compile/src/index.ts
Normal file
5
packages/compile/src/index.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
import * as ts from 'typescript'
|
||||
|
||||
let scan = ts.createScanner(ts.ScriptTarget.ES5, true, ts.LanguageVariant.Standard)
|
||||
scan.setText('let a = 1')
|
||||
scan.tryScan(() => { })
|
||||
7
packages/compile/tsconfig.json
Normal file
7
packages/compile/tsconfig.json
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"baseUrl": "src",
|
||||
"outDir": "dist"
|
||||
}
|
||||
}
|
||||
4
packages/container/.gitignore
vendored
4
packages/container/.gitignore
vendored
@@ -1,4 +0,0 @@
|
||||
/node_modules
|
||||
/dist
|
||||
/package-lock.json
|
||||
/yarn.lock
|
||||
@@ -1,22 +0,0 @@
|
||||
src
|
||||
test
|
||||
typings
|
||||
bundled
|
||||
build
|
||||
coverage
|
||||
docs
|
||||
wiki
|
||||
gulpfile.js
|
||||
bower.json
|
||||
karma.conf.js
|
||||
tsconfig.json
|
||||
typings.json
|
||||
CONTRIBUTING.md
|
||||
ISSUE_TEMPLATE.md
|
||||
PULL_REQUEST_TEMPLATE.md
|
||||
tslint.json
|
||||
wallaby.js
|
||||
.travis.yml
|
||||
.gitignore
|
||||
.vscode
|
||||
type_definitions
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ms/container",
|
||||
"version": "0.0.0",
|
||||
"version": "0.2.1",
|
||||
"description": "MiaoScript container package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -13,18 +13,18 @@
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"publishConfig": {
|
||||
"registry": "https://repo.yumc.pw/repository/npm/"
|
||||
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
|
||||
},
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "npx tsc --watch",
|
||||
"build": "yarn clean && npx tsc",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.0",
|
||||
"typescript": "^3.6.2"
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.8.2"
|
||||
},
|
||||
"dependencies": {
|
||||
"inversify-binding-decorators": "^4.0.0"
|
||||
|
||||
@@ -2,7 +2,7 @@ import { interfaces, Container } from "inversify";
|
||||
|
||||
let _container: Container;
|
||||
|
||||
const CONTAINER = Symbol.for("@ms/ioc:Container");
|
||||
const ContainerInstance = Symbol.for("@ms/ioc:Container");
|
||||
const INJECTION = Symbol.for("INJECTION");
|
||||
|
||||
function _proxyGetter(
|
||||
@@ -11,7 +11,7 @@ function _proxyGetter(
|
||||
resolve: () => any,
|
||||
doCache: boolean
|
||||
) {
|
||||
function getter() {
|
||||
function getter(this: object) {
|
||||
if (doCache && !Reflect.hasMetadata(INJECTION, this, key)) {
|
||||
Reflect.defineMetadata(INJECTION, resolve(), this, key);
|
||||
}
|
||||
@@ -22,7 +22,7 @@ function _proxyGetter(
|
||||
}
|
||||
}
|
||||
|
||||
function setter(newVal: any) {
|
||||
function setter(this: object, newVal: any) {
|
||||
Reflect.defineMetadata(INJECTION, newVal, this, key);
|
||||
}
|
||||
|
||||
@@ -35,12 +35,12 @@ function _proxyGetter(
|
||||
}
|
||||
|
||||
function initContainer(container: Container) {
|
||||
Reflect.defineMetadata(CONTAINER, container, Reflect);
|
||||
Reflect.defineMetadata(ContainerInstance, container, Reflect);
|
||||
_container = container;
|
||||
}
|
||||
|
||||
function getContainer(): Container {
|
||||
return _container || Reflect.getMetadata(CONTAINER, Reflect)
|
||||
return _container || Reflect.getMetadata(ContainerInstance, Reflect)
|
||||
}
|
||||
|
||||
function makePropertyInjectDecorator(doCache: boolean) {
|
||||
@@ -97,6 +97,7 @@ let lazyMultiInject = makePropertyMultiInjectDecorator(doCache)
|
||||
export {
|
||||
initContainer,
|
||||
getContainer,
|
||||
ContainerInstance,
|
||||
lazyInject,
|
||||
lazyInjectNamed,
|
||||
lazyInjectTagged,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import "reflect-metadata";
|
||||
import { initContainer } from './decorators'
|
||||
import { interfaces, Container } from 'inversify';
|
||||
import { fluentProvide } from 'inversify-binding-decorators';
|
||||
|
||||
@@ -11,6 +12,7 @@ const provideSingleton = (identifier: interfaces.ServiceIdentifier<any>) => {
|
||||
};
|
||||
|
||||
const DefaultContainer = new Container();
|
||||
initContainer(DefaultContainer);
|
||||
|
||||
export * from 'inversify'
|
||||
export * from './decorators'
|
||||
|
||||
4
packages/core/.gitignore
vendored
4
packages/core/.gitignore
vendored
@@ -1,4 +0,0 @@
|
||||
/node_modules
|
||||
/dist
|
||||
/package-lock.json
|
||||
/yarn.lock
|
||||
@@ -1,22 +0,0 @@
|
||||
src
|
||||
test
|
||||
typings
|
||||
bundled
|
||||
build
|
||||
coverage
|
||||
docs
|
||||
wiki
|
||||
gulpfile.js
|
||||
bower.json
|
||||
karma.conf.js
|
||||
tsconfig.json
|
||||
typings.json
|
||||
CONTRIBUTING.md
|
||||
ISSUE_TEMPLATE.md
|
||||
PULL_REQUEST_TEMPLATE.md
|
||||
tslint.json
|
||||
wallaby.js
|
||||
.travis.yml
|
||||
.gitignore
|
||||
.vscode
|
||||
type_definitions
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ms/core",
|
||||
"version": "0.0.0",
|
||||
"version": "0.2.1",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -13,21 +13,26 @@
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"publishConfig": {
|
||||
"registry": "https://repo.yumc.pw/repository/npm/"
|
||||
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
|
||||
},
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "npx tsc --watch",
|
||||
"build": "yarn clean && npx tsc",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.0",
|
||||
"typescript": "^3.6.2"
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.8.2"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ms/container": "^0.0.0",
|
||||
"@ms/plugin": "^0.0.0"
|
||||
}
|
||||
"@ms/api": "^0.2.1",
|
||||
"@ms/bukkit": "^0.2.1",
|
||||
"@ms/common": "^0.2.1",
|
||||
"@ms/container": "^0.2.1",
|
||||
"@ms/plugin": "^0.2.1",
|
||||
"@ms/sponge": "^0.2.1"
|
||||
},
|
||||
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
||||
}
|
||||
|
||||
@@ -1,28 +1,97 @@
|
||||
import '@ms/nashorn'
|
||||
|
||||
import { plugin, server } from '@ms/api'
|
||||
import { DefaultContainer as container } from '@ms/container'
|
||||
import '@ms/ployfill'
|
||||
let containerStartTime = new Date().getTime()
|
||||
console.log(`Initialization MiaoScript IOC Container @ms/container. Please wait...`)
|
||||
import { plugin, server, task } from '@ms/api'
|
||||
import { PluginManagerImpl } from '@ms/plugin'
|
||||
import { DefaultContainer as container, injectable, inject, ContainerInstance } from '@ms/container'
|
||||
console.log('MiaoScript IOC Container @ms/container loading completed(' + (new Date().getTime() - containerStartTime) / 1000 + 's)!');
|
||||
|
||||
try {
|
||||
Java.type("org.bukkit.Bukkit");
|
||||
require('@ms/bukkit');
|
||||
} catch (ex) {
|
||||
@injectable()
|
||||
class MiaoScriptCore {
|
||||
@inject(server.Console)
|
||||
private Console: Console;
|
||||
@inject(task.TaskManager)
|
||||
private taskManager: task.TaskManager;
|
||||
@inject(plugin.PluginFolder)
|
||||
private pluginFolder: string;
|
||||
@inject(plugin.PluginManager)
|
||||
private pluginManager: plugin.PluginManager;
|
||||
|
||||
enable() {
|
||||
this.loadServerConsole();
|
||||
this.loadTaskFunction();
|
||||
global.level = "TRACE"
|
||||
this.loadPlugins();
|
||||
return () => this.disable();
|
||||
}
|
||||
|
||||
loadServerConsole() {
|
||||
// @ts-ignore
|
||||
console = new this.Console();
|
||||
}
|
||||
|
||||
loadTaskFunction() {
|
||||
//@ts-ignore
|
||||
global.setTimeout = (func: Function, tick: number, async: boolean = false) => this.taskManager.create(func).later(tick).async(async).submit()
|
||||
//@ts-ignore
|
||||
global.setInterval = (func: Function, tick: number, async: boolean = false) => this.taskManager.create(func).timer(tick).async(async).submit()
|
||||
}
|
||||
|
||||
loadPlugins() {
|
||||
let loadPluginStartTime = new Date().getTime()
|
||||
console.log(`Initialization MiaoScript Plugin System. Please wait...`)
|
||||
this.pluginManager.scan(this.pluginFolder);
|
||||
this.pluginManager.build();
|
||||
this.pluginManager.load();
|
||||
this.pluginManager.enable();
|
||||
console.log('MiaoScript Plugin System loading completed(' + (new Date().getTime() - loadPluginStartTime) / 1000 + 's)!');
|
||||
}
|
||||
|
||||
disable() {
|
||||
this.pluginManager.disable();
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
Java.type("org.spongepowered.api.Sponge");
|
||||
require('@ms/sponge');
|
||||
} catch (ex) {
|
||||
function detectServer() {
|
||||
try {
|
||||
Java.type("org.bukkit.Bukkit");
|
||||
return 'bukkit'
|
||||
} catch (ex) {
|
||||
}
|
||||
try {
|
||||
Java.type("org.spongepowered.api.Sponge");
|
||||
return 'sponge'
|
||||
} catch (ex) {
|
||||
}
|
||||
try {
|
||||
Java.type("cn.nukkit.Nukkit");
|
||||
return 'nukkit'
|
||||
} catch (ex) {
|
||||
}
|
||||
try {
|
||||
Java.type("net.md_5.bungee.api.ProxyServer");
|
||||
return 'bungee'
|
||||
} catch (ex) {
|
||||
}
|
||||
throw Error('Unknow Server Type...')
|
||||
}
|
||||
|
||||
let Console = container.get(server.Console);
|
||||
//@ts-ignore
|
||||
global.console = new Console();
|
||||
function initialize() {
|
||||
let corePackageStartTime = new Date().getTime()
|
||||
container.bind(ContainerInstance).toConstantValue(container);
|
||||
container.bind(plugin.PluginInstance).toConstantValue(base.getInstance());
|
||||
container.bind(plugin.PluginFolder).toConstantValue('plugins');
|
||||
let type = detectServer();
|
||||
console.info(`Detect Compatible Server set ServerType to ${type} ...`)
|
||||
container.bind(server.ServerType).toConstantValue(type);
|
||||
console.log(`Initialization MiaoScript Package @ms/core @ms/${type}. Please wait...`)
|
||||
require(`@ms/${type}`).default(container);
|
||||
container.bind(plugin.PluginManager).to(PluginManagerImpl).inSingletonScope();
|
||||
container.bind(MiaoScriptCore).to(MiaoScriptCore).inSingletonScope();
|
||||
console.log(`MiaoScript Package @ms/core @ms/${type} loading completed(` + (new Date().getTime() - corePackageStartTime) / 1000 + 's)!');
|
||||
let disable = container.get<MiaoScriptCore>(MiaoScriptCore).enable()
|
||||
console.log('MiaoScript ScriptEngine loading completed... Done (' + (new Date().getTime() - global.NashornEngineStartTime) / 1000 + 's)!');
|
||||
return disable;
|
||||
}
|
||||
|
||||
container.bind(plugin.PluginManager).to(PluginManagerImpl).inSingletonScope();
|
||||
|
||||
let manager = container.get<plugin.PluginManager>(plugin.PluginManager);
|
||||
manager.scan('plugins');
|
||||
manager.load(container);
|
||||
manager.enable();
|
||||
export default initialize();
|
||||
|
||||
39
packages/manager/package.json
Normal file
39
packages/manager/package.json
Normal file
@@ -0,0 +1,39 @@
|
||||
{
|
||||
"private": true,
|
||||
"name": "@ms/manager",
|
||||
"version": "0.2.1",
|
||||
"description": "MiaoScript manager package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
"minecraft",
|
||||
"bukkit",
|
||||
"sponge"
|
||||
],
|
||||
"author": "MiaoWoo <admin@yumc.pw>",
|
||||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"publishConfig": {
|
||||
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "ts-node-dev --respawn --debounce=1500 src/index.ts",
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@cc-server/core": "^0.7.0",
|
||||
"mongodb": "^3.5.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/express": "^4.17.2",
|
||||
"@types/mongodb": "^3.3.16",
|
||||
"@types/socket.io": "^2.1.4",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"ts-node-dev": "^1.0.0-pre.44",
|
||||
"typescript": "^3.8.2"
|
||||
}
|
||||
}
|
||||
37
packages/manager/src/controller/Index.ts
Normal file
37
packages/manager/src/controller/Index.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import { DBClient } from '@cc-server/db'
|
||||
import { lazyInjectNamed } from '@cc-server/ioc'
|
||||
import { controller, get, post, requestParam, requestBody, Vaild, NotBlank } from '@cc-server/binding'
|
||||
|
||||
class Plugins {
|
||||
@NotBlank()
|
||||
name?: string;
|
||||
author?: string;
|
||||
version?: string;
|
||||
source?: string;
|
||||
type?: string;
|
||||
dist?: string;
|
||||
}
|
||||
|
||||
type distType = 'npm' | 'git' | 'src'
|
||||
|
||||
@controller('/plugin')
|
||||
class PluginController {
|
||||
@lazyInjectNamed(DBClient, Plugins.name.toLocaleLowerCase())
|
||||
private client: DBClient<Plugins>
|
||||
|
||||
@get('/')
|
||||
index() {
|
||||
return this.client.find({});
|
||||
}
|
||||
|
||||
@get('/:id')
|
||||
details(@requestParam("id") id: string) {
|
||||
return this.client.findOneById(id);
|
||||
}
|
||||
|
||||
@post('/')
|
||||
add(@requestBody() @Vaild() model: Plugins) {
|
||||
return this.client.insertOne(model);
|
||||
}
|
||||
|
||||
}
|
||||
22
packages/manager/src/index.ts
Normal file
22
packages/manager/src/index.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import * as path from 'path'
|
||||
import { Db, MongoClient } from 'mongodb'
|
||||
import { DBClient } from '@cc-server/db'
|
||||
import { interfaces } from '@cc-server/ioc'
|
||||
import { CcServerBoot } from '@cc-server/core'
|
||||
import { MongoCollection, TYPE } from '@cc-server/db-mongo';
|
||||
|
||||
async function main() {
|
||||
let server = new CcServerBoot();
|
||||
let collectionCache = {};
|
||||
server.container.bind(DBClient).toDynamicValue((context: interfaces.Context) => {
|
||||
let name = context.currentRequest.target.getNamedTag().value;
|
||||
if (!name) { return null }
|
||||
if (!collectionCache[name]) { collectionCache[name] = new MongoCollection(context.container.get<Db>(TYPE.DB).collection(name)) }
|
||||
return collectionCache[name];
|
||||
})
|
||||
let client = await MongoClient.connect("mongodb://192.168.2.5:27017", { useNewUrlParser: true, connectTimeoutMS: 10000 })
|
||||
server.container.bind("MONGO_DB").toConstantValue(client.db("mspc"));
|
||||
server.scan(path.join(__dirname, "controller")).start()
|
||||
}
|
||||
|
||||
main()
|
||||
7
packages/manager/tsconfig.json
Normal file
7
packages/manager/tsconfig.json
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"baseUrl": "src",
|
||||
"outDir": "dist"
|
||||
}
|
||||
}
|
||||
4
packages/nashorn/.gitignore
vendored
4
packages/nashorn/.gitignore
vendored
@@ -1,4 +0,0 @@
|
||||
/node_modules
|
||||
/dist
|
||||
/package-lock.json
|
||||
/yarn.lock
|
||||
@@ -1,22 +0,0 @@
|
||||
src
|
||||
test
|
||||
typings
|
||||
bundled
|
||||
build
|
||||
coverage
|
||||
docs
|
||||
wiki
|
||||
gulpfile.js
|
||||
bower.json
|
||||
karma.conf.js
|
||||
tsconfig.json
|
||||
typings.json
|
||||
CONTRIBUTING.md
|
||||
ISSUE_TEMPLATE.md
|
||||
PULL_REQUEST_TEMPLATE.md
|
||||
tslint.json
|
||||
wallaby.js
|
||||
.travis.yml
|
||||
.gitignore
|
||||
.vscode
|
||||
type_definitions
|
||||
12
packages/nashorn/build.sh
Executable file
12
packages/nashorn/build.sh
Executable file
@@ -0,0 +1,12 @@
|
||||
# sponge bukkit jdk bungee nukkit
|
||||
TYPE=nukkit
|
||||
TARGET=../types/dist/typings
|
||||
npx tsc src/build.ts --outDir dist
|
||||
cd dist
|
||||
rm -rf temp
|
||||
mkdir -p temp
|
||||
node build.js ${TYPE}
|
||||
cd ../
|
||||
rm -rf ${TARGET}/${TYPE}
|
||||
mkdir -p ${TARGET}/${TYPE}
|
||||
cp dist/temp/* ${TARGET}/${TYPE}/ -R
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ms/nashorn",
|
||||
"version": "0.0.0",
|
||||
"version": "0.2.1",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -14,17 +14,17 @@
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
"publishConfig": {
|
||||
"registry": "https://repo.yumc.pw/repository/npm/"
|
||||
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
|
||||
},
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "npx tsc --watch",
|
||||
"build": "yarn clean && npx tsc",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.0",
|
||||
"typescript": "^3.6.2"
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.8.2"
|
||||
}
|
||||
}
|
||||
200
packages/nashorn/src/build.ts
Normal file
200
packages/nashorn/src/build.ts
Normal file
@@ -0,0 +1,200 @@
|
||||
import * as fs from "fs";
|
||||
|
||||
function convertJson2TypeDefiend(infile: string, outDir: string) {
|
||||
const file = infile.split(".json")[0];
|
||||
const json = fs.readFileSync(`${inDir}/${file}.json`).toString();
|
||||
const obj = JSON.parse(json);
|
||||
const qnas: string[] = obj.qualifiedName.split(".");
|
||||
let closeBuk = 0;
|
||||
let temp = `declare namespace ${qnas[0]} {\n`;
|
||||
closeBuk++;
|
||||
const nms = qnas.slice(1, qnas.length - 1);
|
||||
for (const nm of nms) {
|
||||
temp += `${' '.repeat(closeBuk)}namespace ${nm.replace('function', 'function$')} {\n`;
|
||||
closeBuk++;
|
||||
}
|
||||
let classModifier = formatClassModifier(obj.modifiers)
|
||||
temp += `${' '.repeat(closeBuk)}// @ts-ignore\n`
|
||||
temp += `${' '.repeat(closeBuk)}${classModifier}${qnas[qnas.length - 1]}`
|
||||
let isInterface = classModifier.includes('interface')
|
||||
let safeInterface = [];
|
||||
for (const ifs of obj.interfaces) {
|
||||
if (!ifs.qualifiedName.startsWith('java')) {
|
||||
safeInterface.push(ifs)
|
||||
}
|
||||
}
|
||||
if (isInterface) {
|
||||
if (safeInterface.length > 0) {
|
||||
temp += ' extends '
|
||||
for (const ifs of safeInterface) {
|
||||
temp += ifs.qualifiedName;
|
||||
temp += ', '
|
||||
}
|
||||
temp = temp.substr(0, temp.length - 2);
|
||||
}
|
||||
} else {
|
||||
temp += `${(obj.superclass) ? (' extends ' + (obj.superclass.qualifiedName == "<any>" ? "object" : obj.superclass.qualifiedName)) : ''}`;
|
||||
if (safeInterface.length > 0) {
|
||||
temp += ' implements '
|
||||
for (const ifs of safeInterface) {
|
||||
temp += ifs.qualifiedName;
|
||||
temp += ', '
|
||||
}
|
||||
temp = temp.substr(0, temp.length - 2);
|
||||
}
|
||||
}
|
||||
temp += ' {\n'
|
||||
closeBuk++;
|
||||
for (const constructor of obj.constructors) {
|
||||
temp += `${formatDoc(constructor.docString, closeBuk)}${' '.repeat(closeBuk)}// @ts-ignore\n${' '.repeat(closeBuk)}constructor(${formatParameters(constructor.parameters)})\n`;
|
||||
}
|
||||
|
||||
let members = [];
|
||||
|
||||
let methods = '';
|
||||
for (const method of obj.methods) {
|
||||
let methodModifier = isInterface ? '' : replaceModifiers(method.modifiers, classModifier.includes('abstract'))
|
||||
if (!whiteKey.includes(method.name)) {
|
||||
if (members[method.name] && methodModifier.includes('abstract')) {
|
||||
continue;
|
||||
}
|
||||
members[method.name] = methodModifier;
|
||||
}
|
||||
methods += `${formatDoc(method.docString, closeBuk)}${' '.repeat(closeBuk)}// @ts-ignore\n${' '.repeat(closeBuk)}${methodModifier} ${method.name}(${formatParameters(method.parameters)}): ${mappingType(method.returnType.type)};\n`;
|
||||
}
|
||||
|
||||
let fields = '';
|
||||
for (const field of obj.fields) {
|
||||
if (members[field.name]) {
|
||||
continue;
|
||||
}
|
||||
fields += `${' '.repeat(closeBuk)}// @ts-ignore\n${' '.repeat(closeBuk)}${isInterface ? '' : replaceModifiers(field.modifiers)} ${field.name}: ${mappingType(field.type ? field.type.type : "any")};\n`;
|
||||
}
|
||||
|
||||
temp += fields + methods;
|
||||
|
||||
for (let index = 0; index < closeBuk; index++) {
|
||||
temp += `${' '.repeat(closeBuk - index - 1)}}\n`;
|
||||
}
|
||||
|
||||
fs.writeFileSync(`${outDir}/${file}.${suffix}`, temp);
|
||||
return `${file}.${suffix}`;
|
||||
}
|
||||
|
||||
function formatClassModifier(modifiers: string) {
|
||||
let tempm = modifiers.replace('public', '').replace('static', '').replace('final', '').trim();
|
||||
if (!modifiers.includes('interface')) { tempm += ' class' }
|
||||
return tempm.length > 0 ? (tempm + ' ') : '';
|
||||
}
|
||||
|
||||
function formatDoc(doc: string, closeBuk: number) {
|
||||
let middleDoc = '';
|
||||
for (const line of doc.split('\n')) {
|
||||
if (line.trim().length != 0) {
|
||||
middleDoc += `${' '.repeat(closeBuk)} * ${line.trim()}\n`
|
||||
}
|
||||
}
|
||||
return middleDoc.length > 0 ? `${' '.repeat(closeBuk)}/**\n${middleDoc}${' '.repeat(closeBuk)} */\n` : '';
|
||||
}
|
||||
|
||||
function replaceModifiers(modifiers: string, absClass = false): string {
|
||||
// modifiers = modifiers.replace(' final', ' readonly');
|
||||
modifiers = modifiers.split(" final")[0];
|
||||
modifiers = modifiers.split(" native")[0];
|
||||
modifiers = modifiers.split(" volatile")[0];
|
||||
modifiers = modifiers.split(" transient")[0];
|
||||
modifiers = modifiers.split(" synchronized")[0];
|
||||
if (!absClass) {
|
||||
modifiers = modifiers.split(" abstract")[0];
|
||||
}
|
||||
return modifiers;
|
||||
}
|
||||
|
||||
function formatParameters(params: any[]) {
|
||||
let tempParam = '';
|
||||
for (const p of params) {
|
||||
tempParam += `${mappingName(p.name)}: ${mappingType(p.type ? p.type.qualifiedName : 'any')}, `
|
||||
}
|
||||
return tempParam.substr(0, tempParam.length - 2);
|
||||
}
|
||||
|
||||
const nameMap = [];
|
||||
nameMap['function'] = 'func'
|
||||
nameMap['in'] = 'input'
|
||||
nameMap['var'] = 'variable'
|
||||
|
||||
function mappingName(name: string) {
|
||||
if (whiteKey.includes(name)) { return name }
|
||||
let outName = nameMap[name] || name || '';
|
||||
return outName;
|
||||
}
|
||||
|
||||
let whiteKey = ['shift', "map", 'filter', 'values', 'valueOf', 'toString', 'length', 'includes', 'entries', 'keys', 'join', 'fill']
|
||||
|
||||
const typeMap = [];
|
||||
typeMap['int'] = 'number';
|
||||
typeMap['int[]'] = 'number[]';
|
||||
typeMap['int[][]'] = 'number[][]';
|
||||
typeMap['byte'] = 'number';
|
||||
typeMap['byte[]'] = 'number[]';
|
||||
typeMap['double'] = 'number';
|
||||
typeMap['double[]'] = 'number[]';
|
||||
typeMap['short'] = 'number';
|
||||
typeMap['short[]'] = 'number[]';
|
||||
typeMap['float'] = 'number';
|
||||
typeMap['float[]'] = 'number[]';
|
||||
typeMap['long'] = 'number';
|
||||
typeMap['long[]'] = 'number[]';
|
||||
typeMap['<any>'] = 'any';
|
||||
typeMap['char'] = 'string';
|
||||
typeMap['char[]'] = 'string[]';
|
||||
typeMap['java.lang.String'] = "string";
|
||||
// typeMap['java.util.Date'] = 'any /*java.util.Date*/'
|
||||
// typeMap['java.util.List'] = 'any[] /*java.util.List*/'
|
||||
// typeMap['java.util.Set'] = 'any[] /*java.util.Set*/'
|
||||
// typeMap['java.util.Collection'] = 'any[] /*java.util.Collection*/'
|
||||
// typeMap['java.util.Map'] = 'Map<any, any> /*java.util.Map*/'
|
||||
// Sponge
|
||||
typeMap['Vectori'] = 'any /*Vector3i*/'
|
||||
typeMap['Vectord'] = 'any /*Vector3d*/'
|
||||
typeMap['Vectorf'] = 'any /*Vector3f*/'
|
||||
typeMap['Vector2i'] = 'any /*Vector2i*/'
|
||||
typeMap['Vector2d'] = 'any /*Vector2d*/'
|
||||
typeMap['Vector2f'] = 'any /*Vector2f*/'
|
||||
typeMap['Vector3i'] = 'any /*Vector3i*/'
|
||||
typeMap['Vector3d'] = 'any /*Vector3d*/'
|
||||
typeMap['Vector3f'] = 'any /*Vector3f*/'
|
||||
typeMap['Type'] = 'any /*Type*/'
|
||||
typeMap['Gson'] = 'any /*Gson*/'
|
||||
typeMap['Logger'] = 'any /*Logger*/'
|
||||
typeMap['MethodVisitor'] = 'any /*MethodVisitor*/'
|
||||
typeMap['ConfigurationNode'] = 'any /*ConfigurationNode*/'
|
||||
typeMap['TypeSerializerCollection'] = 'any /*TypeSerializerCollection*/'
|
||||
typeMap['Quaterniond'] = 'any /*Quaterniond*/'
|
||||
typeMap['Matrix2d'] = 'any /*Matrix2d*/'
|
||||
typeMap['Matrix3d'] = 'any /*Matrix3d*/'
|
||||
typeMap['Matrix4d'] = 'any /*Matrix4d*/'
|
||||
|
||||
function mappingType(type: string): string {
|
||||
let outType = typeMap[type] || type || 'any';
|
||||
if (outType.indexOf('.') != -1) {
|
||||
if (outType.startsWith('java.') || outType.startsWith('org.') || outType.startsWith('net.') || outType.startsWith('cn.')) {
|
||||
|
||||
} else {
|
||||
outType = `any /*${outType}*/`
|
||||
}
|
||||
}
|
||||
return outType.replace('function', 'function$');
|
||||
}
|
||||
|
||||
var args = process.argv.splice(2)
|
||||
|
||||
const suffix = 'd.ts'
|
||||
const inDir = `../docs/${args[0]}`
|
||||
const outDir = "./temp";
|
||||
const files = fs.readdirSync(inDir);
|
||||
let index = '';
|
||||
for (const file of files) {
|
||||
index += `/// <reference path="./${convertJson2TypeDefiend(file, outDir)}" />\n`;
|
||||
}
|
||||
fs.writeFileSync(`${outDir}/index.${suffix}`, index);
|
||||
@@ -1,8 +1,42 @@
|
||||
declare global {
|
||||
const __FILE__: string;
|
||||
const __LINE__: number;
|
||||
const __DIR__: string;
|
||||
let Packages: any;
|
||||
|
||||
function print(...message: any[]): void;
|
||||
function load(script: string | object);
|
||||
function loadWithNewGlobal(script: string | object);
|
||||
function exit(code?: number);
|
||||
function quit(code?: number);
|
||||
function JavaImporter(...className: string[]);
|
||||
|
||||
namespace Java {
|
||||
function type(clazz: string): any;
|
||||
function from(javaObj: any): any[];
|
||||
function to(array: any[]): any;
|
||||
function extend(...parentTypes: any[]);
|
||||
//@ts-ignore
|
||||
// function super(type: any);
|
||||
}
|
||||
|
||||
interface Error {
|
||||
readonly lineNumber?: number;
|
||||
readonly columnNumber?: number;
|
||||
readonly fileName?: string;
|
||||
dumpStack?: Function;
|
||||
printStackTrace?: Function;
|
||||
getStackTrace?: () => any[];
|
||||
}
|
||||
|
||||
interface String {
|
||||
trimLeft();
|
||||
trimRight();
|
||||
}
|
||||
|
||||
interface Object {
|
||||
setPrototypeOf(obj: object, prototype: object);
|
||||
bindProperties(to: object, from: object);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
35
packages/nukkit/package.json
Normal file
35
packages/nukkit/package.json
Normal file
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"name": "@ms/nukkit",
|
||||
"version": "0.2.1",
|
||||
"description": "MiaoScript nukkit package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
"minecraft",
|
||||
"bukkit",
|
||||
"sponge"
|
||||
],
|
||||
"author": "MiaoWoo <admin@yumc.pw>",
|
||||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"publishConfig": {
|
||||
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
|
||||
},
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.8.2"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ms/api": "^0.2.1",
|
||||
"@ms/common": "^0.2.1",
|
||||
"@ms/container": "^0.2.1",
|
||||
"@ms/types": "^0.2.1"
|
||||
}
|
||||
}
|
||||
41
packages/nukkit/src/command.ts
Normal file
41
packages/nukkit/src/command.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import '@ms/nashorn'
|
||||
|
||||
import { command, plugin } from '@ms/api'
|
||||
import { injectable, postConstruct, inject } from '@ms/container'
|
||||
|
||||
let PluginCommand = Java.type('cn.nukkit.command.PluginCommand');
|
||||
let CommandExecutor = Java.type('cn.nukkit.command.CommandExecutor');
|
||||
|
||||
@injectable()
|
||||
export class NukkitCommand extends command.Command {
|
||||
@inject(plugin.PluginInstance)
|
||||
private pluginInstance: any
|
||||
private commandMap: any;
|
||||
|
||||
@postConstruct()
|
||||
init() {
|
||||
this.commandMap = base.getInstance().getServer().getCommandMap();
|
||||
}
|
||||
create(plugin: any, command: string) {
|
||||
var cmd = this.commandMap.getCommand(command)
|
||||
if (cmd && cmd instanceof PluginCommand) { return cmd };
|
||||
cmd = new PluginCommand(command, this.pluginInstance)
|
||||
this.commandMap.register(plugin.description.name, cmd);
|
||||
return cmd;
|
||||
}
|
||||
remove(plugin: any, command: string) {
|
||||
var cmd = this.commandMap.getCommand(command)
|
||||
if (cmd && cmd instanceof PluginCommand) {
|
||||
cmd.unregister(this.commandMap);
|
||||
}
|
||||
}
|
||||
onCommand(plugin: any, command: any, executor: Function) {
|
||||
// 必须指定需要实现的接口类型 否则MOD服会报错
|
||||
command.setExecutor(new CommandExecutor({
|
||||
onCommand: super.setExecutor(plugin, command, executor)
|
||||
}));
|
||||
}
|
||||
onTabComplete(plugin: any, command: any, tabCompleter: Function) {
|
||||
// Not Support
|
||||
}
|
||||
}
|
||||
21
packages/nukkit/src/console.ts
Normal file
21
packages/nukkit/src/console.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import { MiaoScriptConsole } from '@ms/api'
|
||||
|
||||
let Nukkit = base.getInstance().getServer();
|
||||
let CommandSender = Java.type('cn.nukkit.command.CommandSender')
|
||||
|
||||
export class NukkitConsole extends MiaoScriptConsole {
|
||||
sender(sender, ...args) {
|
||||
if (!(sender instanceof CommandSender)) {
|
||||
this.error(`First parameter ${sender} not instanceof cn.nukkit.command.CommandSender can't send message!`)
|
||||
return;
|
||||
}
|
||||
if (Object.prototype.toString.call(args[0]) === "[object Array]") {
|
||||
args[0].forEach(line => sender.sendMessage(this.prefix + line))
|
||||
} else {
|
||||
sender.sendMessage(this.prefix + args.join(' '));
|
||||
}
|
||||
}
|
||||
console(...args: string[]): void {
|
||||
this.sender(Nukkit.getConsoleSender(), args.join(' '));
|
||||
}
|
||||
}
|
||||
47
packages/nukkit/src/event.ts
Normal file
47
packages/nukkit/src/event.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import { event, server, plugin } from '@ms/api'
|
||||
import { injectable, inject } from '@ms/container'
|
||||
|
||||
const Nukkit: cn.nukkit.Server = base.getInstance().getServer();
|
||||
const Event = Java.type("cn.nukkit.event.Event");
|
||||
const Modifier = Java.type("java.lang.reflect.Modifier");
|
||||
const Listener = Java.type("cn.nukkit.event.Listener");
|
||||
const EventPriority = Java.type("cn.nukkit.event.EventPriority");
|
||||
const EventExecutor = Java.type("cn.nukkit.plugin.EventExecutor");
|
||||
|
||||
@injectable()
|
||||
export class NukkitEvent extends event.Event {
|
||||
@inject(plugin.PluginInstance)
|
||||
private pluginInstance: any
|
||||
|
||||
constructor() {
|
||||
super('cn/nukkit/event');
|
||||
}
|
||||
|
||||
getJarFile(resource: string) {
|
||||
return super.getJarFile('cn/nukkit/Nukkit.class')
|
||||
}
|
||||
isValidEvent(clazz: any): boolean {
|
||||
// 继承于 org.bukkit.event.Event
|
||||
return Event.class.isAssignableFrom(clazz) &&
|
||||
// 访问符为Public
|
||||
Modifier.isPublic(clazz.getModifiers()) &&
|
||||
// 不是抽象类
|
||||
!Modifier.isAbstract(clazz.getModifiers());
|
||||
}
|
||||
register(eventCls: any, exec: Function, priority: event.EventPriority, ignoreCancel: boolean) {
|
||||
let listener = new Listener({});
|
||||
Nukkit.getPluginManager().registerEvent(
|
||||
eventCls,
|
||||
listener,
|
||||
EventPriority[priority],
|
||||
new EventExecutor({
|
||||
execute: exec
|
||||
}),
|
||||
this.pluginInstance,
|
||||
ignoreCancel);
|
||||
return listener;
|
||||
}
|
||||
unregister(event: any, listener: any): void {
|
||||
event.getHandlers().unregister(listener);
|
||||
}
|
||||
}
|
||||
18
packages/nukkit/src/index.ts
Normal file
18
packages/nukkit/src/index.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
/// <reference types="@ms/types/dist/typings/nukkit" />
|
||||
|
||||
import { server, command, event, task } from '@ms/api'
|
||||
import { Container } from '@ms/container'
|
||||
|
||||
import { NukkitConsole } from './console';
|
||||
import { NukkitEvent } from './event';
|
||||
import { NukkitServer } from './server';
|
||||
import { NukkitCommand } from './command';
|
||||
import { NukkitTaskManager } from './task';
|
||||
|
||||
export default function NukkitImpl(container: Container) {
|
||||
container.bind(server.Console).toConstantValue(NukkitConsole);
|
||||
container.bind(event.Event).to(NukkitEvent).inSingletonScope();
|
||||
container.bind(server.Server).to(NukkitServer).inSingletonScope();
|
||||
container.bind(command.Command).to(NukkitCommand).inSingletonScope();
|
||||
container.bind(task.TaskManager).to(NukkitTaskManager).inSingletonScope();
|
||||
}
|
||||
35
packages/nukkit/src/server.ts
Normal file
35
packages/nukkit/src/server.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import { server } from '@ms/api'
|
||||
import { injectable } from '@ms/container';
|
||||
|
||||
let Nukkit: cn.nukkit.Server = base.getInstance().getServer();
|
||||
|
||||
@injectable()
|
||||
export class NukkitServer implements server.Server {
|
||||
getPlayer(name: string) {
|
||||
return Nukkit.getPlayer(name)
|
||||
}
|
||||
getVersion(): string {
|
||||
return Nukkit.getVersion()
|
||||
}
|
||||
getOnlinePlayers() {
|
||||
return Nukkit.getOnlinePlayers() as unknown as any[]
|
||||
}
|
||||
getConsoleSender() {
|
||||
return Nukkit.getConsoleSender()
|
||||
}
|
||||
getService(service: string) {
|
||||
return Nukkit.getServiceManager().getProvider(base.getClass(service))
|
||||
}
|
||||
dispatchCommand(sender: string | any, command: string): boolean {
|
||||
if (typeof sender === 'string') {
|
||||
sender = this.getPlayer(sender)
|
||||
}
|
||||
return Nukkit.dispatchCommand(sender, command)
|
||||
}
|
||||
dispatchConsoleCommand(command: string): boolean {
|
||||
return Nukkit.dispatchCommand(Nukkit.getConsoleSender(), command)
|
||||
}
|
||||
sendJson(sender: string | any, json: object | string): void {
|
||||
throw new Error("Method not implemented.");
|
||||
}
|
||||
}
|
||||
35
packages/nukkit/src/task.ts
Normal file
35
packages/nukkit/src/task.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import { task, plugin } from '@ms/api'
|
||||
import { injectable, inject } from '@ms/container';
|
||||
|
||||
const Nukkit: cn.nukkit.Server = base.getInstance().getServer();
|
||||
const NukkitRunnable = Java.type('cn.nukkit.scheduler.NukkitRunnable');
|
||||
const Callable = Java.type('java.util.concurrent.Callable')
|
||||
|
||||
@injectable()
|
||||
export class NukkitTaskManager implements task.TaskManager {
|
||||
@inject(plugin.PluginInstance)
|
||||
private pluginInstance: any;
|
||||
|
||||
create(func: Function): task.Task {
|
||||
if (Object.prototype.toString.call(func) !== "[object Function]") { throw TypeError('第一个参数 Task 必须为 function !'); };
|
||||
return new NukkitTask(this.pluginInstance, func);
|
||||
}
|
||||
callSyncMethod(func: Function): any {
|
||||
return func()
|
||||
}
|
||||
}
|
||||
|
||||
export class NukkitTask extends task.Task {
|
||||
submit(): task.Cancelable {
|
||||
let run = new NukkitRunnable({
|
||||
run: () => this.run()
|
||||
})
|
||||
let funcName = `runTask${this.interval ? 'Timer' : 'Later'}${this.isAsync ? 'Asynchronously' : ''}`
|
||||
if (this.interval) {
|
||||
run[funcName](this.plugin, this.laterTime, this.interval);
|
||||
} else {
|
||||
run[funcName](this.plugin, this.laterTime);
|
||||
}
|
||||
return run;
|
||||
}
|
||||
}
|
||||
7
packages/nukkit/tsconfig.json
Normal file
7
packages/nukkit/tsconfig.json
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"baseUrl": "src",
|
||||
"outDir": "dist"
|
||||
}
|
||||
}
|
||||
28
packages/ployfill/package.json
Normal file
28
packages/ployfill/package.json
Normal file
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"name": "@ms/ployfill",
|
||||
"version": "0.2.1",
|
||||
"description": "MiaoScript ployfill package",
|
||||
"author": "MiaoWoo <admin@yumc.pw>",
|
||||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
"publishConfig": {
|
||||
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
|
||||
},
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ms/nashorn": "^0.2.1",
|
||||
"core-js": "^3.6.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.8.2"
|
||||
}
|
||||
}
|
||||
26
packages/ployfill/src/es5-ext.ts
Normal file
26
packages/ployfill/src/es5-ext.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
// ES2015 String ployfill must force overwrite to js method
|
||||
Object.defineProperty(String.prototype, 'contains', {
|
||||
value: require(`es5-ext/string/#/contains/shim`),
|
||||
configurable: true,
|
||||
enumerable: false,
|
||||
writable: true
|
||||
})
|
||||
Object.defineProperty(String.prototype, 'repeat', {
|
||||
value: require(`es5-ext/string/#/repeat/shim`),
|
||||
configurable: true,
|
||||
enumerable: false,
|
||||
writable: true
|
||||
})
|
||||
Object.defineProperty(String.prototype, 'startsWith', {
|
||||
value: require(`es5-ext/string/#/starts-with/shim`),
|
||||
configurable: true,
|
||||
enumerable: false,
|
||||
writable: true
|
||||
})
|
||||
Object.defineProperty(String.prototype, 'endsWith', {
|
||||
value: require(`es5-ext/string/#/ends-with/shim`),
|
||||
configurable: true,
|
||||
enumerable: false,
|
||||
writable: true
|
||||
})
|
||||
|
||||
@@ -3,7 +3,10 @@ declare global {
|
||||
interface Global {
|
||||
logger: any;
|
||||
debug: boolean;
|
||||
noop: Function;
|
||||
level: string;
|
||||
NashornEngineStartTime: number;
|
||||
setGlobal: (key: string, value: any) => void;
|
||||
noop: () => void;
|
||||
console: Console;
|
||||
}
|
||||
}
|
||||
@@ -12,7 +15,12 @@ declare global {
|
||||
var ScriptEngineContextHolder: any;
|
||||
function engineLoad(str: string): any;
|
||||
interface Core {
|
||||
getClass(name: String);
|
||||
getClass(name: String): any;
|
||||
getProxyClass(): any;
|
||||
getInstance(): any;
|
||||
read(path: string): string;
|
||||
save(path: string, content: string): void;
|
||||
delete(path: string): void;
|
||||
}
|
||||
interface Console {
|
||||
ex(err: Error): void;
|
||||
10
packages/ployfill/src/index.ts
Normal file
10
packages/ployfill/src/index.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
/// <reference path="./global.ts" />
|
||||
/// <reference types='@ms/nashorn' />
|
||||
let ployfillStartTime = new Date().getTime();
|
||||
console.info('Initialization Java Nashorn ployfill. Please wait...');
|
||||
require('./es5-ext');
|
||||
require('core-js');
|
||||
global.setGlobal('Proxy', require('./proxy').Proxy)
|
||||
global.setGlobal('XMLHttpRequest', require('./xml-http-request').XMLHttpRequest)
|
||||
global.setGlobal('Blob', require('blob-polyfill').Blob)
|
||||
console.info('Java Nashorn ployfill loading completed... Cost (' + (new Date().getTime() - ployfillStartTime) / 1000 + 's)!');
|
||||
31
packages/ployfill/src/proxy.ts
Normal file
31
packages/ployfill/src/proxy.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
// Nashorn JSAdapter See https://wiki.openjdk.java.net/display/Nashorn/Nashorn+extensions#Nashornextensions-JSAdapterconstructor
|
||||
let createProxy = eval(`
|
||||
function(handle){ return new JSAdapter(handle) }
|
||||
`)
|
||||
export interface ProxyHandle extends ProxyHandler<any> {
|
||||
// get: (target: any, name: string) => any
|
||||
// set: (target: any, name: string, value: any) => boolean
|
||||
// construct: (target: any, ...args: any[]) => any
|
||||
// has: (target: any, name: string) => boolean
|
||||
// ownKeys: (target: any) => string[]
|
||||
values: (target: any) => any[];
|
||||
// call: (target: any, name: string, ...args: any[]) => any
|
||||
// deleteProperty: (target: any, name: string) => boolean
|
||||
}
|
||||
export class Proxy {
|
||||
static newProxy(target: any, handle: Partial<ProxyHandle>): any {
|
||||
return new Proxy(target, handle)
|
||||
}
|
||||
constructor(target: any, handle: Partial<ProxyHandle>) {
|
||||
return createProxy({
|
||||
__get__: (name: string) => handle.get ? handle.get(target, name, undefined) : target[name],
|
||||
__put__: (name: string, value: any) => handle.set ? handle.set(target, name, value, undefined) : target[name] = value,
|
||||
__call__: (name: string, ...args: any) => handle.apply ? handle.apply(target, name, args) : target[name].apply(target, args),
|
||||
__new__: (...args: any) => handle.construct ? handle.construct(target, args, target) : new target(...args),
|
||||
__getIds__: () => handle.ownKeys ? handle.ownKeys(target) : Object.keys(target),
|
||||
__getValues__: () => handle.values ? handle.values(target) : Object.values(target),
|
||||
__has__: (name: string) => handle.has ? handle.has(target, name) : Object.getOwnPropertyDescriptor(target, name) != undefined,
|
||||
__delete__: (name: string) => handle.deleteProperty ? handle.deleteProperty(target, name) : delete target[name]
|
||||
})
|
||||
}
|
||||
}
|
||||
246
packages/ployfill/src/xml-http-request.ts
Normal file
246
packages/ployfill/src/xml-http-request.ts
Normal file
@@ -0,0 +1,246 @@
|
||||
import '@ms/nashorn'
|
||||
|
||||
const URL = Java.type("java.net.URL");
|
||||
const Files = Java.type("java.nio.file.Files");
|
||||
const StandardCopyOption = Java.type("java.nio.file.StandardCopyOption");
|
||||
const JavaString = Java.type("java.lang.String");
|
||||
const SecureRandom = Java.type("java.security.SecureRandom");
|
||||
const SSLContext = Java.type("javax.net.ssl.SSLContext");
|
||||
const HttpsURLConnection = Java.type("javax.net.ssl.HttpsURLConnection");
|
||||
const HostnameVerifier = Java.type("javax.net.ssl.HostnameVerifier");
|
||||
const X509TrustManager = Java.type("javax.net.ssl.X509TrustManager");
|
||||
|
||||
const SocketTimeoutException = Java.type('java.net.SocketTimeoutException');
|
||||
|
||||
const Callable = Java.type('java.util.concurrent.Callable');
|
||||
const Executors = Java.type('java.util.concurrent.Executors')
|
||||
|
||||
const UTF_8 = "UTF-8"
|
||||
|
||||
const TrustAnyHostnameVerifier = new HostnameVerifier({ verify: () => true });
|
||||
|
||||
const SSLSocketFactory = function initSSLSocketFactory() {
|
||||
let sslContext = SSLContext.getInstance("TLS");
|
||||
sslContext.init(null, [new X509TrustManager({
|
||||
getAcceptedIssuers: () => null,
|
||||
checkClientTrusted: () => { },
|
||||
checkServerTrusted: () => { }
|
||||
})], new SecureRandom());
|
||||
return sslContext.getSocketFactory();
|
||||
}();
|
||||
|
||||
interface Future<T> {
|
||||
cancel(): boolean;
|
||||
isCancelled(): boolean;
|
||||
isDone(): boolean;
|
||||
get(): T;
|
||||
}
|
||||
|
||||
enum ReadyState {
|
||||
UNSENT,//Client has been created. open() not called yet.
|
||||
OPENED,//open() has been called.
|
||||
HEADERS_RECEIVED,//send() has been called, and headers and status are available.
|
||||
LOADING,//Downloading; responseText holds partial data.
|
||||
DONE,//The operation is complete.
|
||||
}
|
||||
type RequestMethod =
|
||||
| 'get' | 'GET'
|
||||
| 'delete' | 'DELETE'
|
||||
| 'head' | 'HEAD'
|
||||
| 'options' | 'OPTIONS'
|
||||
| 'post' | 'POST'
|
||||
| 'put' | 'PUT'
|
||||
| 'patch' | 'PATCH';
|
||||
type ResponseType =
|
||||
| 'arraybuffer'
|
||||
| 'blob'
|
||||
| 'document'
|
||||
| 'json'
|
||||
| 'text'
|
||||
| 'stream';
|
||||
type EventType =
|
||||
| 'load'
|
||||
| 'error'
|
||||
| 'abort'
|
||||
| 'progress'
|
||||
| 'timeout'
|
||||
| 'loadend'
|
||||
| 'loadstart';
|
||||
type HttpHeader = { [key: string]: string };
|
||||
|
||||
|
||||
const executor = Executors.newCachedThreadPool();
|
||||
|
||||
export class XMLHttpRequest {
|
||||
private _timeout: number;
|
||||
private _responseType: ResponseType = 'text';
|
||||
private _withCredentials: boolean;
|
||||
|
||||
private _readyState: ReadyState = ReadyState.UNSENT;
|
||||
|
||||
private _method: RequestMethod;
|
||||
private _url: string;
|
||||
private _async: boolean;
|
||||
private _mimeType: string;
|
||||
|
||||
private _status: number = 0;
|
||||
private _statusText: string = null;
|
||||
private _response: any;
|
||||
private _responseURL: string;
|
||||
private _responseHeaders: HttpHeader;
|
||||
|
||||
private _connection = null;
|
||||
|
||||
get timeout() {
|
||||
return this._timeout;
|
||||
}
|
||||
set timeout(timeout: number) {
|
||||
this._timeout = timeout
|
||||
}
|
||||
get readyState() {
|
||||
return this._readyState;
|
||||
}
|
||||
set responseType(type: ResponseType) {
|
||||
this._responseType = type;
|
||||
}
|
||||
get responseType() {
|
||||
return this._responseType;
|
||||
}
|
||||
|
||||
get status() {
|
||||
return this._status;
|
||||
}
|
||||
get statusText() {
|
||||
return this._statusText;
|
||||
}
|
||||
get response() {
|
||||
return this._response ? JSON.parse(this._response) : this._response;
|
||||
}
|
||||
get responseText() {
|
||||
return this._response;
|
||||
}
|
||||
get responseXML() {
|
||||
return this._response;
|
||||
}
|
||||
get responseURL() {
|
||||
return this._responseURL;
|
||||
}
|
||||
|
||||
onload() { }
|
||||
onerror(ex: Error) { }
|
||||
onabort() { }
|
||||
onprogress() { }
|
||||
ontimeout(ex: Error) { }
|
||||
onloadend() { }
|
||||
onloadstart() { }
|
||||
onreadystatechange() { }
|
||||
|
||||
setRequestHeader(key: string, val: string) {
|
||||
this._connection.setRequestProperty(key, val);
|
||||
}
|
||||
getResponseHeader(key: string): string {
|
||||
return this._responseHeaders[key];
|
||||
}
|
||||
getAllResponseHeaders(): any {
|
||||
return this._responseHeaders;
|
||||
}
|
||||
addEventListener(event: EventType, callback: Function) {
|
||||
this[`on${event.toLowerCase()}`] = callback;
|
||||
}
|
||||
overrideMimeType(mimeType: string) {
|
||||
this._mimeType = mimeType;
|
||||
}
|
||||
open(method: RequestMethod, url: string, async: boolean = true, user?: string, password?: string) {
|
||||
this._method = method;
|
||||
this._url = url;
|
||||
this._async = async;
|
||||
|
||||
this._connection = new URL(this._url).openConnection()
|
||||
if (this._connection instanceof HttpsURLConnection) {
|
||||
this._connection.setHostnameVerifier(TrustAnyHostnameVerifier);
|
||||
this._connection.setSSLSocketFactory(SSLSocketFactory);
|
||||
}
|
||||
this._connection.setRequestMethod(this._method);
|
||||
this._connection.setDoOutput(true);
|
||||
this._connection.setDoInput(true);
|
||||
this._connection.setConnectTimeout(this._timeout);
|
||||
this._connection.setReadTimeout(this._timeout);
|
||||
|
||||
this.setReadyState(ReadyState.OPENED);
|
||||
}
|
||||
send(body?: string | object): Future<string> {
|
||||
if (this._readyState !== ReadyState.OPENED) { throw new Error(`Error Status ${this._readyState}!`) }
|
||||
let future = executor.submit(new Callable({ call: () => this._send(body) }));
|
||||
if (!this._async) { future.get() }
|
||||
return future;
|
||||
}
|
||||
get() {
|
||||
switch (this._responseType) {
|
||||
case "json":
|
||||
return this.response;
|
||||
case "text":
|
||||
return this.responseText;
|
||||
default:
|
||||
throw Error(`Unsupport ResponseType: ${this._responseType} !`)
|
||||
}
|
||||
}
|
||||
abort() {
|
||||
this._connection.disconnect();
|
||||
this.onabort();
|
||||
}
|
||||
|
||||
private _send(body?: string | object) {
|
||||
try {
|
||||
this._connection.connect();
|
||||
this.onloadstart();
|
||||
if (body) {
|
||||
let bodyType = Object.prototype.toString.call(body);
|
||||
if (bodyType !== '[object String]') { throw new Error(`body(${bodyType}) must be string!`) }
|
||||
var out = this._connection.getOutputStream();
|
||||
out.write(new JavaString(body).getBytes(UTF_8));
|
||||
out.flush();
|
||||
out.close();
|
||||
}
|
||||
this.setReadyState(ReadyState.LOADING);
|
||||
this._status = this._connection.getResponseCode();
|
||||
this._statusText = this._connection.getResponseMessage();
|
||||
this.setResponseHeaders(this._connection.getHeaderFields());
|
||||
if (this._status >= 0 && this._status < 300) {
|
||||
this._response = this.readOutput(this._connection.getInputStream());
|
||||
} else if (this._status >= 300 && this._status < 400) {
|
||||
this._responseURL = this.getResponseHeader('Location');
|
||||
} else {
|
||||
this._response = this.readOutput(this._connection.getErrorStream());
|
||||
}
|
||||
this.onloadend();
|
||||
} catch (ex) {
|
||||
if (ex instanceof SocketTimeoutException && this.ontimeout) {
|
||||
return this.ontimeout(ex)
|
||||
} else if (this.onerror) {
|
||||
return this.onerror(ex);
|
||||
}
|
||||
throw ex;
|
||||
} finally {
|
||||
this._connection.disconnect();
|
||||
this.setReadyState(ReadyState.DONE);
|
||||
}
|
||||
}
|
||||
|
||||
private setResponseHeaders(header: any) {
|
||||
this._responseHeaders = {};
|
||||
header.forEach((key, value) => {
|
||||
this._responseHeaders[key] = value[value.length - 1]
|
||||
});
|
||||
}
|
||||
|
||||
private setReadyState(state: ReadyState) {
|
||||
this._readyState = state;
|
||||
this.onreadystatechange();
|
||||
}
|
||||
|
||||
private readOutput(input: any) {
|
||||
var tempFile = Files.createTempFile('xhr', '.response');
|
||||
Files.copy(input, tempFile, StandardCopyOption['REPLACE_EXISTING']); tempFile.toFile().deleteOnExit();
|
||||
return new JavaString(Files.readAllBytes(tempFile), 'UTF-8');
|
||||
}
|
||||
}
|
||||
7
packages/ployfill/tsconfig.json
Normal file
7
packages/ployfill/tsconfig.json
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"baseUrl": "src",
|
||||
"outDir": "dist"
|
||||
}
|
||||
}
|
||||
4
packages/plugin/.gitignore
vendored
4
packages/plugin/.gitignore
vendored
@@ -1,4 +0,0 @@
|
||||
/node_modules
|
||||
/dist
|
||||
/package-lock.json
|
||||
/yarn.lock
|
||||
@@ -1,22 +0,0 @@
|
||||
src
|
||||
test
|
||||
typings
|
||||
bundled
|
||||
build
|
||||
coverage
|
||||
docs
|
||||
wiki
|
||||
gulpfile.js
|
||||
bower.json
|
||||
karma.conf.js
|
||||
tsconfig.json
|
||||
typings.json
|
||||
CONTRIBUTING.md
|
||||
ISSUE_TEMPLATE.md
|
||||
PULL_REQUEST_TEMPLATE.md
|
||||
tslint.json
|
||||
wallaby.js
|
||||
.travis.yml
|
||||
.gitignore
|
||||
.vscode
|
||||
type_definitions
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ms/plugin",
|
||||
"version": "0.0.0",
|
||||
"version": "0.2.1",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -13,22 +13,24 @@
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"publishConfig": {
|
||||
"registry": "https://repo.yumc.pw/repository/npm/"
|
||||
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
|
||||
},
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "npx tsc --watch",
|
||||
"build": "yarn clean && npx tsc",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/js-yaml": "^3.12.2",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.0",
|
||||
"typescript": "^3.6.2"
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.8.2"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ms/api": "^0.0.0",
|
||||
"@ms/common": "^0.0.0",
|
||||
"@ms/container": "^0.0.0"
|
||||
"@ms/api": "^0.2.1",
|
||||
"@ms/common": "^0.2.1",
|
||||
"@ms/container": "^0.2.1",
|
||||
"js-yaml": "^3.13.1"
|
||||
}
|
||||
}
|
||||
40
packages/plugin/src/config.ts
Normal file
40
packages/plugin/src/config.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import * as yaml from 'js-yaml'
|
||||
|
||||
export interface PluginConfigLoader {
|
||||
load(content: string): any;
|
||||
dump(variable: any): string;
|
||||
}
|
||||
|
||||
export class YamlPluginConfig implements PluginConfigLoader {
|
||||
load(content: string) {
|
||||
return yaml.safeLoad(content);
|
||||
}
|
||||
dump(variable: any): string {
|
||||
return yaml.safeDump(variable);
|
||||
}
|
||||
}
|
||||
|
||||
export class JsonPluginConfig implements PluginConfigLoader {
|
||||
load(content: string) {
|
||||
return JSON.parse(content);
|
||||
}
|
||||
dump(variable: any): string {
|
||||
return JSON.stringify(variable);
|
||||
}
|
||||
}
|
||||
|
||||
const configLoaderMap = new Map<string, PluginConfigLoader>();
|
||||
|
||||
export function getConfigLoader(format: string) {
|
||||
if (!configLoaderMap.has(format)) { throw new Error(`Unsupport config format ${format} !`) }
|
||||
return configLoaderMap.get(format);
|
||||
}
|
||||
|
||||
function init() {
|
||||
configLoaderMap.set("json", new JsonPluginConfig())
|
||||
let yaml = new YamlPluginConfig()
|
||||
configLoaderMap.set("yml", yaml)
|
||||
configLoaderMap.set("yaml", yaml)
|
||||
}
|
||||
|
||||
init()
|
||||
@@ -1,3 +1,7 @@
|
||||
export const METADATA_KEY = {
|
||||
plugin: "@ms/plugin:plugin",
|
||||
cmd: "@ms/plugin:cmd",
|
||||
tab: "@ms/plugin:tab",
|
||||
listener: "@ms/plugin:listener",
|
||||
config: "@ms/plugin:config",
|
||||
};
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { injectable, decorate } from "@ms/container";
|
||||
import { interfaces } from './interfaces'
|
||||
import { METADATA_KEY } from './constants'
|
||||
import { injectable, decorate } from "inversify";
|
||||
import { getPluginMetadatas } from './utils'
|
||||
import { getPluginMetadatas, getPluginCommandMetadata, getPluginListenerMetadata, getPluginTabCompleterMetadata, getPluginConfigMetadata } from './utils'
|
||||
|
||||
/**
|
||||
* MiaoScript plugin
|
||||
@@ -9,11 +9,65 @@ import { getPluginMetadatas } from './utils'
|
||||
*/
|
||||
export function plugin(metadata: interfaces.PluginMetadata) {
|
||||
return function(target: any) {
|
||||
target.description = metadata;
|
||||
metadata.target = target;
|
||||
decorate(injectable(), target);
|
||||
Reflect.defineMetadata(METADATA_KEY.plugin, metadata, target);
|
||||
const previousMetadata: interfaces.PluginMetadata[] = getPluginMetadatas();
|
||||
Reflect.defineMetadata(METADATA_KEY.plugin, [metadata, ...previousMetadata], Reflect);
|
||||
const previousMetadata: Map<string, interfaces.PluginMetadata> = getPluginMetadatas();
|
||||
previousMetadata.set(metadata.name, metadata);
|
||||
Reflect.defineMetadata(METADATA_KEY.plugin, previousMetadata, Reflect);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* MiaoScript Command
|
||||
* @param metadata CommandMetadata
|
||||
*/
|
||||
export function cmd(metadata: interfaces.CommandMetadata = {}) {
|
||||
return function(target: any, key: string, value: any) {
|
||||
metadata.name = metadata.name || key;
|
||||
metadata.executor = key;
|
||||
metadata.paramtypes = Reflect.getMetadata("design:paramtypes", target, key)
|
||||
const previousMetadata: Map<string, interfaces.CommandMetadata> = getPluginCommandMetadata(target)
|
||||
previousMetadata.set(metadata.name, metadata);
|
||||
Reflect.defineMetadata(METADATA_KEY.cmd, previousMetadata, target.constructor);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* MiaoScript TabComplete
|
||||
* @param metadata TabCompleterMetadata
|
||||
*/
|
||||
export function tab(metadata: interfaces.TabCompleterMetadata = {}) {
|
||||
return function(target: any, key: string, value: any) {
|
||||
metadata.name = metadata.name || (key.startsWith('tab') ? key.split('tab', 2)[1] : key);
|
||||
if (!metadata.name) { return; }
|
||||
metadata.executor = key;
|
||||
metadata.paramtypes = Reflect.getMetadata("design:paramtypes", target, key)
|
||||
const previousMetadata: Map<string, interfaces.TabCompleterMetadata> = getPluginTabCompleterMetadata(target)
|
||||
previousMetadata.set(metadata.name, metadata)
|
||||
Reflect.defineMetadata(METADATA_KEY.tab, previousMetadata, target.constructor);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* MiaoScript Listener
|
||||
* @param metadata ListenerMetadata
|
||||
*/
|
||||
export function listener(metadata: interfaces.ListenerMetadata = {}) {
|
||||
return function(target: any, key: string, value: any) {
|
||||
metadata.name = metadata.name || key;
|
||||
metadata.executor = key;
|
||||
const previousMetadata: interfaces.ListenerMetadata[] = getPluginListenerMetadata(target)
|
||||
Reflect.defineMetadata(METADATA_KEY.listener, [metadata, ...previousMetadata], target.constructor);
|
||||
};
|
||||
}
|
||||
|
||||
export function config(metadata: interfaces.ConfigMetadata = { version: 1, format: 'yml' }) {
|
||||
return function(target: any, key: string) {
|
||||
metadata.name = metadata.name || key;
|
||||
metadata.variable = key;
|
||||
const previousMetadata: Map<string, interfaces.ConfigMetadata> = getPluginConfigMetadata(target)
|
||||
previousMetadata.set(metadata.name, metadata);
|
||||
Reflect.defineMetadata(METADATA_KEY.config, previousMetadata, target.constructor);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { injectable, postConstruct } from "inversify";
|
||||
import { getPluginMetadata } from './utils'
|
||||
import { server, MiaoScriptConsole } from "@ms/api";
|
||||
import { METADATA_KEY } from './constants'
|
||||
import { injectable, inject, postConstruct } from "@ms/container";
|
||||
import { getPluginMetadata } from "./utils";
|
||||
|
||||
export namespace interfaces {
|
||||
@injectable()
|
||||
@@ -7,14 +9,61 @@ export namespace interfaces {
|
||||
public description: PluginMetadata;
|
||||
public logger: Console;
|
||||
|
||||
constructor(@inject(server.Console) Console: MiaoScriptConsole) {
|
||||
this.description = getPluginMetadata(this)
|
||||
// @ts-ignore
|
||||
this.logger = new Console(this.description.prefix || this.description.name)
|
||||
}
|
||||
|
||||
public load() { }
|
||||
public enable() { }
|
||||
public disable() { }
|
||||
}
|
||||
export interface PluginMetadata {
|
||||
interface BaseMetadata {
|
||||
name?: string;
|
||||
servers?: string[];
|
||||
}
|
||||
export interface PluginMetadata extends BaseMetadata {
|
||||
/**
|
||||
* 插件名称
|
||||
*/
|
||||
name: string;
|
||||
/**
|
||||
* 前缀
|
||||
*/
|
||||
prefix?: string;
|
||||
/**
|
||||
* 插件版本
|
||||
*/
|
||||
version: string;
|
||||
/**
|
||||
* 插件版本
|
||||
*/
|
||||
author: string | string[];
|
||||
/**
|
||||
* 插件源文件 必须指定为 __filename
|
||||
*/
|
||||
source: string;
|
||||
/**
|
||||
* 插件本体
|
||||
*/
|
||||
target?: any;
|
||||
}
|
||||
interface ExecMetadata extends BaseMetadata {
|
||||
executor?: string;
|
||||
}
|
||||
export interface CommandMetadata extends ExecMetadata {
|
||||
paramtypes?: string[];
|
||||
}
|
||||
export interface TabCompleterMetadata extends ExecMetadata {
|
||||
paramtypes?: string[];
|
||||
}
|
||||
export interface ListenerMetadata extends ExecMetadata {
|
||||
}
|
||||
export interface ConfigMetadata extends BaseMetadata {
|
||||
version?: number;
|
||||
variable?: string;
|
||||
format?: string;
|
||||
}
|
||||
export type PluginLike = Plugin | string;
|
||||
}
|
||||
|
||||
@@ -1,139 +1,251 @@
|
||||
import { plugin, server, MiaoScriptConsole } from '@ms/api'
|
||||
import { injectable, inject, postConstruct, Container } from '@ms/container'
|
||||
import { plugin, server, command, event } from '@ms/api'
|
||||
import { injectable, inject, postConstruct, Container, ContainerInstance } from '@ms/container'
|
||||
import * as fs from '@ms/common/dist/fs'
|
||||
|
||||
import { getPluginMetadatas } from './utils'
|
||||
import { interfaces } from './interfaces';
|
||||
import { getPluginMetadatas, getPluginCommandMetadata, getPluginListenerMetadata, getPlugin, getPluginTabCompleterMetadata, getPluginConfigMetadata } from './utils'
|
||||
import { interfaces } from './interfaces'
|
||||
import { getConfigLoader } from './config'
|
||||
|
||||
@injectable()
|
||||
export class PluginManagerImpl implements plugin.PluginManager {
|
||||
@inject(ContainerInstance)
|
||||
private container: Container
|
||||
@inject(plugin.PluginInstance)
|
||||
private pluginInstance: any;
|
||||
private pluginInstance: any
|
||||
@inject(plugin.PluginFolder)
|
||||
private pluginFolder: string;
|
||||
@inject(server.ServerType)
|
||||
private serverType: string;
|
||||
@inject(server.Console)
|
||||
private Console: MiaoScriptConsole;
|
||||
private serverType: string
|
||||
@inject(command.Command)
|
||||
private CommandManager: command.Command
|
||||
@inject(event.Event)
|
||||
private EventManager: event.Event
|
||||
|
||||
private pluginMap: Map<string, interfaces.Plugin>;
|
||||
private pluginMap: Map<string, interfaces.Plugin>
|
||||
|
||||
@postConstruct()
|
||||
init() {
|
||||
initialize() {
|
||||
if (this.pluginInstance !== null) {
|
||||
// 如果plugin不等于null 则代表是正式环境
|
||||
console.info(`Initialization MiaoScript Plugin System: ${this.pluginInstance} ...`);
|
||||
this.pluginMap = new Map();
|
||||
console.info(`Initialization MiaoScript Plugin System: ${this.pluginInstance} ...`)
|
||||
this.pluginMap = new Map()
|
||||
console.info(`${this.EventManager.mapEventName().toFixed(0)} ${this.serverType} Event Mapping Complate...`)
|
||||
}
|
||||
}
|
||||
|
||||
scan(folder: string): void {
|
||||
var plugin = fs.file(root, folder);
|
||||
var plugin = fs.file(root, folder)
|
||||
var files = []
|
||||
// load common plugin
|
||||
.concat(this.scanFloder(plugin))
|
||||
// load space plugin
|
||||
.concat(this.scanFloder(fs.file(plugin, this.serverType)))
|
||||
this.loadPlugins(files);
|
||||
this.loadPlugins(files)
|
||||
}
|
||||
|
||||
load(container: Container): void {
|
||||
this.buildPlugins(container);
|
||||
build(): void {
|
||||
this.buildPlugins()
|
||||
}
|
||||
|
||||
enable(): void {
|
||||
this.pluginMap.forEach(pl => this.runCatch(pl, 'load'));
|
||||
this.pluginMap.forEach(pl => this.runCatch(pl, 'enable'));
|
||||
private logStage(plugin: interfaces.Plugin, stage: string) {
|
||||
console.log(`[${plugin.description.name}] ${stage} ${plugin.description.name} version ${plugin.description.version} by ${plugin.description.author || 'Unknow'}`)
|
||||
}
|
||||
|
||||
disable(): void {
|
||||
throw new Error("Method not implemented.");
|
||||
load(...args: any[]): void {
|
||||
this.checkAndGet(args[0]).forEach((plugin: interfaces.Plugin) => {
|
||||
this.logStage(plugin, "Loading")
|
||||
this.loadConfig(plugin)
|
||||
this.runCatch(plugin, 'load')
|
||||
this.runCatch(plugin, `${this.serverType}load`)
|
||||
})
|
||||
}
|
||||
|
||||
enable(...args: any[]): void {
|
||||
this.checkAndGet(args[0]).forEach((plugin: interfaces.Plugin) => {
|
||||
this.logStage(plugin, "Enabling")
|
||||
this.runCatch(plugin, 'enable')
|
||||
this.runCatch(plugin, `${this.serverType}enable`)
|
||||
this.registryCommand(plugin)
|
||||
this.registryListener(plugin)
|
||||
})
|
||||
}
|
||||
|
||||
disable(...args: any[]): void {
|
||||
this.checkAndGet(args[0]).forEach((plugin: interfaces.Plugin) => {
|
||||
this.logStage(plugin, "Disabling")
|
||||
this.runCatch(plugin, 'disable')
|
||||
this.runCatch(plugin, `${this.serverType}disable`)
|
||||
this.unregistryCommand(plugin)
|
||||
this.unregistryListener(plugin)
|
||||
})
|
||||
}
|
||||
|
||||
reload(...args: any[]): void {
|
||||
this.checkAndGet(args[0]).forEach((pl: interfaces.Plugin) => {
|
||||
this.disable(pl)
|
||||
this.loadPlugin(pl.description.source)
|
||||
pl = this.buildPlugin(getPlugin(pl.description.name))
|
||||
this.load(pl)
|
||||
this.enable(pl)
|
||||
})
|
||||
}
|
||||
|
||||
getPlugins() {
|
||||
return this.pluginMap
|
||||
}
|
||||
|
||||
private runCatch(pl: any, func: string) {
|
||||
try {
|
||||
pl[func].call(pl);
|
||||
if (pl[func]) pl[func].call(pl)
|
||||
} catch (ex) {
|
||||
console.console(`§6插件 §b${pl.description.name} §6执行 §d${func} §6方法时发生错误 §4${ex}`);
|
||||
console.ex(ex);
|
||||
console.console(`§6插件 §b${pl.description.name} §6执行 §d${func} §6方法时发生错误 §4${ex}`)
|
||||
console.ex(ex)
|
||||
}
|
||||
}
|
||||
|
||||
private checkAndGet(name: string | interfaces.Plugin | undefined): Map<string, interfaces.Plugin> | interfaces.Plugin[] {
|
||||
if (name == undefined) { return this.pluginMap }
|
||||
if (typeof name == 'string' && this.pluginMap.has(name)) { return [this.pluginMap.get(name)] }
|
||||
if (name instanceof interfaces.Plugin) { return [name as interfaces.Plugin] }
|
||||
throw new Error(`Plugin ${JSON.stringify(name)} not exist!`)
|
||||
}
|
||||
|
||||
private scanFloder(plugin: any): string[] {
|
||||
var files = [];
|
||||
console.info(`Start Scan Plugins in ${plugin} ...`);
|
||||
this.checkUpdateFolder(plugin);
|
||||
fs.list(plugin).forEach(function searchPlugin(file) {
|
||||
files.push(file.toFile());
|
||||
});
|
||||
return files;
|
||||
var files = []
|
||||
console.info(`Scanning Plugins in ${plugin} ...`)
|
||||
this.checkUpdateFolder(plugin)
|
||||
// must check file is exist maybe is a illegal symbolic link file
|
||||
fs.list(plugin).forEach((file: any) => file.toFile().exists() ? files.push(file.toFile()) : void 0)
|
||||
return files
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新插件
|
||||
* @param path
|
||||
*/
|
||||
private checkUpdateFolder(path) {
|
||||
var update = fs.file(path, "update");
|
||||
private checkUpdateFolder(path: any) {
|
||||
var update = fs.file(path, "update")
|
||||
if (!update.exists()) {
|
||||
update.mkdirs();
|
||||
update.mkdirs()
|
||||
}
|
||||
}
|
||||
|
||||
private loadPlugins(files: any[]): void {
|
||||
this.loadJsPlugins(files);
|
||||
this.loadJsPlugins(files)
|
||||
}
|
||||
|
||||
/**
|
||||
* JS类型插件预加载
|
||||
*/
|
||||
private loadJsPlugins(files: any[]) {
|
||||
files.filter(file => file.name.endsWith(".js")).forEach(file => {
|
||||
try {
|
||||
this.loadPlugin(file)
|
||||
} catch (ex) {
|
||||
console.console(`§6插件 §b${file.name} §6初始化时发生错误 §4${ex.message}`);
|
||||
console.ex(ex);
|
||||
}
|
||||
})
|
||||
files.filter(file => file.name.endsWith(".js")).forEach(file => this.loadPlugin(file))
|
||||
}
|
||||
|
||||
private loadPlugin(file: any) {
|
||||
this.updatePlugin(file);
|
||||
this.createPlugin(file);
|
||||
try {
|
||||
this.updatePlugin(file)
|
||||
this.createPlugin(file)
|
||||
} catch (ex) {
|
||||
console.console(`§6插件 §b${file.name} §6初始化时发生错误 §4${ex.message}`)
|
||||
console.ex(ex)
|
||||
}
|
||||
}
|
||||
|
||||
private updatePlugin(file: any) {
|
||||
var update = fs.file(fs.file(file.parentFile, 'update'), file.name);
|
||||
var update = fs.file(fs.file(file.parentFile, 'update'), file.name)
|
||||
if (update.exists()) {
|
||||
console.info(`Auto Update Plugin ${file.name} ...`);
|
||||
fs.move(update, file, true);
|
||||
console.info(`Auto Update Plugin ${file.name} ...`)
|
||||
fs.move(update, file, true)
|
||||
}
|
||||
}
|
||||
|
||||
private createPlugin(file) {
|
||||
private checkServers(servers: string[]) {
|
||||
if (!servers) { return true }
|
||||
return servers?.indexOf(this.serverType) != -1 && servers?.indexOf(`!${this.serverType}`) == -1
|
||||
}
|
||||
|
||||
private createPlugin(file: string) {
|
||||
//@ts-ignore
|
||||
require(file, {
|
||||
cache: false
|
||||
});
|
||||
require(file, { cache: false })
|
||||
}
|
||||
|
||||
private beforeLoadHook(origin) {
|
||||
var result = origin;
|
||||
// // 注入 console 对象 // 给插件注入单独的 console
|
||||
// result += '\nvar console = new Console(); module.exports.console = console;';
|
||||
// // 插件注入 self 对象
|
||||
// result += '\nvar self = {}; module.exports.self = self;';
|
||||
return result;
|
||||
}
|
||||
|
||||
private buildPlugins(container: Container) {
|
||||
let pluginMetadatas = getPluginMetadatas();
|
||||
for (const metadata of pluginMetadatas) {
|
||||
container.bind(plugin.Plugin).to(metadata.target).inSingletonScope().whenTargetNamed(metadata.name);
|
||||
this.pluginMap.set(metadata.name, container.getNamed(plugin.Plugin, metadata.name));
|
||||
let pluginInstance = this.pluginMap.get(metadata.name)
|
||||
pluginInstance.description = metadata;
|
||||
// @ts-ignore
|
||||
pluginInstance.logger = new this.Console(metadata.name);
|
||||
private buildPlugins() {
|
||||
let pluginMetadatas = getPluginMetadatas()
|
||||
for (const [_, metadata] of pluginMetadatas) {
|
||||
if (!this.checkServers(metadata.servers)) { continue }
|
||||
this.buildPlugin(metadata)
|
||||
}
|
||||
}
|
||||
|
||||
private buildPlugin(metadata: interfaces.PluginMetadata) {
|
||||
this.bindPlugin(metadata)
|
||||
let pluginInstance = this.container.getNamed<interfaces.Plugin>(plugin.Plugin, metadata.name)
|
||||
if (!(pluginInstance instanceof interfaces.Plugin)) {
|
||||
console.console(`§4found error plugin §b${metadata.source} §4it's not extends interfaces.Plugin, the plugin will be ignore!`)
|
||||
return
|
||||
}
|
||||
this.pluginMap.set(metadata.name, pluginInstance)
|
||||
return pluginInstance
|
||||
}
|
||||
|
||||
private bindPlugin(metadata: interfaces.PluginMetadata) {
|
||||
try {
|
||||
let pluginInstance = this.container.getNamed<interfaces.Plugin>(plugin.Plugin, metadata.name)
|
||||
if (pluginInstance.description.source + '' !== metadata.source + '') {
|
||||
console.console(`§4found duplicate plugin §b${pluginInstance.description.source} §4and §b${metadata.source}§4. the first plugin will be ignore!`)
|
||||
}
|
||||
this.container.rebind(plugin.Plugin).to(metadata.target).inSingletonScope().whenTargetNamed(metadata.name)
|
||||
} catch{
|
||||
this.container.bind(plugin.Plugin).to(metadata.target).inSingletonScope().whenTargetNamed(metadata.name)
|
||||
}
|
||||
}
|
||||
|
||||
private loadConfig(plugin: interfaces.Plugin) {
|
||||
let configs = getPluginConfigMetadata(plugin);
|
||||
for (let [_, config] of configs) {
|
||||
let configFile = fs.concat(root, this.pluginFolder, plugin.description.name, config.name + '.' + config.format)
|
||||
console.log(configFile)
|
||||
let configFactory = getConfigLoader(config.format);
|
||||
if (!fs.exists(configFile)) {
|
||||
base.save(configFile, configFactory.dump(plugin[config.variable]))
|
||||
console.log(`[${plugin.description.name}] config ${config.name}.${config.format} don't exists auto create from default variable...`)
|
||||
} else {
|
||||
plugin[config.variable] = configFactory.load(base.read(configFile));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private registryCommand(pluginInstance: interfaces.Plugin) {
|
||||
let cmds = getPluginCommandMetadata(pluginInstance)
|
||||
let tabs = getPluginTabCompleterMetadata(pluginInstance)
|
||||
for (const [_, cmd] of cmds) {
|
||||
let tab = tabs.get(cmd.name)
|
||||
if (!this.checkServers(cmd.servers)) { continue }
|
||||
this.CommandManager.on(pluginInstance, cmd.name, {
|
||||
cmd: pluginInstance[cmd.executor].bind(pluginInstance),
|
||||
tab: tab ? pluginInstance[tab.executor].bind(pluginInstance) : undefined
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
private registryListener(pluginInstance: interfaces.Plugin) {
|
||||
let events = getPluginListenerMetadata(pluginInstance)
|
||||
for (const event of events) {
|
||||
// ignore space listener
|
||||
if (!this.checkServers(event.servers)) { continue }
|
||||
// here must bind this to pluginInstance
|
||||
this.EventManager.listen(pluginInstance, event.name, pluginInstance[event.executor].bind(pluginInstance))
|
||||
}
|
||||
}
|
||||
|
||||
private unregistryCommand(pluginInstance: interfaces.Plugin) {
|
||||
let cmds = getPluginCommandMetadata(pluginInstance)
|
||||
cmds.forEach(cmd => {
|
||||
this.CommandManager.off(pluginInstance, cmd.name)
|
||||
})
|
||||
}
|
||||
|
||||
private unregistryListener(pluginInstance: interfaces.Plugin) {
|
||||
this.EventManager.disable(pluginInstance)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,27 +2,68 @@ import { interfaces } from './interfaces'
|
||||
import { METADATA_KEY } from './constants'
|
||||
|
||||
function getPlugins() {
|
||||
return getPluginMetadatas().map((target) => target.target);
|
||||
return [...getPluginMetadatas().values()].map((target) => target.target);
|
||||
}
|
||||
|
||||
function getPlugin(name: string) {
|
||||
return getPluginMetadatas().get(name);
|
||||
}
|
||||
|
||||
function getPluginMetadatas() {
|
||||
let pluginMetadatas: interfaces.PluginMetadata[] = Reflect.getMetadata(
|
||||
let pluginMetadatas: Map<string, interfaces.PluginMetadata> = Reflect.getMetadata(
|
||||
METADATA_KEY.plugin,
|
||||
Reflect
|
||||
) || [];
|
||||
) || new Map<string, interfaces.PluginMetadata>();
|
||||
return pluginMetadatas;
|
||||
}
|
||||
|
||||
function getPluginMetadata(target: any) {
|
||||
let pluginMetadata: interfaces.PluginMetadata = Reflect.getMetadata(
|
||||
METADATA_KEY.plugin,
|
||||
target
|
||||
target.constructor
|
||||
) || {};
|
||||
return pluginMetadata;
|
||||
}
|
||||
|
||||
function getPluginCommandMetadata(target: any) {
|
||||
let commandMetadata: Map<string, interfaces.CommandMetadata> = Reflect.getMetadata(
|
||||
METADATA_KEY.cmd,
|
||||
target.constructor
|
||||
) || new Map<string, interfaces.CommandMetadata>();
|
||||
return commandMetadata;
|
||||
}
|
||||
|
||||
function getPluginTabCompleterMetadata(target: any) {
|
||||
let tabcompleterMetadata: Map<string, interfaces.TabCompleterMetadata> = Reflect.getMetadata(
|
||||
METADATA_KEY.tab,
|
||||
target.constructor
|
||||
) || new Map<string, interfaces.TabCompleterMetadata>();
|
||||
return tabcompleterMetadata;
|
||||
}
|
||||
|
||||
function getPluginListenerMetadata(target: any) {
|
||||
let listnerMetadata: interfaces.ListenerMetadata[] = Reflect.getMetadata(
|
||||
METADATA_KEY.listener,
|
||||
target.constructor
|
||||
) || [];
|
||||
return listnerMetadata;
|
||||
}
|
||||
|
||||
function getPluginConfigMetadata(target: any) {
|
||||
let configMetadata: Map<string, interfaces.ConfigMetadata> = Reflect.getMetadata(
|
||||
METADATA_KEY.config,
|
||||
target.constructor
|
||||
) || new Map<string, interfaces.ConfigMetadata>();
|
||||
return configMetadata;
|
||||
}
|
||||
|
||||
export {
|
||||
getPlugin,
|
||||
getPlugins,
|
||||
getPluginMetadatas,
|
||||
getPluginMetadata
|
||||
getPluginMetadata,
|
||||
getPluginCommandMetadata,
|
||||
getPluginTabCompleterMetadata,
|
||||
getPluginListenerMetadata,
|
||||
getPluginConfigMetadata
|
||||
}
|
||||
|
||||
36
packages/plugins/package.json
Normal file
36
packages/plugins/package.json
Normal file
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"private": true,
|
||||
"name": "@ms/plugins",
|
||||
"version": "0.2.1",
|
||||
"description": "MiaoScript plugins package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
"minecraft",
|
||||
"bukkit",
|
||||
"sponge"
|
||||
],
|
||||
"author": "MiaoWoo <admin@yumc.pw>",
|
||||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"publishConfig": {
|
||||
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
|
||||
},
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.8.2"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ms/plugin": "^0.2.1",
|
||||
"axios": "^0.19.2",
|
||||
"es6-map": "^0.1.5",
|
||||
"inversify": "^5.0.1"
|
||||
}
|
||||
}
|
||||
78
packages/plugins/public/index.html
Normal file
78
packages/plugins/public/index.html
Normal file
@@ -0,0 +1,78 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
|
||||
<!-- UC应用模式 -->
|
||||
<meta name="browsermode" content="application">
|
||||
<!-- QQ应用模式 -->
|
||||
<meta name="x5-page-mode" content="app">
|
||||
<title>MiaoConsole 调试工具</title>
|
||||
<script src="https://cdn.jsdelivr.net/npm/axios@0.19.0/dist/axios.min.js"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/jquery@3.3.1/dist/jquery.min.js"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/avalon2@2.2.10/dist/avalon.min.js"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@3.4.1/dist/js/bootstrap.min.js"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/js-yaml@3.13.0/dist/js-yaml.min.js"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/messenger-hubspot@1.5.0/build/js/messenger.min.js"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/messenger-hubspot@1.5.0/build/js/messenger-theme-future.js"></script>
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/xterm@3.12.2/dist/xterm.js"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/xterm@3.12.2/dist/addons/fit/fit.js"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/xterm@3.12.2/dist/addons/attach/attach.js"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/xterm@3.12.2/dist/addons/fullscreen/fullscreen.js"></script>
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/xterm@3.12.2/dist/xterm.css" />
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/xterm@3.12.2/dist/addons/fullscreen/fullscreen.css">
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/monaco-editor@0.18.1/min/vs/loader.js"></script>
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/monaco-editor@0.18.1/min/vs/editor/editor.main.css">
|
||||
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.4.1/dist/css/bootstrap.min.css">
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@3.0.1/github-markdown.min.css">
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/messenger-hubspot@1.5.0/build/css/messenger.min.css">
|
||||
<link rel="stylesheet"
|
||||
href="https://cdn.jsdelivr.net/npm/messenger-hubspot@1.5.0/build/css/messenger-theme-future.min.css">
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/axios@0.19.0/dist/axios.min.js"></script>
|
||||
|
||||
<!-- <script src="https://raw.githubusercontent.com/imaya/zlib.js/develop/bin/gzip.min.js"></script>
|
||||
<script src="https://raw.githubusercontent.com/imaya/zlib.js/develop/bin/gunzip.min.js"></script> -->
|
||||
|
||||
<script src="js/message.js"></script>
|
||||
<script src="js/term.js"></script>
|
||||
<script src="js/websocket.js"></script>
|
||||
<script src="js/main.js"></script>
|
||||
<script src="js/editor.js"></script>
|
||||
</head>
|
||||
|
||||
<body noscroll="true">
|
||||
<div class="container-fluid bs-docs-container" :controller="main">
|
||||
<h3>欢迎使用 MiaoConsole 调试控制台</h3>
|
||||
<div class="input-group">
|
||||
<span class="input-group-addon">服务器地址</span>
|
||||
<input id="address" class="form-control" :duplex="@server" :keydown="@connect" style="width: 100%"></input>
|
||||
<a class="input-group-addon btn" :click="@connect">连接</a>
|
||||
</div>
|
||||
<div class="panel panel-success" style="margin-top: 10px; height: 332px;">
|
||||
<div class="panel-heading">服务器日志 当前服务器类型: {{@type}}</div>
|
||||
<div id="terminal" style="height: 300px; width:100%;"></div>
|
||||
</div>
|
||||
<div class="progress progress-striped active" :visible='@classes.total != @classes.loaded'>
|
||||
<div class="progress-bar progress-bar-primary" role="progressbar" aria-valuenow="60" aria-valuemin="0"
|
||||
aria-valuemax="100" :css="{width: (@classes.loaded/@classes.total*100) +'%', 'min-width': '20em'}">
|
||||
<span>正在加载 {{@type}} 类型定义 {{@classes.loaded}}/{{@classes.total}}({{~~(@classes.loaded/@classes.total*100)|percent}}%) </span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="panel panel-info" :visible='@classes.total == @classes.loaded && @classes.total != 0'>
|
||||
<div class="panel-heading">代码编辑器</div>
|
||||
<label class="col-sm-1 control-label">代码页</label>
|
||||
<label :for="el in @codes" class="radio-inline">
|
||||
<input type="radio" :duplex="@code" :attr="{value:el}"> {{el}}
|
||||
</label>
|
||||
<div id="editor" style="height: 450px; width:100%;"></div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
69
packages/plugins/public/js/editor.js
Normal file
69
packages/plugins/public/js/editor.js
Normal file
@@ -0,0 +1,69 @@
|
||||
let editor
|
||||
let monaco_path = 'https://cdn.jsdelivr.net/npm/monaco-editor@0.18.1/min'
|
||||
require.config({ paths: { 'vs': monaco_path + '/vs' } });
|
||||
window.MonacoEnvironment = { getWorkerUrl: () => proxy };
|
||||
let proxy = URL.createObjectURL(new Blob([`self.MonacoEnvironment = {baseUrl: '${monaco_path}/'};
|
||||
importScripts('${monaco_path}/vs/base/worker/workerMain.js');`], { type: 'text/javascript' }));
|
||||
|
||||
function loadExtraLibs(ts_d_src, filter) {
|
||||
let count = 0;
|
||||
axios.get(`${ts_d_src}/index.d.ts`).then(async result => {
|
||||
monaco.languages.typescript.javascriptDefaults.addExtraLib(result.data, 'file:///src/typings/index.d.ts')
|
||||
let classes = result.data.split('\n').map(line => line.match(/.*\.\/(.*)".*/)).filter(line => line).map(dts => dts[1])
|
||||
if (filter) {
|
||||
classes = classes.filter(line => filter(line))
|
||||
}
|
||||
main.classes.total += classes.length
|
||||
for (let fname of classes) {
|
||||
if (count++ % 50 == 0) { await axios.get(`${ts_d_src}/${fname}`) }
|
||||
loadExtraLib(`${ts_d_src}/${fname}`, `file:///src/typings/${fname}`)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function loadExtraLib(url, file) {
|
||||
axios.get(url).then(result => monaco.languages.typescript.javascriptDefaults.addExtraLib(result.data, file)).finally(() => main.classes.loaded++)
|
||||
}
|
||||
|
||||
require(["vs/editor/editor.main"], async function() {
|
||||
main.classes.total = 0
|
||||
main.classes.loaded = 0
|
||||
editor = monaco.editor.create(document.getElementById('editor'), {
|
||||
value: '',
|
||||
language: 'javascript',
|
||||
automaticLayout: true,
|
||||
scrollBeyondLastLine: false,
|
||||
theme: 'vs-dark'
|
||||
});
|
||||
main.load(editor)
|
||||
editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KEY_S, function() {
|
||||
main.save(editor)
|
||||
})
|
||||
editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KEY_R, function() {
|
||||
main.send('execCode', getSelectContent(editor) || editor.getValue())
|
||||
})
|
||||
editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KEY_E, function() {
|
||||
main.send('execCommand', getSelectContent(editor))
|
||||
})
|
||||
editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KEY_Q, function() {
|
||||
main.switch(editor)
|
||||
})
|
||||
loadExtraLibs(`https://cdn.jsdelivr.net/gh/circlecloud/ms@master/packages/types/dist/typings/jdk`, (line) => line.startsWith('java.lang'))
|
||||
if (main.type !== 'unknow') {
|
||||
loadExtraLibs(`https://cdn.jsdelivr.net/gh/circlecloud/ms@master/packages/types/dist/typings/${main.type}`)
|
||||
}
|
||||
});
|
||||
function getSelectContent(editor) {
|
||||
let selInfo = editor.getSelection();
|
||||
if (selInfo.startLineNumber === selInfo.endLineNumber) {
|
||||
return editor.getModel().getLineContent(selInfo.startLineNumber).substr(selInfo.startColumn - 1, selInfo.endColumn - selInfo.startColumn);
|
||||
} else {
|
||||
let first = editor.getModel().getLineContent(selInfo.startLineNumber).substr(selInfo.startColumn - 1)
|
||||
let content = '\n'
|
||||
for (let i = selInfo.startLineNumber + 1; i < selInfo.endLineNumber; i++) {
|
||||
content += editor.getModel().getLineContent(i) + '\n'
|
||||
}
|
||||
let last = editor.getModel().getLineContent(selInfo.endLineNumber).substr(0, selInfo.endColumn - 1)
|
||||
return first + content + last
|
||||
}
|
||||
}
|
||||
55
packages/plugins/public/js/main.js
Normal file
55
packages/plugins/public/js/main.js
Normal file
@@ -0,0 +1,55 @@
|
||||
var SPLIT_LINE = '\\M\\W\\S|T|S|S/L/T/'
|
||||
let serverKey = 'MiaoScript:server'
|
||||
let codeStorageKey = "MiaoScript:code:"
|
||||
var main = avalon.define({
|
||||
$id: 'main',
|
||||
server: window.localStorage.getItem(serverKey) || location.host,
|
||||
type: 'unknow',
|
||||
logs: '',
|
||||
codes: ["default", "bukkit", "sponge", "bungee", "common", "test", "dev", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
|
||||
code: 'default',
|
||||
classes: {
|
||||
total: 0,
|
||||
loaded: 0,
|
||||
},
|
||||
precent: () => {
|
||||
return classes.total
|
||||
},
|
||||
log: (info) => {
|
||||
info.split("\n").forEach((line) => { term.writeln(mcColor2ANSI(line + '§r')) })
|
||||
},
|
||||
send: (type, content) => {
|
||||
if (!ws || ws.readyState != 1) { term.writeln('Please Connect to Server first!'); return; }
|
||||
ws.send(`${type}${SPLIT_LINE}${content}`);
|
||||
},
|
||||
connect: (event = { key: 'Enter' }) => {
|
||||
if (event.key !== "Enter") {
|
||||
return;
|
||||
}
|
||||
connectWebSocket()
|
||||
},
|
||||
init: () => {
|
||||
if (main.server) {
|
||||
main.connect()
|
||||
}
|
||||
},
|
||||
load: (editor) => {
|
||||
editor.setValue(window.localStorage.getItem(codeStorageKey + main.code) || '')
|
||||
},
|
||||
save: (editor) => {
|
||||
window.localStorage.setItem(codeStorageKey + main.code, editor.getValue())
|
||||
showMessenger('代码页 ' + main.code + ' 保存成功!')
|
||||
},
|
||||
switch: (editor) => {
|
||||
let index = main.codes.indexOf(main.code) + 1
|
||||
main.code = main.codes[index == main.codes.length ? 0 : index]
|
||||
}
|
||||
});
|
||||
|
||||
main.$watch('code', (now, old, name) => {
|
||||
window.localStorage.setItem(codeStorageKey + old, editor.getValue())
|
||||
showMessenger('代码页 ' + old + ' 保存成功!')
|
||||
editor.setValue(window.localStorage.getItem(codeStorageKey + now) || '// empty code page ' + now)
|
||||
})
|
||||
|
||||
main.init()
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user