Compare commits
83 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 7b8e693a03 | |||
| 5426023adb | |||
| 73b91c417e | |||
| 2693a22bf0 | |||
| 2322de1e40 | |||
| 2320736a92 | |||
| e8d5d10d44 | |||
| a9996ba297 | |||
| 68380ddbba | |||
| 0baf8f3cab | |||
| a2bce715f3 | |||
| 3c55df03d8 | |||
| f6526e79fc | |||
| f4c2294c06 | |||
| 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 |
3
.gitignore
vendored
3
.gitignore
vendored
@@ -1,5 +1,8 @@
|
|||||||
|
.vscode
|
||||||
|
.theia
|
||||||
node_modules
|
node_modules
|
||||||
dist
|
dist
|
||||||
package-lock.json
|
package-lock.json
|
||||||
yarn.lock
|
yarn.lock
|
||||||
packages/nashorn/docs
|
packages/nashorn/docs
|
||||||
|
!packages/types/dist
|
||||||
|
|||||||
@@ -11,12 +11,19 @@
|
|||||||
├─api 全平台兼容的接口
|
├─api 全平台兼容的接口
|
||||||
├─core 核心代码 用于引导加载
|
├─core 核心代码 用于引导加载
|
||||||
├─common 公共类库代码 例如 http reflect 模块
|
├─common 公共类库代码 例如 http reflect 模块
|
||||||
|
├─compile 实时编译模块 自动编译TS文件为js
|
||||||
├─container IOC容器 用于注入具体实现
|
├─container IOC容器 用于注入具体实现
|
||||||
├─nashorn Nashorn 的类型定义
|
├─nashorn Nashorn 的类型定义
|
||||||
|
├─ployfill Java Nashorn的补丁
|
||||||
|
├─bungee BungeeCordAPI内部实现
|
||||||
├─bukkit BukkitAPI内部实现
|
├─bukkit BukkitAPI内部实现
|
||||||
├─sponge SpongeAPI内部实现
|
├─sponge SpongeAPI内部实现
|
||||||
├─plugin 插件管理器
|
├─plugin 插件管理器
|
||||||
|
├─manager 插件管理中心后端服务
|
||||||
|
├─types Java在TypeScript的类型定义文件
|
||||||
|
├─websocket Netty的WebSocket的MiaoScript实现(兼容socket.io)
|
||||||
└─plugins 这里当然是插件啦
|
└─plugins 这里当然是插件啦
|
||||||
|
├─bungee 只兼容BungeeCord的插件
|
||||||
├─bukkit 只兼容Bukkit的插件
|
├─bukkit 只兼容Bukkit的插件
|
||||||
└─sponge 只兼容Sponge的插件
|
└─sponge 只兼容Sponge的插件
|
||||||
```
|
```
|
||||||
|
|||||||
125
doc/MCBBS.MD
125
doc/MCBBS.MD
@@ -13,8 +13,8 @@
|
|||||||
## 插件简介
|
## 插件简介
|
||||||
|
|
||||||
- 此插件可以实现跨端使用 `TypeScript` 开发 脚本插件
|
- 此插件可以实现跨端使用 `TypeScript` 开发 脚本插件
|
||||||
- 目前已经兼容 `Spigot` `Sponge`
|
- 目前已经兼容 `Spigot` `Sponge` `Paper` `CatServer` `BungeeCord` `Nukkit`
|
||||||
- 后续计划兼容 `BungeeCord` `Nukkit`
|
- 后续计划兼容 暂无
|
||||||
|
|
||||||
## 起源 (可以略过)
|
## 起源 (可以略过)
|
||||||
|
|
||||||
@@ -91,20 +91,32 @@
|
|||||||
├─api 全平台兼容的接口
|
├─api 全平台兼容的接口
|
||||||
├─core 核心代码 用于引导加载
|
├─core 核心代码 用于引导加载
|
||||||
├─common 公共类库代码 例如 http reflect 模块
|
├─common 公共类库代码 例如 http reflect 模块
|
||||||
|
├─client NodeJS的Minecraft客户端 用于调试插件
|
||||||
├─container IOC容器 用于注入具体实现
|
├─container IOC容器 用于注入具体实现
|
||||||
|
├─ployfill Nashorn 的一些自定义增强
|
||||||
├─nashorn Nashorn 的类型定义
|
├─nashorn Nashorn 的类型定义
|
||||||
|
├─bungee BungeeCordAPI内部实现
|
||||||
├─bukkit BukkitAPI内部实现
|
├─bukkit BukkitAPI内部实现
|
||||||
├─sponge SpongeAPI内部实现
|
├─sponge SpongeAPI内部实现
|
||||||
├─ployfill JS环境的相关环境补全
|
├─ployfill JS环境的相关环境补全
|
||||||
├─plugin 插件管理器
|
├─plugin 插件管理器
|
||||||
|
├─type Java的类型定义
|
||||||
|
| ├─bungee BungeeCord类型定义
|
||||||
|
| ├─bukkit Bukkit类型定义
|
||||||
|
| ├─sponge Sponge类型定义
|
||||||
|
| └─nukkit Nukkit类型定义
|
||||||
|
├─websocket Netty的WebSocket注入
|
||||||
└─plugins 这里当然是插件啦
|
└─plugins 这里当然是插件啦
|
||||||
|
├─bungee 只兼容BungeeCord的插件
|
||||||
├─bukkit 只兼容Bukkit的插件
|
├─bukkit 只兼容Bukkit的插件
|
||||||
└─sponge 只兼容Sponge的插件
|
├─sponge 只兼容Sponge的插件
|
||||||
|
└─nukkit 只兼容Nukkit的插件
|
||||||
```
|
```
|
||||||
|
|
||||||
详细的内容就不逼逼了 自己看代码吧
|
详细的内容就不逼逼了 自己看代码吧
|
||||||
|
|
||||||
Github: https://github.com/circlecloud/ms
|
Github: https://github.com/circlecloud/ms
|
||||||
|
YUMC: https://git.yumc.pw/circlecloud/ms
|
||||||
|
|
||||||
## 插件开发基础
|
## 插件开发基础
|
||||||
|
|
||||||
@@ -134,21 +146,28 @@ Github: https://github.com/circlecloud/ms
|
|||||||
先来一个 `HelloWorld.ts` 插件示范!
|
先来一个 `HelloWorld.ts` 插件示范!
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
/// <reference types="@ms/bukkit/dist/typings" />
|
/// <reference types="@ms/types/dist/typings/bukkit" />
|
||||||
/// <reference types="@ms/sponge/dist/typings" />
|
/// <reference types="@ms/types/dist/typings/sponge" />
|
||||||
|
/// <reference types="@ms/types/dist/typings/bungee" />
|
||||||
|
/// <reference types="@ms/types/dist/typings/nukkit" />
|
||||||
|
|
||||||
|
import { server } from '@ms/api';
|
||||||
|
import { inject } from '@ms/container';
|
||||||
import { plugin, interfaces, cmd, listener, tab } from '@ms/plugin'
|
import { plugin, interfaces, cmd, listener, tab } from '@ms/plugin'
|
||||||
|
|
||||||
@plugin({ name: 'HelloWorld', version: '1.0.0', author: 'MiaoWoo', source: __filename })
|
@plugin({ name: 'HelloWorld', version: '1.0.0', author: 'MiaoWoo', source: __filename })
|
||||||
export class HelloWorld extends interfaces.Plugin {
|
export class HelloWorld extends interfaces.Plugin {
|
||||||
|
@inject(server.Server)
|
||||||
|
private Server: server.Server
|
||||||
|
|
||||||
load() {
|
load() {
|
||||||
this.logger.log('Test Plugin load from MiaoScript Plugin System...');
|
this.logger.log('Plugin load from MiaoScript Plugin System...');
|
||||||
}
|
}
|
||||||
enable() {
|
enable() {
|
||||||
this.logger.log('Test Plugin enable from MiaoScript Plugin System...');
|
this.logger.log('Plugin enable from MiaoScript Plugin System...');
|
||||||
}
|
}
|
||||||
disable() {
|
disable() {
|
||||||
this.logger.log('Test Plugin disable from MiaoScript Plugin System...');
|
this.logger.log('Plugin disable from MiaoScript Plugin System...');
|
||||||
}
|
}
|
||||||
|
|
||||||
bukkitload() {
|
bukkitload() {
|
||||||
@@ -171,6 +190,26 @@ export class HelloWorld extends interfaces.Plugin {
|
|||||||
this.logger.log('Disable When ServerType is Sponge!')
|
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!')
|
||||||
|
}
|
||||||
|
|
||||||
|
nukkitload() {
|
||||||
|
this.logger.log('Load When ServerType is Nukkit!')
|
||||||
|
}
|
||||||
|
nukkitenable() {
|
||||||
|
this.logger.log('Enable When ServerType is Nukkit!')
|
||||||
|
}
|
||||||
|
nukkitdisable() {
|
||||||
|
this.logger.log('Disable When ServerType is Nukkit!')
|
||||||
|
}
|
||||||
|
|
||||||
@cmd()
|
@cmd()
|
||||||
hello(sender: any, command: string, args: string[]) {
|
hello(sender: any, command: string, args: string[]) {
|
||||||
this.logger.log(sender, command, args);
|
this.logger.log(sender, command, args);
|
||||||
@@ -182,27 +221,41 @@ export class HelloWorld extends interfaces.Plugin {
|
|||||||
return ['world']
|
return ['world']
|
||||||
}
|
}
|
||||||
|
|
||||||
@listener({ servertype: 'bukkit' })
|
// bukkit nukkit 大部分API神似 可以直接用
|
||||||
playerjoin(event: org.bukkit.event.player.PlayerJoinEvent) {
|
@listener({ servers: ['bukkit', 'nukkit'] })
|
||||||
|
PlayerJoin(event: org.bukkit.event.player.PlayerJoinEvent) {
|
||||||
let plyaer = event.getPlayer();
|
let plyaer = event.getPlayer();
|
||||||
this.logger.console(`§aBukkit PlayerJoinEvent: §b${plyaer.getName()}`)
|
this.logger.console(`§cBukkit §aPlayerJoinEvent: §b${plyaer.getName()}`)
|
||||||
setTimeout(() => this.logger.sender(plyaer, `§a欢迎来到 §bMiaoScript §a的世界!`), 10);
|
setTimeout(() => this.sendWelcome(plyaer), 10);
|
||||||
}
|
}
|
||||||
|
|
||||||
@listener({ servertype: 'sponge' })
|
@listener({ servers: ['sponge'] })
|
||||||
clientconnectionevent$join(event: org.spongepowered.api.event.network.ClientConnectionEvent.Join) {
|
ClientConnectionEvent$Join(event: org.spongepowered.api.event.network.ClientConnectionEvent.Join) {
|
||||||
this.logger.console(`§aSponge ClientConnectionEvent.Join: §b${event.getTargetEntity().getName()}`)
|
this.logger.console(`§cSponge §aClientConnectionEvent.Join: §b${event.getTargetEntity().getName()}`)
|
||||||
setTimeout(() => this.logger.sender(event.getTargetEntity(), `§a欢迎来到 §bMiaoScript §a的世界!`), 10);
|
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`目录
|
- 进入 `ms`目录
|
||||||
- 执行编译 `yarn build:plugins`
|
- 执行编译 `yarn build:plugins`
|
||||||
- 从 `packages/plugins/dist` 中复制 `HelloWorld.js` 文件 到对应的插件目录
|
- 从 `packages/plugins/dist` 中复制 `HelloWorld.js` 和 `HelloWorld.js.map`(可选 用于显示插件原有行数) 文件 到对应的插件目录
|
||||||
|
- Bungee: plugins/MiaoScript/plugins/
|
||||||
- Bukkit: plugins/MiaoScript/plugins/
|
- Bukkit: plugins/MiaoScript/plugins/
|
||||||
- Sponge: config/miaoscript/plugins/
|
- Sponge: config/miaoscript/plugins/
|
||||||
|
- Nukkit: plugins/MiaoScript/plugins/
|
||||||
- 重载 `MiaoScript`
|
- 重载 `MiaoScript`
|
||||||
- 打开客户端进入游戏 预览一下效果
|
- 打开客户端进入游戏 预览一下效果
|
||||||
- 从 Spigot 服务端进入
|
- 从 Spigot 服务端进入
|
||||||
@@ -275,12 +328,13 @@ MiaoScript针对不同的服务端 提供了扩展的周期
|
|||||||
命令 就是玩家在Minecraft中执行命令 下面是一个示例的命令
|
命令 就是玩家在Minecraft中执行命令 下面是一个示例的命令
|
||||||
|
|
||||||
- 命令是一个 `function` 通过 `@cmd` 注解注册
|
- 命令是一个 `function` 通过 `@cmd` 注解注册
|
||||||
|
- 由于不同的服务端有不同的逻辑 所以支持通过 `servers` 指定注册的类型 加上 `!` 代表不注册 不指定 `servers` 则注册所有的类型
|
||||||
- 命令注册时默认使用方法名称为命令名称 当前你可以传入 name 参数指定命令名称 例如 `{name: 'test'}`
|
- 命令注册时默认使用方法名称为命令名称 当前你可以传入 name 参数指定命令名称 例如 `{name: 'test'}`
|
||||||
- 接受三个参数 `sender: any, command: string, args: string[]`
|
- 接受三个参数 `sender: any, command: string, args: string[]`
|
||||||
- 分别代表 命令发送者 命令名称 命令参数
|
- 分别代表 命令发送者 命令名称 命令参数
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
@cmd()
|
@cmd({ servers: ["bukkit", "sponge", "!bungee"] })
|
||||||
hello(sender: any, command: string, args: string[]) {
|
hello(sender: any, command: string, args: string[]) {
|
||||||
this.logger.log(sender, command, args);
|
this.logger.log(sender, command, args);
|
||||||
this.logger.sender(sender, JSON.stringify({ command, args }));
|
this.logger.sender(sender, JSON.stringify({ command, args }));
|
||||||
@@ -291,7 +345,7 @@ hello(sender: any, command: string, args: string[]) {
|
|||||||
|
|
||||||
补全就是 玩家在Minecraft执行命令时 使用 Tab键 补全
|
补全就是 玩家在Minecraft执行命令时 使用 Tab键 补全
|
||||||
|
|
||||||
- 补全是一个 `functio` 一般以 `tab` 开头 需要补全的命令结尾 通过 `@tab` 注解注册
|
- 补全是一个 `function` 一般以 `tab` 开头 需要补全的命令结尾 通过 `@tab` 注解注册
|
||||||
- 补全注册时默认使用方法名称为补全名称 当前你可以传入 name 参数指定命令名称 例如 `{name: 'test'}`
|
- 补全注册时默认使用方法名称为补全名称 当前你可以传入 name 参数指定命令名称 例如 `{name: 'test'}`
|
||||||
- 接受三个参数 `sender: any, command: string, args: string[]`
|
- 接受三个参数 `sender: any, command: string, args: string[]`
|
||||||
- 分别代表 命令发送者 命令名称 命令参数
|
- 分别代表 命令发送者 命令名称 命令参数
|
||||||
@@ -310,6 +364,7 @@ tabhello(_sender: any, _command: string, _args: string[]) {
|
|||||||
事件是指 Minecraft 中发生的各种事情
|
事件是指 Minecraft 中发生的各种事情
|
||||||
|
|
||||||
- 监听事件是一个 `function` 通过 `@listener` 注册
|
- 监听事件是一个 `function` 通过 `@listener` 注册
|
||||||
|
- 由于不同的服务端有不同的逻辑 所以支持通过 `servers` 指定注册的类型 加上 `!` 代表不注册 不指定 `servers` 则注册所有的类型
|
||||||
- 事件名称默认为方法名称
|
- 事件名称默认为方法名称
|
||||||
- 所有类型服务端的事件 MiaoScript 都会进行一次映射 方便使用
|
- 所有类型服务端的事件 MiaoScript 都会进行一次映射 方便使用
|
||||||
- 例如 `PlayerJoinEvent` 会映射为 `PlayerJoinEvent, playerjoinevent, playerjoin` 等
|
- 例如 `PlayerJoinEvent` 会映射为 `PlayerJoinEvent, playerjoinevent, playerjoin` 等
|
||||||
@@ -319,16 +374,30 @@ tabhello(_sender: any, _command: string, _args: string[]) {
|
|||||||
- 事件监听方法的第一个参数就是本次事件的具体内容 (这里就需要自己去查询对应的JavaDoc了)
|
- 事件监听方法的第一个参数就是本次事件的具体内容 (这里就需要自己去查询对应的JavaDoc了)
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
@listener({ servertype: 'bukkit' })
|
// bukkit nukkit 大部分API神似 可以直接用
|
||||||
playerjoin(event: any) {
|
@listener({ servers: ['bukkit', 'nukkit'] })
|
||||||
this.logger.console(`§aBukkit PlayerJoinEvent: §b${event.player.name}`)
|
PlayerJoin(event: org.bukkit.event.player.PlayerJoinEvent) {
|
||||||
setTimeout(() => this.logger.sender(event.player, `§a欢迎来到 §bMiaoScript §a的世界!`), 10);
|
let plyaer = event.getPlayer();
|
||||||
|
this.logger.console(`§cBukkit §aPlayerJoinEvent: §b${plyaer.getName()}`)
|
||||||
|
setTimeout(() => this.sendWelcome(plyaer), 10);
|
||||||
}
|
}
|
||||||
|
|
||||||
@listener({ servertype: 'sponge' })
|
@listener({ servers: ['sponge'] })
|
||||||
clientconnectionevent$join(event: any) {
|
ClientConnectionEvent$Join(event: org.spongepowered.api.event.network.ClientConnectionEvent.Join) {
|
||||||
this.logger.console(`§aSponge ClientConnectionEvent.Join: §b${event.targetEntity.name}`)
|
this.logger.console(`§cSponge §aClientConnectionEvent.Join: §b${event.getTargetEntity().getName()}`)
|
||||||
setTimeout(() => this.logger.sender(event.targetEntity, `§a欢迎来到 §bMiaoScript §a的世界!`), 10);
|
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.1.1",
|
"version": "0.3.0",
|
||||||
"useWorkspaces": true,
|
"useWorkspaces": true,
|
||||||
"npmClient": "yarn",
|
"npmClient": "yarn",
|
||||||
"packages": [
|
"packages": [
|
||||||
|
|||||||
16
package.json
16
package.json
@@ -6,16 +6,18 @@
|
|||||||
"author": "MiaoWoo <admin@yumc.pw>",
|
"author": "MiaoWoo <admin@yumc.pw>",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"clean": "npx lerna run clean",
|
"bs": "lerna bootstrap",
|
||||||
"watch": "npx lerna run watch --parallel",
|
"clean": "lerna run clean",
|
||||||
"build": "npx lerna run build --scope='@ms/!(plugins)'",
|
"watch": "lerna run watch --parallel --scope=\"@ms/!(manager)\"",
|
||||||
"build:plugins": "npx lerna run build --scope=@ms/plugins",
|
"build": "lerna run build --scope=\"@ms/!(plugins|manager)\"",
|
||||||
"lp": "npx lerna publish"
|
"build:plugins": "lerna run build --scope=\"@ms/plugins\"",
|
||||||
|
"ug": "yarn upgrade-interactive --latest",
|
||||||
|
"lp": "lerna publish"
|
||||||
},
|
},
|
||||||
"workspaces": [
|
"workspaces": [
|
||||||
"packages/*"
|
"packages/*"
|
||||||
],
|
],
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"lerna": "^3.16.4"
|
"lerna": "^3.20.2"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ms/api",
|
"name": "@ms/api",
|
||||||
"version": "0.1.1",
|
"version": "0.3.0",
|
||||||
"description": "MiaoScript api package",
|
"description": "MiaoScript api package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -17,17 +17,18 @@
|
|||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"clean": "rimraf dist",
|
"clean": "rimraf dist",
|
||||||
"watch": "npx tsc --watch",
|
"watch": "tsc --watch",
|
||||||
"build": "yarn clean && npx tsc",
|
"build": "yarn clean && tsc",
|
||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ms/container": "^0.1.0",
|
"@ms/container": "^0.3.0",
|
||||||
"@ms/ployfill": "^0.1.0"
|
"@ms/ployfill": "^0.3.0",
|
||||||
|
"source-map-builder": "^0.0.7"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.0",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.6.2"
|
"typescript": "^3.8.2"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
58
packages/api/src/channel.ts
Normal file
58
packages/api/src/channel.ts
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
import { injectable } from "@ms/container";
|
||||||
|
|
||||||
|
export namespace channel {
|
||||||
|
/**
|
||||||
|
* handle plugin message
|
||||||
|
* @param data byte[]
|
||||||
|
*/
|
||||||
|
export type ChannelListener = (data: any) => void
|
||||||
|
|
||||||
|
@injectable()
|
||||||
|
export abstract class Channel {
|
||||||
|
private listenerMap = [];
|
||||||
|
|
||||||
|
listen(plugin: any, channel: string, exec: ChannelListener) {
|
||||||
|
if (!plugin || !plugin.description || !plugin.description.name) throw new TypeError('Plugin can\'t be undefiend!');
|
||||||
|
let name = plugin.description.name;
|
||||||
|
let listener = this.register(channel, exec)
|
||||||
|
if (!this.listenerMap[name]) this.listenerMap[name] = [];
|
||||||
|
let offExec = () => {
|
||||||
|
this.unregister(channel, listener);
|
||||||
|
console.debug(`[${name}] unregister channel ${channel}`);
|
||||||
|
};
|
||||||
|
var off = {
|
||||||
|
channel,
|
||||||
|
listener,
|
||||||
|
off: offExec
|
||||||
|
};
|
||||||
|
this.listenerMap[name].push(off);
|
||||||
|
console.debug(`[${name}] register channel ${channel} => ${exec.name || '[anonymous]'}`);
|
||||||
|
return off;
|
||||||
|
}
|
||||||
|
disable(plugin: any) {
|
||||||
|
var channelCache = this.listenerMap[plugin.description.name];
|
||||||
|
if (channelCache) {
|
||||||
|
channelCache.forEach(t => t.off());
|
||||||
|
delete this.listenerMap[plugin.description.name];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send Channel Message
|
||||||
|
* @param player recover target
|
||||||
|
* @param channel ChannelName
|
||||||
|
* @param data byte[]
|
||||||
|
*/
|
||||||
|
abstract send(player: any, channel: string, data: any)
|
||||||
|
/**
|
||||||
|
* register channel
|
||||||
|
* @param channel ChannelName
|
||||||
|
*/
|
||||||
|
abstract register(channel: string, listener: ChannelListener): any
|
||||||
|
/**
|
||||||
|
* unregister channel
|
||||||
|
* @param channel ChannelName
|
||||||
|
*/
|
||||||
|
abstract unregister(channel: string, listener?: any): void
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import i18n from '@ms/i18n'
|
||||||
import { injectable } from "@ms/container";
|
import { injectable } from "@ms/container";
|
||||||
|
|
||||||
export namespace command {
|
export namespace command {
|
||||||
@@ -5,18 +6,18 @@ export namespace command {
|
|||||||
export abstract class Command {
|
export abstract class Command {
|
||||||
on(plugin: any, name: string, exec: { cmd: Function, tab?: Function }) {
|
on(plugin: any, name: string, exec: { cmd: Function, tab?: Function }) {
|
||||||
var cmd = this.create(plugin, name);
|
var cmd = this.create(plugin, name);
|
||||||
console.debug(`插件 ${plugin.description.name} 创建命令 ${name}(${cmd})...`)
|
console.debug(i18n.translate("ms.api.command.register", { plugin: plugin.description.name, name, cmd }))
|
||||||
if (exec.cmd && typeof exec.cmd === "function") {
|
if (exec.cmd && typeof exec.cmd === "function") {
|
||||||
this.onCommand(plugin, cmd, exec.cmd);
|
this.onCommand(plugin, cmd, exec.cmd);
|
||||||
} else {
|
} else {
|
||||||
throw Error("CommandExec Must be a function... Input: " + exec.cmd)
|
throw Error(i18n.translate("ms.api.command.register.input.error", { exec: exec.cmd }))
|
||||||
}
|
}
|
||||||
if (exec.tab && typeof exec.tab === "function") {
|
if (exec.tab && typeof exec.tab === "function") {
|
||||||
this.onTabComplete(plugin, cmd, exec.tab);
|
this.onTabComplete(plugin, cmd, exec.tab);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
off(plugin: any, name: string) {
|
off(plugin: any, name: string) {
|
||||||
console.debug(`插件 ${plugin.description.name} 注销命令 ${name}...`)
|
console.debug(i18n.translate("ms.api.command.unregister", { plugin: plugin.description.name, name }))
|
||||||
this.remove(plugin, name);
|
this.remove(plugin, name);
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
@@ -28,7 +29,7 @@ export namespace command {
|
|||||||
protected abstract onTabComplete(plugin: any, command: any, tabCompleter: Function);
|
protected abstract onTabComplete(plugin: any, command: any, tabCompleter: Function);
|
||||||
|
|
||||||
protected setExecutor(plugin: any, command: any, executor: Function) {
|
protected setExecutor(plugin: any, command: any, executor: Function) {
|
||||||
return (sender: any, _, command: string, args: string[]) => {
|
return (sender: any, _: any, command: string, args: string[]) => {
|
||||||
try {
|
try {
|
||||||
return executor(sender, command, Java.from(args));
|
return executor(sender, command, Java.from(args));
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
@@ -41,7 +42,7 @@ export namespace command {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected setTabCompleter(plugin: any, command: any, tabCompleter: Function) {
|
protected setTabCompleter(plugin: any, command: any, tabCompleter: Function) {
|
||||||
return (sender: any, _, command: string, args: string[]) => {
|
return (sender: any, _: any, command: string, args: string[]) => {
|
||||||
try {
|
try {
|
||||||
var token = args[args.length - 1];
|
var token = args[args.length - 1];
|
||||||
var complete = tabCompleter(sender, command, Java.from(args)) || [];
|
var complete = tabCompleter(sender, command, Java.from(args)) || [];
|
||||||
|
|||||||
@@ -1,11 +1,30 @@
|
|||||||
let Arrays = Java.type('java.util.Arrays');
|
import i18m from '@ms/i18n'
|
||||||
let Level = Java.type('java.util.logging.Level');
|
import { SourceMapBuilder } from 'source-map-builder'
|
||||||
let ignoreLogPrefix = ['java.', 'net.minecraft.', 'org.bukkit.', 'jdk.nashorn.', 'io.netty.'];
|
|
||||||
|
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 {
|
export class MiaoScriptConsole implements Console {
|
||||||
Console: NodeJS.ConsoleConstructor;
|
Console: NodeJS.ConsoleConstructor;
|
||||||
|
|
||||||
|
private sourceMaps: { [key: string]: SourceMapBuilder } = {};
|
||||||
private _name: string = '';
|
private _name: string = '';
|
||||||
|
private _level: LogLevel = LogLevel.INFO;
|
||||||
|
|
||||||
protected logger: any;
|
protected logger: any;
|
||||||
protected prefix: string = '§6[§bMiaoScript§6]§r ';
|
protected prefix: string = '§6[§bMiaoScript§6]§r ';
|
||||||
@@ -13,6 +32,12 @@ export class MiaoScriptConsole implements Console {
|
|||||||
constructor(name?: string) {
|
constructor(name?: string) {
|
||||||
this.name = name;
|
this.name = name;
|
||||||
this.logger = global.logger;
|
this.logger = global.logger;
|
||||||
|
if (global.debug) {
|
||||||
|
this._level = LogLevel.DEBUG
|
||||||
|
}
|
||||||
|
if (global.level?.toUpperCase() === "TRACE") {
|
||||||
|
this._level = LogLevel.TRACE
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
get name() {
|
get name() {
|
||||||
@@ -26,37 +51,75 @@ export class MiaoScriptConsole implements Console {
|
|||||||
this.prefix = `§6[§cMS§6][§b${name}§6]§r `;
|
this.prefix = `§6[§cMS§6][§b${name}§6]§r `;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
log(...args): void {
|
log(...args: any[]): void {
|
||||||
this.logger.info(this.name + args.join(' '));
|
this.logger.info(this.name + args.join(' '));
|
||||||
}
|
}
|
||||||
info(...args) {
|
info(...args: any[]) {
|
||||||
this.logger.info(this.name + args.join(' '));
|
this.logger.info(this.name + args.join(' '));
|
||||||
};
|
}
|
||||||
warn(...args) {
|
warn(...args: any[]) {
|
||||||
this.logger.warning(this.name + args.join(' '));
|
this.logger.warning(this.name + args.join(' '));
|
||||||
};
|
}
|
||||||
error(...args) {
|
error(...args: any[]) {
|
||||||
this.logger.log(Level.SEVERE, this.name + args.join(' '));
|
this.logger.log(Level.SEVERE, this.name + args.join(' '));
|
||||||
};
|
}
|
||||||
debug(...args) {
|
debug(...args: any[]) {
|
||||||
if (global.debug) {
|
if (global.debug) {
|
||||||
this.logger.info(this.name + '[DEBUG] ' + args.join(' '));
|
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) {
|
sender(...args) {
|
||||||
this.info(args)
|
this.info(args)
|
||||||
}
|
}
|
||||||
console(...args) {
|
console(...args) {
|
||||||
this.info(args)
|
this.info(args)
|
||||||
}
|
}
|
||||||
|
i18n(name: string, param?: { [key: string]: any }) {
|
||||||
|
this.console(i18m.translate(name, param))
|
||||||
|
}
|
||||||
object(obj) {
|
object(obj) {
|
||||||
for (var i in obj) {
|
for (var i in obj) {
|
||||||
this.logger(i, '=>', obj[i])
|
this.info(i, '=>', obj[i])
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
ex(ex: Error) {
|
ex(ex: Error) {
|
||||||
this.stack(ex).forEach(line => this.console(line))
|
this.stack(ex).forEach(line => this.console(line))
|
||||||
};
|
}
|
||||||
|
readSourceMap(fileName: string, lineNumber: number) {
|
||||||
|
try {
|
||||||
|
if (fileName.endsWith('js')) {
|
||||||
|
var file = Paths.get(fileName + '.map');
|
||||||
|
if (this.sourceMaps[fileName] === undefined) {
|
||||||
|
if (file.toFile().exists()) {
|
||||||
|
var sourceMapObj = JSON.parse(new JavaString(Files.readAllBytes(file), "UTF-8"))
|
||||||
|
this.sourceMaps[fileName] = new SourceMapBuilder(sourceMapObj)
|
||||||
|
} else {
|
||||||
|
this.sourceMaps[fileName] = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (this.sourceMaps[fileName]) {
|
||||||
|
var sourceMapping = this.sourceMaps[fileName].getSource(lineNumber, lineNumber);
|
||||||
|
if (sourceMapping) {
|
||||||
|
if (lineNumber != sourceMapping.mapping.sourceLine) {
|
||||||
|
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[] {
|
stack(ex: Error): string[] {
|
||||||
var stack = ex.getStackTrace();
|
var stack = ex.getStackTrace();
|
||||||
var cache = ['§4' + ex];
|
var cache = ['§4' + ex];
|
||||||
@@ -64,16 +127,17 @@ export class MiaoScriptConsole implements Console {
|
|||||||
if (stack.class) {
|
if (stack.class) {
|
||||||
stack = Arrays.asList(stack)
|
stack = Arrays.asList(stack)
|
||||||
}
|
}
|
||||||
stack.forEach(function(trace) {
|
stack.forEach(trace => {
|
||||||
if (trace.className.startsWith('<')) {
|
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(root)) { fileName = fileName.split(root)[1] }
|
||||||
cache.push(` §e->§c ${fileName} => §4${trace.methodName}:${trace.lineNumber}`)
|
cache.push(` §e->§c ${fileName} => §4${trace.methodName}:${lineNumber}`)
|
||||||
} else {
|
} else {
|
||||||
var className = trace.className;
|
var className = trace.className;
|
||||||
var fileName = trace.fileName
|
var fileName = trace.fileName as string;
|
||||||
if (className.startsWith('jdk.nashorn.internal.scripts')) {
|
if (className.startsWith('jdk.nashorn.internal.scripts')) {
|
||||||
className = className.substr(className.lastIndexOf('$') + 1)
|
className = className.substr(className.lastIndexOf('$') + 1)
|
||||||
|
var { fileName, lineNumber } = this.readSourceMap(trace.fileName, trace.lineNumber)
|
||||||
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
|
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
|
||||||
} else {
|
} else {
|
||||||
for (var prefix in ignoreLogPrefix) {
|
for (var prefix in ignoreLogPrefix) {
|
||||||
@@ -126,9 +190,6 @@ export class MiaoScriptConsole implements Console {
|
|||||||
timeLog(label?: string, ...data: any[]): void {
|
timeLog(label?: string, ...data: any[]): void {
|
||||||
throw new Error("Method not implemented.");
|
throw new Error("Method not implemented.");
|
||||||
}
|
}
|
||||||
trace(message?: any, ...optionalParams: any[]): void {
|
|
||||||
throw new Error("Method not implemented.");
|
|
||||||
}
|
|
||||||
markTimeline(label?: string): void {
|
markTimeline(label?: string): void {
|
||||||
throw new Error("Method not implemented.");
|
throw new Error("Method not implemented.");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,23 @@
|
|||||||
'use strict';
|
/// <reference types='@ms/nashorn' />
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* MiaoScript Event处理类
|
* MiaoScript Event处理类
|
||||||
*/
|
*/
|
||||||
import '@ms/core'
|
import i18n from '@ms/i18n'
|
||||||
import '@ms/nashorn'
|
import { injectable, unmanaged } from '@ms/container'
|
||||||
import { injectable } from '@ms/container'
|
|
||||||
|
|
||||||
const Thread = Java.type('java.lang.Thread');
|
const Thread = Java.type('java.lang.Thread');
|
||||||
|
|
||||||
export namespace event {
|
export namespace event {
|
||||||
|
export enum EventPriority {
|
||||||
|
LOWEST = "LOWEST",
|
||||||
|
LOW = "LOW",
|
||||||
|
NORMAL = "NORMAL",
|
||||||
|
HIGH = "HIGH",
|
||||||
|
HIGHEST = "HIGHEST",
|
||||||
|
MONITOR = "MONITOR",
|
||||||
|
}
|
||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
export abstract class Event {
|
export abstract class Event {
|
||||||
private mapEvent = [];
|
private mapEvent = [];
|
||||||
@@ -16,33 +25,31 @@ export namespace event {
|
|||||||
|
|
||||||
protected baseEventDir = '';
|
protected baseEventDir = '';
|
||||||
|
|
||||||
constructor(baseEventDir: string) {
|
constructor(@unmanaged() baseEventDir: string) {
|
||||||
this.baseEventDir = baseEventDir;
|
this.baseEventDir = baseEventDir;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 扫描包 org.bukkit.event 下的所有事件
|
* abstract event map function
|
||||||
* 映射简写名称 org.bukkit.event.player.PlayerLoginEvent => playerloginevent
|
* ig: org.bukkit.event.player.PlayerLoginEvent => playerloginevent
|
||||||
|
* org.spongepowered.api.event.game.GameRegistryEvent.Register => gameregistryevent$register
|
||||||
*/
|
*/
|
||||||
mapEventName() {
|
mapEventName() {
|
||||||
if (this.baseEventDir === "") {
|
if (this.baseEventDir === "") { throw new Error(i18n.translate('ms.api.event.empty.event.dir')); }
|
||||||
throw new Error("事件基础包名为空 无法进行事件映射!");
|
|
||||||
}
|
|
||||||
let count = 0;
|
let count = 0;
|
||||||
let jar = this.getJarFile(this.baseEventDir);
|
let jar = this.getJarFile(this.baseEventDir);
|
||||||
let entries = jar.entries();
|
let entries = jar.entries();
|
||||||
while (entries.hasMoreElements()) {
|
while (entries.hasMoreElements()) {
|
||||||
let entry = entries.nextElement();
|
let entry = entries.nextElement();
|
||||||
let name = entry.name;
|
let name = entry.name;
|
||||||
// 以 org/bukkit/event 开头 并且以 .class 结尾
|
|
||||||
if (name.startsWith(this.baseEventDir) && name.endsWith(".class")) {
|
if (name.startsWith(this.baseEventDir) && name.endsWith(".class")) {
|
||||||
|
// replace name to qualifiedName
|
||||||
let qualifiedName = name.replaceAll('/', '.');
|
let qualifiedName = name.replaceAll('/', '.');
|
||||||
try {
|
try {
|
||||||
let clazz = base.getClass(qualifiedName.substring(0, qualifiedName.length - 6));
|
let clazz = base.getClass(qualifiedName.substring(0, qualifiedName.length - 6));
|
||||||
// 继承于 org.bukkit.event.Event 访问符为Public
|
|
||||||
if (this.isValidEvent(clazz)) {
|
if (this.isValidEvent(clazz)) {
|
||||||
let simpleName = this.class2Name(clazz).toLowerCase();
|
let simpleName = this.class2Name(clazz).toLowerCase();
|
||||||
console.debug(`Mapping Event [${clazz.canonicalName}] => ${simpleName}`);
|
console.trace(i18n.translate("ms.api.event.mapping", { canonicalName: clazz.canonicalName, simpleName }));
|
||||||
this.mapEvent[simpleName] = clazz;
|
this.mapEvent[simpleName] = clazz;
|
||||||
count++;
|
count++;
|
||||||
}
|
}
|
||||||
@@ -60,22 +67,21 @@ export namespace event {
|
|||||||
let url = dirs.nextElement();
|
let url = dirs.nextElement();
|
||||||
if (url.protocol === "jar") { return url.openConnection().jarFile; }
|
if (url.protocol === "jar") { return url.openConnection().jarFile; }
|
||||||
}
|
}
|
||||||
throw new Error(`Can't Mapping Event Because not found Resources ${resource}!`)
|
throw new Error(i18n.translate("ms.api.event.resource.not.found", { resource }))
|
||||||
}
|
}
|
||||||
|
|
||||||
class2Name(clazz) {
|
class2Name(clazz: any) {
|
||||||
return clazz.simpleName;
|
return clazz.simpleName;
|
||||||
}
|
}
|
||||||
|
|
||||||
name2Class(name, event) {
|
name2Class(name: any, event: string) {
|
||||||
var eventCls = this.mapEvent[event.toLowerCase()] || this.mapEvent[event.toLowerCase() + 'event'];
|
let eventCls = this.mapEvent[event.toLowerCase()] || this.mapEvent[event.toLowerCase() + 'event'];
|
||||||
if (!eventCls) {
|
if (!eventCls) {
|
||||||
try {
|
try {
|
||||||
eventCls = base.getClass(eventCls);
|
eventCls = base.getClass(eventCls);
|
||||||
this.mapEvent[event] = eventCls;
|
this.mapEvent[event] = eventCls;
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
console.console(`§6插件 §b${name} §6注册事件 §c${event} §6失败 §4事件未找到!`);
|
console.i18n("ms.api.event.not.found", { name, event })
|
||||||
console.ex(new Error(`插件 ${name} 注册事件 ${event} 失败 事件未找到!`));
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -83,16 +89,19 @@ export namespace event {
|
|||||||
}
|
}
|
||||||
|
|
||||||
execute(name, exec, eventCls) {
|
execute(name, exec, eventCls) {
|
||||||
return (...args) => {
|
return (...args: any[]) => {
|
||||||
try {
|
try {
|
||||||
var time = new Date().getTime()
|
let event = args[args.length - 1];
|
||||||
exec(args[args.length - 1]);
|
if (eventCls.isAssignableFrom(event.getClass())) {
|
||||||
var cost = new Date().getTime() - time;
|
let time = Date.now()
|
||||||
if (cost > 20) {
|
exec(event);
|
||||||
console.console(`§c注意! §6插件 §b${name} §6处理 §d${this.class2Name(eventCls)} §6事件 §c耗时 §4${cost}ms !`)
|
let cost = Date.now() - time;
|
||||||
|
if (cost > 20) {
|
||||||
|
console.i18n("ms.api.event.execute.slow", { name, event: this.class2Name(eventCls), cost })
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
console.console(`§6插件 §b${name} §6处理 §d${this.class2Name(eventCls)} §6事件时发生异常 §4${ex}`);
|
console.i18n("ms.api.event.execute.error", { name, event: this.class2Name(eventCls), ex })
|
||||||
console.ex(ex);
|
console.ex(ex);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -100,31 +109,31 @@ export namespace event {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 添加事件监听
|
* 添加事件监听
|
||||||
* @param plugin
|
* @param plugin {any}
|
||||||
* @param event
|
* @param event {string}
|
||||||
* @param exec {function}
|
* @param exec {function}
|
||||||
* @param priority [LOWEST,LOW,NORMAL,HIGH,HIGHEST,MONITOR]
|
* @param priority {string} [LOWEST,LOW,NORMAL,HIGH,HIGHEST,MONITOR]
|
||||||
* @param ignoreCancel
|
* @param ignoreCancel
|
||||||
*/
|
*/
|
||||||
listen(plugin, event, exec, priority = 'NORMAL', ignoreCancel = false) {
|
listen(plugin: any, event: string, exec: (event: any) => void, priority: EventPriority = EventPriority.NORMAL, ignoreCancel = false) {
|
||||||
if (!plugin || !plugin.description || !plugin.description.name) throw new TypeError('插件名称为空 请检查传入参数!');
|
if (!plugin || !plugin.description || !plugin.description.name) throw new TypeError(i18n.translate("ms.api.event.listen.plugin.name.empty"));
|
||||||
var name = plugin.description.name;
|
var name = plugin.description.name;
|
||||||
var eventCls = this.name2Class(name, event);
|
var eventCls = this.name2Class(name, event);
|
||||||
if (!eventCls) { return; }
|
if (!eventCls) { return; }
|
||||||
if (typeof priority === 'boolean') {
|
if (typeof priority === 'boolean') {
|
||||||
ignoreCancel = priority;
|
ignoreCancel = priority;
|
||||||
priority = 'NORMAL';
|
priority = EventPriority.NORMAL;
|
||||||
}
|
}
|
||||||
priority = priority || 'NORMAL';
|
priority = priority || EventPriority.NORMAL;
|
||||||
ignoreCancel = ignoreCancel || false;
|
ignoreCancel = ignoreCancel || false;
|
||||||
// noinspection JSUnusedGlobalSymbols
|
// noinspection JSUnusedGlobalSymbols
|
||||||
var listener = this.register(eventCls, this.execute(name, exec, eventCls), priority, ignoreCancel);
|
var listener = this.register(eventCls, this.execute(name, exec, eventCls), priority, ignoreCancel);
|
||||||
var listenerMap = this.listenerMap;
|
var listenerMap = this.listenerMap;
|
||||||
// 添加到缓存 用于关闭插件的时候关闭事件
|
// add to cache Be used for close plugin to close event
|
||||||
if (!listenerMap[name]) listenerMap[name] = [];
|
if (!listenerMap[name]) listenerMap[name] = [];
|
||||||
var offExec = () => {
|
var offExec = () => {
|
||||||
this.unregister(eventCls, listener);
|
this.unregister(eventCls, listener);
|
||||||
console.debug(`插件 ${name} 注销事件 ${this.class2Name(eventCls)}`);
|
console.debug(i18n.translate("ms.api.event.unregister", { name, event: this.class2Name(eventCls) }));
|
||||||
};
|
};
|
||||||
var off = {
|
var off = {
|
||||||
event: eventCls,
|
event: eventCls,
|
||||||
@@ -133,7 +142,7 @@ export namespace event {
|
|||||||
};
|
};
|
||||||
listenerMap[name].push(off);
|
listenerMap[name].push(off);
|
||||||
// noinspection JSUnresolvedVariable
|
// noinspection JSUnresolvedVariable
|
||||||
console.debug(`插件 ${name} 注册事件 ${this.class2Name(eventCls)} => ${exec.name || '匿名方法'}`);
|
console.debug(i18n.translate("ms.api.event.register", { name, event: this.class2Name(eventCls) }));
|
||||||
return off;
|
return off;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
/// <reference path="./typings/global.ts" />
|
import "@ms/ployfill"
|
||||||
|
|
||||||
export * from './task'
|
export * from './task'
|
||||||
export * from './event'
|
export * from './event'
|
||||||
export * from './console'
|
export * from './console'
|
||||||
|
export * from './channel'
|
||||||
export * from './command'
|
export * from './command'
|
||||||
export * from './interfaces'
|
export * from './interfaces'
|
||||||
|
|||||||
@@ -1,24 +1,26 @@
|
|||||||
import { Container } from "@ms/container";
|
|
||||||
|
|
||||||
export namespace plugin {
|
export namespace plugin {
|
||||||
/**
|
/**
|
||||||
* MiaoScript Plugin
|
* MiaoScript Plugin
|
||||||
*/
|
*/
|
||||||
export const Plugin = Symbol("Plugin");
|
export const Plugin = Symbol("Plugin");
|
||||||
|
/**
|
||||||
|
* MiaoScript Plugin
|
||||||
|
*/
|
||||||
|
export const PluginFolder = Symbol("PluginFolder");
|
||||||
/**
|
/**
|
||||||
* Runtime Plugin Instance
|
* Runtime Plugin Instance
|
||||||
*/
|
*/
|
||||||
export const PluginInstance = Symbol("PluginInstance");
|
export const PluginInstance = Symbol("PluginInstance");
|
||||||
/**
|
/**
|
||||||
* MiaoScript Plugin Manager
|
* MiaoScript Plugin Manager Symbol
|
||||||
*/
|
*/
|
||||||
export const PluginManager = Symbol("PluginManager");
|
export const PluginManager = Symbol("PluginManager");
|
||||||
/**
|
/**
|
||||||
* MiaoScript Plugin Manager
|
* MiaoScript Plugin Manager Interface
|
||||||
*/
|
*/
|
||||||
export interface PluginManager {
|
export interface PluginManager {
|
||||||
scan(folder: string): void;
|
scan(folder: string): void;
|
||||||
build(container: Container): void;
|
build(): void;
|
||||||
load(...args: any[]): void;
|
load(...args: any[]): void;
|
||||||
enable(...args: any[]): void;
|
enable(...args: any[]): void;
|
||||||
disable(...args: any[]): void;
|
disable(...args: any[]): void;
|
||||||
|
|||||||
@@ -1,9 +1,31 @@
|
|||||||
export namespace server {
|
export namespace server {
|
||||||
|
/**
|
||||||
|
* Runtime ServerType
|
||||||
|
*/
|
||||||
export const ServerType = Symbol("ServerType");
|
export const ServerType = Symbol("ServerType");
|
||||||
|
/**
|
||||||
|
* Runtime Console
|
||||||
|
*/
|
||||||
export const Console = Symbol("Console");
|
export const Console = Symbol("Console");
|
||||||
|
/**
|
||||||
|
* MiaoScript Server
|
||||||
|
*/
|
||||||
export const Server = Symbol("Server");
|
export const Server = Symbol("Server");
|
||||||
|
/**
|
||||||
|
* Runtime Server Instance
|
||||||
|
*/
|
||||||
|
export const ServerInstance = Symbol("ServerInstance");
|
||||||
|
/**
|
||||||
|
* MiaoScript Server
|
||||||
|
*/
|
||||||
export interface Server {
|
export interface Server {
|
||||||
getVersion(): string;
|
getVersion(): string;
|
||||||
getPlayer(name: string): any;
|
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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ export namespace task {
|
|||||||
export const TaskManager = Symbol('TaskManager')
|
export const TaskManager = Symbol('TaskManager')
|
||||||
export interface TaskManager {
|
export interface TaskManager {
|
||||||
create(func: Function): task.Task;
|
create(func: Function): task.Task;
|
||||||
|
callSyncMethod(func: Function): any;
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* 任务抽象
|
* 任务抽象
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "@ms/bukkit",
|
"name": "@ms/bukkit",
|
||||||
"version": "0.1.1",
|
"version": "0.3.0",
|
||||||
"description": "MiaoScript api package",
|
"description": "MiaoScript bukkit package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
"minecraft",
|
"minecraft",
|
||||||
@@ -17,19 +17,19 @@
|
|||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"clean": "rimraf dist",
|
"clean": "rimraf dist",
|
||||||
"watch": "npx tsc --watch",
|
"watch": "tsc --watch",
|
||||||
"build": "yarn clean && npx tsc",
|
"build": "yarn clean && tsc",
|
||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.0",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.6.2"
|
"typescript": "^3.8.2"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ms/api": "^0.1.1",
|
"@ms/api": "^0.3.0",
|
||||||
"@ms/common": "^0.1.0",
|
"@ms/common": "^0.3.0",
|
||||||
"@ms/container": "^0.1.0",
|
"@ms/container": "^0.3.0",
|
||||||
"@ms/types": "^0.1.1"
|
"@ms/types": "^0.3.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
28
packages/bukkit/src/channel.ts
Normal file
28
packages/bukkit/src/channel.ts
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
import { channel, plugin } from '@ms/api'
|
||||||
|
import { inject, provideSingleton } from '@ms/container'
|
||||||
|
|
||||||
|
const Bukkit = org.bukkit.Bukkit
|
||||||
|
const PluginMessageListener = Java.type("org.bukkit.plugin.messaging.PluginMessageListener")
|
||||||
|
const Messenger = Bukkit.getMessenger()
|
||||||
|
|
||||||
|
@provideSingleton(channel.Channel)
|
||||||
|
export class BukkitChannel extends channel.Channel {
|
||||||
|
@inject(plugin.PluginInstance)
|
||||||
|
private pluginInstance: any;
|
||||||
|
|
||||||
|
send(player: any, channel: string, data: any) {
|
||||||
|
player.sendPluginMessage(this.pluginInstance, channel, data);
|
||||||
|
}
|
||||||
|
register(channel: string, listener: channel.ChannelListener) {
|
||||||
|
Messenger.registerIncomingPluginChannel(this.pluginInstance, channel, new PluginMessageListener({
|
||||||
|
onPluginMessageReceived: (/**String */ var1, /**Player */ var2, /**byte[] */var3) => {
|
||||||
|
listener(var3)
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
Messenger.registerOutgoingPluginChannel(this.pluginInstance, channel);
|
||||||
|
}
|
||||||
|
unregister(channel: string, listener: any) {
|
||||||
|
Messenger.unregisterIncomingPluginChannel(this.pluginInstance, channel)
|
||||||
|
Messenger.unregisterOutgoingPluginChannel(this.pluginInstance, channel)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,14 +2,14 @@ import '@ms/nashorn'
|
|||||||
|
|
||||||
import { command, plugin } from '@ms/api'
|
import { command, plugin } from '@ms/api'
|
||||||
import * as reflect from '@ms/common/dist/reflect'
|
import * as reflect from '@ms/common/dist/reflect'
|
||||||
import { injectable, postConstruct, inject } from '@ms/container'
|
import { provideSingleton, postConstruct, inject } from '@ms/container'
|
||||||
|
|
||||||
let Bukkit = org.bukkit.Bukkit;
|
let Bukkit = org.bukkit.Bukkit;
|
||||||
let TabCompleter = Java.type('org.bukkit.command.TabCompleter');
|
let TabCompleter = Java.type('org.bukkit.command.TabCompleter');
|
||||||
let PluginCommand = Java.type('org.bukkit.command.PluginCommand');
|
let PluginCommand = Java.type('org.bukkit.command.PluginCommand');
|
||||||
let CommandExecutor = Java.type('org.bukkit.command.CommandExecutor');
|
let CommandExecutor = Java.type('org.bukkit.command.CommandExecutor');
|
||||||
|
|
||||||
@injectable()
|
@provideSingleton(command.Command)
|
||||||
export class BukkitCommand extends command.Command {
|
export class BukkitCommand extends command.Command {
|
||||||
@inject(plugin.PluginInstance)
|
@inject(plugin.PluginInstance)
|
||||||
private pluginInstance: any
|
private pluginInstance: any
|
||||||
@@ -19,7 +19,6 @@ export class BukkitCommand extends command.Command {
|
|||||||
init() {
|
init() {
|
||||||
this.commandMap = reflect.on(Bukkit.getPluginManager()).get('commandMap').get();
|
this.commandMap = reflect.on(Bukkit.getPluginManager()).get('commandMap').get();
|
||||||
}
|
}
|
||||||
|
|
||||||
create(plugin: any, command: string) {
|
create(plugin: any, command: string) {
|
||||||
var cmd = this.commandMap.getCommand(command)
|
var cmd = this.commandMap.getCommand(command)
|
||||||
if (cmd && cmd instanceof PluginCommand) { return cmd };
|
if (cmd && cmd instanceof PluginCommand) { return cmd };
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ let Bukkit = org.bukkit.Bukkit;
|
|||||||
export class BukkitConsole extends MiaoScriptConsole {
|
export class BukkitConsole extends MiaoScriptConsole {
|
||||||
sender(sender, ...args) {
|
sender(sender, ...args) {
|
||||||
if (!(sender instanceof Java.type('org.bukkit.command.CommandSender'))) {
|
if (!(sender instanceof Java.type('org.bukkit.command.CommandSender'))) {
|
||||||
this.error("第一个参数未实现 org.bukkit.command.CommandSender 无法发送消息!")
|
this.error(`First parameter ${sender} not instanceof org.bukkit.command.CommandSender can't send message!`)
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (Object.prototype.toString.call(args[0]) === "[object Array]") {
|
if (Object.prototype.toString.call(args[0]) === "[object Array]") {
|
||||||
@@ -14,7 +14,7 @@ export class BukkitConsole extends MiaoScriptConsole {
|
|||||||
sender.sendMessage(this.prefix + args.join(' '));
|
sender.sendMessage(this.prefix + args.join(' '));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
console(...args): void {
|
console(...args: string[]): void {
|
||||||
this.sender(Bukkit.getConsoleSender(), args.join(' '));
|
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
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { event, server, plugin } from '@ms/api'
|
import { event, plugin } from '@ms/api'
|
||||||
import { injectable, inject } from '@ms/container';
|
import { inject, provideSingleton } from '@ms/container';
|
||||||
import * as reflect from '@ms/common/dist/reflect'
|
import * as reflect from '@ms/common/dist/reflect'
|
||||||
|
|
||||||
const Bukkit = Java.type("org.bukkit.Bukkit");
|
const Bukkit = Java.type("org.bukkit.Bukkit");
|
||||||
@@ -9,7 +9,7 @@ const Listener = Java.type("org.bukkit.event.Listener");
|
|||||||
const EventPriority = Java.type("org.bukkit.event.EventPriority");
|
const EventPriority = Java.type("org.bukkit.event.EventPriority");
|
||||||
const EventExecutor = Java.type("org.bukkit.plugin.EventExecutor");
|
const EventExecutor = Java.type("org.bukkit.plugin.EventExecutor");
|
||||||
|
|
||||||
@injectable()
|
@provideSingleton(event.Event)
|
||||||
export class BukkitEvent extends event.Event {
|
export class BukkitEvent extends event.Event {
|
||||||
@inject(plugin.PluginInstance)
|
@inject(plugin.PluginInstance)
|
||||||
private pluginInstance: any
|
private pluginInstance: any
|
||||||
@@ -29,7 +29,7 @@ export class BukkitEvent extends event.Event {
|
|||||||
// 不是抽象类
|
// 不是抽象类
|
||||||
!Modifier.isAbstract(clazz.getModifiers());
|
!Modifier.isAbstract(clazz.getModifiers());
|
||||||
}
|
}
|
||||||
register(eventCls: any, exec: Function, priority: any, ignoreCancel: boolean) {
|
register(eventCls: any, exec: Function, priority: event.EventPriority, ignoreCancel: boolean) {
|
||||||
let listener = new Listener({});
|
let listener = new Listener({});
|
||||||
Bukkit.pluginManager.registerEvent(
|
Bukkit.pluginManager.registerEvent(
|
||||||
eventCls,
|
eventCls,
|
||||||
|
|||||||
@@ -1,22 +1,15 @@
|
|||||||
/// <reference types="@ms/types/dist/typings/bukkit" />
|
/// <reference types="@ms/types/dist/typings/bukkit" />
|
||||||
|
|
||||||
import { server, plugin, command, event, task } from '@ms/api'
|
import { server } from '@ms/api'
|
||||||
import { DefaultContainer as container } from '@ms/container'
|
import { Container } from '@ms/container'
|
||||||
|
|
||||||
import { BukkitConsole } from './console';
|
import { BukkitConsole } from './console';
|
||||||
import { BukkitEvent } from './event';
|
import './event';
|
||||||
import { BukkitCommand } from './command';
|
import './server';
|
||||||
import { BukkitTaskManager } from './task';
|
import './command';
|
||||||
|
import './channel';
|
||||||
|
import './task';
|
||||||
|
|
||||||
let BukkitServerType = 'bukkit';
|
export default function BukkitImpl(container: Container) {
|
||||||
let Bukkit = Java.type("org.bukkit.Bukkit");
|
container.bind(server.Console).toConstantValue(BukkitConsole);
|
||||||
|
}
|
||||||
container.bind(server.Console).toConstantValue(BukkitConsole);
|
|
||||||
container.bind(server.ServerType).toConstantValue(BukkitServerType);
|
|
||||||
container.bind(plugin.PluginInstance).toConstantValue(Bukkit.pluginManager.getPlugin('MiaoScript'));
|
|
||||||
|
|
||||||
container.bind(event.Event).to(BukkitEvent).inSingletonScope();
|
|
||||||
container.bind(command.Command).to(BukkitCommand).inSingletonScope();
|
|
||||||
container.bind(task.TaskManager).to(BukkitTaskManager).inSingletonScope();
|
|
||||||
|
|
||||||
console.debug(`Detect Bukkit Compatible set ServerType to ${BukkitServerType} ...`)
|
|
||||||
|
|||||||
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 { provideSingleton } from '@ms/container';
|
||||||
|
|
||||||
|
import chat from './enhance/chat'
|
||||||
|
|
||||||
|
let Bukkit = org.bukkit.Bukkit;
|
||||||
|
|
||||||
|
@provideSingleton(server.Server)
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,9 +1,11 @@
|
|||||||
import { task, plugin } from '@ms/api'
|
import { task, plugin } from '@ms/api'
|
||||||
import { injectable, inject } from '@ms/container';
|
import { inject, provideSingleton } from '@ms/container';
|
||||||
|
|
||||||
let BukkitRunnable = Java.type('org.bukkit.scheduler.BukkitRunnable');
|
const Bukkit = Java.type('org.bukkit.Bukkit');
|
||||||
|
const BukkitRunnable = Java.type('org.bukkit.scheduler.BukkitRunnable');
|
||||||
|
const Callable = Java.type('java.util.concurrent.Callable')
|
||||||
|
|
||||||
@injectable()
|
@provideSingleton(task.TaskManager)
|
||||||
export class BukkitTaskManager implements task.TaskManager {
|
export class BukkitTaskManager implements task.TaskManager {
|
||||||
@inject(plugin.PluginInstance)
|
@inject(plugin.PluginInstance)
|
||||||
private pluginInstance: any;
|
private pluginInstance: any;
|
||||||
@@ -12,6 +14,9 @@ export class BukkitTaskManager implements task.TaskManager {
|
|||||||
if (Object.prototype.toString.call(func) !== "[object Function]") { throw TypeError('第一个参数 Task 必须为 function !'); };
|
if (Object.prototype.toString.call(func) !== "[object Function]") { throw TypeError('第一个参数 Task 必须为 function !'); };
|
||||||
return new BukkitTask(this.pluginInstance, func);
|
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 {
|
export class BukkitTask extends task.Task {
|
||||||
|
|||||||
35
packages/bungee/package.json
Normal file
35
packages/bungee/package.json
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
{
|
||||||
|
"name": "@ms/bungee",
|
||||||
|
"version": "0.3.0",
|
||||||
|
"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.3.0",
|
||||||
|
"@ms/common": "^0.3.0",
|
||||||
|
"@ms/container": "^0.3.0",
|
||||||
|
"@ms/types": "^0.3.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
18
packages/bungee/src/channel.ts
Normal file
18
packages/bungee/src/channel.ts
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
import { channel } from '@ms/api'
|
||||||
|
import { provideSingleton } from '@ms/container'
|
||||||
|
|
||||||
|
const Bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy()
|
||||||
|
|
||||||
|
@provideSingleton(channel.Channel)
|
||||||
|
export class BungeeChannel extends channel.Channel {
|
||||||
|
send(player: any, channel: string, data: any) {
|
||||||
|
throw new Error("Method not implemented.");
|
||||||
|
}
|
||||||
|
register(channel: string, listener: channel.ChannelListener) {
|
||||||
|
Bungee.registerChannel(channel);
|
||||||
|
console.console('§6[§eWARN§6] §eBungeeCord Channel only registerChannel you need self hanler PluginMessageEvent!')
|
||||||
|
}
|
||||||
|
unregister(channel: string, listener: any) {
|
||||||
|
Bungee.unregisterChannel(channel);
|
||||||
|
}
|
||||||
|
}
|
||||||
65
packages/bungee/src/command.ts
Normal file
65
packages/bungee/src/command.ts
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
import { command, plugin } from "@ms/api";
|
||||||
|
import { inject, provideSingleton } from "@ms/container";
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
`)
|
||||||
|
|
||||||
|
@provideSingleton(command.Command)
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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})`
|
||||||
|
}
|
||||||
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(' '));
|
||||||
|
}
|
||||||
|
}
|
||||||
117
packages/bungee/src/event.ts
Normal file
117
packages/bungee/src/event.ts
Normal file
@@ -0,0 +1,117 @@
|
|||||||
|
import { event } from '@ms/api'
|
||||||
|
import { provideSingleton, 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
|
||||||
|
*/
|
||||||
|
@provideSingleton(event.Event)
|
||||||
|
export class BungeeEvent extends event.Event {
|
||||||
|
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()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
15
packages/bungee/src/index.ts
Normal file
15
packages/bungee/src/index.ts
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
/// <reference types="@ms/types/dist/typings/bungee" />
|
||||||
|
|
||||||
|
import { server } from '@ms/api'
|
||||||
|
import { Container } from '@ms/container'
|
||||||
|
|
||||||
|
import { BungeeConsole } from './console';
|
||||||
|
import './event';
|
||||||
|
import './server';
|
||||||
|
import './command';
|
||||||
|
import './channel';
|
||||||
|
import './task';
|
||||||
|
|
||||||
|
export default function BungeeImpl(container: Container) {
|
||||||
|
container.bind(server.Console).toConstantValue(BungeeConsole);
|
||||||
|
}
|
||||||
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 { provideSingleton } from '@ms/container';
|
||||||
|
|
||||||
|
let Bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy();
|
||||||
|
|
||||||
|
@provideSingleton(server.Server)
|
||||||
|
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 { inject, provideSingleton } from '@ms/container';
|
||||||
|
|
||||||
|
var Runnable = Java.type('java.lang.Runnable')
|
||||||
|
let TimeUnit = Java.type('java.util.concurrent.TimeUnit')
|
||||||
|
|
||||||
|
@provideSingleton(task.TaskManager)
|
||||||
|
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.3.0",
|
||||||
|
"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"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ms/common",
|
"name": "@ms/common",
|
||||||
"version": "0.1.0",
|
"version": "0.3.0",
|
||||||
"description": "MiaoScript api package",
|
"description": "MiaoScript api package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -17,18 +17,18 @@
|
|||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"clean": "rimraf dist",
|
"clean": "rimraf dist",
|
||||||
"watch": "npx tsc --watch",
|
"watch": "tsc --watch",
|
||||||
"build": "yarn clean && npx tsc",
|
"build": "yarn clean && tsc",
|
||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.0",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.6.2"
|
"typescript": "^3.8.2"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ms/nashorn": "^0.1.0",
|
"@ms/nashorn": "^0.3.0",
|
||||||
"@ms/ployfill": "^0.1.0"
|
"@ms/ployfill": "^0.3.0"
|
||||||
},
|
},
|
||||||
"gitHead": "562e2d00175c9d3a99c8b672aa07e6d92706a027"
|
"gitHead": "562e2d00175c9d3a99c8b672aa07e6d92706a027"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,8 +12,8 @@ const StandardCopyOption = Java.type("java.nio.file.StandardCopyOption");
|
|||||||
/**
|
/**
|
||||||
* 用文件分割符合并路径
|
* 用文件分割符合并路径
|
||||||
*/
|
*/
|
||||||
export function concat() {
|
export function concat(...args: string[]) {
|
||||||
return Array.prototype.join.call(arguments, separatorChar);
|
return args.join(separatorChar);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -23,12 +23,12 @@ export function concat() {
|
|||||||
* @returns {*}
|
* @returns {*}
|
||||||
*/
|
*/
|
||||||
export function file(...opts: any[]): any {
|
export function file(...opts: any[]): any {
|
||||||
if (!arguments[0]) {
|
if (!opts[0]) {
|
||||||
console.warn("文件名称不得为 undefined 或者 null !");
|
console.warn("文件名称不得为 undefined 或者 null !");
|
||||||
}
|
}
|
||||||
switch (arguments.length) {
|
switch (opts.length) {
|
||||||
case 1:
|
case 1:
|
||||||
var f = arguments[0];
|
var f = opts[0];
|
||||||
if (f instanceof File) {
|
if (f instanceof File) {
|
||||||
return f;
|
return f;
|
||||||
}
|
}
|
||||||
@@ -40,7 +40,7 @@ export function file(...opts: any[]): any {
|
|||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
default:
|
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
|
* @param path
|
||||||
*/
|
*/
|
||||||
export function mkdirs(path) {
|
export function mkdirs(path: any) {
|
||||||
// noinspection JSUnresolvedVariable
|
// noinspection JSUnresolvedVariable
|
||||||
file(path).parentFile.mkdirs();
|
file(path).parentFile.mkdirs();
|
||||||
}
|
}
|
||||||
@@ -57,7 +57,7 @@ export function mkdirs(path) {
|
|||||||
* 创建文件
|
* 创建文件
|
||||||
* @param file
|
* @param file
|
||||||
*/
|
*/
|
||||||
export function create(path) {
|
export function create(path: any) {
|
||||||
var f = file(path);
|
var f = file(path);
|
||||||
if (!f.exists()) {
|
if (!f.exists()) {
|
||||||
mkdirs(f);
|
mkdirs(f);
|
||||||
@@ -70,7 +70,7 @@ export function create(path) {
|
|||||||
* @param file
|
* @param file
|
||||||
* @returns {*}
|
* @returns {*}
|
||||||
*/
|
*/
|
||||||
export function path(f) {
|
export function path(f: any) {
|
||||||
return file(f).canonicalPath;
|
return file(f).canonicalPath;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -80,7 +80,7 @@ export function path(f) {
|
|||||||
* @param target 目标文件
|
* @param target 目标文件
|
||||||
* @param override 是否覆盖
|
* @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']);
|
Files.copy(inputStream, target.toPath(), StandardCopyOption[override ? 'REPLACE_EXISTING' : 'ATOMIC_MOVE']);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -24,8 +24,11 @@ function request(config: RequestConfig) {
|
|||||||
for (const header in config.headers) {
|
for (const header in config.headers) {
|
||||||
xhr.setRequestHeader(header, config.headers[header]);
|
xhr.setRequestHeader(header, config.headers[header]);
|
||||||
}
|
}
|
||||||
let future = xhr.send(config.data);
|
xhr.send(config.data);
|
||||||
return future.get();
|
if ((xhr.getResponseHeader("Content-Type") + '').indexOf('application/json') != -1) {
|
||||||
|
xhr.responseType = "json"
|
||||||
|
}
|
||||||
|
return xhr.get();
|
||||||
}
|
}
|
||||||
|
|
||||||
function _proxy(method: Method) {
|
function _proxy(method: Method) {
|
||||||
|
|||||||
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
|
||||||
@@ -2,7 +2,6 @@
|
|||||||
"extends": "../../tsconfig.json",
|
"extends": "../../tsconfig.json",
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"baseUrl": "src",
|
"baseUrl": "src",
|
||||||
"outDir": "dist",
|
"outDir": "dist"
|
||||||
"declaration": true
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
29
packages/compile/package.json
Normal file
29
packages/compile/package.json
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
{
|
||||||
|
"name": "@ms/compile",
|
||||||
|
"version": "0.3.0",
|
||||||
|
"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"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ms/container",
|
"name": "@ms/container",
|
||||||
"version": "0.1.0",
|
"version": "0.3.0",
|
||||||
"description": "MiaoScript container package",
|
"description": "MiaoScript container package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -17,14 +17,14 @@
|
|||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"clean": "rimraf dist",
|
"clean": "rimraf dist",
|
||||||
"watch": "npx tsc --watch",
|
"watch": "tsc --watch",
|
||||||
"build": "yarn clean && npx tsc",
|
"build": "yarn clean && tsc",
|
||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.0",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.6.2"
|
"typescript": "^3.8.2"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"inversify-binding-decorators": "^4.0.0"
|
"inversify-binding-decorators": "^4.0.0"
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { interfaces, Container } from "inversify";
|
|||||||
|
|
||||||
let _container: Container;
|
let _container: Container;
|
||||||
|
|
||||||
const CONTAINER = Symbol.for("@ms/ioc:Container");
|
const ContainerInstance = Symbol.for("@ms/ioc:Container");
|
||||||
const INJECTION = Symbol.for("INJECTION");
|
const INJECTION = Symbol.for("INJECTION");
|
||||||
|
|
||||||
function _proxyGetter(
|
function _proxyGetter(
|
||||||
@@ -35,12 +35,12 @@ function _proxyGetter(
|
|||||||
}
|
}
|
||||||
|
|
||||||
function initContainer(container: Container) {
|
function initContainer(container: Container) {
|
||||||
Reflect.defineMetadata(CONTAINER, container, Reflect);
|
Reflect.defineMetadata(ContainerInstance, container, Reflect);
|
||||||
_container = container;
|
_container = container;
|
||||||
}
|
}
|
||||||
|
|
||||||
function getContainer(): Container {
|
function getContainer(): Container {
|
||||||
return _container || Reflect.getMetadata(CONTAINER, Reflect)
|
return _container || Reflect.getMetadata(ContainerInstance, Reflect)
|
||||||
}
|
}
|
||||||
|
|
||||||
function makePropertyInjectDecorator(doCache: boolean) {
|
function makePropertyInjectDecorator(doCache: boolean) {
|
||||||
@@ -97,6 +97,7 @@ let lazyMultiInject = makePropertyMultiInjectDecorator(doCache)
|
|||||||
export {
|
export {
|
||||||
initContainer,
|
initContainer,
|
||||||
getContainer,
|
getContainer,
|
||||||
|
ContainerInstance,
|
||||||
lazyInject,
|
lazyInject,
|
||||||
lazyInjectNamed,
|
lazyInjectNamed,
|
||||||
lazyInjectTagged,
|
lazyInjectTagged,
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ms/core",
|
"name": "@ms/core",
|
||||||
"version": "0.1.1",
|
"version": "0.3.0",
|
||||||
"description": "MiaoScript api package",
|
"description": "MiaoScript api package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -12,27 +12,27 @@
|
|||||||
"homepage": "https://github.com/circlecloud/ms.git",
|
"homepage": "https://github.com/circlecloud/ms.git",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"main": "dist/index.js",
|
"main": "dist/index.js",
|
||||||
"typings": "dist/index.d.ts",
|
|
||||||
"publishConfig": {
|
"publishConfig": {
|
||||||
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
|
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"clean": "rimraf dist",
|
"clean": "rimraf dist",
|
||||||
"watch": "npx tsc --watch",
|
"watch": "tsc --watch",
|
||||||
"build": "yarn clean && npx tsc",
|
"build": "yarn clean && tsc",
|
||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.0",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.6.2"
|
"typescript": "^3.8.2"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ms/api": "^0.1.1",
|
"@ms/api": "^0.3.0",
|
||||||
"@ms/bukkit": "^0.1.1",
|
"@ms/bukkit": "^0.3.0",
|
||||||
"@ms/common": "^0.1.0",
|
"@ms/common": "^0.3.0",
|
||||||
"@ms/container": "^0.1.0",
|
"@ms/container": "^0.3.0",
|
||||||
"@ms/plugin": "^0.1.1",
|
"@ms/plugin": "^0.3.0",
|
||||||
"@ms/sponge": "^0.1.1"
|
"@ms/sponge": "^0.3.0"
|
||||||
}
|
},
|
||||||
}
|
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,38 +1,34 @@
|
|||||||
import '@ms/nashorn'
|
/// <reference types="@ms/nashorn" />
|
||||||
|
import '@ms/i18n'
|
||||||
|
|
||||||
|
let containerStartTime = Date.now();
|
||||||
|
console.i18n("ms.core.ioc.initialize");
|
||||||
import { plugin, server, task } from '@ms/api'
|
import { plugin, server, task } from '@ms/api'
|
||||||
import { PluginManagerImpl } from '@ms/plugin'
|
import { DefaultContainer as container, inject, provideSingleton, ContainerInstance, buildProviderModule } from '@ms/container'
|
||||||
import { XMLHttpRequest as xhr } from '@ms/ployfill'
|
console.i18n("ms.core.ioc.completed", { time: (Date.now() - containerStartTime) / 1000 })
|
||||||
import { DefaultContainer as container, injectable, inject, postConstruct } from '@ms/container'
|
|
||||||
|
|
||||||
let startTime = new Date().getTime();
|
@provideSingleton(MiaoScriptCore)
|
||||||
|
|
||||||
@injectable()
|
|
||||||
class MiaoScriptCore {
|
class MiaoScriptCore {
|
||||||
@inject(server.Console)
|
@inject(server.Console)
|
||||||
private Console: Console;
|
private Console: Console;
|
||||||
@inject(task.TaskManager)
|
@inject(task.TaskManager)
|
||||||
private taskManager: task.TaskManager;
|
private taskManager: task.TaskManager;
|
||||||
|
@inject(plugin.PluginFolder)
|
||||||
|
private pluginFolder: string;
|
||||||
@inject(plugin.PluginManager)
|
@inject(plugin.PluginManager)
|
||||||
private pluginManager: plugin.PluginManager;
|
private pluginManager: plugin.PluginManager;
|
||||||
|
|
||||||
enable() {
|
enable() {
|
||||||
try {
|
this.loadServerConsole();
|
||||||
this.loadServerConsole();
|
this.loadTaskFunction();
|
||||||
this.loadTaskFunction();
|
global.level = "TRACE"
|
||||||
this.loadPlugins();
|
this.loadPlugins();
|
||||||
} catch (error) {
|
|
||||||
console.console(`§cMiaoScript start error please contact plugin author!`);
|
|
||||||
console.ex(error);
|
|
||||||
}
|
|
||||||
console.log('MiaoScript engine loading completed... Done (' + (new Date().getTime() - startTime) / 1000 + 's)!');
|
|
||||||
return () => this.disable();
|
return () => this.disable();
|
||||||
}
|
}
|
||||||
|
|
||||||
loadServerConsole() {
|
loadServerConsole() {
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
console = new this.Console();
|
console = new this.Console();
|
||||||
XMLHttpRequest = xhr;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
loadTaskFunction() {
|
loadTaskFunction() {
|
||||||
@@ -43,34 +39,61 @@ class MiaoScriptCore {
|
|||||||
}
|
}
|
||||||
|
|
||||||
loadPlugins() {
|
loadPlugins() {
|
||||||
this.pluginManager.scan('plugins');
|
let loadPluginStartTime = new Date().getTime()
|
||||||
this.pluginManager.build(container);
|
console.i18n("ms.core.plugin.initialize")
|
||||||
|
this.pluginManager.scan(this.pluginFolder);
|
||||||
|
this.pluginManager.build();
|
||||||
this.pluginManager.load();
|
this.pluginManager.load();
|
||||||
this.pluginManager.enable();
|
this.pluginManager.enable();
|
||||||
|
console.i18n("ms.core.plugin.completed", { time: (new Date().getTime() - loadPluginStartTime) / 1000 })
|
||||||
}
|
}
|
||||||
|
|
||||||
disable() {
|
disable() {
|
||||||
|
console.i18n("ms.core.engine.disable")
|
||||||
this.pluginManager.disable();
|
this.pluginManager.disable();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function init() {
|
function detectServer() {
|
||||||
try {
|
try {
|
||||||
Java.type("org.bukkit.Bukkit");
|
Java.type("org.bukkit.Bukkit");
|
||||||
require('@ms/bukkit');
|
return 'bukkit'
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
Java.type("org.spongepowered.api.Sponge");
|
Java.type("org.spongepowered.api.Sponge");
|
||||||
require('@ms/sponge');
|
return 'sponge'
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
}
|
}
|
||||||
|
try {
|
||||||
container.bind(plugin.PluginManager).to(PluginManagerImpl).inSingletonScope();
|
Java.type("cn.nukkit.Nukkit");
|
||||||
container.bind(MiaoScriptCore).to(MiaoScriptCore).inSingletonScope();
|
return 'nukkit'
|
||||||
|
} catch (ex) {
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
Java.type("net.md_5.bungee.api.ProxyServer");
|
||||||
|
return 'bungee'
|
||||||
|
} catch (ex) {
|
||||||
|
}
|
||||||
|
throw Error('Unknow Server Type...')
|
||||||
}
|
}
|
||||||
|
|
||||||
init();
|
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.i18n("ms.core.initialize.detect", { type });
|
||||||
|
container.bind(server.ServerType).toConstantValue(type);
|
||||||
|
console.i18n("ms.core.package.initialize", { type });
|
||||||
|
require(`@ms/${type}`).default(container);
|
||||||
|
require('@ms/plugin')
|
||||||
|
container.load(buildProviderModule());
|
||||||
|
console.i18n("ms.core.package.completed", { type, time: (Date.now() - corePackageStartTime) / 1000 });
|
||||||
|
let disable = container.get<MiaoScriptCore>(MiaoScriptCore).enable()
|
||||||
|
console.i18n("ms.core.engine.completed", { time: (Date.now() - global.NashornEngineStartTime) / 1000 });
|
||||||
|
return disable;
|
||||||
|
}
|
||||||
|
|
||||||
export default container.get<MiaoScriptCore>(MiaoScriptCore).enable();
|
export default initialize();
|
||||||
|
|||||||
38
packages/i18n/languages/en.yml
Normal file
38
packages/i18n/languages/en.yml
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
ms.ployfill.initialize: "Initialization Java Nashorn ployfill. Please wait..."
|
||||||
|
ms.ployfill.completed: "Java Nashorn ployfill loading completed... Cost ({time}s)!"
|
||||||
|
|
||||||
|
ms.core.ioc.initialize: "Initialization MiaoScript IOC Container @ms/container. Please wait..."
|
||||||
|
ms.core.ioc.completed: "MiaoScript IOC Container @ms/container loading completed({time}s)!"
|
||||||
|
ms.core.initialize.detect: "Detect Compatible Server set ServerType to {type} ..."
|
||||||
|
ms.core.package.initialize: "Initialization MiaoScript Package @ms/core @ms/{type} @ms/plugin. Please wait..."
|
||||||
|
ms.core.package.completed: "MiaoScript Package @ms/core @ms/{type} @ms/plugin loading completed({time}s)!"
|
||||||
|
ms.core.plugin.initialize: "Initialization MiaoScript Plugin System. Please wait..."
|
||||||
|
ms.core.plugin.completed: "MiaoScript Plugin System loading completed({time}s)!"
|
||||||
|
ms.core.engine.completed: "MiaoScript ScriptEngine loading completed... Done({time}s)!"
|
||||||
|
ms.core.engine.disable: "Disable MiaoScript Engine..."
|
||||||
|
|
||||||
|
ms.api.event.resource.not.found: "Can't Mapping Event Because not found Resources {resource}!"
|
||||||
|
ms.api.event.empty.event.dir: "base event dir is empty, can't map event name !"
|
||||||
|
ms.api.event.mapping: "Mapping Event [{canonicalName}] => {simpleName}"
|
||||||
|
ms.api.event.not.found: "§6Plugin §b{name} §6register {event} error. event not found!"
|
||||||
|
ms.api.event.execute.slow: "§cWARN! §6Plugin §b{name} §6execute §d{event} §6evnet §ccost §4{cost}ms !"
|
||||||
|
ms.api.event.execute.error: "§6Plugin §b{name} §6execute §d{event} §6event error §4{ex}"
|
||||||
|
ms.api.event.listen.plugin.name.empty: "Plugin name can't be empty!"
|
||||||
|
ms.api.event.register: "[{name}] register event {event}"
|
||||||
|
ms.api.event.unregister: "[{name}] unregister event {event}"
|
||||||
|
ms.api.command.register.input.error: "CommandExec Must be a function... Input: {exec}"
|
||||||
|
ms.api.command.register: "[{plugin}] register command {name}({cmd})..."
|
||||||
|
ms.api.command.unregister: "[{plugin}] unregister command {name}..."
|
||||||
|
|
||||||
|
ms.plugin.initialize: "Initialization MiaoScript Plugin System: {plugin} ..."
|
||||||
|
ms.plugin.event.map: "Total {count} {type} Event Mapping Complate..."
|
||||||
|
ms.plugin.manager.scan: "Scanning Plugins in {folder} ..."
|
||||||
|
ms.plugin.manager.initialize.error: "§6Plugin §b{name} §6initialize error §4{ex}"
|
||||||
|
ms.plugin.manager.stage: "{stage} {plugin} version {version} by {author}"
|
||||||
|
ms.plugin.manager.stage.load: "Loading"
|
||||||
|
ms.plugin.manager.stage.enable: "Enabling"
|
||||||
|
ms.plugin.manager.stage.disable: "Disabling"
|
||||||
|
ms.plugin.manager.build.update: "Auto Update Plugin {name} ..."
|
||||||
|
ms.plugin.manager.build.not.extends: "§4Found error plugin §b{source} §4it's not extends interfaces.Plugin, the plugin will be ignore!"
|
||||||
|
ms.plugin.manager.build.exists: "§4Found duplicate plugin §b{exists} §4and §b{source}§4. the first plugin will be ignore!"
|
||||||
|
ms.plugin.manager.config.save.default: "[{plugin}] config {name}.{format} not exists. auto create from default variable..."
|
||||||
38
packages/i18n/languages/zh_cn.yml
Normal file
38
packages/i18n/languages/zh_cn.yml
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
ms.ployfill.initialize: "初始化 Java Nashorn 补丁. 请稍候..."
|
||||||
|
ms.ployfill.completed: "Java Nashorn 补丁 加载完成... 耗时 ({time}s)!"
|
||||||
|
|
||||||
|
ms.core.ioc.initialize: "初始化 MiaoScript IOC 容器 @ms/container. 请稍候..."
|
||||||
|
ms.core.ioc.completed: "MiaoScript IOC 容器 @ms/container 加载完成 耗时({time}s)"
|
||||||
|
ms.core.initialize.detect: "检测到兼容的服务器类型. 设置 ServerType 值 {type} ..."
|
||||||
|
ms.core.package.initialize: "初始化 MiaoScript 扩展 @ms/core @ms/{type} @ms/plugin. 请稍候..."
|
||||||
|
ms.core.package.completed: "MiaoScript 扩展 @ms/core @ms/{type} @ms/plugin 加载完成 耗时({time}s)"
|
||||||
|
ms.core.plugin.initialize: "MiaoScript 开始引导插件系统. 请稍候..."
|
||||||
|
ms.core.plugin.completed: "MiaoScript 插件加载完毕 耗时({time}s)!"
|
||||||
|
ms.core.engine.completed: "MiaoScript 脚本引擎 加载完毕... 耗时({time}s)!"
|
||||||
|
ms.core.engine.disable: "关闭 MiaoScript 引擎..."
|
||||||
|
|
||||||
|
ms.api.event.resource.not.found: "无法映射事件 未找到资源文件 {resource}!"
|
||||||
|
ms.api.event.empty.event.dir: "事件基础目录为空, 无法映射事件!"
|
||||||
|
ms.api.event.mapping: "映射事件 [{canonicalName}] => {simpleName}"
|
||||||
|
ms.api.event.not.found: "§6插件 §b{name} §6注册事件 §c{event} §6失败. §4事件未找到!"
|
||||||
|
ms.api.event.execute.slow: "§c注意! §6插件 §b{name} §6处理 §d{event} §6事件 §c耗时 §4{cost}ms !"
|
||||||
|
ms.api.event.execute.error: "§6插件 §b{name} §6处理 §d{event} §6事件时发生异常 §4{ex}"
|
||||||
|
ms.api.event.listen.plugin.name.empty: "插件名称为空 请检查传入参数!"
|
||||||
|
ms.api.event.register: "[{name}] 注册事件 {event}"
|
||||||
|
ms.api.event.unregister: "[{name}] 注销事件 {event}"
|
||||||
|
ms.api.command.register.input.error: "CommandExec 必须为一个函数... 输入: {exec}"
|
||||||
|
ms.api.command.register: "[{plugin}] 注册命令 {name}({cmd})..."
|
||||||
|
ms.api.command.unregister: "[{plugin}] 注销命令 {name}..."
|
||||||
|
|
||||||
|
ms.plugin.initialize: "初始化 MiaoScript 插件系统: {plugin} ..."
|
||||||
|
ms.plugin.event.map: "总计 {count} 个 {type} 事件 映射完成..."
|
||||||
|
ms.plugin.manager.scan: "在 {folder} 文件夹中扫描插件..."
|
||||||
|
ms.plugin.manager.initialize.error: "§6插件 §b{name} §6初始化错误 §4{ex}"
|
||||||
|
ms.plugin.manager.stage: "{stage} {plugin} 版本 {version} 作者 {author}"
|
||||||
|
ms.plugin.manager.stage.load: "加载"
|
||||||
|
ms.plugin.manager.stage.enable: "启用"
|
||||||
|
ms.plugin.manager.stage.disable: "关闭"
|
||||||
|
ms.plugin.manager.build.update: "自动更新插件 {name} ..."
|
||||||
|
ms.plugin.manager.build.not.extends: "§4发现错误的插件 §b{source} §4未继承接口 interfaces.Plugin, 将不会被载入到服务器!"
|
||||||
|
ms.plugin.manager.build.duplicate: "§4发现已存在插件 §b{exists} §4和 §b{source}§4 存在冲突. 已存在插件将会被替换!"
|
||||||
|
ms.plugin.manager.config.save.default: "[{plugin}] 配置 {name}.{format} 不存在. 从默认值自动创建保存..."
|
||||||
37
packages/i18n/package.json
Normal file
37
packages/i18n/package.json
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
{
|
||||||
|
"name": "@ms/i18n",
|
||||||
|
"version": "0.3.0",
|
||||||
|
"description": "MiaoScript i18n 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": {
|
||||||
|
"@types/js-yaml": "^3.12.2",
|
||||||
|
"reflect-metadata": "^0.1.13",
|
||||||
|
"rimraf": "^3.0.2",
|
||||||
|
"typescript": "^3.8.2"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@ms/common": "^0.3.0",
|
||||||
|
"@ms/container": "^0.3.0",
|
||||||
|
"@ms/ployfill": "^0.3.0",
|
||||||
|
"js-yaml": "^3.13.1"
|
||||||
|
},
|
||||||
|
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
||||||
|
}
|
||||||
42
packages/i18n/src/index.ts
Normal file
42
packages/i18n/src/index.ts
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
import '@ms/ployfill'
|
||||||
|
import * as yaml from 'js-yaml'
|
||||||
|
|
||||||
|
import * as fs from '@ms/common/dist/fs'
|
||||||
|
|
||||||
|
let langMap = {};
|
||||||
|
let fallbackMap = {};
|
||||||
|
|
||||||
|
type TranslateParam = { [key: string]: any }
|
||||||
|
|
||||||
|
function translate(name: string, param?: TranslateParam) {
|
||||||
|
let langText: string = langMap[name] || fallbackMap[name];
|
||||||
|
if (!langText) { return '[WARN] @ms/i18n miss lang translate: ' + name }
|
||||||
|
for (const key in param) {
|
||||||
|
langText = langText.replace("{" + key + "}", param[key])
|
||||||
|
}
|
||||||
|
return langText;
|
||||||
|
}
|
||||||
|
|
||||||
|
function initialize(lang: string = 'zh_cn', fallback: string = 'zh_cn') {
|
||||||
|
langMap = readYamlFile(root, lang) || readYamlFile(fs.concat(__dirname, '..'), lang)
|
||||||
|
fallbackMap = readYamlFile(root, fallback) || readYamlFile(fs.concat(__dirname, '..'), fallback)
|
||||||
|
console.i18n = function i18n(name: string, param?: TranslateParam) {
|
||||||
|
console.log(translate(name, param))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function readYamlFile(dir: string, name: string) {
|
||||||
|
let langFile = fs.concat(dir, 'languages', name + '.yml');
|
||||||
|
return fs.exists(langFile) && yaml.safeLoad(base.read(langFile))
|
||||||
|
}
|
||||||
|
|
||||||
|
declare global {
|
||||||
|
interface Console {
|
||||||
|
i18n(name: string, param?: TranslateParam);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default {
|
||||||
|
initialize,
|
||||||
|
translate
|
||||||
|
};
|
||||||
7
packages/i18n/tsconfig.json
Normal file
7
packages/i18n/tsconfig.json
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"extends": "../../tsconfig.json",
|
||||||
|
"compilerOptions": {
|
||||||
|
"baseUrl": "src",
|
||||||
|
"outDir": "dist"
|
||||||
|
}
|
||||||
|
}
|
||||||
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.3.0",
|
||||||
|
"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"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,11 +1,12 @@
|
|||||||
# sponge bukkit
|
# sponge bukkit jdk bungee nukkit
|
||||||
TYPE=sponge
|
TYPE=nukkit
|
||||||
|
TARGET=../types/dist/typings
|
||||||
npx tsc src/build.ts --outDir dist
|
npx tsc src/build.ts --outDir dist
|
||||||
cd dist
|
cd dist
|
||||||
rm -rf temp
|
rm -rf temp
|
||||||
mkdir -p temp
|
mkdir -p temp
|
||||||
node build.js ${TYPE}
|
node build.js ${TYPE}
|
||||||
cd ../
|
cd ../
|
||||||
rm -rf src/typings
|
rm -rf ${TARGET}/${TYPE}
|
||||||
mkdir -p src/typings/${TYPE}
|
mkdir -p ${TARGET}/${TYPE}
|
||||||
cp dist/temp/* src/typings/${TYPE}/ -R
|
cp dist/temp/* ${TARGET}/${TYPE}/ -R
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ms/nashorn",
|
"name": "@ms/nashorn",
|
||||||
"version": "0.1.0",
|
"version": "0.3.0",
|
||||||
"description": "MiaoScript api package",
|
"description": "MiaoScript api package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -18,13 +18,13 @@
|
|||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"clean": "rimraf dist",
|
"clean": "rimraf dist",
|
||||||
"watch": "npx tsc --watch",
|
"watch": "tsc --watch",
|
||||||
"build": "yarn clean && npx tsc",
|
"build": "yarn clean && tsc",
|
||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.0",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.6.2"
|
"typescript": "^3.8.2"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ function convertJson2TypeDefiend(infile: string, outDir: string) {
|
|||||||
closeBuk++;
|
closeBuk++;
|
||||||
const nms = qnas.slice(1, qnas.length - 1);
|
const nms = qnas.slice(1, qnas.length - 1);
|
||||||
for (const nm of nms) {
|
for (const nm of nms) {
|
||||||
temp += `${' '.repeat(closeBuk)}namespace ${nm} {\n`;
|
temp += `${' '.repeat(closeBuk)}namespace ${nm.replace('function', 'function$')} {\n`;
|
||||||
closeBuk++;
|
closeBuk++;
|
||||||
}
|
}
|
||||||
let classModifier = formatClassModifier(obj.modifiers)
|
let classModifier = formatClassModifier(obj.modifiers)
|
||||||
@@ -33,7 +33,7 @@ function convertJson2TypeDefiend(infile: string, outDir: string) {
|
|||||||
temp = temp.substr(0, temp.length - 2);
|
temp = temp.substr(0, temp.length - 2);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
temp += `${(obj.superclass && obj.superclass.qualifiedName.startsWith('org.')) ? (' extends ' + obj.superclass.qualifiedName) : ''}`;
|
temp += `${(obj.superclass) ? (' extends ' + (obj.superclass.qualifiedName == "<any>" ? "object" : obj.superclass.qualifiedName)) : ''}`;
|
||||||
if (safeInterface.length > 0) {
|
if (safeInterface.length > 0) {
|
||||||
temp += ' implements '
|
temp += ' implements '
|
||||||
for (const ifs of safeInterface) {
|
for (const ifs of safeInterface) {
|
||||||
@@ -46,7 +46,7 @@ function convertJson2TypeDefiend(infile: string, outDir: string) {
|
|||||||
temp += ' {\n'
|
temp += ' {\n'
|
||||||
closeBuk++;
|
closeBuk++;
|
||||||
for (const constructor of obj.constructors) {
|
for (const constructor of obj.constructors) {
|
||||||
temp += `${formatDoc(constructor.docString, closeBuk)}${' '.repeat(closeBuk)}constructor(${formatParameters(constructor.parameters)})\n`;
|
temp += `${formatDoc(constructor.docString, closeBuk)}${' '.repeat(closeBuk)}// @ts-ignore\n${' '.repeat(closeBuk)}constructor(${formatParameters(constructor.parameters)})\n`;
|
||||||
}
|
}
|
||||||
|
|
||||||
let members = [];
|
let members = [];
|
||||||
@@ -77,8 +77,8 @@ function convertJson2TypeDefiend(infile: string, outDir: string) {
|
|||||||
temp += `${' '.repeat(closeBuk - index - 1)}}\n`;
|
temp += `${' '.repeat(closeBuk - index - 1)}}\n`;
|
||||||
}
|
}
|
||||||
|
|
||||||
fs.writeFileSync(`${outDir}/${file}.ts`, temp);
|
fs.writeFileSync(`${outDir}/${file}.${suffix}`, temp);
|
||||||
return `${file}.ts`;
|
return `${file}.${suffix}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatClassModifier(modifiers: string) {
|
function formatClassModifier(modifiers: string) {
|
||||||
@@ -98,7 +98,11 @@ function formatDoc(doc: string, closeBuk: number) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function replaceModifiers(modifiers: string, absClass = false): string {
|
function replaceModifiers(modifiers: string, absClass = false): string {
|
||||||
|
// modifiers = modifiers.replace(' final', ' readonly');
|
||||||
modifiers = modifiers.split(" final")[0];
|
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];
|
modifiers = modifiers.split(" synchronized")[0];
|
||||||
if (!absClass) {
|
if (!absClass) {
|
||||||
modifiers = modifiers.split(" abstract")[0];
|
modifiers = modifiers.split(" abstract")[0];
|
||||||
@@ -117,6 +121,7 @@ function formatParameters(params: any[]) {
|
|||||||
const nameMap = [];
|
const nameMap = [];
|
||||||
nameMap['function'] = 'func'
|
nameMap['function'] = 'func'
|
||||||
nameMap['in'] = 'input'
|
nameMap['in'] = 'input'
|
||||||
|
nameMap['var'] = 'variable'
|
||||||
|
|
||||||
function mappingName(name: string) {
|
function mappingName(name: string) {
|
||||||
if (whiteKey.includes(name)) { return name }
|
if (whiteKey.includes(name)) { return name }
|
||||||
@@ -124,7 +129,7 @@ function mappingName(name: string) {
|
|||||||
return outName;
|
return outName;
|
||||||
}
|
}
|
||||||
|
|
||||||
let whiteKey = ['shift', "map", 'filter', 'values', 'valueOf', 'toString', 'length', 'includes', 'entries','keys']
|
let whiteKey = ['shift', "map", 'filter', 'values', 'valueOf', 'toString', 'length', 'includes', 'entries', 'keys', 'join', 'fill']
|
||||||
|
|
||||||
const typeMap = [];
|
const typeMap = [];
|
||||||
typeMap['int'] = 'number';
|
typeMap['int'] = 'number';
|
||||||
@@ -133,17 +138,22 @@ typeMap['int[][]'] = 'number[][]';
|
|||||||
typeMap['byte'] = 'number';
|
typeMap['byte'] = 'number';
|
||||||
typeMap['byte[]'] = 'number[]';
|
typeMap['byte[]'] = 'number[]';
|
||||||
typeMap['double'] = 'number';
|
typeMap['double'] = 'number';
|
||||||
|
typeMap['double[]'] = 'number[]';
|
||||||
typeMap['short'] = 'number';
|
typeMap['short'] = 'number';
|
||||||
|
typeMap['short[]'] = 'number[]';
|
||||||
typeMap['float'] = 'number';
|
typeMap['float'] = 'number';
|
||||||
|
typeMap['float[]'] = 'number[]';
|
||||||
typeMap['long'] = 'number';
|
typeMap['long'] = 'number';
|
||||||
|
typeMap['long[]'] = 'number[]';
|
||||||
typeMap['<any>'] = 'any';
|
typeMap['<any>'] = 'any';
|
||||||
typeMap['char'] = 'string';
|
typeMap['char'] = 'string';
|
||||||
|
typeMap['char[]'] = 'string[]';
|
||||||
typeMap['java.lang.String'] = "string";
|
typeMap['java.lang.String'] = "string";
|
||||||
typeMap['java.util.Date'] = 'any /*java.util.Date*/'
|
// typeMap['java.util.Date'] = 'any /*java.util.Date*/'
|
||||||
typeMap['java.util.List'] = 'any[] /*java.util.List*/'
|
// typeMap['java.util.List'] = 'any[] /*java.util.List*/'
|
||||||
typeMap['java.util.Set'] = 'any[] /*java.util.Set*/'
|
// typeMap['java.util.Set'] = 'any[] /*java.util.Set*/'
|
||||||
typeMap['java.util.Collection'] = 'any[] /*java.util.Collection*/'
|
// typeMap['java.util.Collection'] = 'any[] /*java.util.Collection*/'
|
||||||
typeMap['java.util.Map'] = 'Map<any, any> /*java.util.Map*/'
|
// typeMap['java.util.Map'] = 'Map<any, any> /*java.util.Map*/'
|
||||||
// Sponge
|
// Sponge
|
||||||
typeMap['Vectori'] = 'any /*Vector3i*/'
|
typeMap['Vectori'] = 'any /*Vector3i*/'
|
||||||
typeMap['Vectord'] = 'any /*Vector3d*/'
|
typeMap['Vectord'] = 'any /*Vector3d*/'
|
||||||
@@ -167,12 +177,19 @@ typeMap['Matrix4d'] = 'any /*Matrix4d*/'
|
|||||||
|
|
||||||
function mappingType(type: string): string {
|
function mappingType(type: string): string {
|
||||||
let outType = typeMap[type] || type || 'any';
|
let outType = typeMap[type] || type || 'any';
|
||||||
outType = outType.startsWith('java.') || outType.startsWith('javax.') ? 'any' : outType;
|
if (outType.indexOf('.') != -1) {
|
||||||
return outType;
|
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)
|
var args = process.argv.splice(2)
|
||||||
|
|
||||||
|
const suffix = 'd.ts'
|
||||||
const inDir = `../docs/${args[0]}`
|
const inDir = `../docs/${args[0]}`
|
||||||
const outDir = "./temp";
|
const outDir = "./temp";
|
||||||
const files = fs.readdirSync(inDir);
|
const files = fs.readdirSync(inDir);
|
||||||
@@ -180,4 +197,4 @@ let index = '';
|
|||||||
for (const file of files) {
|
for (const file of files) {
|
||||||
index += `/// <reference path="./${convertJson2TypeDefiend(file, outDir)}" />\n`;
|
index += `/// <reference path="./${convertJson2TypeDefiend(file, outDir)}" />\n`;
|
||||||
}
|
}
|
||||||
fs.writeFileSync(`${outDir}/index.ts`, index);
|
fs.writeFileSync(`${outDir}/index.${suffix}`, index);
|
||||||
|
|||||||
35
packages/nukkit/package.json
Normal file
35
packages/nukkit/package.json
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
{
|
||||||
|
"name": "@ms/nukkit",
|
||||||
|
"version": "0.3.0",
|
||||||
|
"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.3.0",
|
||||||
|
"@ms/common": "^0.3.0",
|
||||||
|
"@ms/container": "^0.3.0",
|
||||||
|
"@ms/types": "^0.3.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
40
packages/nukkit/src/command.ts
Normal file
40
packages/nukkit/src/command.ts
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
import '@ms/nashorn'
|
||||||
|
|
||||||
|
import { command, plugin } from '@ms/api'
|
||||||
|
import { inject, provideSingleton, postConstruct } from '@ms/container'
|
||||||
|
|
||||||
|
let PluginCommand = Java.type('cn.nukkit.command.PluginCommand');
|
||||||
|
let CommandExecutor = Java.type('cn.nukkit.command.CommandExecutor');
|
||||||
|
|
||||||
|
@provideSingleton(command.Command)
|
||||||
|
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) {
|
||||||
|
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, plugin } from '@ms/api'
|
||||||
|
import { inject, provideSingleton } 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");
|
||||||
|
|
||||||
|
@provideSingleton(event.Event)
|
||||||
|
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.getMethod('getHandlers').invoke(null).unregister(listener);
|
||||||
|
}
|
||||||
|
}
|
||||||
14
packages/nukkit/src/index.ts
Normal file
14
packages/nukkit/src/index.ts
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
/// <reference types="@ms/types/dist/typings/nukkit" />
|
||||||
|
|
||||||
|
import { server } from '@ms/api'
|
||||||
|
import { Container } from '@ms/container'
|
||||||
|
|
||||||
|
import { NukkitConsole } from './console';
|
||||||
|
import './event';
|
||||||
|
import './server';
|
||||||
|
import './command';
|
||||||
|
import './task';
|
||||||
|
|
||||||
|
export default function NukkitImpl(container: Container) {
|
||||||
|
container.bind(server.Console).toConstantValue(NukkitConsole);
|
||||||
|
}
|
||||||
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 { provideSingleton } from '@ms/container';
|
||||||
|
|
||||||
|
let Nukkit: cn.nukkit.Server = base.getInstance().getServer();
|
||||||
|
|
||||||
|
@provideSingleton(server.Server)
|
||||||
|
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.");
|
||||||
|
}
|
||||||
|
}
|
||||||
33
packages/nukkit/src/task.ts
Normal file
33
packages/nukkit/src/task.ts
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
import { task, plugin } from '@ms/api'
|
||||||
|
import { inject, provideSingleton } from '@ms/container';
|
||||||
|
|
||||||
|
const NukkitRunnable = Java.type('cn.nukkit.scheduler.NukkitRunnable');
|
||||||
|
|
||||||
|
@provideSingleton(task.TaskManager)
|
||||||
|
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"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ms/ployfill",
|
"name": "@ms/ployfill",
|
||||||
"version": "0.1.0",
|
"version": "0.3.0",
|
||||||
"description": "MiaoScript ployfill package",
|
"description": "MiaoScript ployfill package",
|
||||||
"author": "MiaoWoo <admin@yumc.pw>",
|
"author": "MiaoWoo <admin@yumc.pw>",
|
||||||
"homepage": "https://github.com/circlecloud/ms.git",
|
"homepage": "https://github.com/circlecloud/ms.git",
|
||||||
@@ -12,16 +12,17 @@
|
|||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"clean": "rimraf dist",
|
"clean": "rimraf dist",
|
||||||
"watch": "npx tsc --watch",
|
"watch": "tsc --watch",
|
||||||
"build": "yarn clean && npx tsc",
|
"build": "yarn clean && tsc",
|
||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ms/nashorn": "^0.1.0"
|
"@ms/nashorn": "^0.3.0",
|
||||||
|
"core-js": "^3.6.4"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.0",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.6.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
|
||||||
|
})
|
||||||
|
|
||||||
@@ -1,28 +1,33 @@
|
|||||||
import { XMLHttpRequest as xhr } from '@ms/ployfill'
|
|
||||||
|
|
||||||
declare global {
|
declare global {
|
||||||
namespace NodeJS {
|
namespace NodeJS {
|
||||||
interface Global {
|
interface Global {
|
||||||
logger: any;
|
logger: any;
|
||||||
debug: boolean;
|
debug: boolean;
|
||||||
noop: Function;
|
level: string;
|
||||||
|
NashornEngineStartTime: number;
|
||||||
|
setGlobal: (key: string, value: any) => void;
|
||||||
|
noop: () => void;
|
||||||
console: Console;
|
console: Console;
|
||||||
XMLHttpRequest: typeof xhr;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
var root: string;
|
var root: string;
|
||||||
var base: Core;
|
var base: Core;
|
||||||
var XMLHttpRequest: typeof xhr;
|
|
||||||
var ScriptEngineContextHolder: any;
|
var ScriptEngineContextHolder: any;
|
||||||
function engineLoad(str: string): any;
|
function engineLoad(str: string): any;
|
||||||
interface Core {
|
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 {
|
interface Console {
|
||||||
ex(err: Error): void;
|
ex(err: Error): void;
|
||||||
stack(err: Error): string[];
|
stack(err: Error): string[];
|
||||||
sender(...args: any): void;
|
sender(...args: any): void;
|
||||||
console(...args: any): void;
|
console(...args: any): void;
|
||||||
|
i18n(name: string, ...params: any[]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
export { }
|
export { }
|
||||||
@@ -1,7 +1,12 @@
|
|||||||
import { XMLHttpRequest as xhr } from './xml-http-request'
|
/// <reference path="./global.ts" />
|
||||||
|
/// <reference types='@ms/nashorn' />
|
||||||
var XMLHttpRequest = xhr;
|
import i18n from '@ms/i18n'
|
||||||
|
let ployfillStartTime = new Date().getTime();
|
||||||
export {
|
i18n.initialize();
|
||||||
XMLHttpRequest
|
console.i18n("ms.ployfill.initialize");
|
||||||
}
|
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.i18n("ms.ployfill.completed", { time: (new Date().getTime() - ployfillStartTime) / 1000 });
|
||||||
|
|||||||
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]
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -114,7 +114,7 @@ export class XMLHttpRequest {
|
|||||||
return this._statusText;
|
return this._statusText;
|
||||||
}
|
}
|
||||||
get response() {
|
get response() {
|
||||||
return JSON.parse(this._response);
|
return this._response ? JSON.parse(this._response) : this._response;
|
||||||
}
|
}
|
||||||
get responseText() {
|
get responseText() {
|
||||||
return this._response;
|
return this._response;
|
||||||
@@ -174,6 +174,16 @@ export class XMLHttpRequest {
|
|||||||
if (!this._async) { future.get() }
|
if (!this._async) { future.get() }
|
||||||
return future;
|
return future;
|
||||||
}
|
}
|
||||||
|
get() {
|
||||||
|
switch (this._responseType) {
|
||||||
|
case "json":
|
||||||
|
return this.response;
|
||||||
|
case "text":
|
||||||
|
return this.responseText;
|
||||||
|
default:
|
||||||
|
throw Error(`Unsupport ResponseType: ${this._responseType} !`)
|
||||||
|
}
|
||||||
|
}
|
||||||
abort() {
|
abort() {
|
||||||
this._connection.disconnect();
|
this._connection.disconnect();
|
||||||
this.onabort();
|
this.onabort();
|
||||||
@@ -182,7 +192,6 @@ export class XMLHttpRequest {
|
|||||||
private _send(body?: string | object) {
|
private _send(body?: string | object) {
|
||||||
try {
|
try {
|
||||||
this._connection.connect();
|
this._connection.connect();
|
||||||
|
|
||||||
this.onloadstart();
|
this.onloadstart();
|
||||||
if (body) {
|
if (body) {
|
||||||
let bodyType = Object.prototype.toString.call(body);
|
let bodyType = Object.prototype.toString.call(body);
|
||||||
@@ -204,14 +213,6 @@ export class XMLHttpRequest {
|
|||||||
this._response = this.readOutput(this._connection.getErrorStream());
|
this._response = this.readOutput(this._connection.getErrorStream());
|
||||||
}
|
}
|
||||||
this.onloadend();
|
this.onloadend();
|
||||||
switch (this._responseType) {
|
|
||||||
case "json":
|
|
||||||
return this.response;
|
|
||||||
case "text":
|
|
||||||
return this.responseText;
|
|
||||||
default:
|
|
||||||
throw Error(`Unsupport ResponseType: ${this._responseType} !`)
|
|
||||||
}
|
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
if (ex instanceof SocketTimeoutException && this.ontimeout) {
|
if (ex instanceof SocketTimeoutException && this.ontimeout) {
|
||||||
return this.ontimeout(ex)
|
return this.ontimeout(ex)
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ms/plugin",
|
"name": "@ms/plugin",
|
||||||
"version": "0.1.1",
|
"version": "0.3.0",
|
||||||
"description": "MiaoScript api package",
|
"description": "MiaoScript api package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -17,18 +17,21 @@
|
|||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"clean": "rimraf dist",
|
"clean": "rimraf dist",
|
||||||
"watch": "npx tsc --watch",
|
"watch": "tsc --watch",
|
||||||
"build": "yarn clean && npx tsc",
|
"build": "yarn clean && tsc",
|
||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@types/js-yaml": "^3.12.2",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.0",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.6.2"
|
"typescript": "^3.8.2"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ms/api": "^0.1.1",
|
"@ms/api": "^0.3.0",
|
||||||
"@ms/common": "^0.1.0",
|
"@ms/common": "^0.3.0",
|
||||||
"@ms/container": "^0.1.0"
|
"@ms/container": "^0.3.0",
|
||||||
|
"@ms/i18n": "^0.3.0",
|
||||||
|
"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()
|
||||||
@@ -3,4 +3,5 @@ export const METADATA_KEY = {
|
|||||||
cmd: "@ms/plugin:cmd",
|
cmd: "@ms/plugin:cmd",
|
||||||
tab: "@ms/plugin:tab",
|
tab: "@ms/plugin:tab",
|
||||||
listener: "@ms/plugin:listener",
|
listener: "@ms/plugin:listener",
|
||||||
|
config: "@ms/plugin:config",
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { injectable, decorate } from "@ms/container";
|
import { injectable, decorate } from "@ms/container";
|
||||||
import { interfaces } from './interfaces'
|
import { interfaces } from './interfaces'
|
||||||
import { METADATA_KEY } from './constants'
|
import { METADATA_KEY } from './constants'
|
||||||
import { getPluginMetadatas, getPluginCommandMetadata, getPluginListenerMetadata, getPluginTabCompleterMetadata } from './utils'
|
import { getPluginMetadatas, getPluginCommandMetadata, getPluginListenerMetadata, getPluginTabCompleterMetadata, getPluginConfigMetadata } from './utils'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* MiaoScript plugin
|
* MiaoScript plugin
|
||||||
@@ -9,10 +9,9 @@ import { getPluginMetadatas, getPluginCommandMetadata, getPluginListenerMetadata
|
|||||||
*/
|
*/
|
||||||
export function plugin(metadata: interfaces.PluginMetadata) {
|
export function plugin(metadata: interfaces.PluginMetadata) {
|
||||||
return function(target: any) {
|
return function(target: any) {
|
||||||
target.description = metadata;
|
|
||||||
metadata.target = target;
|
metadata.target = target;
|
||||||
decorate(injectable(), target);
|
decorate(injectable(), target);
|
||||||
Reflect.defineMetadata(METADATA_KEY.plugin, metadata, target.constructor);
|
Reflect.defineMetadata(METADATA_KEY.plugin, metadata, target);
|
||||||
const previousMetadata: Map<string, interfaces.PluginMetadata> = getPluginMetadatas();
|
const previousMetadata: Map<string, interfaces.PluginMetadata> = getPluginMetadatas();
|
||||||
previousMetadata.set(metadata.name, metadata);
|
previousMetadata.set(metadata.name, metadata);
|
||||||
Reflect.defineMetadata(METADATA_KEY.plugin, previousMetadata, Reflect);
|
Reflect.defineMetadata(METADATA_KEY.plugin, previousMetadata, Reflect);
|
||||||
@@ -62,3 +61,13 @@ export function listener(metadata: interfaces.ListenerMetadata = {}) {
|
|||||||
Reflect.defineMetadata(METADATA_KEY.listener, [metadata, ...previousMetadata], target.constructor);
|
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,4 +1,7 @@
|
|||||||
import { injectable } from "@ms/container";
|
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 {
|
export namespace interfaces {
|
||||||
@injectable()
|
@injectable()
|
||||||
@@ -6,11 +9,27 @@ export namespace interfaces {
|
|||||||
public description: PluginMetadata;
|
public description: PluginMetadata;
|
||||||
public logger: Console;
|
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 load() { }
|
||||||
public enable() { }
|
public enable() { }
|
||||||
public disable() { }
|
public disable() { }
|
||||||
}
|
}
|
||||||
export interface PluginMetadata {
|
interface BaseMetadata {
|
||||||
|
/**
|
||||||
|
* 名称 为空则为对象名称
|
||||||
|
*/
|
||||||
|
name?: string;
|
||||||
|
/**
|
||||||
|
* 支持的服务器列表 为空则代表所有
|
||||||
|
*/
|
||||||
|
servers?: string[];
|
||||||
|
}
|
||||||
|
export interface PluginMetadata extends BaseMetadata {
|
||||||
/**
|
/**
|
||||||
* 插件名称
|
* 插件名称
|
||||||
*/
|
*/
|
||||||
@@ -36,20 +55,39 @@ export namespace interfaces {
|
|||||||
*/
|
*/
|
||||||
target?: any;
|
target?: any;
|
||||||
}
|
}
|
||||||
export interface CommandMetadata {
|
interface ExecMetadata extends BaseMetadata {
|
||||||
name?: string;
|
/**
|
||||||
|
* 执行器
|
||||||
|
*/
|
||||||
executor?: string;
|
executor?: string;
|
||||||
|
}
|
||||||
|
export interface CommandMetadata extends ExecMetadata {
|
||||||
|
/**
|
||||||
|
* 参数列表
|
||||||
|
*/
|
||||||
paramtypes?: string[];
|
paramtypes?: string[];
|
||||||
}
|
}
|
||||||
export interface TabCompleterMetadata {
|
export interface TabCompleterMetadata extends ExecMetadata {
|
||||||
name?: string;
|
/**
|
||||||
executor?: string;
|
* 参数列表
|
||||||
|
*/
|
||||||
paramtypes?: string[];
|
paramtypes?: string[];
|
||||||
}
|
}
|
||||||
export interface ListenerMetadata {
|
export interface ListenerMetadata extends ExecMetadata {
|
||||||
name?: string;
|
}
|
||||||
executor?: string;
|
export interface ConfigMetadata extends BaseMetadata {
|
||||||
servertype?: string;
|
/**
|
||||||
|
* 配置文件版本号
|
||||||
|
*/
|
||||||
|
version?: number;
|
||||||
|
/**
|
||||||
|
* 实体变量名称
|
||||||
|
*/
|
||||||
|
variable?: string;
|
||||||
|
/**
|
||||||
|
* 配置文件格式 默认 yml
|
||||||
|
*/
|
||||||
|
format?: string;
|
||||||
}
|
}
|
||||||
export type PluginLike = Plugin | string;
|
export type PluginLike = Plugin | string;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,18 +1,22 @@
|
|||||||
import { plugin, server, command, event, MiaoScriptConsole } from '@ms/api'
|
import i18n from '@ms/i18n'
|
||||||
import { injectable, inject, postConstruct, Container, DefaultContainer as container } from '@ms/container'
|
import { plugin, server, command, event } from '@ms/api'
|
||||||
|
import { inject, provideSingleton, postConstruct, Container, ContainerInstance } from '@ms/container'
|
||||||
import * as fs from '@ms/common/dist/fs'
|
import * as fs from '@ms/common/dist/fs'
|
||||||
|
|
||||||
import { getPluginMetadatas, getPluginCommandMetadata, getPluginListenerMetadata, getPlugin, getPluginTabCompleterMetadata } from './utils'
|
import { getPluginMetadatas, getPluginCommandMetadata, getPluginListenerMetadata, getPlugin, getPluginTabCompleterMetadata, getPluginConfigMetadata } from './utils'
|
||||||
import { interfaces } from './interfaces'
|
import { interfaces } from './interfaces'
|
||||||
|
import { getConfigLoader } from './config'
|
||||||
|
|
||||||
@injectable()
|
@provideSingleton(plugin.PluginManager)
|
||||||
export class PluginManagerImpl implements plugin.PluginManager {
|
export class PluginManagerImpl implements plugin.PluginManager {
|
||||||
|
@inject(ContainerInstance)
|
||||||
|
private container: Container
|
||||||
@inject(plugin.PluginInstance)
|
@inject(plugin.PluginInstance)
|
||||||
private pluginInstance: any
|
private pluginInstance: any
|
||||||
|
@inject(plugin.PluginFolder)
|
||||||
|
private pluginFolder: string;
|
||||||
@inject(server.ServerType)
|
@inject(server.ServerType)
|
||||||
private serverType: string
|
private serverType: string
|
||||||
@inject(server.Console)
|
|
||||||
private Console: MiaoScriptConsole
|
|
||||||
@inject(command.Command)
|
@inject(command.Command)
|
||||||
private CommandManager: command.Command
|
private CommandManager: command.Command
|
||||||
@inject(event.Event)
|
@inject(event.Event)
|
||||||
@@ -21,12 +25,12 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
|||||||
private pluginMap: Map<string, interfaces.Plugin>
|
private pluginMap: Map<string, interfaces.Plugin>
|
||||||
|
|
||||||
@postConstruct()
|
@postConstruct()
|
||||||
init() {
|
initialize() {
|
||||||
if (this.pluginInstance !== null) {
|
if (this.pluginInstance !== null) {
|
||||||
// 如果plugin不等于null 则代表是正式环境
|
// 如果plugin不等于null 则代表是正式环境
|
||||||
console.info(`Initialization MiaoScript Plugin System: ${this.pluginInstance} ...`)
|
console.i18n('ms.plugin.initialize', { plugin: this.pluginInstance })
|
||||||
this.pluginMap = new Map()
|
this.pluginMap = new Map()
|
||||||
console.info(`${this.EventManager.mapEventName().toFixed(0)} ${this.serverType} Event Mapping Complate...`)
|
console.i18n('ms.plugin.event.map', { count: this.EventManager.mapEventName().toFixed(0), type: this.serverType });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -34,25 +38,32 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
|||||||
var plugin = fs.file(root, folder)
|
var plugin = fs.file(root, folder)
|
||||||
var files = []
|
var files = []
|
||||||
// load common plugin
|
// load common plugin
|
||||||
.concat(this.scanFloder(plugin))
|
.concat(this.scanFolder(plugin))
|
||||||
// load space plugin
|
// load space plugin
|
||||||
.concat(this.scanFloder(fs.file(plugin, this.serverType)))
|
.concat(this.scanFolder(fs.file(plugin, this.serverType)))
|
||||||
this.loadPlugins(files)
|
this.loadPlugins(files)
|
||||||
}
|
}
|
||||||
|
|
||||||
build(container: Container): void {
|
build(): void {
|
||||||
this.buildPlugins(container)
|
this.buildPlugins()
|
||||||
|
}
|
||||||
|
|
||||||
|
private logStage(plugin: interfaces.Plugin, stage: string) {
|
||||||
|
console.i18n("ms.plugin.manager.stage", { stage, plugin: plugin.description.name, version: plugin.description.version, author: plugin.description.author })
|
||||||
}
|
}
|
||||||
|
|
||||||
load(...args: any[]): void {
|
load(...args: any[]): void {
|
||||||
this.checkAndGet(args[0]).forEach(pl => {
|
this.checkAndGet(args[0]).forEach((plugin: interfaces.Plugin) => {
|
||||||
this.runCatch(pl, 'load')
|
this.logStage(plugin, i18n.translate("ms.plugin.manager.stage.load"))
|
||||||
this.runCatch(pl, `${this.serverType}load`)
|
this.loadConfig(plugin)
|
||||||
|
this.runCatch(plugin, 'load')
|
||||||
|
this.runCatch(plugin, `${this.serverType}load`)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
enable(...args: any[]): void {
|
enable(...args: any[]): void {
|
||||||
this.checkAndGet(args[0]).forEach(plugin => {
|
this.checkAndGet(args[0]).forEach((plugin: interfaces.Plugin) => {
|
||||||
|
this.logStage(plugin, i18n.translate("ms.plugin.manager.stage.enable"))
|
||||||
this.runCatch(plugin, 'enable')
|
this.runCatch(plugin, 'enable')
|
||||||
this.runCatch(plugin, `${this.serverType}enable`)
|
this.runCatch(plugin, `${this.serverType}enable`)
|
||||||
this.registryCommand(plugin)
|
this.registryCommand(plugin)
|
||||||
@@ -61,11 +72,12 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
disable(...args: any[]): void {
|
disable(...args: any[]): void {
|
||||||
this.checkAndGet(args[0]).forEach(pl => {
|
this.checkAndGet(args[0]).forEach((plugin: interfaces.Plugin) => {
|
||||||
this.runCatch(pl, 'disable')
|
this.logStage(plugin, i18n.translate("ms.plugin.manager.stage.disable"))
|
||||||
this.runCatch(pl, `${this.serverType}disable`)
|
this.runCatch(plugin, 'disable')
|
||||||
this.unregistryCommand(pl)
|
this.runCatch(plugin, `${this.serverType}disable`)
|
||||||
this.unregistryListener(pl)
|
this.unregistryCommand(plugin)
|
||||||
|
this.unregistryListener(plugin)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -87,7 +99,7 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
|||||||
try {
|
try {
|
||||||
if (pl[func]) pl[func].call(pl)
|
if (pl[func]) pl[func].call(pl)
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
console.console(`§6插件 §b${pl.description.name} §6执行 §d${func} §6方法时发生错误 §4${ex}`)
|
console.console(`§6Plugin §b${pl.description.name} §6exec §d${func} §6function error §4${ex}`)
|
||||||
console.ex(ex)
|
console.ex(ex)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -99,11 +111,12 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
|||||||
throw new Error(`Plugin ${JSON.stringify(name)} not exist!`)
|
throw new Error(`Plugin ${JSON.stringify(name)} not exist!`)
|
||||||
}
|
}
|
||||||
|
|
||||||
private scanFloder(plugin: any): string[] {
|
private scanFolder(folder: any): string[] {
|
||||||
var files = []
|
var files = []
|
||||||
console.info(`Scanning Plugins in ${plugin} ...`)
|
console.i18n('ms.plugin.manager.scan', { folder })
|
||||||
this.checkUpdateFolder(plugin)
|
this.checkUpdateFolder(folder)
|
||||||
fs.list(plugin).forEach((file: any) => files.push(file.toFile()))
|
// must check file is exist maybe is a illegal symbolic link file
|
||||||
|
fs.list(folder).forEach((file: any) => file.toFile().exists() ? files.push(file.toFile()) : void 0)
|
||||||
return files
|
return files
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -111,7 +124,7 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
|||||||
* 更新插件
|
* 更新插件
|
||||||
* @param path
|
* @param path
|
||||||
*/
|
*/
|
||||||
private checkUpdateFolder(path) {
|
private checkUpdateFolder(path: any) {
|
||||||
var update = fs.file(path, "update")
|
var update = fs.file(path, "update")
|
||||||
if (!update.exists()) {
|
if (!update.exists()) {
|
||||||
update.mkdirs()
|
update.mkdirs()
|
||||||
@@ -134,7 +147,7 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
|||||||
this.updatePlugin(file)
|
this.updatePlugin(file)
|
||||||
this.createPlugin(file)
|
this.createPlugin(file)
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
console.console(`§6插件 §b${file.name} §6初始化时发生错误 §4${ex.message}`)
|
console.i18n("ms.plugin.manager.initialize.error", { name: file.name, ex })
|
||||||
console.ex(ex)
|
console.ex(ex)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -142,68 +155,85 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
|||||||
private updatePlugin(file: any) {
|
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()) {
|
if (update.exists()) {
|
||||||
console.info(`Auto Update Plugin ${file.name} ...`)
|
console.i18n("ms.plugin.manager.build.update", { name: file.name })
|
||||||
fs.move(update, file, true)
|
fs.move(update, file, true)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private createPlugin(file) {
|
private checkServers(servers: string[]) {
|
||||||
//@ts-ignore
|
if (!servers) { return true }
|
||||||
require(file, {
|
if (servers.indexOf(`!${this.serverType}`) != -1) { return false }
|
||||||
cache: false
|
return servers?.indexOf(this.serverType) != -1
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private buildPlugins(container: Container) {
|
private createPlugin(file: string) {
|
||||||
|
//@ts-ignore
|
||||||
|
require(file, { cache: false })
|
||||||
|
}
|
||||||
|
|
||||||
|
private buildPlugins() {
|
||||||
let pluginMetadatas = getPluginMetadatas()
|
let pluginMetadatas = getPluginMetadatas()
|
||||||
pluginMetadatas.forEach(metadata => {
|
for (const [_, metadata] of pluginMetadatas) {
|
||||||
|
if (!this.checkServers(metadata.servers)) { continue }
|
||||||
this.buildPlugin(metadata)
|
this.buildPlugin(metadata)
|
||||||
})
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private buildPlugin(metadata: interfaces.PluginMetadata) {
|
private buildPlugin(metadata: interfaces.PluginMetadata) {
|
||||||
this.bindPlugin(metadata)
|
this.bindPlugin(metadata)
|
||||||
let pluginInstance = container.getNamed<interfaces.Plugin>(plugin.Plugin, metadata.name)
|
let pluginInstance = this.container.getNamed<interfaces.Plugin>(plugin.Plugin, metadata.name)
|
||||||
if (!(pluginInstance instanceof interfaces.Plugin)) {
|
if (!(pluginInstance instanceof interfaces.Plugin)) {
|
||||||
console.console(`§4found error plugin §b${metadata.source} §4it's not extends interfaces.Plugin, the plugin will be ignore!`)
|
console.i18n('ms.plugin.manager.build.not.extends', { source: metadata.source })
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
this.pluginMap.set(metadata.name, pluginInstance)
|
this.pluginMap.set(metadata.name, pluginInstance)
|
||||||
pluginInstance.description = metadata
|
|
||||||
// @ts-ignore
|
|
||||||
pluginInstance.logger = new this.Console(metadata.prefix || metadata.name)
|
|
||||||
return pluginInstance
|
return pluginInstance
|
||||||
}
|
}
|
||||||
|
|
||||||
private bindPlugin(metadata: interfaces.PluginMetadata) {
|
private bindPlugin(metadata: interfaces.PluginMetadata) {
|
||||||
try {
|
try {
|
||||||
let pluginInstance = container.getNamed<interfaces.Plugin>(plugin.Plugin, metadata.name)
|
let pluginInstance = this.container.getNamed<interfaces.Plugin>(plugin.Plugin, metadata.name)
|
||||||
if (pluginInstance.description.source + '' !== metadata.source + '') {
|
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!`)
|
console.i18n('ms.plugin.manager.build.duplicate', { exists: pluginInstance.description.source, source: metadata.source })
|
||||||
}
|
}
|
||||||
container.rebind(plugin.Plugin).to(metadata.target).inSingletonScope().whenTargetNamed(metadata.name)
|
this.container.rebind(plugin.Plugin).to(metadata.target).inSingletonScope().whenTargetNamed(metadata.name)
|
||||||
} catch{
|
} catch{
|
||||||
container.bind(plugin.Plugin).to(metadata.target).inSingletonScope().whenTargetNamed(metadata.name)
|
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)
|
||||||
|
let configFactory = getConfigLoader(config.format);
|
||||||
|
if (!fs.exists(configFile)) {
|
||||||
|
base.save(configFile, configFactory.dump(plugin[config.variable]))
|
||||||
|
console.i18n("ms.plugin.manager.config.save.default", { plugin: plugin.description.name, name: config.name, format: config.format })
|
||||||
|
} else {
|
||||||
|
plugin[config.variable] = configFactory.load(base.read(configFile));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private registryCommand(pluginInstance: interfaces.Plugin) {
|
private registryCommand(pluginInstance: interfaces.Plugin) {
|
||||||
let cmds = getPluginCommandMetadata(pluginInstance)
|
let cmds = getPluginCommandMetadata(pluginInstance)
|
||||||
let tabs = getPluginTabCompleterMetadata(pluginInstance)
|
let tabs = getPluginTabCompleterMetadata(pluginInstance)
|
||||||
cmds.forEach(cmd => {
|
for (const [_, cmd] of cmds) {
|
||||||
let tab = tabs.get(cmd.name)
|
let tab = tabs.get(cmd.name)
|
||||||
|
if (!this.checkServers(cmd.servers)) { continue }
|
||||||
this.CommandManager.on(pluginInstance, cmd.name, {
|
this.CommandManager.on(pluginInstance, cmd.name, {
|
||||||
cmd: pluginInstance[cmd.executor].bind(pluginInstance),
|
cmd: pluginInstance[cmd.executor].bind(pluginInstance),
|
||||||
tab: tab ? pluginInstance[tab.executor].bind(pluginInstance) : undefined
|
tab: tab ? pluginInstance[tab.executor].bind(pluginInstance) : undefined
|
||||||
})
|
})
|
||||||
})
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private registryListener(pluginInstance: interfaces.Plugin) {
|
private registryListener(pluginInstance: interfaces.Plugin) {
|
||||||
let events = getPluginListenerMetadata(pluginInstance)
|
let events = getPluginListenerMetadata(pluginInstance)
|
||||||
for (const event of events) {
|
for (const event of events) {
|
||||||
// ignore space listener
|
// ignore space listener
|
||||||
if (event.servertype && event.servertype != this.serverType) { continue }
|
if (!this.checkServers(event.servers)) { continue }
|
||||||
// here must bind this to pluginInstance
|
// here must bind this to pluginInstance
|
||||||
this.EventManager.listen(pluginInstance, event.name, pluginInstance[event.executor].bind(pluginInstance))
|
this.EventManager.listen(pluginInstance, event.name, pluginInstance[event.executor].bind(pluginInstance))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -49,6 +49,14 @@ function getPluginListenerMetadata(target: any) {
|
|||||||
return listnerMetadata;
|
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 {
|
export {
|
||||||
getPlugin,
|
getPlugin,
|
||||||
getPlugins,
|
getPlugins,
|
||||||
@@ -57,4 +65,5 @@ export {
|
|||||||
getPluginCommandMetadata,
|
getPluginCommandMetadata,
|
||||||
getPluginTabCompleterMetadata,
|
getPluginTabCompleterMetadata,
|
||||||
getPluginListenerMetadata,
|
getPluginListenerMetadata,
|
||||||
|
getPluginConfigMetadata
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"private": true,
|
"private": true,
|
||||||
"name": "@ms/plugins",
|
"name": "@ms/plugins",
|
||||||
"version": "0.1.1",
|
"version": "0.3.0",
|
||||||
"description": "MiaoScript plugins package",
|
"description": "MiaoScript plugins package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -18,17 +18,18 @@
|
|||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"clean": "rimraf dist",
|
"clean": "rimraf dist",
|
||||||
"watch": "npx tsc --watch",
|
"watch": "tsc --watch",
|
||||||
"build": "yarn clean && npx tsc",
|
"build": "yarn clean && tsc",
|
||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.0",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.6.2"
|
"typescript": "^3.8.2"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ms/plugin": "^0.1.1",
|
"@ms/plugin": "^0.3.0",
|
||||||
|
"axios": "^0.19.2",
|
||||||
"es6-map": "^0.1.5",
|
"es6-map": "^0.1.5",
|
||||||
"inversify": "^5.0.1"
|
"inversify": "^5.0.1"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,6 +10,7 @@
|
|||||||
<!-- QQ应用模式 -->
|
<!-- QQ应用模式 -->
|
||||||
<meta name="x5-page-mode" content="app">
|
<meta name="x5-page-mode" content="app">
|
||||||
<title>MiaoConsole 调试工具</title>
|
<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/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/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/bootstrap@3.4.1/dist/js/bootstrap.min.js"></script>
|
||||||
@@ -40,6 +41,7 @@
|
|||||||
|
|
||||||
<script src="js/message.js"></script>
|
<script src="js/message.js"></script>
|
||||||
<script src="js/term.js"></script>
|
<script src="js/term.js"></script>
|
||||||
|
<script src="js/websocket.js"></script>
|
||||||
<script src="js/main.js"></script>
|
<script src="js/main.js"></script>
|
||||||
<script src="js/editor.js"></script>
|
<script src="js/editor.js"></script>
|
||||||
</head>
|
</head>
|
||||||
@@ -58,12 +60,16 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="progress progress-striped active" :visible='@classes.total != @classes.loaded'>
|
<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"
|
<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': '30em'}">
|
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>
|
<span>正在加载 {{@type}} 类型定义 {{@classes.loaded}}/{{@classes.total}}({{~~(@classes.loaded/@classes.total*100)|percent}}%) </span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="panel panel-info" :visible='@classes.total == @classes.loaded'>
|
<div class="panel panel-info" :visible='@classes.total == @classes.loaded && @classes.total != 0'>
|
||||||
<div class="panel-heading">代码编辑器</div>
|
<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 id="editor" style="height: 450px; width:100%;"></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,42 +1,43 @@
|
|||||||
let editor
|
let editor
|
||||||
let codeStorageKey = "MiaoScript:code";
|
|
||||||
|
|
||||||
let monaco_path = 'https://cdn.jsdelivr.net/npm/monaco-editor@0.18.1/min'
|
let monaco_path = 'https://cdn.jsdelivr.net/npm/monaco-editor@0.18.1/min'
|
||||||
require.config({ paths: { 'vs': monaco_path + '/vs' } });
|
require.config({ paths: { 'vs': monaco_path + '/vs' } });
|
||||||
window.MonacoEnvironment = { getWorkerUrl: () => proxy };
|
window.MonacoEnvironment = { getWorkerUrl: () => proxy };
|
||||||
let proxy = URL.createObjectURL(new Blob([`
|
let proxy = URL.createObjectURL(new Blob([`self.MonacoEnvironment = {baseUrl: '${monaco_path}/'};
|
||||||
self.MonacoEnvironment = {
|
importScripts('${monaco_path}/vs/base/worker/workerMain.js');`], { type: 'text/javascript' }));
|
||||||
baseUrl: '${monaco_path}/'
|
|
||||||
};
|
|
||||||
importScripts('${monaco_path}/vs/base/worker/workerMain.js');
|
|
||||||
`], { type: 'text/javascript' }));
|
|
||||||
|
|
||||||
require(["vs/editor/editor.main"], function() {
|
function loadExtraLibs(ts_d_src, filter) {
|
||||||
if (main.type !== 'unknow') {
|
let count = 0;
|
||||||
let ts_d_src = `https://cdn.jsdelivr.net/gh/circlecloud/ms@master/packages/${main.type}/src/typings`
|
axios.get(`${ts_d_src}/index.d.ts`).then(async result => {
|
||||||
$.get(`${ts_d_src}/index.ts`, (res) => {
|
monaco.languages.typescript.javascriptDefaults.addExtraLib(result.data, 'file:///src/typings/index.d.ts')
|
||||||
monaco.languages.typescript.javascriptDefaults.addExtraLib(res, 'file:///src/typings/index.ts')
|
let classes = result.data.split('\n').map(line => line.match(/.*\.\/(.*)".*/)).filter(line => line).map(dts => dts[1])
|
||||||
let classes = res.split('\n').map(line => line.match(/.*\.\/(.*)".*/)).filter(line => line).map(dts => dts[1])
|
if (filter) {
|
||||||
main.classes.total = classes.length
|
classes = classes.filter(line => filter(line))
|
||||||
main.classes.loaded = 0
|
}
|
||||||
classes.forEach(fname => {
|
main.classes.total += classes.length
|
||||||
$.get(`${ts_d_src}/${fname}`, content => {
|
for (let fname of classes) {
|
||||||
monaco.languages.typescript.javascriptDefaults.addExtraLib(content, `file:///src/typings/${fname}`)
|
if (count++ % 50 == 0) { await axios.get(`${ts_d_src}/${fname}`) }
|
||||||
main.classes.loaded++
|
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'), {
|
editor = monaco.editor.create(document.getElementById('editor'), {
|
||||||
value: window.localStorage.getItem(codeStorageKey) || 'org.bukkit.Bukkit.server.version',
|
value: '',
|
||||||
language: 'javascript',
|
language: 'javascript',
|
||||||
automaticLayout: true,
|
automaticLayout: true,
|
||||||
scrollBeyondLastLine: false,
|
scrollBeyondLastLine: false,
|
||||||
theme: 'vs-dark'
|
theme: 'vs-dark'
|
||||||
});
|
});
|
||||||
|
main.load(editor)
|
||||||
editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KEY_S, function() {
|
editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KEY_S, function() {
|
||||||
window.localStorage.setItem(codeStorageKey, editor.getValue())
|
main.save(editor)
|
||||||
showMessenger('代码保存成功!')
|
|
||||||
})
|
})
|
||||||
editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KEY_R, function() {
|
editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KEY_R, function() {
|
||||||
main.send('execCode', getSelectContent(editor) || editor.getValue())
|
main.send('execCode', getSelectContent(editor) || editor.getValue())
|
||||||
@@ -45,10 +46,24 @@ require(["vs/editor/editor.main"], function() {
|
|||||||
main.send('execCommand', getSelectContent(editor))
|
main.send('execCommand', getSelectContent(editor))
|
||||||
})
|
})
|
||||||
editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KEY_Q, function() {
|
editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KEY_Q, function() {
|
||||||
console.log('switch')
|
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) {
|
function getSelectContent(editor) {
|
||||||
let selInfo = editor.getSelection();
|
let selInfo = editor.getSelection();
|
||||||
return editor.getModel().getLineContent(selInfo.startLineNumber).substr(selInfo.startColumn - 1, selInfo.endColumn - selInfo.startColumn);
|
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
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,13 +1,15 @@
|
|||||||
var ws
|
|
||||||
var SPLIT_LINE = '\\M\\W\\S|T|S|S/L/T/'
|
var SPLIT_LINE = '\\M\\W\\S|T|S|S/L/T/'
|
||||||
let serverKey = 'MiaoScript:server'
|
let serverKey = 'MiaoScript:server'
|
||||||
|
let codeStorageKey = "MiaoScript:code:"
|
||||||
var main = avalon.define({
|
var main = avalon.define({
|
||||||
$id: 'main',
|
$id: 'main',
|
||||||
server: window.localStorage.getItem(serverKey) || location.host,
|
server: window.localStorage.getItem(serverKey) || location.host,
|
||||||
type: 'unknow',
|
type: 'unknow',
|
||||||
logs: '',
|
logs: '',
|
||||||
|
codes: ["default", "bukkit", "sponge", "bungee", "common", "test", "dev", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
|
||||||
|
code: 'default',
|
||||||
classes: {
|
classes: {
|
||||||
total: 1,
|
total: 0,
|
||||||
loaded: 0,
|
loaded: 0,
|
||||||
},
|
},
|
||||||
precent: () => {
|
precent: () => {
|
||||||
@@ -24,39 +26,30 @@ var main = avalon.define({
|
|||||||
if (event.key !== "Enter") {
|
if (event.key !== "Enter") {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (ws && ws.readyState == 1) {
|
connectWebSocket()
|
||||||
ws.close()
|
|
||||||
}
|
|
||||||
window.localStorage.setItem(serverKey, main.server)
|
|
||||||
ws = new WebSocket(`${location.protocol == 'http:' ? 'ws' : 'wss'}://${main.server}/ws`)
|
|
||||||
ws.onmessage = (event) => {
|
|
||||||
const [type, obj] = event.data.split(SPLIT_LINE)
|
|
||||||
switch (type) {
|
|
||||||
case "log":
|
|
||||||
main.log(obj)
|
|
||||||
break;
|
|
||||||
case "type":
|
|
||||||
main.type = obj;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ws.onopen = () => {
|
|
||||||
main.send("execDetect", "type");
|
|
||||||
}
|
|
||||||
ws.onclose = (ev) => {
|
|
||||||
main.log(`Remote Server Close Connection... ${ev.code}`)
|
|
||||||
if (ev.code == 1006) {
|
|
||||||
setTimeout(() => {
|
|
||||||
main.connect()
|
|
||||||
}, 1000)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
init: () => {
|
init: () => {
|
||||||
if (main.server) {
|
if (main.server) {
|
||||||
main.connect()
|
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()
|
main.init()
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
var ws;
|
||||||
|
function connectWebSocket() {
|
||||||
|
if (ws && ws.readyState == 1) {
|
||||||
|
ws.close()
|
||||||
|
}
|
||||||
|
window.localStorage.setItem(serverKey, main.server)
|
||||||
|
ws = new WebSocket(`${location.protocol == 'http:' ? 'ws' : 'wss'}://${main.server}/ws`)
|
||||||
|
ws.onmessage = (event) => {
|
||||||
|
const [type, obj] = event.data.split(SPLIT_LINE)
|
||||||
|
switch (type) {
|
||||||
|
case "log":
|
||||||
|
main.log(obj)
|
||||||
|
break;
|
||||||
|
case "type":
|
||||||
|
main.type = obj;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ws.onopen = () => {
|
||||||
|
main.send("execDetect", "type");
|
||||||
|
}
|
||||||
|
ws.onclose = (ev) => {
|
||||||
|
main.log(`Remote Server Close Connection... ${ev.code}`)
|
||||||
|
if (ev.code == 1006) {
|
||||||
|
setTimeout(() => {
|
||||||
|
main.connect()
|
||||||
|
}, 1000)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,15 +1,25 @@
|
|||||||
|
/// <reference types="@ms/types/dist/typings/bukkit" />
|
||||||
|
/// <reference types="@ms/types/dist/typings/sponge" />
|
||||||
|
/// <reference types="@ms/types/dist/typings/bungee" />
|
||||||
|
/// <reference types="@ms/types/dist/typings/nukkit" />
|
||||||
|
|
||||||
|
import { server } from '@ms/api';
|
||||||
|
import { inject } from '@ms/container';
|
||||||
import { plugin, interfaces, cmd, listener, tab } from '@ms/plugin'
|
import { plugin, interfaces, cmd, listener, tab } from '@ms/plugin'
|
||||||
|
|
||||||
@plugin({ name: 'HelloWorld', version: '1.0.0', author: 'MiaoWoo', source: __filename })
|
@plugin({ name: 'HelloWorld', version: '1.0.0', author: 'MiaoWoo', source: __filename })
|
||||||
export class HelloWorld extends interfaces.Plugin {
|
export class HelloWorld extends interfaces.Plugin {
|
||||||
|
@inject(server.Server)
|
||||||
|
private Server: server.Server
|
||||||
|
|
||||||
load() {
|
load() {
|
||||||
this.logger.log('Test Plugin load from MiaoScript Plugin System...');
|
this.logger.log('Plugin load from MiaoScript Plugin System...');
|
||||||
}
|
}
|
||||||
enable() {
|
enable() {
|
||||||
this.logger.log('Test Plugin enable from MiaoScript Plugin System...');
|
this.logger.log('Plugin enable from MiaoScript Plugin System...');
|
||||||
}
|
}
|
||||||
disable() {
|
disable() {
|
||||||
this.logger.log('Test Plugin disable from MiaoScript Plugin System...');
|
this.logger.log('Plugin disable from MiaoScript Plugin System...');
|
||||||
}
|
}
|
||||||
|
|
||||||
bukkitload() {
|
bukkitload() {
|
||||||
@@ -32,6 +42,16 @@ export class HelloWorld extends interfaces.Plugin {
|
|||||||
this.logger.log('Disable When ServerType is Sponge!')
|
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()
|
@cmd()
|
||||||
hello(sender: any, command: string, args: string[]) {
|
hello(sender: any, command: string, args: string[]) {
|
||||||
this.logger.log(sender, command, args);
|
this.logger.log(sender, command, args);
|
||||||
@@ -43,15 +63,28 @@ export class HelloWorld extends interfaces.Plugin {
|
|||||||
return ['world']
|
return ['world']
|
||||||
}
|
}
|
||||||
|
|
||||||
@listener({ servertype: 'bukkit' })
|
@listener({ servers: ['bukkit', 'nukkit'] })
|
||||||
playerjoin(event: any) {
|
PlayerJoin(event: org.bukkit.event.player.PlayerJoinEvent) {
|
||||||
this.logger.console(`§aBukkit PlayerJoinEvent: §b${event.player.name}`)
|
let plyaer = event.getPlayer();
|
||||||
setTimeout(() => this.logger.sender(event.player, `§a欢迎来到 §bMiaoScript §a的世界!`), 10);
|
this.logger.console(`§cBukkit §aPlayerJoinEvent: §b${plyaer.getName()}`)
|
||||||
|
setTimeout(() => this.sendWelcome(plyaer), 10);
|
||||||
}
|
}
|
||||||
|
|
||||||
@listener({ servertype: 'sponge' })
|
@listener({ servers: ['sponge'] })
|
||||||
clientconnectionevent$join(event: any) {
|
ClientConnectionEvent$Join(event: org.spongepowered.api.event.network.ClientConnectionEvent.Join) {
|
||||||
this.logger.console(`§aSponge ClientConnectionEvent.Join: §b${event.targetEntity.name}`)
|
this.logger.console(`§cSponge §aClientConnectionEvent.Join: §b${event.getTargetEntity().getName()}`)
|
||||||
setTimeout(() => this.logger.sender(event.targetEntity, `§a欢迎来到 §bMiaoScript §a的世界!`), 10);
|
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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
356
packages/plugins/src/MiaoChat.ts
Normal file
356
packages/plugins/src/MiaoChat.ts
Normal file
@@ -0,0 +1,356 @@
|
|||||||
|
/// <reference types="@ms/types/dist/typings/bukkit" />
|
||||||
|
/// <reference types="@ms/types/dist/typings/sponge" />
|
||||||
|
/// <reference types="@ms/types/dist/typings/bungee" />
|
||||||
|
|
||||||
|
import { server, plugin as pluginApi, channel } from '@ms/api'
|
||||||
|
import { inject } from '@ms/container';
|
||||||
|
import { plugin, interfaces, cmd, listener, tab, config } from '@ms/plugin'
|
||||||
|
import Tellraw from '@ms/common/dist/tellraw'
|
||||||
|
|
||||||
|
const ByteArrayInputStream = Java.type("java.io.ByteArrayInputStream");
|
||||||
|
const ByteArrayOutputStream = Java.type("java.io.ByteArrayOutputStream");
|
||||||
|
const StandardCharsets = Java.type("java.nio.charset.StandardCharsets");
|
||||||
|
const GZIPInputStream = Java.type("java.util.zip.GZIPInputStream");
|
||||||
|
const GZIPOutputStream = Java.type("java.util.zip.GZIPOutputStream");
|
||||||
|
const Consumer = Java.type("java.util.function.Consumer");
|
||||||
|
const ByteArray = Java.type("byte[]")
|
||||||
|
|
||||||
|
const BiConsumer = Java.type('java.util.function.BiConsumer')
|
||||||
|
|
||||||
|
class MiaoMessage {
|
||||||
|
// public static final String CHANNEL = "MiaoChat:Default".toLowerCase();
|
||||||
|
public static CHANNEL: string = "MiaoChat:Default".toLowerCase()
|
||||||
|
// private static final int MAX_MESSAGE_LENGTH = 32000;
|
||||||
|
private static MAX_MESSAGE_LENGTH = 32000;
|
||||||
|
|
||||||
|
private static copy(input, output) {
|
||||||
|
let buffer = new ByteArray(1024);
|
||||||
|
let n: number;
|
||||||
|
while ((n = input.read(buffer)) != -1) {
|
||||||
|
output.write(buffer, 0, n);
|
||||||
|
}
|
||||||
|
input.close();
|
||||||
|
output.close();
|
||||||
|
}
|
||||||
|
public static encode(input: any): any {
|
||||||
|
return new MiaoMessage(input).encode();
|
||||||
|
}
|
||||||
|
public static decode(input: any): MiaoMessage {
|
||||||
|
let baos = new ByteArrayOutputStream();
|
||||||
|
MiaoMessage.copy(new GZIPInputStream(new ByteArrayInputStream(input)), baos);
|
||||||
|
return new MiaoMessage(baos.toString(StandardCharsets.UTF_8.name()));
|
||||||
|
}
|
||||||
|
|
||||||
|
// private String json;
|
||||||
|
constructor(public json: any) { }
|
||||||
|
|
||||||
|
public encode(): any {
|
||||||
|
let baos = new ByteArrayOutputStream();
|
||||||
|
MiaoMessage.copy(new ByteArrayInputStream(this.json.getBytes(StandardCharsets.UTF_8)), new GZIPOutputStream(baos));
|
||||||
|
if (baos.size() > MiaoMessage.MAX_MESSAGE_LENGTH) { return null; }
|
||||||
|
return baos.toByteArray();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@plugin({ name: 'MiaoChat', version: '1.0.0', author: 'MiaoWoo', source: __filename })
|
||||||
|
export class MiaoChat extends interfaces.Plugin {
|
||||||
|
@inject(server.Server)
|
||||||
|
private Server: server.Server
|
||||||
|
@inject(server.ServerType)
|
||||||
|
private ServerType: string
|
||||||
|
@inject(channel.Channel)
|
||||||
|
private Channel: channel.Channel
|
||||||
|
|
||||||
|
@config()
|
||||||
|
private config = {
|
||||||
|
Version: "1.0.0",
|
||||||
|
BungeeCord: true,
|
||||||
|
Server: "生存服",
|
||||||
|
ChatFormats: {
|
||||||
|
default: {
|
||||||
|
index: 50,
|
||||||
|
permission: "MiaoChat.default",
|
||||||
|
range: 0,
|
||||||
|
format: "[world][player]: ",
|
||||||
|
item: true,
|
||||||
|
itemformat: "&6[&b%s&6]&r"
|
||||||
|
},
|
||||||
|
admin: {
|
||||||
|
index: 49,
|
||||||
|
permission: "MiaoChat.admin",
|
||||||
|
format: "[admin][world][player][help]: ",
|
||||||
|
range: 0,
|
||||||
|
item: true,
|
||||||
|
itemformat: "&6[&b%s&6]&r"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
StyleFormats: {
|
||||||
|
world: {
|
||||||
|
text: "&6[&a%player_world%&6]",
|
||||||
|
hover: [
|
||||||
|
"&6当前所在位置:",
|
||||||
|
"&6世界: &d%player_world%",
|
||||||
|
"&6坐标: &aX:%player_x% Y: %player_y% Z: %player_z%",
|
||||||
|
"",
|
||||||
|
"&c点击即可TP我!"
|
||||||
|
],
|
||||||
|
click: {
|
||||||
|
type: "COMMAND",
|
||||||
|
command: "/tpa %player_name%"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
player: {
|
||||||
|
text: "&b%player_name%",
|
||||||
|
hover: [
|
||||||
|
"&6玩家名称: &b%player_name%",
|
||||||
|
"&6玩家等级: &a%player_level%",
|
||||||
|
"&6玩家血量: &c%player_health%",
|
||||||
|
"&6玩家饥饿: &d%player_food_level%",
|
||||||
|
"&6游戏模式: &4%player_gamemode%",
|
||||||
|
"",
|
||||||
|
"&c点击与我聊天"
|
||||||
|
],
|
||||||
|
click: {
|
||||||
|
type: "SUGGEST",
|
||||||
|
command: "/tell %player_name%"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
admin: {
|
||||||
|
text: "&6[&c管理员&6]"
|
||||||
|
},
|
||||||
|
help: {
|
||||||
|
text: "&4[求助]",
|
||||||
|
hover: [
|
||||||
|
"点击求助OP"
|
||||||
|
],
|
||||||
|
click: {
|
||||||
|
type: "COMMAND",
|
||||||
|
command: "管理员@%player_name% 我需要你的帮助!"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private chatFormats: any[];
|
||||||
|
private styleFormats: any;
|
||||||
|
// 用于匹配 '[xx]' 聊天格式
|
||||||
|
private FORMAT_PATTERN = /[\[]([^\[\]]+)[\]]/ig;
|
||||||
|
|
||||||
|
private PlaceholderAPI: { setPlaceholders: (player: any, str: string) => string };
|
||||||
|
|
||||||
|
load() {
|
||||||
|
this.chatFormats = Object.values(this.config.ChatFormats);
|
||||||
|
this.chatFormats.sort(this.compare('index'));
|
||||||
|
this.initFormat(this.chatFormats);
|
||||||
|
this.styleFormats = this.config.StyleFormats;
|
||||||
|
}
|
||||||
|
|
||||||
|
private compare(prop: string) {
|
||||||
|
return function(obj1: { [x: string]: any; }, obj2: { [x: string]: any; }) {
|
||||||
|
var val1 = obj1[prop];
|
||||||
|
var val2 = obj2[prop];
|
||||||
|
if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
|
||||||
|
val1 = Number(val1);
|
||||||
|
val2 = Number(val2);
|
||||||
|
}
|
||||||
|
if (val1 < val2) {
|
||||||
|
return -1;
|
||||||
|
} else if (val1 > val2) {
|
||||||
|
return 1;
|
||||||
|
} else {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
enable() {
|
||||||
|
this.PlaceholderAPI = {
|
||||||
|
setPlaceholders: (player: any, string: string) => {
|
||||||
|
return string;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.Channel.listen(this, MiaoMessage.CHANNEL, (data) => {
|
||||||
|
this.sendChatAll(MiaoMessage.decode(data).json)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
disable() {
|
||||||
|
}
|
||||||
|
|
||||||
|
bukkitenable() {
|
||||||
|
// 尝试加载 Bukkit 的 PlaceholderAPI
|
||||||
|
try {
|
||||||
|
//@ts-ignore
|
||||||
|
this.PlaceholderAPI = base.getClass("me.clip.placeholderapi.PlaceholderAPI").static;
|
||||||
|
this.logger.log('[PAPI] Found Bukkit PlaceholderAPI Hooking...')
|
||||||
|
} catch (ex) {
|
||||||
|
this.logger.console("§cCan't found me.clip.placeholderapi.PlaceholderAPI variable will not be replaced! Err: " + ex)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bukkitdisable() {
|
||||||
|
}
|
||||||
|
|
||||||
|
spongeenable() {
|
||||||
|
// 尝试加载 Sponge 的 PlaceholderAPI
|
||||||
|
try {
|
||||||
|
var spongePapi = this.Server.getService('me.rojo8399.placeholderapi.PlaceholderService');
|
||||||
|
var s = org.spongepowered.api.text.serializer.TextSerializers.formattingCode('§');
|
||||||
|
if (spongePapi) {
|
||||||
|
this.PlaceholderAPI = {
|
||||||
|
setPlaceholders: (player: any, string: string) => {
|
||||||
|
return s.serialize(spongePapi.replacePlaceholders(string, player, player));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
this.logger.log('[PAPI] Found Sponge PlaceholderAPI Hooking...')
|
||||||
|
}
|
||||||
|
} catch (ex) {
|
||||||
|
this.logger.console("§cCan't found me.rojo8399.placeholderapi.PlaceholderService variable will not be replaced! Err: " + ex)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
spongedisable() {
|
||||||
|
}
|
||||||
|
|
||||||
|
bungeeenable() {
|
||||||
|
}
|
||||||
|
|
||||||
|
bungeedisable() {
|
||||||
|
}
|
||||||
|
|
||||||
|
@cmd({ servers: ["bungee"] })
|
||||||
|
mct(sender: any, command: string, args: string[]) {
|
||||||
|
this.logger.log(sender, command, args);
|
||||||
|
sender.sendMessage(JSON.stringify({ command, ...args }))
|
||||||
|
}
|
||||||
|
|
||||||
|
@cmd({ servers: ["!bungee"] })
|
||||||
|
mchat(sender: any, command: string, args: string[]) {
|
||||||
|
this.logger.log(sender, command, args);
|
||||||
|
sender.sendMessage(JSON.stringify({ command, ...args }))
|
||||||
|
}
|
||||||
|
|
||||||
|
@tab()
|
||||||
|
tabmchat(_sender: any, _command: string, _args: string[]) {
|
||||||
|
}
|
||||||
|
|
||||||
|
@listener({ servers: ['bukkit'] })
|
||||||
|
AsyncPlayerChatEvent(event: org.bukkit.event.player.AsyncPlayerChatEvent) {
|
||||||
|
this.sendChat(event.getPlayer(), event.getMessage(), function() {
|
||||||
|
event.setCancelled(true);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@listener({ servers: ['sponge'] })
|
||||||
|
MessageChannelEvent$Chat(event: org.spongepowered.api.event.message.MessageChannelEvent.Chat) {
|
||||||
|
//@ts-ignore
|
||||||
|
var player = event.getCause().first(org.spongepowered.api.entity.living.player.Player.class).orElse(null);
|
||||||
|
if (player == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
var plain = event.getRawMessage().toPlain();
|
||||||
|
if (plain.startsWith(Tellraw.duplicateChar)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.sendChat(player, plain, function() {
|
||||||
|
event.setMessageCancelled(true)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@listener({ servers: ['bungee'] })
|
||||||
|
PluginMessageEvent(e: any) {
|
||||||
|
let bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy()
|
||||||
|
let event = e as net.md_5.bungee.api.event.PluginMessageEvent
|
||||||
|
if (event.getTag() == MiaoMessage.CHANNEL) {
|
||||||
|
let origin = event.getSender().getAddress();
|
||||||
|
bungee.getServers().forEach(new BiConsumer({
|
||||||
|
accept: (s, server) => {
|
||||||
|
if (server.getAddress() != origin && server.getPlayers().size() > 0) {
|
||||||
|
server.sendData(event.getTag(), event.getData())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
initFormat(chatFormats: any[]) {
|
||||||
|
chatFormats.forEach(chatFormat => {
|
||||||
|
var chat_format_str = chatFormat.format;
|
||||||
|
var temp = [];
|
||||||
|
var r: any[];
|
||||||
|
while (r = this.FORMAT_PATTERN.exec(chat_format_str)) {
|
||||||
|
temp.push(r[1]);
|
||||||
|
}
|
||||||
|
var format_list = [];
|
||||||
|
temp.forEach(t => {
|
||||||
|
var arr = chat_format_str.split('[' + t + ']', 2);
|
||||||
|
if (arr[0]) {
|
||||||
|
format_list.push(arr[0]);
|
||||||
|
}
|
||||||
|
format_list.push(t);
|
||||||
|
chat_format_str = arr[1];
|
||||||
|
});
|
||||||
|
if (chat_format_str) {
|
||||||
|
format_list.push(chat_format_str);
|
||||||
|
}
|
||||||
|
chatFormat.format_list = format_list;
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
sendChat(player: any, plain: string, callback: { (): void; }) {
|
||||||
|
var chat_format = this.getChatFormat(player);
|
||||||
|
if (!chat_format) {
|
||||||
|
console.debug('未获得用户', player.getName(), '的 ChatRule 跳过执行...');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
callback();
|
||||||
|
var tr = Tellraw.create();
|
||||||
|
chat_format.format_list.forEach((format) => {
|
||||||
|
var style = this.styleFormats[format];
|
||||||
|
if (style) {
|
||||||
|
tr.then(this.replace(player, style.text));
|
||||||
|
if (style.hover) {
|
||||||
|
tr.tip(this.replace(player, style.hover.join('\n')));
|
||||||
|
}
|
||||||
|
if (style.click && style.click.type && style.click.command) {
|
||||||
|
var command = this.replace(player, style.click.command);
|
||||||
|
switch (style.click.type.toUpperCase()) {
|
||||||
|
case "COMMAND":
|
||||||
|
tr.command(command);
|
||||||
|
break;
|
||||||
|
case "OPENURL":
|
||||||
|
tr.link(command);
|
||||||
|
break;
|
||||||
|
case "SUGGEST":
|
||||||
|
tr.suggest(command);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
tr.then(this.replace(player, format));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let json = tr.then(this.replace(player, plain)).json()
|
||||||
|
this.sendChatAll(json)
|
||||||
|
this.Channel.send(player, MiaoMessage.CHANNEL, MiaoMessage.encode(json))
|
||||||
|
}
|
||||||
|
|
||||||
|
sendChatAll(json: string) {
|
||||||
|
this.Server.getOnlinePlayers().forEach(player => this.Server.sendJson(player, json))
|
||||||
|
}
|
||||||
|
|
||||||
|
getChatFormat(player: any) {
|
||||||
|
for (var i in this.chatFormats) {
|
||||||
|
var format = this.chatFormats[i];
|
||||||
|
if (player.hasPermission(format.permission)) {
|
||||||
|
return format;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
replace(player: any, target: string) {
|
||||||
|
return this.PlaceholderAPI.setPlaceholders(player, target)
|
||||||
|
}
|
||||||
|
}
|
||||||
242
packages/plugins/src/MiaoConsole.ts
Normal file
242
packages/plugins/src/MiaoConsole.ts
Normal file
@@ -0,0 +1,242 @@
|
|||||||
|
/// <reference types="@ms/types/dist/typings/bukkit" />
|
||||||
|
/// <reference types="@ms/types/dist/typings/sponge" />
|
||||||
|
/// <reference types="@ms/types/dist/typings/bungee" />
|
||||||
|
|
||||||
|
import { plugin as pluginApi, server, task } from '@ms/api'
|
||||||
|
import { plugin, interfaces, cmd } from '@ms/plugin'
|
||||||
|
import { inject, Container, ContainerInstance, postConstruct } from '@ms/container'
|
||||||
|
import * as reflect from '@ms/common/dist/reflect'
|
||||||
|
|
||||||
|
let clients: any[] = []
|
||||||
|
let SPLIT_LINE = '\\M\\W\\S|T|S|S/L/T/'
|
||||||
|
let MessageHandle = Symbol.for('MiaoConsole:MessageHandle')
|
||||||
|
const refList: Array<{ server: string, future: string }> = [
|
||||||
|
{ server: 'an', future: 'g' },//spigot 1.12.2
|
||||||
|
{ server: 'getServerConnection', future: 'f' },//after spigot 1.14.4
|
||||||
|
{ server: 'func_147137_ag', future: 'field_151274_e' }//catserver 1.12.2
|
||||||
|
]
|
||||||
|
|
||||||
|
@plugin({ name: 'MiaoConsole', version: '1.0.0', author: 'MiaoWoo', source: __filename })
|
||||||
|
export class MiaoConsole extends interfaces.Plugin {
|
||||||
|
public static GlobalContainer: Container
|
||||||
|
public static GlobalLogger: Console
|
||||||
|
|
||||||
|
@inject(ContainerInstance)
|
||||||
|
private container: Container
|
||||||
|
@inject(pluginApi.PluginManager)
|
||||||
|
private PluginManager: pluginApi.PluginManager
|
||||||
|
@inject(server.ServerType)
|
||||||
|
private ServerType: string
|
||||||
|
@inject(server.Server)
|
||||||
|
private Server: server.Server
|
||||||
|
@inject(task.TaskManager)
|
||||||
|
private Task: task.TaskManager
|
||||||
|
|
||||||
|
private pipeline: any
|
||||||
|
|
||||||
|
@cmd()
|
||||||
|
mconsole(sender: any, command: string, args: string[]) {
|
||||||
|
switch (args[0]) {
|
||||||
|
case "reload":
|
||||||
|
this.PluginManager.reload(this)
|
||||||
|
break
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
enable() {
|
||||||
|
MiaoConsole.GlobalLogger = this.logger
|
||||||
|
MiaoConsole.GlobalContainer = this.container
|
||||||
|
}
|
||||||
|
|
||||||
|
disable() {
|
||||||
|
if (this.pipeline) {
|
||||||
|
if (this.pipeline.names().contains('miao_detect')) {
|
||||||
|
this.pipeline.remove('miao_detect')
|
||||||
|
}
|
||||||
|
clients.forEach(c => c.close())
|
||||||
|
this.container.unbind(MessageHandle)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bukkitenable() {
|
||||||
|
let Bukkit = Java.type('org.bukkit.Bukkit')
|
||||||
|
let consoleServer = reflect.on(Bukkit.getServer()).get('console').get()
|
||||||
|
this.reflectChannel(this.reflectPromise(consoleServer))
|
||||||
|
this.injectMiaoDetect()
|
||||||
|
}
|
||||||
|
|
||||||
|
spongeenable() {
|
||||||
|
let Sponge = Java.type('org.spongepowered.api.Sponge')
|
||||||
|
let consoleServer = reflect.on(Sponge.getServer()).get()
|
||||||
|
this.reflectChannel(this.reflectPromise(consoleServer))
|
||||||
|
this.injectMiaoDetect()
|
||||||
|
}
|
||||||
|
|
||||||
|
bungeeenable() {
|
||||||
|
let wait = this.Task.create(() => {
|
||||||
|
try {
|
||||||
|
// @ts-ignore
|
||||||
|
this.pipeline = reflect.on(base.getInstance().getProxy()).get('listeners').get().toArray()[0].pipeline()
|
||||||
|
this.injectMiaoDetect()
|
||||||
|
wait.cancel();
|
||||||
|
} catch (ex) {
|
||||||
|
this.logger.warn('Wait BungeeCord start ready to get netty channel pipeline. Err: ' + ex)
|
||||||
|
}
|
||||||
|
}).later(300).timer(500).submit()
|
||||||
|
}
|
||||||
|
|
||||||
|
reflectPromise(consoleServer) {
|
||||||
|
for (const ref of refList) {
|
||||||
|
try { return reflect.on(consoleServer).call(ref.server).get(ref.future).get().get(0) } catch (error) { }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
reflectChannel(promise) {
|
||||||
|
if (!promise) { throw Error(`Can't found ServerConnection or ChannelFuture !`) }
|
||||||
|
this.pipeline = reflect.on(promise).get('channel').get().pipeline()
|
||||||
|
}
|
||||||
|
|
||||||
|
injectMiaoDetect() {
|
||||||
|
this.pipeline.addFirst('miao_detect', new MiaoDetectHandler())
|
||||||
|
this.container.bind(MessageHandle).toFunction(this.onmessage.bind(this))
|
||||||
|
this.logger.info('Netty Channel Pipeline Inject MiaoDetectHandler Successful!')
|
||||||
|
}
|
||||||
|
|
||||||
|
onmessage(ctx: any, msg: any) {
|
||||||
|
let text: string = msg.text()
|
||||||
|
const [type, content] = text.split(SPLIT_LINE)
|
||||||
|
try {
|
||||||
|
var result = this[type](ctx, content)
|
||||||
|
} catch (ex) {
|
||||||
|
var result = '§4代码执行异常\n' + console.stack(ex).join('\n')
|
||||||
|
}
|
||||||
|
result && this.sendResult(ctx, "log", result)
|
||||||
|
}
|
||||||
|
|
||||||
|
execCommand(ctx: any, cmd: string) {
|
||||||
|
setTimeout(() => this.Server.dispatchConsoleCommand(cmd), 0)
|
||||||
|
return `§6命令: §b${cmd} §a执行成功!`
|
||||||
|
}
|
||||||
|
|
||||||
|
execCode(ctx: any, code: string) {
|
||||||
|
return this.Task.callSyncMethod(() => eval(code)) + '';
|
||||||
|
}
|
||||||
|
|
||||||
|
execDetect(ctx: any, cmd: string) {
|
||||||
|
switch (cmd) {
|
||||||
|
case "type":
|
||||||
|
this.sendResult(ctx, "type", this.ServerType)
|
||||||
|
return `Currect Server Version is ${this.Server.getVersion()}`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sendResult(ctx: any, type: string, msg: string) {
|
||||||
|
ctx.writeAndFlush(new TextWebSocketFrame(`${type}${SPLIT_LINE}${msg}`))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const ChannelInboundHandlerAdapter = Java.type('io.netty.channel.ChannelInboundHandlerAdapter')
|
||||||
|
const CharsetUtil = Java.type('io.netty.util.CharsetUtil')
|
||||||
|
const TextWebSocketFrame = Java.type('io.netty.handler.codec.http.websocketx.TextWebSocketFrame')
|
||||||
|
const MiaoDetectHandler = Java.extend(ChannelInboundHandlerAdapter, {
|
||||||
|
channelRead: (ctx: any, channel: any) => {
|
||||||
|
channel.pipeline().addFirst('miaowebsocket', new WebSocketHandler())
|
||||||
|
ctx.fireChannelRead(channel)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
const TypeParameterMatcher = Java.type('io.netty.util.internal.TypeParameterMatcher')
|
||||||
|
const DefaultHttpResponse = Java.type('io.netty.handler.codec.http.DefaultHttpResponse')
|
||||||
|
const DefaultFullHttpResponse = Java.type('io.netty.handler.codec.http.DefaultFullHttpResponse')
|
||||||
|
const HttpHeaders = Java.type('io.netty.handler.codec.http.HttpHeaders')
|
||||||
|
const HttpVersion = Java.type('io.netty.handler.codec.http.HttpVersion')
|
||||||
|
const HttpResponseStatus = Java.type('io.netty.handler.codec.http.HttpResponseStatus')
|
||||||
|
const LastHttpContent = Java.type('io.netty.handler.codec.http.LastHttpContent')
|
||||||
|
const HttpServerCodec = Java.type('io.netty.handler.codec.http.HttpServerCodec')
|
||||||
|
const ChunkedWriteHandler = Java.type('io.netty.handler.stream.ChunkedWriteHandler')
|
||||||
|
const HttpObjectAggregator = Java.type('io.netty.handler.codec.http.HttpObjectAggregator')
|
||||||
|
const WebSocketServerProtocolHandler = Java.type('io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler')
|
||||||
|
const SimpleChannelInboundHandler = Java.type('io.netty.channel.SimpleChannelInboundHandler')
|
||||||
|
const FullHttpRequestMatcher = TypeParameterMatcher.get(base.getClass('io.netty.handler.codec.http.FullHttpRequest'))
|
||||||
|
const File = Java.type('java.io.File')
|
||||||
|
const Runnable = Java.type('java.lang.Runnable')
|
||||||
|
const RandomAccessFile = Java.type('java.io.RandomAccessFile')
|
||||||
|
const DefaultFileRegion = Java.type('io.netty.channel.DefaultFileRegion')
|
||||||
|
const ChannelFutureListener = Java.type('io.netty.channel.ChannelFutureListener')
|
||||||
|
const HttpRequestHandler = Java.extend(SimpleChannelInboundHandler, {
|
||||||
|
acceptInboundMessage: (msg: any) => {
|
||||||
|
return FullHttpRequestMatcher.match(msg)
|
||||||
|
},
|
||||||
|
channelRead0: (ctx: any, request: any) => {
|
||||||
|
if ('/ws' == request.getUri()) {
|
||||||
|
ctx.fireChannelRead(request.retain())
|
||||||
|
} else {
|
||||||
|
ctx.executor().execute(new Runnable({
|
||||||
|
run: () => {
|
||||||
|
if (HttpHeaders.is100ContinueExpected(request)) {
|
||||||
|
ctx.writeAndFlush(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE))
|
||||||
|
}
|
||||||
|
let filename = request.getUri().split('?')[0].substr(1)
|
||||||
|
let file = new File('/home/project/WebWorkSpace/MiaoConsole', filename || 'index.html')
|
||||||
|
if (!file.exists() || !file.isFile()) {
|
||||||
|
ctx.write(new DefaultHttpResponse(request.getProtocolVersion(), HttpResponseStatus.NOT_FOUND))
|
||||||
|
ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT).addListener(ChannelFutureListener.CLOSE)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
let response = new DefaultHttpResponse(request.getProtocolVersion(), HttpResponseStatus.OK)
|
||||||
|
response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/html charset=UTF-8")
|
||||||
|
let raf = new RandomAccessFile(file, 'r')
|
||||||
|
let keepAlive = HttpHeaders.isKeepAlive(request)
|
||||||
|
if (keepAlive) {
|
||||||
|
response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, file.length())
|
||||||
|
response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE)
|
||||||
|
}
|
||||||
|
ctx.write(response)
|
||||||
|
ctx.write(new DefaultFileRegion(raf.getChannel(), 0, raf.length()))
|
||||||
|
let future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT)
|
||||||
|
if (!keepAlive) {
|
||||||
|
future.addListener(ChannelFutureListener.CLOSE)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
const TextWebSocketFrameMatcher = TypeParameterMatcher.get(base.getClass('io.netty.handler.codec.http.websocketx.TextWebSocketFrame'))
|
||||||
|
const TextWebSocketFrameHandler = Java.extend(SimpleChannelInboundHandler, {
|
||||||
|
userEventTriggered: (ctx: any, evt: any) => {
|
||||||
|
if (evt == 'HANDSHAKE_COMPLETE') {
|
||||||
|
clients.push(ctx.channel())
|
||||||
|
MiaoConsole.GlobalLogger.console(`new client §b${ctx.channel().id()} §aconnected...`)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
acceptInboundMessage: (msg: any) => {
|
||||||
|
return TextWebSocketFrameMatcher.match(msg)
|
||||||
|
},
|
||||||
|
channelRead0: (ctx: any, msg: any) => {
|
||||||
|
MiaoConsole.GlobalContainer.get<any>(MessageHandle)(ctx, msg)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
const WebSocketHandler = Java.extend(ChannelInboundHandlerAdapter, {
|
||||||
|
channelRead: function(ctx: any, msg: any) {
|
||||||
|
msg.markReaderIndex()
|
||||||
|
let message: string = msg.toString(CharsetUtil.UTF_8)
|
||||||
|
let channel = ctx.channel()
|
||||||
|
let pipeline = channel.pipeline()
|
||||||
|
if (message.indexOf('HTTP/1.1') > 0) {
|
||||||
|
pipeline.names().forEach(f => {
|
||||||
|
if (f == 'miaowebsocket' || f.indexOf('DefaultChannelPipeline') > -1) { return }
|
||||||
|
pipeline.remove(f)
|
||||||
|
})
|
||||||
|
pipeline.addLast('http', new HttpServerCodec())
|
||||||
|
pipeline.addLast('chunk', new ChunkedWriteHandler())
|
||||||
|
pipeline.addLast('httpobj', new HttpObjectAggregator(64 * 1024))
|
||||||
|
pipeline.addLast('http_request', new HttpRequestHandler())
|
||||||
|
pipeline.addLast('websocket', new WebSocketServerProtocolHandler("/ws"))
|
||||||
|
pipeline.addLast('websocket_handler', new TextWebSocketFrameHandler())
|
||||||
|
}
|
||||||
|
pipeline.remove('miaowebsocket')
|
||||||
|
msg.resetReaderIndex()
|
||||||
|
ctx.fireChannelRead(msg)
|
||||||
|
}
|
||||||
|
})
|
||||||
26
packages/plugins/src/MiaoPluginManager.ts
Normal file
26
packages/plugins/src/MiaoPluginManager.ts
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
import { plugin, interfaces, cmd } from "@ms/plugin";
|
||||||
|
|
||||||
|
import http from '@ms/common/dist/http'
|
||||||
|
|
||||||
|
@plugin({ name: 'MiaoPluginManager', prefix: 'MPM', version: '1.0.0', author: 'MiaoWoo', source: __filename })
|
||||||
|
export class MiaoPluginManager extends interfaces.Plugin {
|
||||||
|
@cmd()
|
||||||
|
mpman(sender: any, command: string, args: string[]) {
|
||||||
|
|
||||||
|
}
|
||||||
|
@cmd()
|
||||||
|
bktman(sender: any, command: string, args: string[]) {
|
||||||
|
switch (args[0]) {
|
||||||
|
case "s":
|
||||||
|
case "search":
|
||||||
|
if (args[1]) {
|
||||||
|
let result = http.get('https://servermods.forgesvc.net/servermods/projects?search=' + args[1])
|
||||||
|
for (let item of result) {
|
||||||
|
this.logger.sender(sender, "ID:", item.id, "名称:", item.name, JSON.stringify(item))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,11 +1,13 @@
|
|||||||
import { plugin as pluginApi, task } from '@ms/api'
|
import { plugin as pluginApi, task, server } from '@ms/api'
|
||||||
|
|
||||||
|
import * as fs from '@ms/common/dist/fs'
|
||||||
import { inject } from '@ms/container';
|
import { inject } from '@ms/container';
|
||||||
import { plugin, cmd, tab } from '@ms/plugin'
|
import { interfaces, plugin, cmd, tab } from '@ms/plugin'
|
||||||
|
|
||||||
let help = [
|
let help = [
|
||||||
'§6========= §6[§aMiaoScriptPackageManager§6] 帮助 §aBy §b喵♂呜 §6=========',
|
'§6========= §6[§aMiaoScriptPackageManager§6] 帮助 §aBy §b喵♂呜 §6=========',
|
||||||
'§6/mpm §ainstall §e<插件名称> §6- §3安装插件',
|
'§6/mpm §ainstall §e<插件名称> §6- §3安装插件',
|
||||||
|
'§6/mpm §auninstall §e<插件名称> §6- §3卸载插件',
|
||||||
'§6/mpm §alist [install]§6- §3列出仓库插件[已安装的插件]',
|
'§6/mpm §alist [install]§6- §3列出仓库插件[已安装的插件]',
|
||||||
'§6/mpm §aupdate §e<插件名称> §6- §3更新插件(无插件名称则更新源)',
|
'§6/mpm §aupdate §e<插件名称> §6- §3更新插件(无插件名称则更新源)',
|
||||||
'§6/mpm §aupgrade §e<插件名称> §6- §3及时更新插件(update需要重启生效)',
|
'§6/mpm §aupgrade §e<插件名称> §6- §3及时更新插件(update需要重启生效)',
|
||||||
@@ -16,30 +18,24 @@ let help = [
|
|||||||
];
|
];
|
||||||
|
|
||||||
@plugin({ name: 'MiaoScriptPackageManager', prefix: 'PM', version: '1.0.0', author: 'MiaoWoo', source: __filename })
|
@plugin({ name: 'MiaoScriptPackageManager', prefix: 'PM', version: '1.0.0', author: 'MiaoWoo', source: __filename })
|
||||||
export class MiaoScriptPackageManager {
|
export class MiaoScriptPackageManager extends interfaces.Plugin {
|
||||||
@inject(pluginApi.PluginManager)
|
@inject(pluginApi.PluginManager)
|
||||||
private pluginManager: pluginApi.PluginManager;
|
private pluginManager: pluginApi.PluginManager;
|
||||||
@inject(task.TaskManager)
|
@inject(task.TaskManager)
|
||||||
private taskManager: task.TaskManager;
|
private taskManager: task.TaskManager;
|
||||||
|
@inject(server.ServerType)
|
||||||
|
private serverType: string;
|
||||||
|
@inject(server.Server)
|
||||||
|
private server: server.Server
|
||||||
|
|
||||||
private pluginCache = [];
|
private packageCache: any[] = [];
|
||||||
private packageCache = [];
|
private packageNameCache: any[] = [];
|
||||||
private packageNameCache = [];
|
|
||||||
|
|
||||||
load() {
|
load() {
|
||||||
this.taskManager.create(() => {
|
this.taskManager.create(() => {
|
||||||
this.pluginCache = [...this.pluginManager.getPlugins().keys()];
|
|
||||||
// JSON.parse(http.get(self.config.center)).data.forEach(function cachePackageName(pkg) {
|
|
||||||
// packageCache[pkg.name] = pkg;
|
|
||||||
// })
|
|
||||||
// packageNameCache = Object.keys(packageCache);
|
|
||||||
}).async().submit();
|
}).async().submit();
|
||||||
}
|
}
|
||||||
|
|
||||||
enable() {
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
@cmd()
|
@cmd()
|
||||||
mpm(sender: any, command: string, args: string[]) {
|
mpm(sender: any, command: string, args: string[]) {
|
||||||
this.taskManager.create(() => this.main(sender, command, args)).async().submit();
|
this.taskManager.create(() => this.main(sender, command, args)).async().submit();
|
||||||
@@ -47,19 +43,19 @@ export class MiaoScriptPackageManager {
|
|||||||
|
|
||||||
main(sender: any, command: string, args: string[]) {
|
main(sender: any, command: string, args: string[]) {
|
||||||
if (!args[0] || args[1] === 'help') {
|
if (!args[0] || args[1] === 'help') {
|
||||||
console.sender(sender, help);
|
this.logger.sender(sender, help);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
switch (args[0]) {
|
switch (args[0]) {
|
||||||
case "list":
|
case "list":
|
||||||
if (args[1]) {
|
if (args[1]) {
|
||||||
console.sender(sender, '§6当前 §bMiaoScript §6已安装下列插件:');
|
this.logger.sender(sender, '§6当前 §bMiaoScript §6已安装下列插件:');
|
||||||
this.pluginCache.forEach(function listInfo(pluginName) {
|
this.pluginManager.getPlugins().forEach((plugin) => {
|
||||||
// var desc = manager.plugins[pluginName].description;
|
var desc = plugin.description;
|
||||||
// console.sender(sender, `§6插件名称: §b${desc.name} §6版本: §a${desc.version|| '1.0'} §6作者: §3${desc.author || '未知'}`)
|
this.logger.sender(sender, `§6插件名称: §b${desc.name} §6版本: §a${desc.version || '1.0'} §6作者: §3${desc.author || '未知'}`)
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
console.sender(sender, '§6当前 §bMiaoScriptPackageCenter §6中存在下列插件:');
|
this.logger.sender(sender, '§6当前 §bMiaoScriptPackageCenter §6中存在下列插件:');
|
||||||
for (var pkgName in this.packageCache) {
|
for (var pkgName in this.packageCache) {
|
||||||
var pkg = this.packageCache[pkgName];
|
var pkg = this.packageCache[pkgName];
|
||||||
// console.sender(sender, '§6插件名称: §b%s §6版本: §a%s §6作者: §3%s'.format(pkg.name, pkg.version || '1.0', pkg.author || '未知'))
|
// console.sender(sender, '§6插件名称: §b%s §6版本: §a%s §6作者: §3%s'.format(pkg.name, pkg.version || '1.0', pkg.author || '未知'))
|
||||||
@@ -73,6 +69,8 @@ export class MiaoScriptPackageManager {
|
|||||||
// console.sender(sender, '§c请输入插件名称!')
|
// console.sender(sender, '§c请输入插件名称!')
|
||||||
// }
|
// }
|
||||||
break;
|
break;
|
||||||
|
case "uninstall":
|
||||||
|
break;
|
||||||
case "update":
|
case "update":
|
||||||
// if (args.length > 1) {
|
// if (args.length > 1) {
|
||||||
// update(sender, args[1]);
|
// update(sender, args[1]);
|
||||||
@@ -82,6 +80,9 @@ export class MiaoScriptPackageManager {
|
|||||||
// }
|
// }
|
||||||
break;
|
break;
|
||||||
case "upgrade":
|
case "upgrade":
|
||||||
|
if (args[3] === "engine") {
|
||||||
|
fs.del(fs.concat(root, '', ''))
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
case "delete":
|
case "delete":
|
||||||
// if (args.length > 1) {
|
// if (args.length > 1) {
|
||||||
@@ -90,58 +91,83 @@ export class MiaoScriptPackageManager {
|
|||||||
// console.sender(sender, '§c请输入插件名称!')
|
// console.sender(sender, '§c请输入插件名称!')
|
||||||
// }
|
// }
|
||||||
break;
|
break;
|
||||||
|
case "load":
|
||||||
|
if (args.length > 1) {
|
||||||
|
var pname = args[1];
|
||||||
|
if (!this.pluginManager.getPlugins().has(pname)) {
|
||||||
|
this.logger.sender(sender, `§6插件 §b${pname} §c不存在!`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
this.pluginManager.load(pname)
|
||||||
|
this.pluginManager.enable(pname)
|
||||||
|
this.logger.sender(sender, `§6插件 §b${pname} §a已加载!`)
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case "unload":
|
||||||
|
if (args.length > 1) {
|
||||||
|
var pname = args[1];
|
||||||
|
if (!this.pluginManager.getPlugins().has(pname)) {
|
||||||
|
this.logger.sender(sender, `§6插件 §b${pname} §c不存在!`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
this.pluginManager.disable(pname)
|
||||||
|
this.logger.sender(sender, `§6插件 §b${pname} §a已卸载!`)
|
||||||
|
}
|
||||||
|
break;
|
||||||
case "reload":
|
case "reload":
|
||||||
// if (args.length > 1) {
|
if (args.length > 1) {
|
||||||
// var pname = args[1];
|
var pname = args[1];
|
||||||
// if (pluginCache.indexOf(pname) !== -1) {
|
if (!this.pluginManager.getPlugins().has(pname)) {
|
||||||
// manager.reload(pname)
|
this.logger.sender(sender, `§6插件 §b${pname} §c不存在!`)
|
||||||
// console.sender(sender, '§6插件 §b%s §a重载完成!'.format(pname))
|
return
|
||||||
// } else {
|
}
|
||||||
// console.sender(sender, '§c插件 §b%s §c不存在!'.format(pname))
|
this.pluginManager.reload(pname);
|
||||||
// }
|
this.logger.sender(sender, `§6插件 §b${pname} §a重载完成!`)
|
||||||
// } else {
|
}
|
||||||
// self.reloadConfig();
|
|
||||||
// load();
|
|
||||||
// }
|
|
||||||
break;
|
break;
|
||||||
case "restart":
|
case "restart":
|
||||||
|
if (this.serverType === "sponge") {
|
||||||
|
setTimeout(() => this.server.dispatchConsoleCommand('sponge plugins reload'), 0)
|
||||||
|
return
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
console.sender(sender, '§6Reloading §3MiaoScript Engine...');
|
this.logger.sender(sender, '§6Reloading §3MiaoScript Engine...');
|
||||||
ScriptEngineContextHolder.disableEngine();
|
ScriptEngineContextHolder.disableEngine();
|
||||||
ScriptEngineContextHolder.enableEngine();
|
ScriptEngineContextHolder.enableEngine();
|
||||||
console.sender(sender, '§3MiaoScript Engine §6Reload §aSuccessful...');
|
this.logger.sender(sender, '§3MiaoScript Engine §6Reload §aSuccessful...');
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
console.sender(sender, "§3MiaoScript Engine §6Reload §cError! ERR: " + ex);
|
this.logger.sender(sender, "§3MiaoScript Engine §6Reload §cError! ERR: " + ex);
|
||||||
console.sender(sender, console.stack(ex));
|
this.logger.sender(sender, this.logger.stack(ex));
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case "run":
|
case "run":
|
||||||
args.shift();
|
args.shift();
|
||||||
try {
|
try {
|
||||||
var script = args.join(' ')
|
var script = args.join(' ');
|
||||||
console.sender(sender, '§b运行脚本:§r', script)
|
this.logger.sender(sender, '§b运行脚本:§r', script);
|
||||||
console.sender(sender, '§a返回结果:§r', eval(script) || '§4没有返回结果!');
|
this.logger.sender(sender, '§a返回结果:§r', eval(script) || '§4没有返回结果!');
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
console.sender(sender, console.stack(ex))
|
this.logger.sender(sender, this.logger.stack(ex));
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case "create":
|
case "create":
|
||||||
|
this.logger.sender(sender, `§4当前暂不支持生成插件模板!`);
|
||||||
// var name = args[1];
|
// var name = args[1];
|
||||||
// if (!name) {
|
// if (!name) {
|
||||||
// console.sender(sender, '§4参数错误 /mpm create <插件名称> [作者] [版本] [主命令]');
|
// this.logger.sender(sender, '§4参数错误 /mpm create <插件名称> [作者] [版本] [主命令]');
|
||||||
// return;
|
// return;
|
||||||
// }
|
// }
|
||||||
// var result = template.create(http.get(self.config.template)).render({
|
// // var result = template.create(http.get(self.config.template)).render({
|
||||||
// name: name,
|
// // name: name,
|
||||||
// author: args[2] || 'MiaoWoo',
|
// // author: args[2] || 'MiaoWoo',
|
||||||
// version: args[3] || '1.0',
|
// // version: args[3] || '1.0',
|
||||||
// command: args[4] || name.toLowerCase(),
|
// // command: args[4] || name.toLowerCase(),
|
||||||
// });
|
// // });
|
||||||
// fs.save(fs.file(__dirname, name + '.js'), result);
|
// // fs.save(fs.file(__dirname, name + '.js'), result);
|
||||||
// console.sender(sender, '§6插件 §a' + name + ' §6已生成到插件目录...');
|
// this.logger.sender(sender, '§6插件 §a' + name + ' §6已生成到插件目录...');
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
console.sender(sender, help);
|
this.logger.sender(sender, help);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -155,9 +181,11 @@ export class MiaoScriptPackageManager {
|
|||||||
return this.packageNameCache;
|
return this.packageNameCache;
|
||||||
case "update":
|
case "update":
|
||||||
case "upgrade":
|
case "upgrade":
|
||||||
|
case "load":
|
||||||
|
case "unload":
|
||||||
case "reload":
|
case "reload":
|
||||||
return this.pluginCache;
|
return [...this.pluginManager.getPlugins().keys()];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,9 @@ import { plugin as pluginApi } from '@ms/api'
|
|||||||
import { plugin, interfaces, cmd, listener, tab } from '@ms/plugin'
|
import { plugin, interfaces, cmd, listener, tab } from '@ms/plugin'
|
||||||
import { inject } from '@ms/container';
|
import { inject } from '@ms/container';
|
||||||
|
|
||||||
|
import * as reflect from '@ms/common/dist/reflect';
|
||||||
|
import http from '@ms/common/dist/http';
|
||||||
|
|
||||||
@plugin({ name: 'Test', version: '1.0.0', author: 'MiaoWoo', source: __filename })
|
@plugin({ name: 'Test', version: '1.0.0', author: 'MiaoWoo', source: __filename })
|
||||||
export class Test extends interfaces.Plugin {
|
export class Test extends interfaces.Plugin {
|
||||||
@inject(pluginApi.PluginManager)
|
@inject(pluginApi.PluginManager)
|
||||||
@@ -51,7 +54,18 @@ export class Test extends interfaces.Plugin {
|
|||||||
setTimeout(() => location.block.type = Java.type('org.bukkit.Material').STONE, 8);
|
setTimeout(() => location.block.type = Java.type('org.bukkit.Material').STONE, 8);
|
||||||
break;
|
break;
|
||||||
case "add":
|
case "add":
|
||||||
require('js-yaml1');
|
break;
|
||||||
|
case "get":
|
||||||
|
let result = http.get('https://www.baidu.com');
|
||||||
|
this.logger.sender(sender, JSON.stringify(result));
|
||||||
|
// 好了 扯结束 继续咸鱼
|
||||||
|
break;
|
||||||
|
case "ws":
|
||||||
|
let Sponge = Java.type('org.spongepowered.api.Sponge');
|
||||||
|
// let promise = reflect.on(Bukkit.server).get('console').get('field_147144_o').get('field_151274_e').get().get(0);
|
||||||
|
console.log(reflect.on(Sponge.server).get('field_147144_o').get())
|
||||||
|
// let channel = reflect.on(promise).get('channel').get().pipeline().first();
|
||||||
|
// console.log(channel);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
this.logger.log(sender, command, args);
|
this.logger.log(sender, command, args);
|
||||||
@@ -64,7 +78,7 @@ export class Test extends interfaces.Plugin {
|
|||||||
return ['run', 'reload', 'channel', 'add', 'yaml', 'speed', 'top', 'up']
|
return ['run', 'reload', 'channel', 'add', 'yaml', 'speed', 'top', 'up']
|
||||||
}
|
}
|
||||||
|
|
||||||
@listener({ servertype: 'bukkit' })
|
@listener({ servers: ['bukkit'] })
|
||||||
playerjoin(event: any) {
|
playerjoin(event: any) {
|
||||||
this.logger.console('PlayerJoinEvent: ', event.player.name)
|
this.logger.console('PlayerJoinEvent: ', event.player.name)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,197 +0,0 @@
|
|||||||
import { plugin as pluginApi, server } from '@ms/api'
|
|
||||||
import { plugin, interfaces, cmd } from '@ms/plugin'
|
|
||||||
import { DefaultContainer as container, inject, postConstruct } from '@ms/container';
|
|
||||||
import * as reflect from '@ms/common/dist/reflect'
|
|
||||||
|
|
||||||
let clients: any[] = [];
|
|
||||||
let SPLIT_LINE = '\\M\\W\\S|T|S|S/L/T/'
|
|
||||||
const refList: Array<{ server: string, future: string }> = [
|
|
||||||
{ server: 'an', future: 'g' },
|
|
||||||
{ server: 'getServerConnection', future: 'f' },
|
|
||||||
{ server: 'func_147137_ag', future: 'field_151274_e' }
|
|
||||||
];
|
|
||||||
|
|
||||||
@plugin({ name: 'WebSocket', version: '1.0.0', author: 'MiaoWoo', source: __filename })
|
|
||||||
export class WebSocket extends interfaces.Plugin {
|
|
||||||
@inject(pluginApi.PluginManager)
|
|
||||||
private PluginManager: pluginApi.PluginManager;
|
|
||||||
@inject(server.ServerType)
|
|
||||||
private ServerType: string;
|
|
||||||
private pipeline: any;
|
|
||||||
|
|
||||||
@cmd()
|
|
||||||
ws(sender: any, command: string, args: string[]) {
|
|
||||||
switch (args[0]) {
|
|
||||||
case "reload":
|
|
||||||
this.PluginManager.reload(this);
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
disable() {
|
|
||||||
if (this.pipeline) {
|
|
||||||
this.pipeline.remove('miao_detect');
|
|
||||||
clients.forEach(c => c.close())
|
|
||||||
container.unbind('onmessage')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
bukkitenable() {
|
|
||||||
let Bukkit = Java.type('org.bukkit.Bukkit');
|
|
||||||
let consoleServer = reflect.on(Bukkit.getServer()).get('console').get();
|
|
||||||
this.injectMiaoDetect(this.reflectPromise(consoleServer))
|
|
||||||
}
|
|
||||||
|
|
||||||
spongeenable() {
|
|
||||||
let Sponge = Java.type('org.spongepowered.api.Sponge');
|
|
||||||
let consoleServer = reflect.on(Sponge.getServer()).get();
|
|
||||||
this.injectMiaoDetect(this.reflectPromise(consoleServer))
|
|
||||||
}
|
|
||||||
|
|
||||||
reflectPromise(consoleServer) {
|
|
||||||
for (const ref of refList) {
|
|
||||||
try { return reflect.on(consoleServer).call(ref.server).get(ref.future).get().get(0); } catch (error) { }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
injectMiaoDetect(promise) {
|
|
||||||
if (!promise) { throw Error(`Can't found ServerConnection or ChannelFuture !`) };
|
|
||||||
this.pipeline = reflect.on(promise).get('channel').get().pipeline();
|
|
||||||
this.pipeline.addFirst('miao_detect', new MiaoDetectHandler());
|
|
||||||
container.bind('onmessage').toFunction(this.onmessage.bind(this))
|
|
||||||
}
|
|
||||||
|
|
||||||
onmessage(ctx: any, msg: any) {
|
|
||||||
let text: string = msg.text()
|
|
||||||
const [type, content] = text.split('\\M\\W\\S|T|S|S/L/T/')
|
|
||||||
try {
|
|
||||||
var result = this[type](ctx, content)
|
|
||||||
} catch (ex) {
|
|
||||||
var result = '§4代码执行异常\n' + console.stack(ex).join('\n')
|
|
||||||
}
|
|
||||||
result && this.sendResult(ctx, "log", result)
|
|
||||||
}
|
|
||||||
|
|
||||||
execCommand(ctx: any, cmd: string) {
|
|
||||||
org.bukkit.Bukkit.dispatchCommand(org.bukkit.Bukkit.getConsoleSender(), cmd)
|
|
||||||
return `§6命令: §b${cmd} §a执行成功!`
|
|
||||||
}
|
|
||||||
|
|
||||||
execCode(ctx: any, code: string) {
|
|
||||||
return eval(code) || '无返回结果'
|
|
||||||
}
|
|
||||||
|
|
||||||
execDetect(ctx: any, cmd: string) {
|
|
||||||
switch (cmd) {
|
|
||||||
case "type":
|
|
||||||
let version = this.ServerType == 'bukkit' ? org.bukkit.Bukkit.getServer().getVersion() : org.spongepowered.api.Sponge.getPlatform().getMinecraftVersion();
|
|
||||||
this.sendResult(ctx, "type", this.ServerType)
|
|
||||||
return `Currect Server Version is ${version}`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
sendResult(ctx: any, type: string, msg: string) {
|
|
||||||
ctx.writeAndFlush(new TextWebSocketFrame(`${type}${SPLIT_LINE}${msg}`))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const ChannelInboundHandlerAdapter = Java.type('io.netty.channel.ChannelInboundHandlerAdapter');
|
|
||||||
const CharsetUtil = Java.type('io.netty.util.CharsetUtil')
|
|
||||||
const TextWebSocketFrame = Java.type('io.netty.handler.codec.http.websocketx.TextWebSocketFrame')
|
|
||||||
const MiaoDetectHandler = Java.extend(ChannelInboundHandlerAdapter, {
|
|
||||||
channelRead: function(ctx: any, channel: any) {
|
|
||||||
channel.pipeline().addFirst('miaowebsocket', new WebSocketHandler())
|
|
||||||
ctx.fireChannelRead(channel);
|
|
||||||
}
|
|
||||||
})
|
|
||||||
const TypeParameterMatcher = Java.type('io.netty.util.internal.TypeParameterMatcher')
|
|
||||||
const DefaultHttpResponse = Java.type('io.netty.handler.codec.http.DefaultHttpResponse');
|
|
||||||
const DefaultFullHttpResponse = Java.type('io.netty.handler.codec.http.DefaultFullHttpResponse');
|
|
||||||
const HttpHeaders = Java.type('io.netty.handler.codec.http.HttpHeaders');
|
|
||||||
const HttpVersion = Java.type('io.netty.handler.codec.http.HttpVersion');
|
|
||||||
const HttpResponseStatus = Java.type('io.netty.handler.codec.http.HttpResponseStatus');
|
|
||||||
const LastHttpContent = Java.type('io.netty.handler.codec.http.LastHttpContent');
|
|
||||||
const HttpServerCodec = Java.type('io.netty.handler.codec.http.HttpServerCodec');
|
|
||||||
const ChunkedWriteHandler = Java.type('io.netty.handler.stream.ChunkedWriteHandler');
|
|
||||||
const HttpObjectAggregator = Java.type('io.netty.handler.codec.http.HttpObjectAggregator');
|
|
||||||
const WebSocketServerProtocolHandler = Java.type('io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler');
|
|
||||||
const SimpleChannelInboundHandler = Java.type('io.netty.channel.SimpleChannelInboundHandler');
|
|
||||||
const FullHttpRequestMatcher = TypeParameterMatcher.get(base.getClass('io.netty.handler.codec.http.FullHttpRequest'))
|
|
||||||
const File = Java.type('java.io.File');
|
|
||||||
const RandomAccessFile = Java.type('java.io.RandomAccessFile');
|
|
||||||
const DefaultFileRegion = Java.type('io.netty.channel.DefaultFileRegion');
|
|
||||||
const ChannelFutureListener = Java.type('io.netty.channel.ChannelFutureListener');
|
|
||||||
const HttpRequestHandler = Java.extend(SimpleChannelInboundHandler, {
|
|
||||||
acceptInboundMessage: (msg: any) => {
|
|
||||||
return FullHttpRequestMatcher.match(msg);
|
|
||||||
},
|
|
||||||
channelRead0: (ctx: any, request: any) => {
|
|
||||||
if ('/ws' == request.getUri()) {
|
|
||||||
ctx.fireChannelRead(request.retain())
|
|
||||||
} else {
|
|
||||||
if (HttpHeaders.is100ContinueExpected(request)) {
|
|
||||||
ctx.writeAndFlush(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE));
|
|
||||||
}
|
|
||||||
let file = new File('/home/project/TSWorkSpace/ms/packages/plugins/public', request.getUri().split('?')[0])
|
|
||||||
if (!file.exists()) {
|
|
||||||
ctx.write(new DefaultHttpResponse(request.getProtocolVersion(), HttpResponseStatus.NOT_FOUND));
|
|
||||||
ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT).addListener(ChannelFutureListener.CLOSE);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let response = new DefaultHttpResponse(request.getProtocolVersion(), HttpResponseStatus.OK)
|
|
||||||
response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/html; charset=UTF-8");
|
|
||||||
let raf = new RandomAccessFile(file, 'r');
|
|
||||||
let keepAlive = HttpHeaders.isKeepAlive(request);
|
|
||||||
if (keepAlive) {
|
|
||||||
response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, file.length());
|
|
||||||
response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
|
|
||||||
}
|
|
||||||
ctx.write(response);
|
|
||||||
ctx.write(new DefaultFileRegion(raf.getChannel(), 0, raf.length()));
|
|
||||||
let future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
|
|
||||||
if (!keepAlive) {
|
|
||||||
future.addListener(ChannelFutureListener.CLOSE);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
const TextWebSocketFrameMatcher = TypeParameterMatcher.get(base.getClass('io.netty.handler.codec.http.websocketx.TextWebSocketFrame'))
|
|
||||||
const TextWebSocketFrameHandler = Java.extend(SimpleChannelInboundHandler, {
|
|
||||||
userEventTriggered: (ctx: any, evt: any) => {
|
|
||||||
if (evt == 'HANDSHAKE_COMPLETE') {
|
|
||||||
clients.push(ctx.channel());
|
|
||||||
console.console(`§6[§cMS§6][§bWebSocket§6]§r new client §b${ctx.channel().id()} §aconnected...`)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
acceptInboundMessage: (msg: any) => {
|
|
||||||
return TextWebSocketFrameMatcher.match(msg);
|
|
||||||
},
|
|
||||||
channelRead0: (ctx: any, msg: any) => {
|
|
||||||
container.get<any>('onmessage')(ctx, msg);
|
|
||||||
}
|
|
||||||
})
|
|
||||||
const WebSocketHandler = Java.extend(ChannelInboundHandlerAdapter, {
|
|
||||||
channelRead: function(ctx: any, msg: any) {
|
|
||||||
msg.markReaderIndex();
|
|
||||||
let message: string = msg.toString(CharsetUtil.UTF_8);
|
|
||||||
let channel = ctx.channel();
|
|
||||||
let pipeline = channel.pipeline();
|
|
||||||
if (message.indexOf('HTTP/1.1') > 0) {
|
|
||||||
try {
|
|
||||||
'protocol_lib_finish protocol_lib_decoder protocol_lib_encoder'.split(' ').forEach(f => channel.pipeline().remove(f))
|
|
||||||
} catch (error) {
|
|
||||||
}
|
|
||||||
'timeout legacy_query splitter decoder prepender encoder packet_handler'.split(' ').forEach(f => channel.pipeline().remove(f))
|
|
||||||
pipeline.addLast('http', new HttpServerCodec());
|
|
||||||
pipeline.addLast('chunk', new ChunkedWriteHandler());
|
|
||||||
pipeline.addLast('httpobj', new HttpObjectAggregator(64 * 1024));
|
|
||||||
pipeline.addLast('http_request', new HttpRequestHandler());
|
|
||||||
pipeline.addLast('websocket', new WebSocketServerProtocolHandler("/ws"));
|
|
||||||
pipeline.addLast('websocket_handler', new TextWebSocketFrameHandler());
|
|
||||||
}
|
|
||||||
pipeline.remove('miaowebsocket');
|
|
||||||
msg.resetReaderIndex();
|
|
||||||
ctx.fireChannelRead(msg);
|
|
||||||
}
|
|
||||||
})
|
|
||||||
@@ -2,6 +2,11 @@
|
|||||||
"extends": "../../tsconfig.json",
|
"extends": "../../tsconfig.json",
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"baseUrl": "src",
|
"baseUrl": "src",
|
||||||
"outDir": "dist"
|
"outDir": "dist",
|
||||||
}
|
"skipLibCheck": true
|
||||||
|
},
|
||||||
|
"exclude": [
|
||||||
|
"dist",
|
||||||
|
"public"
|
||||||
|
]
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ms/sponge",
|
"name": "@ms/sponge",
|
||||||
"version": "0.1.1",
|
"version": "0.3.0",
|
||||||
"description": "MiaoScript api package",
|
"description": "MiaoScript api package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -17,19 +17,19 @@
|
|||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"clean": "rimraf dist",
|
"clean": "rimraf dist",
|
||||||
"watch": "npx tsc --watch",
|
"watch": "tsc --watch",
|
||||||
"build": "yarn clean && npx tsc",
|
"build": "yarn clean && tsc",
|
||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.0",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.6.2"
|
"typescript": "^3.8.2"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ms/api": "^0.1.1",
|
"@ms/api": "^0.3.0",
|
||||||
"@ms/common": "^0.1.0",
|
"@ms/common": "^0.3.0",
|
||||||
"@ms/container": "^0.1.0",
|
"@ms/container": "^0.3.0",
|
||||||
"@ms/types": "^0.1.1"
|
"@ms/types": "^0.3.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
38
packages/sponge/src/channel.ts
Normal file
38
packages/sponge/src/channel.ts
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
import { channel, plugin } from '@ms/api'
|
||||||
|
import { inject, provideSingleton } from '@ms/container'
|
||||||
|
|
||||||
|
const Sponge = org.spongepowered.api.Sponge
|
||||||
|
const RawDataListener = Java.type("org.spongepowered.api.network.RawDataListener")
|
||||||
|
const ChannelRegistrar = Sponge.getChannelRegistrar()
|
||||||
|
const Consumer = Java.type("java.util.function.Consumer");
|
||||||
|
|
||||||
|
@provideSingleton(channel.Channel)
|
||||||
|
export class SpongeChannel extends channel.Channel {
|
||||||
|
@inject(plugin.PluginInstance)
|
||||||
|
private pluginInstance: any;
|
||||||
|
|
||||||
|
private channelMap = new Map<string, any>();
|
||||||
|
|
||||||
|
send(player: any, channel: string, data: any) {
|
||||||
|
if (!this.channelMap.has(channel)) { return }
|
||||||
|
this.channelMap.get(channel).sendTo(player, new Consumer({
|
||||||
|
accept: (channelBuf: any) => channelBuf.writeBytes(data)
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
register(channel: string, listener: channel.ChannelListener) {
|
||||||
|
if (!this.channelMap.has(channel)) {
|
||||||
|
this.channelMap.set(channel, ChannelRegistrar.getOrCreateRaw(this.pluginInstance, channel))
|
||||||
|
}
|
||||||
|
let innerListener = new RawDataListener({
|
||||||
|
handlePayload: (/* ChannelBuf */ data: any, /**RemoteConnection */ connection: any, /**Platform.Type */ side: any) => {
|
||||||
|
listener(data.readBytes(data.available()))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
this.channelMap.get(channel).addListener(innerListener);
|
||||||
|
return innerListener;
|
||||||
|
}
|
||||||
|
unregister(channel: string, listener: any) {
|
||||||
|
if (!this.channelMap.has(channel)) { return }
|
||||||
|
this.channelMap.get(channel).removeListener(listener);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,22 +1,51 @@
|
|||||||
import { command, plugin } from "@ms/api";
|
import { command, plugin } from "@ms/api";
|
||||||
import { inject, injectable } from "@ms/container";
|
import { inject, provideSingleton } from "@ms/container";
|
||||||
|
|
||||||
let Sponge = Java.type('org.spongepowered.api.Sponge');
|
let Sponge = Java.type('org.spongepowered.api.Sponge');
|
||||||
|
let Text = Java.type('org.spongepowered.api.text.Text');
|
||||||
var CommandCallable = Java.type('org.spongepowered.api.command.CommandCallable');
|
var CommandCallable = Java.type('org.spongepowered.api.command.CommandCallable');
|
||||||
var CommandResult = Java.type('org.spongepowered.api.command.CommandResult');
|
var CommandResult = Java.type('org.spongepowered.api.command.CommandResult');
|
||||||
|
|
||||||
let Text = Java.type('org.spongepowered.api.text.Text');
|
|
||||||
|
|
||||||
var Optional = Java.type('java.util.Optional');
|
var Optional = Java.type('java.util.Optional');
|
||||||
|
|
||||||
|
@provideSingleton(command.Command)
|
||||||
|
export class SpongeCommand extends command.Command {
|
||||||
|
@inject(plugin.PluginInstance)
|
||||||
|
private pluginInstance: any
|
||||||
|
private commandMapping: any[] = [];
|
||||||
|
|
||||||
|
create(plugin: any, command: string) {
|
||||||
|
let commandKey = this.getCommandKey(plugin, command);
|
||||||
|
let commandCallable = new SimpleCommandCallable(command);
|
||||||
|
this.commandMapping[commandKey] = Sponge.getCommandManager().register(this.pluginInstance, commandCallable.callable, command, commandKey).orElse(null);
|
||||||
|
return commandCallable;
|
||||||
|
}
|
||||||
|
remove(plugin: any, command: string) {
|
||||||
|
var commandKey = this.getCommandKey(plugin, command);
|
||||||
|
if (this.commandMapping[commandKey]) {
|
||||||
|
Sponge.getCommandManager().removeMapping(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.setTabCompleter(super.setTabCompleter(plugin, command, tabCompleter));
|
||||||
|
}
|
||||||
|
|
||||||
|
private getCommandKey(plugin: any, command: string) {
|
||||||
|
return plugin.description.name.toLowerCase() + ":" + command;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
class SimpleCommandCallable {
|
class SimpleCommandCallable {
|
||||||
public callable: any;
|
public callable: any;
|
||||||
|
private name: string;
|
||||||
private executor: Function;
|
private executor: Function;
|
||||||
private tabCompleter: Function;
|
private tabCompleter: Function;
|
||||||
|
|
||||||
constructor(command: string, description: string = '暂无描述!') {
|
constructor(command: string, description: string = '暂无描述!') {
|
||||||
|
this.name = command;
|
||||||
this.callable = new CommandCallable({
|
this.callable = new CommandCallable({
|
||||||
//CommandResult process(CommandSource source, String arguments) throws CommandException;
|
//CommandResult process(CommandSource source, String arguments) throws CommandException;
|
||||||
process: (sender: any, args) => {
|
process: (sender: any, args) => {
|
||||||
@@ -47,36 +76,5 @@ class SimpleCommandCallable {
|
|||||||
|
|
||||||
setExecutor = (executor: Function) => this.executor = executor;
|
setExecutor = (executor: Function) => this.executor = executor;
|
||||||
setTabCompleter = (tabCompleter: Function) => this.tabCompleter = tabCompleter;
|
setTabCompleter = (tabCompleter: Function) => this.tabCompleter = tabCompleter;
|
||||||
toString = () => `Sponge SimpleCommandCallable`
|
toString = () => `Sponge SimpleCommandCallable(${this.name})`
|
||||||
}
|
}
|
||||||
|
|
||||||
@injectable()
|
|
||||||
export class SpongeCommand extends command.Command {
|
|
||||||
@inject(plugin.PluginInstance)
|
|
||||||
private pluginInstance: any
|
|
||||||
private commandMapping: any[] = [];
|
|
||||||
|
|
||||||
create(plugin: any, command: string) {
|
|
||||||
let commandKey = this.getCommandKey(plugin, command);
|
|
||||||
let commandCallable = new SimpleCommandCallable(command);
|
|
||||||
this.commandMapping[commandKey] = Sponge.getCommandManager().register(this.pluginInstance, commandCallable.callable, command, commandKey).orElse(null);
|
|
||||||
return commandCallable;
|
|
||||||
}
|
|
||||||
remove(plugin: any, command: string) {
|
|
||||||
var commandKey = this.getCommandKey(plugin, command);
|
|
||||||
if (this.commandMapping[commandKey]) {
|
|
||||||
Sponge.getCommandManager().removeMapping(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.setTabCompleter(super.setTabCompleter(plugin, command, tabCompleter));
|
|
||||||
}
|
|
||||||
|
|
||||||
private getCommandKey(plugin: any, command: string) {
|
|
||||||
return plugin.description.name.toLowerCase() + ":" + command;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { event, plugin } from '@ms/api'
|
import { event, plugin } from '@ms/api'
|
||||||
import { injectable, inject } from '@ms/container';
|
import { inject, provideSingleton } from '@ms/container';
|
||||||
|
|
||||||
let Modifier = Java.type("java.lang.reflect.Modifier");
|
let Modifier = Java.type("java.lang.reflect.Modifier");
|
||||||
let Order = Java.type("org.spongepowered.api.event.Order");
|
let Order = Java.type("org.spongepowered.api.event.Order");
|
||||||
@@ -19,7 +19,7 @@ let priorityMap = {
|
|||||||
/**
|
/**
|
||||||
* Sponge Event Impl
|
* Sponge Event Impl
|
||||||
*/
|
*/
|
||||||
@injectable()
|
@provideSingleton(event.Event)
|
||||||
export class SpongeEvent extends event.Event {
|
export class SpongeEvent extends event.Event {
|
||||||
@inject(plugin.PluginInstance)
|
@inject(plugin.PluginInstance)
|
||||||
private pluginInstance: any;
|
private pluginInstance: any;
|
||||||
@@ -40,7 +40,7 @@ export class SpongeEvent extends event.Event {
|
|||||||
class2Name(clazz: any) {
|
class2Name(clazz: any) {
|
||||||
return clazz.name.substring(clazz.name.lastIndexOf(".") + 1);
|
return clazz.name.substring(clazz.name.lastIndexOf(".") + 1);
|
||||||
}
|
}
|
||||||
register(eventCls: any, exec: Function, priority: any = 'NORMAL', ignoreCancel: boolean = true) {
|
register(eventCls: any, exec: Function, priority: event.EventPriority = event.EventPriority.NORMAL, ignoreCancel: boolean = true) {
|
||||||
var listener = new EventListener({
|
var listener = new EventListener({
|
||||||
handle: exec
|
handle: exec
|
||||||
});
|
});
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user