Compare commits

...

128 Commits

Author SHA1 Message Date
0c69462bb4 v0.4.1 2020-03-31 16:16:40 +08:00
78a5ed31b3 fix: disable server error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-31 14:53:23 +08:00
f4e9b2627d feat: add new nodejs modules
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-31 14:51:44 +08:00
9dd7abe6fd feat: update plugins
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-30 18:49:19 +08:00
12743bbbe0 feat: instance i18n object
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-30 18:49:08 +08:00
d9a2ea9c78 v0.4.0 2020-03-25 13:54:45 +08:00
c505cda10b feat: export error handle & merge config
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-24 18:30:50 +08:00
100ccbcde3 feat: add api doc
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-24 17:59:18 +08:00
c6575ed481 fix: sourceMap sometime error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-24 15:02:20 +08:00
83359d8cb9 fix: ack callback call twice
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-24 14:52:50 +08:00
cca4979f16 feat: optimize framework add error catch(only log)
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-24 13:27:11 +08:00
251c9366f5 style: change error color
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-24 13:26:15 +08:00
8f01dcc8e8 feat: complate sockt.io server
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-23 18:33:12 +08:00
c25a616dba feat: add adapter and socket
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-23 00:58:53 +08:00
aa9169b043 feat: tracatch plugin build
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-21 15:48:45 +08:00
d87e152f3b feat: add nodejs package
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-21 15:47:59 +08:00
2fcadeda4e feat: complate socket.io base framework
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-21 15:47:42 +08:00
b7927830ae v0.3.2 2020-03-18 11:19:08 +08:00
2dbd2182c2 fix: source map print error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-18 11:15:49 +08:00
01df79eaf1 refactor: move docs to MiaoDocs
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-10 13:19:48 +08:00
16fe9ba9bd update: README
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-04 02:23:37 +08:00
950ce69b83 feat: modify stage order
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-04 02:11:55 +08:00
fa8e44d838 feat: update readme and fix container package error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-04 02:04:35 +08:00
b7af785273 feat: add docs package
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-04 02:04:02 +08:00
6c9f7bbcf6 v0.3.1 2020-03-03 01:14:22 +08:00
c4c4c7f301 feat: public types package
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-03 01:11:49 +08:00
6538c4b7bb feat: complate spiget and forgesvc api
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-02 22:40:18 +08:00
a4e6d1660d feat: update readme
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-02 22:38:34 +08:00
511b042eba feat: update MCBBS.MD
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-02 22:37:08 +08:00
6f0b5a5572 feat: add error handle
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-02 22:28:27 +08:00
e9ac46487c feat: merge type defiend
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-02 22:29:29 +08:00
9371823d30 remove: manager package
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-02 21:00:54 +08:00
c86f0d9ec1 feat: add complate function
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-02 00:32:07 +08:00
c2d94ef104 feat: optimize types ref
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-01 20:28:16 +08:00
6ada3e41d0 fix: Dependency cycles
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-01 19:37:34 +08:00
8c12319dc9 feat: add i18n to ployfill
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-01 17:01:27 +08:00
395d2d8816 feat: add NativePluginManager
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-01 15:19:43 +08:00
6f628a3d7e feat: add download and getPluginsFolder
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-29 22:28:43 +08:00
2232e82c36 feat: upgrade typescript
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-29 18:21:02 +08:00
291b5010e7 feat: add command error i18n
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-29 00:44:11 +08:00
3595294444 feat: add normal env task
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-27 18:20:45 +08:00
e38358ef98 feat: MiaoConsole exclude nukkit
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-27 18:15:33 +08:00
4c418c33c0 feat: channel add ext data
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-27 18:14:17 +08:00
65d112be09 feat: add nukkit example
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-27 17:59:06 +08:00
15a75dffe2 fix: servers check error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-27 17:57:29 +08:00
7b8e693a03 v0.3.0 2020-02-27 12:27:19 +08:00
5426023adb feat: optimize code
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-27 12:26:04 +08:00
73b91c417e feat: improve i18n scope
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-27 12:11:18 +08:00
2693a22bf0 feat: support i18n translate
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-27 01:58:23 +08:00
2322de1e40 feat: add package i18n
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-27 01:57:44 +08:00
2320736a92 feat: remove async check
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-26 10:43:47 +08:00
e8d5d10d44 feat: unmanaged baseEventDir
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-26 10:36:30 +08:00
a9996ba297 feat: use inversify autoProvide inject
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-26 10:15:33 +08:00
68380ddbba feat: exclude async event monitor
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-25 23:32:12 +08:00
0baf8f3cab fix: event execute class type error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-25 23:15:39 +08:00
a2bce715f3 fix: nukkit unregister event error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-25 18:25:16 +08:00
3c55df03d8 feat: use new channel service
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-24 18:36:32 +08:00
f6526e79fc feat: add channel support for bungee bukkit sponge
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-24 18:36:08 +08:00
f4c2294c06 feat: update ignore file
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-24 16:35:19 +08:00
cf9508ba31 v0.2.1 2020-02-24 16:27:49 +08:00
e0f4c5e77d feat: add nukkit support
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-24 16:25:54 +08:00
e4a87095ce feat: add config support
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-24 16:25:38 +08:00
950575edbc feat: inject config folder
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-24 16:25:16 +08:00
c2a71b9a7a feat: add config support
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-24 16:24:36 +08:00
068ac7b76e feat: update typescript version
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-24 15:28:47 +08:00
05cbd85828 feat: add nukkit support
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-24 04:02:29 +08:00
ea28d20aa1 feat: add nukkit package 2020-02-24 04:01:39 +08:00
d3f33f50e0 feat: add nukkit type defiend 2020-02-24 02:54:05 +08:00
d004ba17e6 v0.2.0 2020-02-24 00:21:48 +08:00
7a25dd8b3b feat: set manager and client to private
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-24 00:19:13 +08:00
dedc8393da feat: update plugins
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-24 00:13:19 +08:00
8d344492d9 feat: add config decorator bate
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-24 00:12:32 +08:00
81a76af7be feat: update mcbbs file
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-24 00:11:46 +08:00
b458da7a6e feat: add auto respawn support
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-23 22:35:05 +08:00
45cb6fa667 fix: some bug at xhr and console
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-23 22:33:51 +08:00
9c4543df30 feat: channelRead0 处理逻辑移动到业务线程
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-19 19:46:50 +08:00
512bdb22c5 feat: update main script
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-19 19:03:09 +08:00
f6e39c131c feat: add source map support
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-19 19:00:26 +08:00
73d4dad7f6 feat: add mc console client package
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-19 18:59:02 +08:00
de4a22362f feat: remove script npx
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-19 18:56:02 +08:00
5fde2e5554 feat: update example plugin
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-15 19:40:25 +08:00
6a6765e5c3 feat: add source map support(only local)
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-15 19:39:45 +08:00
4a1f25ee6a feat: enable sourceMap
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-15 18:49:18 +08:00
5999567ee3 feat: update dependencies version
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-15 18:48:46 +08:00
fad4e27a7f fix: bungee servers forEach error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-14 04:03:25 +08:00
b477938e4f fix: bungee unregister error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-14 04:02:37 +08:00
7cbd91826a feat: chat compatible catserver
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-14 04:02:18 +08:00
6797761a2f feat: add bungee tab complate
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-09 22:07:00 +08:00
be114e6d1b feat: add core-js
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-09 22:06:45 +08:00
3e40934339 feat: rename plugin
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-08 17:07:56 +08:00
3e6c7b2d8c fix: compile error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-02 01:58:07 +08:00
6c0bb75561 feat: use dom types and set Proxy global
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-02 01:56:45 +08:00
a47896a97f feat: update Proxy handle and optimize core index
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-01 03:37:56 +08:00
1d97bbc9ce feat: update Readme
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-01 02:54:03 +08:00
b1f1f9837e feat: add websocket package
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-01 02:47:39 +08:00
99dee28fd4 feat: add plugin stage log
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-01 02:46:55 +08:00
c7f66d8252 feat: move type bind and export impl function
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-01 02:46:06 +08:00
8c4f266356 feat: move global declare to @ms/ployfill
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-01 02:44:23 +08:00
39e899211b feat: complete cross server
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-01-17 17:48:23 +08:00
da72a0dac6 feat: optimize code
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-01-17 17:47:38 +08:00
9984787202 fix: sponge task callSyncMethod
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-01-17 17:45:39 +08:00
4493d35786 feat: optimiz plugin system
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-01-17 17:45:13 +08:00
e1aad59eeb feat: add tellraw string
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-01-17 17:44:08 +08:00
849393492f feat: update server filter
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-01-17 17:43:45 +08:00
1ff33702d8 feat: plugin & cmd add server check
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-01-17 11:11:20 +08:00
e68005fd6f feat: use inject container
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-01-17 11:10:30 +08:00
17269b50f4 fix: bungee event error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-01-17 11:09:16 +08:00
363d0c164a feat: add callSyncMethod
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-01-17 11:08:51 +08:00
13a0b62103 fix: with error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-01-17 11:08:10 +08:00
cb4e152800 feat: add plugin controller
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-01-16 17:28:10 +08:00
fb83acfcc8 feat: update plugins
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-01-16 17:27:24 +08:00
7263fbb437 feat: add bungee support
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-01-16 17:26:31 +08:00
23868a58b9 feat: complete event and dispatch command
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-01-16 17:19:10 +08:00
effa7f70ec feat: add tellraw & Proxy utils
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-01-15 18:38:22 +08:00
eef0baa740 feat: formatting code & remove chinese
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-01-15 16:48:18 +08:00
4d0c0122c7 feat: completion base func
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-01-15 16:44:14 +08:00
aa581afbe5 feat: add bungee package
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-01-15 16:43:00 +08:00
1425c473fd feat: delombok and regenerate d.ts
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-01-15 16:42:15 +08:00
53e4f6c658 feat: update bungee type file
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-01-15 01:02:08 +08:00
73db4a9169 feat: add server module
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-01-14 17:44:20 +08:00
a2efd878db feat: add bungee typings
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-01-14 17:40:28 +08:00
4e6cda0545 feat: support multi code page
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-01-13 15:28:25 +08:00
859a3a9171 feat: upgrade version
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-01-08 09:48:37 +08:00
96481032c5 feat: update websocket server
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-11-10 10:11:13 +08:00
f950c3dae8 feat: update gitignore 2019-11-09 18:35:26 +08:00
9248294cb3 feat: add jdk support 2019-11-09 18:34:54 +08:00
53873d7b63 feat: update type defiend 2019-11-07 16:40:27 +08:00
be59ae480b feat: add bukkit sponge jdk type 2019-11-07 15:13:28 +08:00
6606 changed files with 386868 additions and 947 deletions

3
.gitignore vendored
View File

@@ -1,5 +1,8 @@
.vscode
.theia
node_modules
dist
package-lock.json
yarn.lock
packages/nashorn/docs
!packages/types/dist

View File

@@ -11,12 +11,24 @@
├─api 全平台兼容的接口
├─core 核心代码 用于引导加载
├─common 公共类库代码 例如 http reflect 模块
├─client NodeJS的Minecraft客户端 用于调试插件
├─container IOC容器 用于注入具体实现
├─ployfill Nashorn 的一些自定义增强
├─nashorn Nashorn 的类型定义
├─bungee BungeeCordAPI内部实现
├─bukkit BukkitAPI内部实现
├─sponge SpongeAPI内部实现
├─nukkit NukkitAPI内部实现
├─plugin 插件管理器
├─websocket Netty的WebSocket注入
├─type Java的类型定义
| ├─bungee BungeeCord类型定义
| ├─bukkit Bukkit类型定义
| ├─sponge Sponge类型定义
| └─nukkit Nukkit类型定义
└─plugins 这里当然是插件啦
├─bungee 只兼容BungeeCord的插件
├─bukkit 只兼容Bukkit的插件
─sponge 只兼容Sponge的插件
─sponge 只兼容Sponge的插件
└─nukkit 只兼容Nukkit的插件
```

62
cli.sh
View File

@@ -1,62 +0,0 @@
#!/bin/bash
SHELL_PREFIX="[FAAS-CLI]"
# Shell Base Script
set -e
c_red="\033[38;5;1m"
c_blue="\033[38;5;4m"
c_green="\033[38;5;2m"
c_reset="\033[0m"
c_yellow="\033[38;5;3m"
c_prefix="${c_blue}${SHELL_PREFIX}>>${c_reset}"
dateStr() {
echo -e "[$(date '+%H:%M:%S')]"
}
info() {
echo -e "${c_prefix}$(dateStr) ${*}"
}
warn() {
echo -e "${c_prefix}$(dateStr) ${c_yellow}${*}${c_reset}"
}
error() {
echo -e "${c_prefix}$(dateStr) ${c_red}${*}${c_reset}"
}
#====================
cd $(dirname $0)
# User Input Variable
action=
while [[ $# -gt 0 ]]; do
case "$1" in
-a)
action="$2"
shift
;;
-*)
echo "Illegal option $1"
;;
esac
shift $(( $# > 0 ? 1 : 0 ))
done
case "${action}" in
undo)
hash=$(git log -n 1 --format=format:%H)
tag=$(git tag -l --contains=${hash})
if [[ -z "${tag}" ]]; then
error "last commit not have tag exit..."
exit 0
fi
git reset HEAD^
git tag -d ${tag}
git push origin master -f
git push origin :${tag}
;;
esac

View File

@@ -5,16 +5,61 @@
### 更新日志
- 2020-03-03
- 发布 `v0.3.1` 版本
- 2020-03-02
- 杂项 更新文档以及示例插件
- 2020-03-01
- 修复 多个包之间的循环依赖问题
- 优化 `@ms/types` 的引用逻辑
- 2020-02-29
- 更新 `TypeScript` 版本为 `3.8.3`
- 新增 `@ms/common` 的 `http` 下载功能
- 2020-02-27
- 发布 `v0.3.0` 版本
- 新增 `@ms/i18n` 国际化包的支持
- 修复 `@ms/plugin` 对 `servers` 相关处理异常
- 优化 `@ms/api` 的 `Channel` 处理增加 扩展原始数据
- 2020-02-26
- 优化 `@ms/container` 使用 `autoProvide` 自动注入依赖
- 2020-02-25
- 修复 `@ms/api` 对 `evnet` 的类型处理异常
- 2020-02-24
- 发布 `v0.2.1` 版本
- 完善 对 `Nukkit` 端的支持
- 新增 `@ms/api` 通道相关的支持
- 2020-02-23
- 新增 `@ms/nukkit` 包 对 `Nukkit` 端的支持
- 新增 `@ms/type` 的 `nukkit` 类型自动补全
- 2020-02-22
- 发布 `v0.2.0` 版本
- 新增 `@ms/plugin` 的 `@config` 注解 目前支持 `json` `yml` 格式的配置
- 2020-02-15
- 新增 `SourceMap` 的支持 用于跟踪源代码行数
- 2020-02-09
- 新增 `core-js` 用于支持大部分新ES语法
- 2020-01-31
- 优化 `@ms/ployfill` 全局处理
- 2020-01-15
- 新增 `@ms/bungee` 包 对 `BungeeCord` 端的支持
- 2020-01-14
- 新增 `@ms/type` 的 `bungee` 类型自动补全
- 2019-11-10
- 新增 `WebSocket` 的注入支持
- 2019-11-07
- 新增 `@ms/type` 的 `jdk` 类型自动补全
- 2019-09-27
- 新增 `CatServer` MOD端的支持
- 2019-09-25
- 完善 `Sponge` 类型自动补全
- 新增 `@ms/type` 的 `sponge` 类型自动补全
- 2019-09-24
- 完善 `Bukkit` 类型自动补全
- 新增 `@ms/type` 的 `bukkit` 类型自动补全
## 插件简介
- 此插件可以实现跨端使用 `TypeScript` 开发 脚本插件
- 目前已经兼容 `Spigot` `Sponge`
- 后续计划兼容 `BungeeCord` `Nukkit`
- 目前已经兼容 `Spigot` `Sponge` `Paper` `CatServer` `BungeeCord` `Nukkit`
- 后续计划兼容 暂无
## 起源 (可以略过)
@@ -65,6 +110,8 @@
- 完整的服务端Java类自动补全
- 全新的 IOC容器 注入功能
- 注解式 注册命令 注册事件
- 2020年3月2日 发布0.3.0版本
- 支持 Bukkit Nukkit BungeeCord Sponge
### 进展
@@ -91,20 +138,33 @@
├─api 全平台兼容的接口
├─core 核心代码 用于引导加载
├─common 公共类库代码 例如 http reflect 模块
├─client NodeJS的Minecraft客户端 用于调试插件
├─container IOC容器 用于注入具体实现
├─ployfill Nashorn 的一些自定义增强
├─nashorn Nashorn 的类型定义
├─bungee BungeeCordAPI内部实现
├─bukkit BukkitAPI内部实现
├─sponge SpongeAPI内部实现
├─nukkit NukkitAPI内部实现
├─ployfill JS环境的相关环境补全
├─plugin 插件管理器
├─websocket Netty的WebSocket注入
├─type Java的类型定义
| ├─bungee BungeeCord类型定义
| ├─bukkit Bukkit类型定义
| ├─sponge Sponge类型定义
| └─nukkit Nukkit类型定义
└─plugins 这里当然是插件啦
├─bungee 只兼容BungeeCord的插件
├─bukkit 只兼容Bukkit的插件
─sponge 只兼容Sponge的插件
─sponge 只兼容Sponge的插件
└─nukkit 只兼容Nukkit的插件
```
详细的内容就不逼逼了 自己看代码吧
Github: https://github.com/circlecloud/ms
YUMC: https://git.yumc.pw/circlecloud/ms
## 插件开发基础
@@ -120,8 +180,12 @@ Github: https://github.com/circlecloud/ms
- 进入目录 `ms`
- 安装 npm 包
- `yarn`
- 建立内部依赖链接
- `yarn bs`
- 编译一次生成对应的类库
- `yarn build`
- 编译插件
- `yarn build:plugins`
### 直接在 MiaoScript Online WebIDE 开发
@@ -134,21 +198,29 @@ Github: https://github.com/circlecloud/ms
先来一个 `HelloWorld.ts` 插件示范!
```ts
/// <reference types="@ms/bukkit/dist/typings" />
/// <reference types="@ms/sponge/dist/typings" />
/// <reference types="@ms/types" />
import { server } from '@ms/api';
import { inject } from '@ms/container';
import { plugin, interfaces, cmd, listener, tab } from '@ms/plugin'
@plugin({ name: 'HelloWorld', version: '1.0.0', author: 'MiaoWoo', source: __filename })
export class HelloWorld extends interfaces.Plugin {
@inject(server.Server)
private Server: server.Server
@config()
private config = {
version: 1.0.0
}
load() {
this.logger.log('Test Plugin load from MiaoScript Plugin System...');
this.logger.log('Plugin load from MiaoScript Plugin System...');
}
enable() {
this.logger.log('Test Plugin enable from MiaoScript Plugin System...');
this.logger.log('Plugin enable from MiaoScript Plugin System...');
}
disable() {
this.logger.log('Test Plugin disable from MiaoScript Plugin System...');
this.logger.log('Plugin disable from MiaoScript Plugin System...');
}
bukkitload() {
@@ -171,6 +243,26 @@ export class HelloWorld extends interfaces.Plugin {
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()
hello(sender: any, command: string, args: string[]) {
this.logger.log(sender, command, args);
@@ -182,27 +274,41 @@ export class HelloWorld extends interfaces.Plugin {
return ['world']
}
@listener({ servertype: 'bukkit' })
playerjoin(event: org.bukkit.event.player.PlayerJoinEvent) {
// bukkit nukkit 大部分API神似 可以直接用
@listener({ servers: ['bukkit', 'nukkit'] })
PlayerJoin(event: org.bukkit.event.player.PlayerJoinEvent) {
let plyaer = event.getPlayer();
this.logger.console(`§aBukkit PlayerJoinEvent: §b${plyaer.getName()}`)
setTimeout(() => this.logger.sender(plyaer, `§a欢迎来到 §bMiaoScript §a的世界!`), 10);
this.logger.console(`§cBukkit §aPlayerJoinEvent: §b${plyaer.getName()}`)
setTimeout(() => this.sendWelcome(plyaer), 10);
}
@listener({ servertype: 'sponge' })
clientconnectionevent$join(event: org.spongepowered.api.event.network.ClientConnectionEvent.Join) {
this.logger.console(`§aSponge ClientConnectionEvent.Join: §b${event.getTargetEntity().getName()}`)
setTimeout(() => this.logger.sender(event.getTargetEntity(), `§a欢迎来到 §bMiaoScript §a的世界!`), 10);
@listener({ servers: ['sponge'] })
ClientConnectionEvent$Join(event: org.spongepowered.api.event.network.ClientConnectionEvent.Join) {
this.logger.console(`§cSponge §aClientConnectionEvent.Join: §b${event.getTargetEntity().getName()}`)
setTimeout(() => this.sendWelcome(event.getTargetEntity()), 10);
}
private sendWelcome(player: any) {
this.logger.sender(player, `§a欢迎来到 §bMiaoScript §a的世界!`)
this.logger.sender(player, `§6当前版本: §c${this.Server.getVersion()}`)
}
@listener({ servers: ['bungee'] })
ServerConnected(e: any) {
let event = e as net.md_5.bungee.api.event.ServerConnectedEvent
this.logger.console(`§cBungeeCord §aServerConnectedEvent: §b${event.getPlayer().getDisplayName()}`)
setTimeout(() => this.logger.sender(event.getPlayer(), `§a欢迎来到 §bMiaoScript §a的世界 §6来自 §cBungeeCord §6的问候!`), 10);
}
}
```
- 进入 `ms`目录
- 执行编译 `yarn build:plugins`
- 从 `packages/plugins/dist` 中复制 `HelloWorld.js` 文件 到对应的插件目录
- 从 `packages/plugins/dist` 中复制 `HelloWorld.js` 和 `HelloWorld.js.map`(可选 用于显示插件原有行数) 文件 到对应的插件目录
- Bungee: plugins/MiaoScript/plugins/
- Bukkit: plugins/MiaoScript/plugins/
- Sponge: config/miaoscript/plugins/
- Nukkit: plugins/MiaoScript/plugins/
- 重载 `MiaoScript`
- 打开客户端进入游戏 预览一下效果
- 从 Spigot 服务端进入
@@ -222,6 +328,10 @@ export interface PluginMetadata {
* 插件名称
*/
name: string;
/**
* 支持的服务器列表 为空则代表所有
*/
servers?: string[];
/**
* 前缀
*/
@@ -247,10 +357,10 @@ export interface PluginMetadata {
### 插件生命周期
MiaoScript的生命周期遵循了 Bukkit 的生命周期
MiaoScript 的生命周期遵循了 Bukkit 的生命周期
MiaoScript针对不同的服务端 提供了扩展的周期
以服务端类型开头阶段名结束 例如 `bukkitload` `spongeenbale`
MiaoScript 针对不同的服务端 提供了扩展的周期
以服务端类型开头阶段名结束 例如 `bukkitload` `spongeenbale` `bungeedisable`
扩展的生命周期只会在特定的服务器执行
### load 加载阶段
@@ -275,12 +385,13 @@ MiaoScript针对不同的服务端 提供了扩展的周期
命令 就是玩家在Minecraft中执行命令 下面是一个示例的命令
- 命令是一个 `function` 通过 `@cmd` 注解注册
- 由于不同的服务端有不同的逻辑 所以支持通过 `servers` 指定注册的类型 加上 `!` 代表不注册 不指定 `servers` 则注册所有的类型
- 命令注册时默认使用方法名称为命令名称 当前你可以传入 name 参数指定命令名称 例如 `{name: 'test'}`
- 接受三个参数 `sender: any, command: string, args: string[]`
- 分别代表 命令发送者 命令名称 命令参数
```ts
@cmd()
@cmd({ servers: ["bukkit", "sponge", "!bungee"] })
hello(sender: any, command: string, args: string[]) {
this.logger.log(sender, command, args);
this.logger.sender(sender, JSON.stringify({ command, args }));
@@ -291,7 +402,7 @@ hello(sender: any, command: string, args: string[]) {
补全就是 玩家在Minecraft执行命令时 使用 Tab键 补全
- 补全是一个 `functio` 一般以 `tab` 开头 需要补全的命令结尾 通过 `@tab` 注解注册
- 补全是一个 `function` 一般以 `tab` 开头 需要补全的命令结尾 通过 `@tab` 注解注册
- 补全注册时默认使用方法名称为补全名称 当前你可以传入 name 参数指定命令名称 例如 `{name: 'test'}`
- 接受三个参数 `sender: any, command: string, args: string[]`
- 分别代表 命令发送者 命令名称 命令参数
@@ -310,6 +421,7 @@ tabhello(_sender: any, _command: string, _args: string[]) {
事件是指 Minecraft 中发生的各种事情
- 监听事件是一个 `function` 通过 `@listener` 注册
- 由于不同的服务端有不同的逻辑 所以支持通过 `servers` 指定注册的类型 加上 `!` 代表不注册 不指定 `servers` 则注册所有的类型
- 事件名称默认为方法名称
- 所有类型服务端的事件 MiaoScript 都会进行一次映射 方便使用
- 例如 `PlayerJoinEvent` 会映射为 `PlayerJoinEvent, playerjoinevent, playerjoin` 等
@@ -319,16 +431,43 @@ tabhello(_sender: any, _command: string, _args: string[]) {
- 事件监听方法的第一个参数就是本次事件的具体内容 (这里就需要自己去查询对应的JavaDoc了)
```ts
@listener({ servertype: 'bukkit' })
playerjoin(event: any) {
this.logger.console(`§aBukkit PlayerJoinEvent: §b${event.player.name}`)
setTimeout(() => this.logger.sender(event.player, `§a欢迎来到 §bMiaoScript §a的世界!`), 10);
// bukkit nukkit 大部分API神似 可以直接用
@listener({ servers: ['bukkit', 'nukkit'] })
PlayerJoin(event: org.bukkit.event.player.PlayerJoinEvent) {
let plyaer = event.getPlayer();
this.logger.console(`§cBukkit §aPlayerJoinEvent: §b${plyaer.getName()}`)
setTimeout(() => this.sendWelcome(plyaer), 10);
}
@listener({ servertype: 'sponge' })
clientconnectionevent$join(event: any) {
this.logger.console(`§aSponge ClientConnectionEvent.Join: §b${event.targetEntity.name}`)
setTimeout(() => this.logger.sender(event.targetEntity, `§a欢迎来到 §bMiaoScript §a的世界!`), 10);
@listener({ servers: ['sponge'] })
ClientConnectionEvent$Join(event: org.spongepowered.api.event.network.ClientConnectionEvent.Join) {
this.logger.console(`§cSponge §aClientConnectionEvent.Join: §b${event.getTargetEntity().getName()}`)
setTimeout(() => this.sendWelcome(event.getTargetEntity()), 10);
}
private sendWelcome(player: any) {
this.logger.sender(player, `§a欢迎来到 §bMiaoScript §a的世界!`)
this.logger.sender(player, `§6当前版本: §c${this.Server.getVersion()}`)
}
@listener({ servers: ['bungee'] })
ServerConnected(e: any) {
let event = e as net.md_5.bungee.api.event.ServerConnectedEvent
this.logger.console(`§cBungeeCord §aServerConnectedEvent: §b${event.getPlayer().getDisplayName()}`)
setTimeout(() => this.logger.sender(event.getPlayer(), `§a欢迎来到 §bMiaoScript §a的世界 §6来自 §cBungeeCord §6的问候!`), 10);
}
```
## 配置文件
配置文件 默认读取的是 `MiaoScript根目录/plugins/插件名称/配置名称.配置格式`
例如下面文件 默认处理的是 `plugins/MiaoScript/plugins/HelloWorld/config.yml`
```ts
@config()
private config = {
version: 1.0.0
}
```

View File

@@ -1,5 +1,5 @@
{
"version": "0.1.1",
"version": "0.4.1",
"useWorkspaces": true,
"npmClient": "yarn",
"packages": [

View File

@@ -6,16 +6,18 @@
"author": "MiaoWoo <admin@yumc.pw>",
"license": "MIT",
"scripts": {
"clean": "npx lerna run clean",
"watch": "npx lerna run watch --parallel",
"build": "npx lerna run build --scope='@ms/!(plugins)'",
"build:plugins": "npx lerna run build --scope=@ms/plugins",
"lp": "npx lerna publish"
"bs": "lerna bootstrap",
"clean": "lerna run clean",
"watch": "lerna run watch --parallel",
"build": "lerna run build --scope=\"@ms/!(plugins)\"",
"build:plugins": "lerna run build --scope=\"@ms/plugins\"",
"ug": "yarn upgrade-interactive --latest",
"lp": "lerna publish"
},
"workspaces": [
"packages/*"
],
"devDependencies": {
"lerna": "^3.16.4"
"lerna": "^3.20.2"
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@ms/api",
"version": "0.1.1",
"version": "0.4.1",
"description": "MiaoScript api package",
"keywords": [
"miaoscript",
@@ -17,17 +17,18 @@
},
"scripts": {
"clean": "rimraf dist",
"watch": "npx tsc --watch",
"build": "yarn clean && npx tsc",
"watch": "tsc --watch",
"build": "yarn clean && tsc",
"test": "echo \"Error: run tests from root\" && exit 1"
},
"dependencies": {
"@ms/container": "^0.1.0",
"@ms/ployfill": "^0.1.0"
"@ms/container": "^0.4.0",
"@ms/ployfill": "^0.4.1",
"source-map-builder": "^0.0.7"
},
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.0",
"typescript": "^3.6.2"
"rimraf": "^3.0.2",
"typescript": "^3.8.3"
}
}

View File

@@ -0,0 +1,66 @@
import { injectable } from "@ms/container";
export namespace channel {
/**
* handle plugin message
* @param data byte[]
*/
export type ChannelListener = (data: any, exts?: any) => void
@injectable()
export abstract class Channel {
private listenerMap = [];
/**
* 注册通道
* @param plugin 插件
* @param channel 通道
* @param exec 执行器
*/
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;
}
/**
* 关闭插件注册的通道
* @param plugin 插件
*/
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
}
}

View File

@@ -1,63 +1,70 @@
import i18n from '@ms/i18n'
import { injectable } from "@ms/container";
export namespace command {
@injectable()
export abstract class Command {
/**
* 注册插件命令
* @param plugin 插件
* @param name 命令
* @param exec 执行器
*/
on(plugin: any, name: string, exec: { cmd: Function, tab?: Function }) {
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") {
this.onCommand(plugin, cmd, exec.cmd);
} 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") {
this.onTabComplete(plugin, cmd, exec.tab);
}
}
/**
* 取消命令注册
* @param plugin 插件
* @param name 命令
*/
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);
}
/**
* Create Server Command Object
*/
protected abstract create(plugin: any, command: string);
protected abstract remove(plugin: any, command: string);
protected abstract onCommand(plugin: any, command: any, executor: Function);
protected abstract onTabComplete(plugin: any, command: any, tabCompleter: Function);
protected setExecutor(plugin: any, command: any, executor: Function) {
return (sender: any, _, command: string, args: string[]) => {
return (sender: any, _: any, command: string, args: string[]) => {
try {
return executor(sender, command, Java.from(args));
} catch (ex) {
console.console(`§6玩家 §a${sender.name} §6执行 §b${plugin.description.name} §6插件 §d${command} ${Java.from(args).join(' ')} §6命令时发生异常 §4${ex}`);
console.i18n("ms.api.command.execute.error", { sender: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex })
console.ex(ex);
console.sender(sender, [`§6执行 §b${plugin.description.name} §6插件 §d${command} ${Java.from(args).join(' ')} §6命令时发生异常`, ...console.stack(ex)])
console.sender(sender, [i18n.translate("ms.api.command.execute.error", { sender: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex }), ...console.stack(ex)])
return true;
}
}
}
protected setTabCompleter(plugin: any, command: any, tabCompleter: Function) {
return (sender: any, _, command: string, args: string[]) => {
return (sender: any, _: any, command: string, args: string[]) => {
try {
var token = args[args.length - 1];
var complete = tabCompleter(sender, command, Java.from(args)) || [];
return this.copyPartialMatches(complete, token);
} catch (ex) {
console.console(`§6玩家 §a${sender.name} §6执行 §b${plugin.description.name} §6插件 §d${command} ${Java.from(args).join(' ')} §6补全时发生异常 §4${ex}`);
console.i18n("ms.api.command.tab.completer.error", { sender: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex })
console.ex(ex);
console.sender(sender, [`§6执行 §b${plugin.description.name} §6插件 §d${command} ${Java.from(args).join(' ')} §6补全时发生异常 §4${ex}`, ...console.stack(ex)]);
console.sender(sender, [i18n.translate("ms.api.command.tab.completer.error", { sender: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex }), ...console.stack(ex)]);
return [];
}
}
}
protected copyPartialMatches(complete: string[], token: string, array: string[] = []): string[] {
if (!token) { return complete }
complete.forEach(function(e) {
complete.forEach(function (e) {
if (typeof e === "string" && e.toLowerCase().startsWith(token.toLowerCase())) {
array.push(e)
}

View File

@@ -1,11 +1,30 @@
let Arrays = Java.type('java.util.Arrays');
let Level = Java.type('java.util.logging.Level');
let ignoreLogPrefix = ['java.', 'net.minecraft.', 'org.bukkit.', 'jdk.nashorn.', 'io.netty.'];
import i18m from '@ms/i18n'
import { SourceMapBuilder } from 'source-map-builder'
const Arrays = Java.type('java.util.Arrays');
const Level = Java.type('java.util.logging.Level');
const JavaString = Java.type('java.lang.String');
const Files = Java.type('java.nio.file.Files');
const Paths = Java.type('java.nio.file.Paths');
const ignoreLogPrefix = ['java.', 'net.minecraft.', 'org.bukkit.', 'jdk.nashorn.', 'io.netty.', 'org.spongepowered.'];
enum LogLevel {
ALL,
TRACE,
DEBUG,
INFO,
WARN,
ERROR,
FATAL,
OFF
}
export class MiaoScriptConsole implements Console {
Console: NodeJS.ConsoleConstructor;
private sourceMaps: { [key: string]: SourceMapBuilder } = {};
private _name: string = '';
private _level: LogLevel = LogLevel.INFO;
protected logger: any;
protected prefix: string = '§6[§bMiaoScript§6]§r ';
@@ -13,6 +32,12 @@ export class MiaoScriptConsole implements Console {
constructor(name?: string) {
this.name = name;
this.logger = global.logger;
if (global.debug) {
this._level = LogLevel.DEBUG
}
if (global.level?.toUpperCase() === "TRACE") {
this._level = LogLevel.TRACE
}
}
get name() {
@@ -26,54 +51,93 @@ export class MiaoScriptConsole implements Console {
this.prefix = `§6[§cMS§6][§b${name}§6]§r `;
}
}
log(...args): void {
log(...args: any[]): void {
this.logger.info(this.name + args.join(' '));
}
info(...args) {
info(...args: any[]) {
this.logger.info(this.name + args.join(' '));
};
warn(...args) {
}
warn(...args: any[]) {
this.logger.warning(this.name + args.join(' '));
};
error(...args) {
}
error(...args: any[]) {
this.logger.log(Level.SEVERE, this.name + args.join(' '));
};
debug(...args) {
}
debug(...args: any[]) {
if (global.debug) {
this.logger.info(this.name + '[DEBUG] ' + args.join(' '));
}
};
}
trace(...args: any[]): void {
if (this._level <= LogLevel.TRACE) {
this.logger.info(this.name + '[TRACE] ' + args.join(' '));
}
}
sender(...args) {
this.info(args)
}
console(...args) {
this.info(args)
}
i18n(name: string, param?: { [key: string]: any }) {
this.console(i18m.translate(name, param))
}
object(obj) {
for (var i in obj) {
this.logger(i, '=>', obj[i])
this.info(i, '=>', obj[i])
}
};
}
ex(ex: Error) {
this.stack(ex).forEach(line => this.console(line))
};
}
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, 25, true);
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[] {
var stack = ex.getStackTrace();
var cache = [4' + ex];
var cache = [c' + ex];
//@ts-ignore
if (stack.class) {
stack = Arrays.asList(stack)
}
stack.forEach(function(trace) {
stack.forEach(trace => {
if (trace.className.startsWith('<')) {
var fileName = trace.fileName
var { fileName, lineNumber } = this.readSourceMap(trace.fileName, trace.lineNumber)
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
cache.push(` §e->§c ${fileName} => §4${trace.methodName}:${trace.lineNumber}`)
cache.push(` §e->§c ${fileName} => §4${trace.methodName}:${lineNumber}`)
} else {
var className = trace.className;
var fileName = trace.fileName
var fileName = trace.fileName as string;
if (className.startsWith('jdk.nashorn.internal.scripts')) {
className = className.substr(className.lastIndexOf('$') + 1)
var { fileName, lineNumber } = this.readSourceMap(trace.fileName, trace.lineNumber)
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
} else {
for (var prefix in ignoreLogPrefix) {
@@ -82,7 +146,7 @@ export class MiaoScriptConsole implements Console {
}
}
}
cache.push(` §e->§c ${className}.${trace.methodName}(§4${fileName}:${trace.lineNumber}§c)`);
cache.push(` §e->§c ${className}.${trace.methodName}(§4${fileName}:${lineNumber}§c)`);
}
});
return cache;
@@ -126,9 +190,6 @@ export class MiaoScriptConsole implements Console {
timeLog(label?: string, ...data: any[]): void {
throw new Error("Method not implemented.");
}
trace(message?: any, ...optionalParams: any[]): void {
throw new Error("Method not implemented.");
}
markTimeline(label?: string): void {
throw new Error("Method not implemented.");
}

View File

@@ -1,14 +1,24 @@
'use strict';
/**
* MiaoScript Event处理类
*/
import '@ms/core'
import '@ms/nashorn'
import { injectable } from '@ms/container'
import i18n from '@ms/i18n'
import { injectable, unmanaged } from '@ms/container'
const Thread = Java.type('java.lang.Thread');
export namespace event {
/**
* 事件监听优先级
*/
export enum EventPriority {
LOWEST = "LOWEST",
LOW = "LOW",
NORMAL = "NORMAL",
HIGH = "HIGH",
HIGHEST = "HIGHEST",
MONITOR = "MONITOR",
}
@injectable()
export abstract class Event {
private mapEvent = [];
@@ -16,33 +26,31 @@ export namespace event {
protected baseEventDir = '';
constructor(baseEventDir: string) {
constructor(@unmanaged() baseEventDir: string) {
this.baseEventDir = baseEventDir;
}
/**
* 扫描包 org.bukkit.event 下的所有事件
* 映射简写名称 org.bukkit.event.player.PlayerLoginEvent => playerloginevent
* abstract event map function
* ig: org.bukkit.event.player.PlayerLoginEvent => playerloginevent
* org.spongepowered.api.event.game.GameRegistryEvent.Register => gameregistryevent$register
*/
mapEventName() {
if (this.baseEventDir === "") {
throw new Error("事件基础包名为空 无法进行事件映射!");
}
if (this.baseEventDir === "") { throw new Error(i18n.translate('ms.api.event.empty.event.dir')); }
let count = 0;
let jar = this.getJarFile(this.baseEventDir);
let entries = jar.entries();
while (entries.hasMoreElements()) {
let entry = entries.nextElement();
let name = entry.name;
// 以 org/bukkit/event 开头 并且以 .class 结尾
if (name.startsWith(this.baseEventDir) && name.endsWith(".class")) {
// replace name to qualifiedName
let qualifiedName = name.replaceAll('/', '.');
try {
let clazz = base.getClass(qualifiedName.substring(0, qualifiedName.length - 6));
// 继承于 org.bukkit.event.Event 访问符为Public
if (this.isValidEvent(clazz)) {
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;
count++;
}
@@ -60,22 +68,21 @@ export namespace event {
let url = dirs.nextElement();
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;
}
name2Class(name, event) {
var eventCls = this.mapEvent[event.toLowerCase()] || this.mapEvent[event.toLowerCase() + 'event'];
name2Class(name: any, event: string) {
let eventCls = this.mapEvent[event.toLowerCase()] || this.mapEvent[event.toLowerCase() + 'event'];
if (!eventCls) {
try {
eventCls = base.getClass(eventCls);
this.mapEvent[event] = eventCls;
} catch (ex) {
console.console(`§6插件 §b${name} §6注册事件 §c${event} §6失败 §4事件未找到!`);
console.ex(new Error(`插件 ${name} 注册事件 ${event} 失败 事件未找到!`));
console.i18n("ms.api.event.not.found", { name, event })
return;
}
}
@@ -83,16 +90,19 @@ export namespace event {
}
execute(name, exec, eventCls) {
return (...args) => {
return (...args: any[]) => {
try {
var time = new Date().getTime()
exec(args[args.length - 1]);
var cost = new Date().getTime() - time;
if (cost > 20) {
console.console(`§c注意! §6插件 §b${name} §6处理 §d${this.class2Name(eventCls)} §6事件 §c耗时 §4${cost}ms !`)
let event = args[args.length - 1];
if (eventCls.isAssignableFrom(event.getClass())) {
let time = Date.now()
exec(event);
let cost = Date.now() - time;
if (cost > 20) {
console.i18n("ms.api.event.execute.slow", { name, event: this.class2Name(eventCls), cost })
}
}
} 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);
}
}
@@ -100,31 +110,31 @@ export namespace event {
/**
* 添加事件监听
* @param plugin
* @param event
* @param plugin {any}
* @param event {string}
* @param exec {function}
* @param priority [LOWEST,LOW,NORMAL,HIGH,HIGHEST,MONITOR]
* @param priority {string} [LOWEST,LOW,NORMAL,HIGH,HIGHEST,MONITOR]
* @param ignoreCancel
*/
listen(plugin, event, exec, priority = 'NORMAL', ignoreCancel = false) {
if (!plugin || !plugin.description || !plugin.description.name) throw new TypeError('插件名称为空 请检查传入参数!');
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(i18n.translate("ms.api.event.listen.plugin.name.empty"));
var name = plugin.description.name;
var eventCls = this.name2Class(name, event);
if (!eventCls) { return; }
if (typeof priority === 'boolean') {
ignoreCancel = priority;
priority = 'NORMAL';
priority = EventPriority.NORMAL;
}
priority = priority || 'NORMAL';
priority = priority || EventPriority.NORMAL;
ignoreCancel = ignoreCancel || false;
// noinspection JSUnusedGlobalSymbols
var listener = this.register(eventCls, this.execute(name, exec, eventCls), priority, ignoreCancel);
var listenerMap = this.listenerMap;
// 添加到缓存 用于关闭插件的时候关闭事件
// add to cache Be used for close plugin to close event
if (!listenerMap[name]) listenerMap[name] = [];
var offExec = () => {
this.unregister(eventCls, listener);
console.debug(`插件 ${name} 注销事件 ${this.class2Name(eventCls)}`);
console.debug(i18n.translate("ms.api.event.unregister", { name, event: this.class2Name(eventCls) }));
};
var off = {
event: eventCls,
@@ -133,10 +143,14 @@ export namespace event {
};
listenerMap[name].push(off);
// 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;
}
/**
* 关闭插件监听任务
* @param plugin 插件
*/
disable(plugin: any) {
var eventCache = this.listenerMap[plugin.description.name];
if (eventCache) {
@@ -145,8 +159,24 @@ export namespace event {
}
}
/**
* 判断
* @param clazz 事件类
*/
abstract isValidEvent(clazz: any): boolean;
/**
* 注册事件
* @param eventCls 事件类
* @param exec 执行器
* @param priority 优先级
* @param ignoreCancel 是否忽略已取消的事件
*/
abstract register(eventCls: any, exec: Function, priority: any, ignoreCancel: boolean): any;
/**
* 取消监听事件
* @param event 事件
* @param listener 监听器
*/
abstract unregister(event: any, listener: any): void;
}
}

View File

@@ -1,7 +1,7 @@
/// <reference path="./typings/global.ts" />
import "@ms/nashorn"
export * from './task'
export * from './event'
export * from './console'
export * from './channel'
export * from './command'
export * from './interfaces'

View File

@@ -1,24 +1,26 @@
import { Container } from "@ms/container";
export namespace plugin {
/**
* MiaoScript Plugin
*/
export const Plugin = Symbol("Plugin");
/**
* MiaoScript Plugin Folder
*/
export const PluginFolder = Symbol("PluginFolder");
/**
* Runtime Plugin Instance
*/
export const PluginInstance = Symbol("PluginInstance");
/**
* MiaoScript Plugin Manager
* MiaoScript Plugin Manager Symbol
*/
export const PluginManager = Symbol("PluginManager");
/**
* MiaoScript Plugin Manager
* MiaoScript Plugin Manager Interface
*/
export interface PluginManager {
scan(folder: string): void;
build(container: Container): void;
build(): void;
load(...args: any[]): void;
enable(...args: any[]): void;
disable(...args: any[]): void;

View File

@@ -1,9 +0,0 @@
export namespace server {
export const ServerType = Symbol("ServerType");
export const Console = Symbol("Console");
export const Server = Symbol("Server");
export interface Server {
getVersion(): string;
getPlayer(name: string): any;
}
}

View File

@@ -0,0 +1,35 @@
import { NativePluginManager } from './native_plugin'
export namespace server {
/**
* Runtime ServerType
*/
export const ServerType = Symbol("ServerType");
/**
* Runtime Console
*/
export const Console = Symbol("Console");
/**
* MiaoScript Server
*/
export const Server = Symbol("Server");
/**
* Runtime Server Instance
*/
export const ServerInstance = Symbol("ServerInstance");
/**
* MiaoScript Server
*/
export interface Server {
getVersion(): string;
getPlayer(name: string): any;
getOnlinePlayers(): any[];
getConsoleSender(): any;
getService(service: string): any;
dispatchCommand(sender: string | any, command: string): boolean;
dispatchConsoleCommand(command: string): boolean;
getPluginsFolder(): string;
getNativePluginManager(): NativePluginManager;
sendJson(sender: string | any, json: object | string): void;
}
}

View File

@@ -0,0 +1,6 @@
export interface NativePluginManager {
load(name: string): boolean;
unload(name: string): boolean;
reload(name: string): boolean;
delete(name: string): boolean;
}

View File

@@ -1,9 +1,16 @@
import { injectable, DefaultContainer as container } from "@ms/container";
export namespace task {
export const TaskManager = Symbol('TaskManager')
export interface TaskManager {
/**
* 创建任务
* @param func 任务内容
*/
create(func: Function): task.Task;
/**
* 在主线程执行代码
* @param func 执行内容
*/
callSyncMethod(func: Function): any;
}
/**
* 任务抽象
@@ -20,16 +27,28 @@ export namespace task {
this.func = func;
}
/**
* 设置任务异步执行
* @param isAsync 是否异步
*/
async(isAsync: boolean = true): task.Task {
this.isAsync = isAsync;
return this;
}
/**
* 设置任务延时执行
* @param tick 延时 Tick
*/
later(tick: number): task.Task {
this.laterTime = tick;
return this;
}
/**
* 设置任务循环执行
* @param tick 循环时间 Tick
*/
timer(tick: number): task.Task {
this.interval = tick;
return this;
@@ -44,6 +63,9 @@ export namespace task {
}
}
/**
* 提交任务
*/
abstract submit(): Cancelable;
}
/**

View File

@@ -1,28 +0,0 @@
import { XMLHttpRequest as xhr } from '@ms/ployfill'
declare global {
namespace NodeJS {
interface Global {
logger: any;
debug: boolean;
noop: Function;
console: Console;
XMLHttpRequest: typeof xhr;
}
}
var root: string;
var base: Core;
var XMLHttpRequest: typeof xhr;
var ScriptEngineContextHolder: any;
function engineLoad(str: string): any;
interface Core {
getClass(name: String);
}
interface Console {
ex(err: Error): void;
stack(err: Error): string[];
sender(...args: any): void;
console(...args: any): void;
}
}
export { }

View File

@@ -1,7 +1,7 @@
{
"name": "@ms/bukkit",
"version": "0.1.1",
"description": "MiaoScript api package",
"version": "0.4.1",
"description": "MiaoScript bukkit package",
"keywords": [
"miaoscript",
"minecraft",
@@ -17,19 +17,18 @@
},
"scripts": {
"clean": "rimraf dist",
"watch": "npx tsc --watch",
"build": "yarn clean && npx tsc",
"watch": "tsc --watch",
"build": "yarn clean && tsc",
"test": "echo \"Error: run tests from root\" && exit 1"
},
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.0",
"typescript": "^3.6.2"
"rimraf": "^3.0.2",
"typescript": "^3.8.3"
},
"dependencies": {
"@ms/api": "^0.1.1",
"@ms/common": "^0.1.0",
"@ms/container": "^0.1.0",
"@ms/types": "^0.1.1"
"@ms/api": "^0.4.1",
"@ms/common": "^0.4.0",
"@ms/container": "^0.4.0"
}
}

View 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 */ channel, /**Player */ player, /**byte[] */data) => {
listener(data, { channel, player, data })
}
}));
Messenger.registerOutgoingPluginChannel(this.pluginInstance, channel);
}
unregister(channel: string, listener: any) {
Messenger.unregisterIncomingPluginChannel(this.pluginInstance, channel)
Messenger.unregisterOutgoingPluginChannel(this.pluginInstance, channel)
}
}

View File

@@ -2,14 +2,14 @@ import '@ms/nashorn'
import { command, plugin } from '@ms/api'
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 TabCompleter = Java.type('org.bukkit.command.TabCompleter');
let PluginCommand = Java.type('org.bukkit.command.PluginCommand');
let CommandExecutor = Java.type('org.bukkit.command.CommandExecutor');
@injectable()
@provideSingleton(command.Command)
export class BukkitCommand extends command.Command {
@inject(plugin.PluginInstance)
private pluginInstance: any
@@ -19,7 +19,6 @@ export class BukkitCommand extends command.Command {
init() {
this.commandMap = reflect.on(Bukkit.getPluginManager()).get('commandMap').get();
}
create(plugin: any, command: string) {
var cmd = this.commandMap.getCommand(command)
if (cmd && cmd instanceof PluginCommand) { return cmd };

View File

@@ -5,7 +5,7 @@ let Bukkit = org.bukkit.Bukkit;
export class BukkitConsole extends MiaoScriptConsole {
sender(sender, ...args) {
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;
}
if (Object.prototype.toString.call(args[0]) === "[object Array]") {
@@ -14,7 +14,7 @@ export class BukkitConsole extends MiaoScriptConsole {
sender.sendMessage(this.prefix + args.join(' '));
}
}
console(...args): void {
console(...args: string[]): void {
this.sender(Bukkit.getConsoleSender(), args.join(' '));
}
}

View 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

View File

@@ -1,5 +1,5 @@
import { event, server, plugin } from '@ms/api'
import { injectable, inject } from '@ms/container';
import { event, plugin } from '@ms/api'
import { inject, provideSingleton } from '@ms/container';
import * as reflect from '@ms/common/dist/reflect'
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 EventExecutor = Java.type("org.bukkit.plugin.EventExecutor");
@injectable()
@provideSingleton(event.Event)
export class BukkitEvent extends event.Event {
@inject(plugin.PluginInstance)
private pluginInstance: any
@@ -29,7 +29,7 @@ export class BukkitEvent extends event.Event {
// 不是抽象类
!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({});
Bukkit.pluginManager.registerEvent(
eventCls,

View File

@@ -1,22 +1,15 @@
/// <reference types="@ms/types/dist/typings/bukkit" />
import { server, plugin, command, event, task } from '@ms/api'
import { DefaultContainer as container } from '@ms/container'
import { server } from '@ms/api'
import { Container } from '@ms/container'
import { BukkitConsole } from './console';
import { BukkitEvent } from './event';
import { BukkitCommand } from './command';
import { BukkitTaskManager } from './task';
import './event';
import './server';
import './command';
import './channel';
import './task';
let BukkitServerType = 'bukkit';
let Bukkit = Java.type("org.bukkit.Bukkit");
container.bind(server.Console).toConstantValue(BukkitConsole);
container.bind(server.ServerType).toConstantValue(BukkitServerType);
container.bind(plugin.PluginInstance).toConstantValue(Bukkit.pluginManager.getPlugin('MiaoScript'));
container.bind(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} ...`)
export default function BukkitImpl(container: Container) {
container.bind(server.Console).toConstantValue(BukkitConsole);
}

View File

@@ -0,0 +1,55 @@
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 {
private pluginsFolder: string;
constructor() {
this.pluginsFolder = Bukkit.getUpdateFolderFile().getParentFile().getCanonicalPath();
}
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)
}
getPluginsFolder(): string {
return this.pluginsFolder;
}
getNativePluginManager() {
return Bukkit.getPluginManager() as any;
}
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)
}
}
}

View File

@@ -1,9 +1,11 @@
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 {
@inject(plugin.PluginInstance)
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 !'); };
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 {

View File

@@ -0,0 +1,34 @@
{
"name": "@ms/bungee",
"version": "0.4.1",
"description": "MiaoScript bungee package",
"keywords": [
"miaoscript",
"minecraft",
"bukkit",
"sponge"
],
"author": "MiaoWoo <admin@yumc.pw>",
"homepage": "https://github.com/circlecloud/ms.git",
"license": "ISC",
"main": "dist/index.js",
"publishConfig": {
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
},
"scripts": {
"clean": "rimraf dist",
"watch": "tsc --watch",
"build": "yarn clean && tsc",
"test": "echo \"Error: run tests from root\" && exit 1"
},
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.8.3"
},
"dependencies": {
"@ms/api": "^0.4.1",
"@ms/common": "^0.4.0",
"@ms/container": "^0.4.0"
}
}

View File

@@ -0,0 +1,25 @@
import { channel, event } from '@ms/api'
import { provideSingleton, inject } from '@ms/container'
const Bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy()
@provideSingleton(channel.Channel)
export class BungeeChannel extends channel.Channel {
@inject(event.Event)
private eventManager: event.Event;
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] §eMiaoScript channel in BungeeCord only register. you need self hanler PluginMessageEvent!')
return this.eventManager.listen({ description: { name: channel } }, "PluginMessageEvent", (event: net.md_5.bungee.api.event.PluginMessageEvent) => {
listener(event.getData(), event)
})
}
unregister(channel: string, listener: any) {
Bungee.unregisterChannel(channel);
listener.off();
}
}

View 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})`
}

View 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(' '));
}
}

View 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()
}
}
}

View 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);
}

View File

@@ -0,0 +1,47 @@
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 {
private pluginsFolder: string;
constructor() {
this.pluginsFolder = Bungee.getPluginsFolder().getCanonicalPath();
}
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)
}
getPluginsFolder(): string {
return this.pluginsFolder;
}
getNativePluginManager() {
return Bungee.getPluginManager() as any
}
sendJson(sender: string | any, json: string): void {
throw new Error("Method not implemented.");
}
}

View 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)
}
}
}

View File

@@ -0,0 +1,8 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"baseUrl": "src",
"outDir": "dist",
"allowJs": true
}
}

View File

@@ -0,0 +1,35 @@
{
"private": true,
"name": "@ms/client",
"version": "0.4.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.3"
}
}

View 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,
$
}

View 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) {
}
})
}

View 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)
});
}
});
}

View File

@@ -0,0 +1,77 @@
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('error', (error) => {
console.log("Client Error", error)
})
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,
completer: (line, func) => {
let args = line.split(' ')
let comp = args[args.length - 1]
client.once('tab_complete', (msg) => {
let mcts = msg.matches.filter(s => s)
func(null, [mcts, comp])
})
client.write('tab_complete', {
text: line
})
},
terminal: true,
prompt: ''
})
rl.on('line', function (line) {
switch (line) {
case "":
break;
case "eval":
break;
case "write":
break;
case "/respawn":
client.write('client_command', { payload: 0 })
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()
})

View File

@@ -0,0 +1,7 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"baseUrl": "src",
"outDir": "dist"
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@ms/common",
"version": "0.1.0",
"version": "0.4.0",
"description": "MiaoScript api package",
"keywords": [
"miaoscript",
@@ -17,18 +17,17 @@
},
"scripts": {
"clean": "rimraf dist",
"watch": "npx tsc --watch",
"build": "yarn clean && npx tsc",
"watch": "tsc --watch",
"build": "yarn clean && tsc",
"test": "echo \"Error: run tests from root\" && exit 1"
},
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.0",
"typescript": "^3.6.2"
"rimraf": "^3.0.2",
"typescript": "^3.8.3"
},
"dependencies": {
"@ms/nashorn": "^0.1.0",
"@ms/ployfill": "^0.1.0"
"@ms/nashorn": "^0.4.0"
},
"gitHead": "562e2d00175c9d3a99c8b672aa07e6d92706a027"
}

View File

@@ -12,8 +12,8 @@ const StandardCopyOption = Java.type("java.nio.file.StandardCopyOption");
/**
* 用文件分割符合并路径
*/
export function concat() {
return Array.prototype.join.call(arguments, separatorChar);
export function concat(...args: string[]) {
return args.join(separatorChar);
}
/**
@@ -23,12 +23,12 @@ export function concat() {
* @returns {*}
*/
export function file(...opts: any[]): any {
if (!arguments[0]) {
if (!opts[0]) {
console.warn("文件名称不得为 undefined 或者 null !");
}
switch (arguments.length) {
switch (opts.length) {
case 1:
var f = arguments[0];
var f = opts[0];
if (f instanceof File) {
return f;
}
@@ -40,7 +40,7 @@ export function file(...opts: any[]): any {
}
break;
default:
return new File(file(arguments[0]), arguments[1]);
return new File(file(opts[0]), opts[1]);
}
}
@@ -48,7 +48,7 @@ export function file(...opts: any[]): any {
* 创建目录
* @param path
*/
export function mkdirs(path) {
export function mkdirs(path: any) {
// noinspection JSUnresolvedVariable
file(path).parentFile.mkdirs();
}
@@ -57,7 +57,7 @@ export function mkdirs(path) {
* 创建文件
* @param file
*/
export function create(path) {
export function create(path: any) {
var f = file(path);
if (!f.exists()) {
mkdirs(f);
@@ -70,7 +70,7 @@ export function create(path) {
* @param file
* @returns {*}
*/
export function path(f) {
export function path(f: any) {
return file(f).canonicalPath;
}
@@ -80,7 +80,7 @@ export function path(f) {
* @param target 目标文件
* @param override 是否覆盖
*/
export function copy(inputStream, target, override) {
export function copy(inputStream: any, target: any, override: any) {
Files.copy(inputStream, target.toPath(), StandardCopyOption[override ? 'REPLACE_EXISTING' : 'ATOMIC_MOVE']);
}

View File

@@ -1,4 +1,7 @@
import '@ms/api'
const URL = Java.type('java.net.URL')
const Paths = Java.type('java.nio.file.Paths');
const Files = Java.type('java.nio.file.Files');
const StandardCopyOption = Java.type('java.nio.file.StandardCopyOption');
export type Method =
| 'get' | 'GET'
@@ -24,12 +27,21 @@ function request(config: RequestConfig) {
for (const header in config.headers) {
xhr.setRequestHeader(header, config.headers[header]);
}
let future = xhr.send(config.data);
return future.get();
xhr.send(config.data);
if ((xhr.getResponseHeader("Content-Type") + '').indexOf('application/json') != -1) {
xhr.responseType = "json"
}
return xhr.get();
}
function download(url: string, target: string) {
console.debug(`Start Download file ${target} from ${url}....`)
Files.copy(new URL(url).openStream(), Paths.get(target), StandardCopyOption.REPLACE_EXISTING);
console.debug(`File ${target} Download Complate...`)
}
function _proxy(method: Method) {
return function(url: string, data?: any, config?: RequestConfig) {
return function (url: string, data?: any, config?: RequestConfig) {
return request({ url, method, data, ...config });
}
}
@@ -37,5 +49,6 @@ function _proxy(method: Method) {
export default {
get: _proxy('GET'),
post: _proxy('POST'),
request
request,
download
}

View File

@@ -1,4 +1,3 @@
import '@ms/core'
/**
* 反射工具类
* Created by MiaoWoo on 2017/2/9 0009.

View 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

View File

@@ -2,7 +2,6 @@
"extends": "../../tsconfig.json",
"compilerOptions": {
"baseUrl": "src",
"outDir": "dist",
"declaration": true
"outDir": "dist"
}
}

View File

@@ -0,0 +1,29 @@
{
"name": "@ms/compile",
"version": "0.4.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.3"
}
}

View 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(() => { })

View File

@@ -0,0 +1,7 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"baseUrl": "src",
"outDir": "dist"
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@ms/container",
"version": "0.1.0",
"version": "0.4.0",
"description": "MiaoScript container package",
"keywords": [
"miaoscript",
@@ -17,16 +17,17 @@
},
"scripts": {
"clean": "rimraf dist",
"watch": "npx tsc --watch",
"build": "yarn clean && npx tsc",
"watch": "tsc --watch",
"build": "yarn clean && tsc",
"test": "echo \"Error: run tests from root\" && exit 1"
},
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.0",
"typescript": "^3.6.2"
"rimraf": "^3.0.2",
"typescript": "^3.8.3"
},
"dependencies": {
"inversify": "^5.0.1",
"inversify-binding-decorators": "^4.0.0"
}
}

View File

@@ -2,7 +2,7 @@ import { interfaces, Container } from "inversify";
let _container: Container;
const CONTAINER = Symbol.for("@ms/ioc:Container");
const ContainerInstance = Symbol.for("@ms/ioc:Container");
const INJECTION = Symbol.for("INJECTION");
function _proxyGetter(
@@ -35,12 +35,12 @@ function _proxyGetter(
}
function initContainer(container: Container) {
Reflect.defineMetadata(CONTAINER, container, Reflect);
Reflect.defineMetadata(ContainerInstance, container, Reflect);
_container = container;
}
function getContainer(): Container {
return _container || Reflect.getMetadata(CONTAINER, Reflect)
return _container || Reflect.getMetadata(ContainerInstance, Reflect)
}
function makePropertyInjectDecorator(doCache: boolean) {
@@ -97,6 +97,7 @@ let lazyMultiInject = makePropertyMultiInjectDecorator(doCache)
export {
initContainer,
getContainer,
ContainerInstance,
lazyInject,
lazyInjectNamed,
lazyInjectTagged,

View File

@@ -1,6 +1,6 @@
{
"name": "@ms/core",
"version": "0.1.1",
"version": "0.4.1",
"description": "MiaoScript api package",
"keywords": [
"miaoscript",
@@ -12,27 +12,23 @@
"homepage": "https://github.com/circlecloud/ms.git",
"license": "ISC",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
"publishConfig": {
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
},
"scripts": {
"clean": "rimraf dist",
"watch": "npx tsc --watch",
"build": "yarn clean && npx tsc",
"watch": "tsc --watch",
"build": "yarn clean && tsc",
"test": "echo \"Error: run tests from root\" && exit 1"
},
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.0",
"typescript": "^3.6.2"
"rimraf": "^3.0.2",
"typescript": "^3.8.3"
},
"dependencies": {
"@ms/api": "^0.1.1",
"@ms/bukkit": "^0.1.1",
"@ms/common": "^0.1.0",
"@ms/container": "^0.1.0",
"@ms/plugin": "^0.1.1",
"@ms/sponge": "^0.1.1"
}
"@ms/api": "^0.4.1",
"@ms/container": "^0.4.0"
},
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
}

View File

@@ -1,38 +1,31 @@
import '@ms/nashorn'
let containerStartTime = Date.now();
console.i18n("ms.core.ioc.initialize");
import { plugin, server, task } from '@ms/api'
import { PluginManagerImpl } from '@ms/plugin'
import { XMLHttpRequest as xhr } from '@ms/ployfill'
import { DefaultContainer as container, injectable, inject, postConstruct } from '@ms/container'
import { DefaultContainer as container, inject, provideSingleton, ContainerInstance, buildProviderModule } from '@ms/container'
console.i18n("ms.core.ioc.completed", { time: (Date.now() - containerStartTime) / 1000 })
let startTime = new Date().getTime();
@injectable()
@provideSingleton(MiaoScriptCore)
class MiaoScriptCore {
@inject(server.Console)
private Console: Console;
@inject(task.TaskManager)
private taskManager: task.TaskManager;
@inject(plugin.PluginFolder)
private pluginFolder: string;
@inject(plugin.PluginManager)
private pluginManager: plugin.PluginManager;
enable() {
try {
this.loadServerConsole();
this.loadTaskFunction();
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)!');
this.loadServerConsole();
this.loadTaskFunction();
global.level = "TRACE"
this.loadPlugins();
return () => this.disable();
}
loadServerConsole() {
// @ts-ignore
console = new this.Console();
XMLHttpRequest = xhr;
}
loadTaskFunction() {
@@ -43,34 +36,61 @@ class MiaoScriptCore {
}
loadPlugins() {
this.pluginManager.scan('plugins');
this.pluginManager.build(container);
let loadPluginStartTime = new Date().getTime()
console.i18n("ms.core.plugin.initialize")
this.pluginManager.scan(this.pluginFolder);
this.pluginManager.build();
this.pluginManager.load();
this.pluginManager.enable();
console.i18n("ms.core.plugin.completed", { time: (new Date().getTime() - loadPluginStartTime) / 1000 })
}
disable() {
console.i18n("ms.core.engine.disable")
this.pluginManager.disable();
}
}
function init() {
function detectServer() {
try {
Java.type("org.bukkit.Bukkit");
require('@ms/bukkit');
return 'bukkit'
} catch (ex) {
}
try {
Java.type("org.spongepowered.api.Sponge");
require('@ms/sponge');
return 'sponge'
} catch (ex) {
}
container.bind(plugin.PluginManager).to(PluginManagerImpl).inSingletonScope();
container.bind(MiaoScriptCore).to(MiaoScriptCore).inSingletonScope();
try {
Java.type("cn.nukkit.Nukkit");
return 'nukkit'
} catch (ex) {
}
try {
Java.type("net.md_5.bungee.api.ProxyServer");
return 'bungee'
} catch (ex) {
}
throw Error('Unknow Server Type...')
}
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();

View File

@@ -0,0 +1,40 @@
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.api.command.execute.error: "§6Player {player} §6exec §b{plugin} §6Plugin Command §d{command} {args} §6error §4{ex}"
ms.api.command.tab.completer.error: "§6Player {player} §6exec §b{plugin} §6Plugin TabComplete §d{command} {args} §6error §4{ex}"
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..."

View File

@@ -0,0 +1,40 @@
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.api.command.execute.error: "§6玩家 §a{player} §6执行 §b{plugin} §6插件 §d{command} {args} §6命令时发生异常 §4{ex}"
ms.api.command.tab.completer.error: "§6玩家 §a{player} §6执行 §b{plugin} §6插件 §d{command} {args} §6补全时发生异常 §4{ex}"
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} 不存在. 从默认值自动创建保存..."

View File

@@ -0,0 +1,35 @@
{
"name": "@ms/i18n",
"version": "0.4.1",
"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.3"
},
"dependencies": {
"@ms/nashorn": "^0.4.0",
"js-yaml": "^3.13.1"
},
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
}

View File

@@ -0,0 +1,69 @@
/// <reference types="@ms/nashorn" />
import * as yaml from 'js-yaml'
const File = Java.type("java.io.File");
const separatorChar = File.separatorChar;
type TranslateParam = { [key: string]: any }
declare global {
interface Console {
i18n(name: string, param?: TranslateParam);
}
}
type TranslateContent = {
langMap: TranslateParam,
fallbackMap?: TranslateParam
}
export class Translate {
private root = '';
private langMap = {};
private fallbackMap = {};
constructor(root: string | TranslateContent) {
if (typeof root == 'string') {
this.root = root;
} else {
this.langMap = root.langMap;
this.fallbackMap = root.fallbackMap || {};
}
}
translate(name: string, param?: TranslateParam) {
let langText: string = this.langMap[name] || this.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;
}
initialize(lang: string = 'zh_cn', fallback: string = 'zh_cn') {
this.langMap = this.readYamlFile(this.root, lang) || this.readYamlFile(this.concat(__dirname, '..'), lang)
this.fallbackMap = this.readYamlFile(this.root, fallback) || this.readYamlFile(this.concat(__dirname, '..'), fallback)
console.i18n = (name: string, param?: TranslateParam) => {
console.log(this.translate(name, param))
}
}
readYamlFile(dir: string, name: string) {
let langFile = this.concat(dir, 'languages', name + '.yml');
return this.exists(langFile) && yaml.safeLoad(base.read(langFile))
}
concat(...args: string[]) {
return args.join(separatorChar)
}
exists(path: string) {
return new File(path).exists()
}
}
let systemTranslate = new Translate(root)
export default {
initialize: systemTranslate.initialize.bind(systemTranslate),
translate: systemTranslate.translate.bind(systemTranslate)
}

View File

@@ -0,0 +1,7 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"baseUrl": "src",
"outDir": "dist"
}
}

View File

@@ -1,11 +1,12 @@
# sponge bukkit
TYPE=sponge
# sponge bukkit jdk bungee nukkit
TYPE=nukkit
TARGET=../types/dist/typings
npx tsc src/build.ts --outDir dist
cd dist
rm -rf temp
mkdir -p temp
node build.js ${TYPE}
cd ../
rm -rf src/typings
mkdir -p src/typings/${TYPE}
cp dist/temp/* src/typings/${TYPE}/ -R
rm -rf ${TARGET}/${TYPE}
mkdir -p ${TARGET}/${TYPE}
cp dist/temp/* ${TARGET}/${TYPE}/ -R

View File

@@ -1,6 +1,6 @@
{
"name": "@ms/nashorn",
"version": "0.1.0",
"version": "0.4.0",
"description": "MiaoScript api package",
"keywords": [
"miaoscript",
@@ -18,13 +18,13 @@
},
"scripts": {
"clean": "rimraf dist",
"watch": "npx tsc --watch",
"build": "yarn clean && npx tsc",
"watch": "tsc --watch",
"build": "yarn clean && tsc",
"test": "echo \"Error: run tests from root\" && exit 1"
},
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.0",
"typescript": "^3.6.2"
"rimraf": "^3.0.2",
"typescript": "^3.8.3"
}
}

View File

@@ -10,7 +10,7 @@ function convertJson2TypeDefiend(infile: string, outDir: string) {
closeBuk++;
const nms = qnas.slice(1, qnas.length - 1);
for (const nm of nms) {
temp += `${' '.repeat(closeBuk)}namespace ${nm} {\n`;
temp += `${' '.repeat(closeBuk)}namespace ${nm.replace('function', 'function$')} {\n`;
closeBuk++;
}
let classModifier = formatClassModifier(obj.modifiers)
@@ -33,7 +33,7 @@ function convertJson2TypeDefiend(infile: string, outDir: string) {
temp = temp.substr(0, temp.length - 2);
}
} 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) {
temp += ' implements '
for (const ifs of safeInterface) {
@@ -46,7 +46,7 @@ function convertJson2TypeDefiend(infile: string, outDir: string) {
temp += ' {\n'
closeBuk++;
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 = [];
@@ -77,8 +77,8 @@ function convertJson2TypeDefiend(infile: string, outDir: string) {
temp += `${' '.repeat(closeBuk - index - 1)}}\n`;
}
fs.writeFileSync(`${outDir}/${file}.ts`, temp);
return `${file}.ts`;
fs.writeFileSync(`${outDir}/${file}.${suffix}`, temp);
return `${file}.${suffix}`;
}
function formatClassModifier(modifiers: string) {
@@ -98,7 +98,11 @@ function formatDoc(doc: string, closeBuk: number) {
}
function replaceModifiers(modifiers: string, absClass = false): string {
// modifiers = modifiers.replace(' final', ' readonly');
modifiers = modifiers.split(" final")[0];
modifiers = modifiers.split(" native")[0];
modifiers = modifiers.split(" volatile")[0];
modifiers = modifiers.split(" transient")[0];
modifiers = modifiers.split(" synchronized")[0];
if (!absClass) {
modifiers = modifiers.split(" abstract")[0];
@@ -117,6 +121,7 @@ function formatParameters(params: any[]) {
const nameMap = [];
nameMap['function'] = 'func'
nameMap['in'] = 'input'
nameMap['var'] = 'variable'
function mappingName(name: string) {
if (whiteKey.includes(name)) { return name }
@@ -124,7 +129,7 @@ function mappingName(name: string) {
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 = [];
typeMap['int'] = 'number';
@@ -133,17 +138,22 @@ typeMap['int[][]'] = 'number[][]';
typeMap['byte'] = 'number';
typeMap['byte[]'] = 'number[]';
typeMap['double'] = 'number';
typeMap['double[]'] = 'number[]';
typeMap['short'] = 'number';
typeMap['short[]'] = 'number[]';
typeMap['float'] = 'number';
typeMap['float[]'] = 'number[]';
typeMap['long'] = 'number';
typeMap['long[]'] = 'number[]';
typeMap['<any>'] = 'any';
typeMap['char'] = 'string';
typeMap['char[]'] = 'string[]';
typeMap['java.lang.String'] = "string";
typeMap['java.util.Date'] = 'any /*java.util.Date*/'
typeMap['java.util.List'] = 'any[] /*java.util.List*/'
typeMap['java.util.Set'] = 'any[] /*java.util.Set*/'
typeMap['java.util.Collection'] = 'any[] /*java.util.Collection*/'
typeMap['java.util.Map'] = 'Map<any, any> /*java.util.Map*/'
// typeMap['java.util.Date'] = 'any /*java.util.Date*/'
// typeMap['java.util.List'] = 'any[] /*java.util.List*/'
// typeMap['java.util.Set'] = 'any[] /*java.util.Set*/'
// typeMap['java.util.Collection'] = 'any[] /*java.util.Collection*/'
// typeMap['java.util.Map'] = 'Map<any, any> /*java.util.Map*/'
// Sponge
typeMap['Vectori'] = 'any /*Vector3i*/'
typeMap['Vectord'] = 'any /*Vector3d*/'
@@ -167,12 +177,19 @@ typeMap['Matrix4d'] = 'any /*Matrix4d*/'
function mappingType(type: string): string {
let outType = typeMap[type] || type || 'any';
outType = outType.startsWith('java.') || outType.startsWith('javax.') ? 'any' : outType;
return outType;
if (outType.indexOf('.') != -1) {
if (outType.startsWith('java.') || outType.startsWith('org.') || outType.startsWith('net.') || outType.startsWith('cn.')) {
} else {
outType = `any /*${outType}*/`
}
}
return outType.replace('function', 'function$');
}
var args = process.argv.splice(2)
const suffix = 'd.ts'
const inDir = `../docs/${args[0]}`
const outDir = "./temp";
const files = fs.readdirSync(inDir);
@@ -180,4 +197,4 @@ let index = '';
for (const file of files) {
index += `/// <reference path="./${convertJson2TypeDefiend(file, outDir)}" />\n`;
}
fs.writeFileSync(`${outDir}/index.ts`, index);
fs.writeFileSync(`${outDir}/index.${suffix}`, index);

View File

@@ -38,6 +38,37 @@ declare global {
setPrototypeOf(obj: object, prototype: object);
bindProperties(to: object, from: object);
}
namespace NodeJS {
interface Global {
logger: any;
debug: boolean;
level: string;
NashornEngineStartTime: number;
setGlobal: (key: string, value: any) => void;
noop: () => void;
console: Console;
}
}
var root: string;
var base: Core;
var ScriptEngineContextHolder: any;
function engineLoad(str: string): any;
interface Core {
getClass(name: String): any;
getProxyClass(): any;
getInstance(): any;
read(path: string): string;
save(path: string, content: string): void;
delete(path: string): void;
}
interface Console {
ex(err: Error): void;
stack(err: Error): string[];
sender(...args: any): void;
console(...args: any): void;
i18n(name: string, ...params: any[]);
}
}
export { };

View File

@@ -0,0 +1,33 @@
{
"name": "@ms/nodejs",
"version": "0.4.1",
"description": "MiaoScript nodejs 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.3"
},
"dependencies": {
"@ms/nashorn": "^0.4.0"
},
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
}

View File

@@ -0,0 +1,455 @@
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
var R = typeof Reflect === 'object' ? Reflect : null
var ReflectApply = R && typeof R.apply === 'function'
? R.apply
: function ReflectApply(target, receiver, args) {
return Function.prototype.apply.call(target, receiver, args);
}
var ReflectOwnKeys
if (R && typeof R.ownKeys === 'function') {
ReflectOwnKeys = R.ownKeys
} else if (Object.getOwnPropertySymbols) {
ReflectOwnKeys = function ReflectOwnKeys(target) {
return Object.getOwnPropertyNames(target)
// @ts-ignore
.concat(Object.getOwnPropertySymbols(target));
};
} else {
ReflectOwnKeys = function ReflectOwnKeys(target) {
return Object.getOwnPropertyNames(target);
};
}
function ProcessEmitWarning(warning) {
if (console && console.warn) console.warn(warning);
}
var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
return value !== value;
}
function EventEmitter(this: any) {
EventEmitter.init.call(this);
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._eventsCount = 0;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
var defaultMaxListeners = 10;
function checkListener(listener) {
if (typeof listener !== 'function') {
throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
}
}
Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
enumerable: true,
get: function () {
return defaultMaxListeners;
},
set: function (arg) {
if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
}
defaultMaxListeners = arg;
}
});
EventEmitter.init = function () {
// @ts-ignore
if (this._events === undefined ||
// @ts-ignore
this._events === Object.getPrototypeOf(this)._events) {
// @ts-ignore
this._events = Object.create(null);
// @ts-ignore
this._eventsCount = 0;
}
// @ts-ignore
this._maxListeners = this._maxListeners || undefined;
};
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
}
this._maxListeners = n;
return this;
};
function _getMaxListeners(that) {
if (that._maxListeners === undefined)
// @ts-ignore
return EventEmitter.defaultMaxListeners;
return that._maxListeners;
}
EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
return _getMaxListeners(this);
};
EventEmitter.prototype.emit = function emit(type) {
var args = [];
for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
var doError = (type === 'error');
var events = this._events;
if (events !== undefined)
doError = (doError && events.error === undefined);
else if (!doError)
return false;
// If there is no 'error' event listener then throw.
if (doError) {
var er;
if (args.length > 0)
er = args[0];
if (er instanceof Error) {
// Note: The comments on the `throw` lines are intentional, they show
// up in Node's output if this results in an unhandled exception.
throw er; // Unhandled 'error' event
}
// At least give some kind of context to the user
var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
// @ts-ignore
err.context = er;
throw err; // Unhandled 'error' event
}
var handler = events[type];
if (handler === undefined)
return false;
if (typeof handler === 'function') {
ReflectApply(handler, this, args);
} else {
var len = handler.length;
var listeners = arrayClone(handler, len);
for (var i = 0; i < len; ++i)
ReflectApply(listeners[i], this, args);
}
return true;
};
function _addListener(target, type, listener, prepend) {
var m;
var events;
var existing;
checkListener(listener);
events = target._events;
if (events === undefined) {
events = target._events = Object.create(null);
target._eventsCount = 0;
} else {
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (events.newListener !== undefined) {
target.emit('newListener', type,
listener.listener ? listener.listener : listener);
// Re-assign `events` because a newListener handler could have caused the
// this._events to be assigned to a new object
events = target._events;
}
existing = events[type];
}
if (existing === undefined) {
// Optimize the case of one listener. Don't need the extra array object.
existing = events[type] = listener;
++target._eventsCount;
} else {
if (typeof existing === 'function') {
// Adding the second element, need to change to array.
existing = events[type] =
prepend ? [listener, existing] : [existing, listener];
// If we've already got an array, just append.
} else if (prepend) {
existing.unshift(listener);
} else {
existing.push(listener);
}
// Check for listener leak
m = _getMaxListeners(target);
if (m > 0 && existing.length > m && !existing.warned) {
existing.warned = true;
// No error code for this since it is a Warning
// eslint-disable-next-line no-restricted-syntax
var w = new Error('Possible EventEmitter memory leak detected. ' +
existing.length + ' ' + String(type) + ' listeners ' +
'added. Use emitter.setMaxListeners() to ' +
'increase limit');
w.name = 'MaxListenersExceededWarning';
// @ts-ignore
w.emitter = target;
// @ts-ignore
w.type = type;
// @ts-ignore
w.count = existing.length;
ProcessEmitWarning(w);
}
}
return target;
}
EventEmitter.prototype.addListener = function addListener(type, listener) {
return _addListener(this, type, listener, false);
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.prependListener =
function prependListener(type, listener) {
return _addListener(this, type, listener, true);
};
function onceWrapper(this: any) {
if (!this.fired) {
this.target.removeListener(this.type, this.wrapFn);
this.fired = true;
if (arguments.length === 0)
return this.listener.call(this.target);
return this.listener.apply(this.target, arguments);
}
}
function _onceWrap(target, type, listener) {
var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
var wrapped = onceWrapper.bind(state);
// @ts-ignore
wrapped.listener = listener;
state.wrapFn = wrapped;
return wrapped;
}
EventEmitter.prototype.once = function once(type, listener) {
checkListener(listener);
this.on(type, _onceWrap(this, type, listener));
return this;
};
EventEmitter.prototype.prependOnceListener =
function prependOnceListener(type, listener) {
checkListener(listener);
this.prependListener(type, _onceWrap(this, type, listener));
return this;
};
// Emits a 'removeListener' event if and only if the listener was removed.
EventEmitter.prototype.removeListener =
function removeListener(type, listener) {
var list, events, position, i, originalListener;
checkListener(listener);
events = this._events;
if (events === undefined)
return this;
list = events[type];
if (list === undefined)
return this;
if (list === listener || list.listener === listener) {
if (--this._eventsCount === 0)
this._events = Object.create(null);
else {
delete events[type];
if (events.removeListener)
this.emit('removeListener', type, list.listener || listener);
}
} else if (typeof list !== 'function') {
position = -1;
for (i = list.length - 1; i >= 0; i--) {
if (list[i] === listener || list[i].listener === listener) {
originalListener = list[i].listener;
position = i;
break;
}
}
if (position < 0)
return this;
if (position === 0)
list.shift();
else {
spliceOne(list, position);
}
if (list.length === 1)
events[type] = list[0];
if (events.removeListener !== undefined)
this.emit('removeListener', type, originalListener || listener);
}
return this;
};
EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
EventEmitter.prototype.removeAllListeners =
function removeAllListeners(type) {
var listeners, events, i;
events = this._events;
if (events === undefined)
return this;
// not listening for removeListener, no need to emit
if (events.removeListener === undefined) {
if (arguments.length === 0) {
this._events = Object.create(null);
this._eventsCount = 0;
} else if (events[type] !== undefined) {
if (--this._eventsCount === 0)
this._events = Object.create(null);
else
delete events[type];
}
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
var keys = Object.keys(events);
var key;
for (i = 0; i < keys.length; ++i) {
key = keys[i];
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = Object.create(null);
this._eventsCount = 0;
return this;
}
listeners = events[type];
if (typeof listeners === 'function') {
this.removeListener(type, listeners);
} else if (listeners !== undefined) {
// LIFO order
for (i = listeners.length - 1; i >= 0; i--) {
this.removeListener(type, listeners[i]);
}
}
return this;
};
function _listeners(target, type, unwrap) {
var events = target._events;
if (events === undefined)
return [];
var evlistener = events[type];
if (evlistener === undefined)
return [];
if (typeof evlistener === 'function')
return unwrap ? [evlistener.listener || evlistener] : [evlistener];
return unwrap ?
unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
}
EventEmitter.prototype.listeners = function listeners(type) {
return _listeners(this, type, true);
};
EventEmitter.prototype.rawListeners = function rawListeners(type) {
return _listeners(this, type, false);
};
EventEmitter.listenerCount = function (emitter, type) {
if (typeof emitter.listenerCount === 'function') {
return emitter.listenerCount(type);
} else {
return listenerCount.call(emitter, type);
}
};
EventEmitter.prototype.listenerCount = listenerCount;
function listenerCount(this: any, type) {
var events = this._events;
if (events !== undefined) {
var evlistener = events[type];
if (typeof evlistener === 'function') {
return 1;
} else if (evlistener !== undefined) {
return evlistener.length;
}
}
return 0;
}
EventEmitter.prototype.eventNames = function eventNames() {
return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
};
function arrayClone(arr, n) {
var copy = new Array(n);
for (var i = 0; i < n; ++i)
copy[i] = arr[i];
return copy;
}
function spliceOne(list, index) {
for (; index + 1 < list.length; index++)
list[index] = list[index + 1];
list.pop();
}
function unwrapListeners(arr) {
var ret = new Array(arr.length);
for (var i = 0; i < ret.length; ++i) {
ret[i] = arr[i].listener || arr[i];
}
return ret;
}

View File

@@ -0,0 +1,101 @@
import '@ms/nashorn'
import { URL } from "url";
const Path = Java.type("java.nio.file.Path");
const JavaString = Java.type("java.lang.String");
const File = Java.type("java.io.File");
const Files = Java.type("java.nio.file.Files");
const Collector = Java.type("java.util.stream.Collector")
const separatorChar = File.separatorChar;
const StandardCopyOption = Java.type("java.nio.file.StandardCopyOption");
/**
* Valid types for path values in "fs".
*/
type PathLike = string | Buffer | URL;
function javaFile(...opts: any[]) {
if (!opts[0]) {
console.warn("文件名称不得为 undefined 或者 null !");
}
switch (opts.length) {
case 1:
var f = opts[0];
if (f instanceof File) {
return f;
}
if (typeof f === "string") {
return new File(f);
}
if (f instanceof Path) {
return f.toFile();
}
break;
default:
return new File(javaFile(opts[0]), opts[1]);
}
}
export function renameSync(oldPath: PathLike, newPath: PathLike): void {
}
export function truncateSync() {
}
export function chownSync() {
}
export function chmodSync() {
}
export function statSync() {
}
export function symlinkSync() {
}
export function readlinkSync() {
}
export function realpathSync() {
}
export function unlinkSync() {
}
export function rmdirSync() {
}
export function mkdirSync() {
}
export function mkdtempSync() {
}
export function readdirSync() {
}
export function readFileSync() {
}
export function writeFileSync() {
}
export function appendFileSync() {
}
export function watchFile() {
}
export function unwatchFile() {
}
export function existsSync() {
}
export function accessSync() {
}
export function copyFileSync() {
}

View File

@@ -0,0 +1 @@
export { }

View File

@@ -0,0 +1,626 @@
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
// @ts-ignore
var isWindows = java.lang.System.getProperties().getProperty("os.name").toUpperCase().indexOf("WINDOWS") != -1;
// @ts-ignore
var util = require('util');
// resolves . and .. elements in a path array with directory names there
// must be no slashes or device names (c:\) in the array
// (so also no leading and trailing slashes - it does not distinguish
// relative and absolute paths)
function normalizeArray(parts, allowAboveRoot) {
var res = [];
for (var i = 0; i < parts.length; i++) {
var p = parts[i];
// ignore empty parts
if (!p || p === '.')
continue;
if (p === '..') {
if (res.length && res[res.length - 1] !== '..') {
res.pop();
} else if (allowAboveRoot) {
res.push('..');
}
} else {
res.push(p);
}
}
return res;
}
// returns an array with empty elements removed from either end of the input
// array or the original array if no elements need to be removed
function trimArray(arr) {
var lastIndex = arr.length - 1;
var start = 0;
for (; start <= lastIndex; start++) {
if (arr[start])
break;
}
var end = lastIndex;
for (; end >= 0; end--) {
if (arr[end])
break;
}
if (start === 0 && end === lastIndex)
return arr;
if (start > end)
return [];
return arr.slice(start, end + 1);
}
// Regex to split a windows path into three parts: [*, device, slash,
// tail] windows-only
var splitDeviceRe =
/^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;
// Regex to split the tail part of the above into [*, dir, basename, ext]
var splitTailRe =
/^([\s\S]*?)((?:\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))(?:[\\\/]*)$/;
var win32: any = {};
// Function to split a filename into [root, dir, basename, ext]
function win32SplitPath(filename) {
// Separate device+slash from tail
var result = splitDeviceRe.exec(filename),
device = (result[1] || '') + (result[2] || ''),
tail = result[3] || '';
// Split the tail into dir, basename and extension
var result2 = splitTailRe.exec(tail),
dir = result2[1],
basename = result2[2],
ext = result2[3];
return [device, dir, basename, ext];
}
function win32StatPath(path) {
var result = splitDeviceRe.exec(path),
device = result[1] || '',
isUnc = !!device && device[1] !== ':';
return {
device: device,
isUnc: isUnc,
isAbsolute: isUnc || !!result[2], // UNC paths are always absolute
tail: result[3]
};
}
function normalizeUNCRoot(device) {
return '\\\\' + device.replace(/^[\\\/]+/, '').replace(/[\\\/]+/g, '\\');
}
// path.resolve([from ...], to)
win32.resolve = function () {
var resolvedDevice = '',
resolvedTail = '',
resolvedAbsolute = false;
for (var i = arguments.length - 1; i >= -1; i--) {
var path;
if (i >= 0) {
path = arguments[i];
} else if (!resolvedDevice) {
path = process.cwd();
} else {
// Windows has the concept of drive-specific current working
// directories. If we've resolved a drive letter but not yet an
// absolute path, get cwd for that drive. We're sure the device is not
// an unc path at this points, because unc paths are always absolute.
path = process.env['=' + resolvedDevice];
// Verify that a drive-local cwd was found and that it actually points
// to our drive. If not, default to the drive's root.
if (!path || path.substr(0, 3).toLowerCase() !==
resolvedDevice.toLowerCase() + '\\') {
path = resolvedDevice + '\\';
}
}
// Skip empty and invalid entries
if (!util.isString(path)) {
throw new TypeError('Arguments to path.resolve must be strings');
} else if (!path) {
continue;
}
var result = win32StatPath(path),
device = result.device,
isUnc = result.isUnc,
isAbsolute = result.isAbsolute,
tail = result.tail;
if (device &&
resolvedDevice &&
device.toLowerCase() !== resolvedDevice.toLowerCase()) {
// This path points to another device so it is not applicable
continue;
}
if (!resolvedDevice) {
resolvedDevice = device;
}
if (!resolvedAbsolute) {
resolvedTail = tail + '\\' + resolvedTail;
resolvedAbsolute = isAbsolute;
}
if (resolvedDevice && resolvedAbsolute) {
break;
}
}
// Convert slashes to backslashes when `resolvedDevice` points to an UNC
// root. Also squash multiple slashes into a single one where appropriate.
if (isUnc) {
resolvedDevice = normalizeUNCRoot(resolvedDevice);
}
// At this point the path should be resolved to a full absolute path,
// but handle relative paths to be safe (might happen when process.cwd()
// fails)
// Normalize the tail path
resolvedTail = normalizeArray(resolvedTail.split(/[\\\/]+/),
!resolvedAbsolute).join('\\');
return (resolvedDevice + (resolvedAbsolute ? '\\' : '') + resolvedTail) ||
'.';
};
win32.normalize = function (path) {
var result = win32StatPath(path),
device = result.device,
isUnc = result.isUnc,
isAbsolute = result.isAbsolute,
tail = result.tail,
trailingSlash = /[\\\/]$/.test(tail);
// Normalize the tail path
tail = normalizeArray(tail.split(/[\\\/]+/), !isAbsolute).join('\\');
if (!tail && !isAbsolute) {
tail = '.';
}
if (tail && trailingSlash) {
tail += '\\';
}
// Convert slashes to backslashes when `device` points to an UNC root.
// Also squash multiple slashes into a single one where appropriate.
if (isUnc) {
device = normalizeUNCRoot(device);
}
return device + (isAbsolute ? '\\' : '') + tail;
};
win32.isAbsolute = function (path) {
return win32StatPath(path).isAbsolute;
};
win32.join = function () {
var paths = [];
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (!util.isString(arg)) {
throw new TypeError('Arguments to path.join must be strings');
}
if (arg) {
paths.push(arg);
}
}
var joined = paths.join('\\');
// Make sure that the joined path doesn't start with two slashes, because
// normalize() will mistake it for an UNC path then.
//
// This step is skipped when it is very clear that the user actually
// intended to point at an UNC path. This is assumed when the first
// non-empty string arguments starts with exactly two slashes followed by
// at least one more non-slash character.
//
// Note that for normalize() to treat a path as an UNC path it needs to
// have at least 2 components, so we don't filter for that here.
// This means that the user can use join to construct UNC paths from
// a server name and a share name; for example:
// path.join('//server', 'share') -> '\\\\server\\share\')
if (!/^[\\\/]{2}[^\\\/]/.test(paths[0])) {
joined = joined.replace(/^[\\\/]{2,}/, '\\');
}
return win32.normalize(joined);
};
// path.relative(from, to)
// it will solve the relative path from 'from' to 'to', for instance:
// from = 'C:\\orandea\\test\\aaa'
// to = 'C:\\orandea\\impl\\bbb'
// The output of the function should be: '..\\..\\impl\\bbb'
win32.relative = function (from, to) {
from = win32.resolve(from);
to = win32.resolve(to);
// windows is not case sensitive
var lowerFrom = from.toLowerCase();
var lowerTo = to.toLowerCase();
var toParts = trimArray(to.split('\\'));
var lowerFromParts = trimArray(lowerFrom.split('\\'));
var lowerToParts = trimArray(lowerTo.split('\\'));
var length = Math.min(lowerFromParts.length, lowerToParts.length);
var samePartsLength = length;
for (var i = 0; i < length; i++) {
if (lowerFromParts[i] !== lowerToParts[i]) {
samePartsLength = i;
break;
}
}
if (samePartsLength == 0) {
return to;
}
var outputParts = [];
for (var i = samePartsLength; i < lowerFromParts.length; i++) {
outputParts.push('..');
}
outputParts = outputParts.concat(toParts.slice(samePartsLength));
return outputParts.join('\\');
};
win32._makeLong = function (path) {
// Note: this will *probably* throw somewhere.
if (!util.isString(path))
return path;
if (!path) {
return '';
}
var resolvedPath = win32.resolve(path);
if (/^[a-zA-Z]\:\\/.test(resolvedPath)) {
// path is local filesystem path, which needs to be converted
// to long UNC path.
return '\\\\?\\' + resolvedPath;
} else if (/^\\\\[^?.]/.test(resolvedPath)) {
// path is network UNC path, which needs to be converted
// to long UNC path.
return '\\\\?\\UNC\\' + resolvedPath.substring(2);
}
return path;
};
win32.dirname = function (path) {
var result = win32SplitPath(path),
root = result[0],
dir = result[1];
if (!root && !dir) {
// No dirname whatsoever
return '.';
}
if (dir) {
// It has a dirname, strip trailing slash
dir = dir.substr(0, dir.length - 1);
}
return root + dir;
};
win32.basename = function (path, ext) {
var f = win32SplitPath(path)[2];
// TODO: make this comparison case-insensitive on windows?
if (ext && f.substr(-1 * ext.length) === ext) {
f = f.substr(0, f.length - ext.length);
}
return f;
};
win32.extname = function (path) {
return win32SplitPath(path)[3];
};
win32.format = function (pathObject) {
if (!util.isObject(pathObject)) {
throw new TypeError(
"Parameter 'pathObject' must be an object, not " + typeof pathObject
);
}
var root = pathObject.root || '';
if (!util.isString(root)) {
throw new TypeError(
"'pathObject.root' must be a string or undefined, not " +
typeof pathObject.root
);
}
var dir = pathObject.dir;
var base = pathObject.base || '';
if (!dir) {
return base;
}
if (dir[dir.length - 1] === win32.sep) {
return dir + base;
}
return dir + win32.sep + base;
};
win32.parse = function (pathString) {
if (!util.isString(pathString)) {
throw new TypeError(
"Parameter 'pathString' must be a string, not " + typeof pathString
);
}
var allParts = win32SplitPath(pathString);
if (!allParts || allParts.length !== 4) {
throw new TypeError("Invalid path '" + pathString + "'");
}
return {
root: allParts[0],
dir: allParts[0] + allParts[1].slice(0, -1),
base: allParts[2],
ext: allParts[3],
name: allParts[2].slice(0, allParts[2].length - allParts[3].length)
};
};
win32.sep = '\\';
win32.delimiter = ';';
// Split a filename into [root, dir, basename, ext], unix version
// 'root' is just a slash, or nothing.
var splitPathRe =
/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
var posix: any = {};
function posixSplitPath(filename) {
return splitPathRe.exec(filename).slice(1);
}
// path.resolve([from ...], to)
// posix version
posix.resolve = function () {
var resolvedPath = '',
resolvedAbsolute = false;
for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
var path = (i >= 0) ? arguments[i] : process.cwd();
// Skip empty and invalid entries
if (!util.isString(path)) {
throw new TypeError('Arguments to path.resolve must be strings');
} else if (!path) {
continue;
}
resolvedPath = path + '/' + resolvedPath;
resolvedAbsolute = path[0] === '/';
}
// At this point the path should be resolved to a full absolute path, but
// handle relative paths to be safe (might happen when process.cwd() fails)
// Normalize the path
resolvedPath = normalizeArray(resolvedPath.split('/'),
!resolvedAbsolute).join('/');
return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
};
// path.normalize(path)
// posix version
posix.normalize = function (path) {
var isAbsolute = posix.isAbsolute(path),
trailingSlash = path && path[path.length - 1] === '/';
// Normalize the path
path = normalizeArray(path.split('/'), !isAbsolute).join('/');
if (!path && !isAbsolute) {
path = '.';
}
if (path && trailingSlash) {
path += '/';
}
return (isAbsolute ? '/' : '') + path;
};
// posix version
posix.isAbsolute = function (path) {
return path.charAt(0) === '/';
};
// posix version
posix.join = function () {
var path = '';
for (var i = 0; i < arguments.length; i++) {
var segment = arguments[i];
if (!util.isString(segment)) {
throw new TypeError('Arguments to path.join must be strings');
}
if (segment) {
if (!path) {
path += segment;
} else {
path += '/' + segment;
}
}
}
return posix.normalize(path);
};
// path.relative(from, to)
// posix version
posix.relative = function (from, to) {
from = posix.resolve(from).substr(1);
to = posix.resolve(to).substr(1);
var fromParts = trimArray(from.split('/'));
var toParts = trimArray(to.split('/'));
var length = Math.min(fromParts.length, toParts.length);
var samePartsLength = length;
for (var i = 0; i < length; i++) {
if (fromParts[i] !== toParts[i]) {
samePartsLength = i;
break;
}
}
var outputParts = [];
for (var i = samePartsLength; i < fromParts.length; i++) {
outputParts.push('..');
}
outputParts = outputParts.concat(toParts.slice(samePartsLength));
return outputParts.join('/');
};
posix._makeLong = function (path) {
return path;
};
posix.dirname = function (path) {
var result = posixSplitPath(path),
root = result[0],
dir = result[1];
if (!root && !dir) {
// No dirname whatsoever
return '.';
}
if (dir) {
// It has a dirname, strip trailing slash
dir = dir.substr(0, dir.length - 1);
}
return root + dir;
};
posix.basename = function (path, ext) {
var f = posixSplitPath(path)[2];
// TODO: make this comparison case-insensitive on windows?
if (ext && f.substr(-1 * ext.length) === ext) {
f = f.substr(0, f.length - ext.length);
}
return f;
};
posix.extname = function (path) {
return posixSplitPath(path)[3];
};
posix.format = function (pathObject) {
if (!util.isObject(pathObject)) {
throw new TypeError(
"Parameter 'pathObject' must be an object, not " + typeof pathObject
);
}
var root = pathObject.root || '';
if (!util.isString(root)) {
throw new TypeError(
"'pathObject.root' must be a string or undefined, not " +
typeof pathObject.root
);
}
var dir = pathObject.dir ? pathObject.dir + posix.sep : '';
var base = pathObject.base || '';
return dir + base;
};
posix.parse = function (pathString) {
if (!util.isString(pathString)) {
throw new TypeError(
"Parameter 'pathString' must be a string, not " + typeof pathString
);
}
var allParts = posixSplitPath(pathString);
if (!allParts || allParts.length !== 4) {
throw new TypeError("Invalid path '" + pathString + "'");
}
allParts[1] = allParts[1] || '';
allParts[2] = allParts[2] || '';
allParts[3] = allParts[3] || '';
return {
root: allParts[0],
dir: allParts[0] + allParts[1].slice(0, -1),
base: allParts[2],
ext: allParts[3],
name: allParts[2].slice(0, allParts[2].length - allParts[3].length)
};
};
posix.sep = '/';
posix.delimiter = ':';
if (isWindows)
module.exports = win32;
else /* posix */
module.exports = posix;
module.exports.posix = posix;
module.exports.win32 = win32;

View File

@@ -0,0 +1,81 @@
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
// If obj.hasOwnProperty has been overridden, then calling
// obj.hasOwnProperty(prop) will break.
// See: https://github.com/joyent/node/issues/1707
// @ts-ignore
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
module.exports = function (qs, sep, eq, options) {
sep = sep || '&';
eq = eq || '=';
var obj = {};
if (typeof qs !== 'string' || qs.length === 0) {
return obj;
}
var regexp = /\+/g;
qs = qs.split(sep);
var maxKeys = 1000;
if (options && typeof options.maxKeys === 'number') {
maxKeys = options.maxKeys;
}
var len = qs.length;
// maxKeys <= 0 means that we should not limit keys count
if (maxKeys > 0 && len > maxKeys) {
len = maxKeys;
}
for (var i = 0; i < len; ++i) {
var x = qs[i].replace(regexp, '%20'),
idx = x.indexOf(eq),
kstr, vstr, k, v;
if (idx >= 0) {
kstr = x.substr(0, idx);
vstr = x.substr(idx + 1);
} else {
kstr = x;
vstr = '';
}
k = decodeURIComponent(kstr);
v = decodeURIComponent(vstr);
if (!hasOwnProperty(obj, k)) {
obj[k] = v;
} else if (Array.isArray(obj[k])) {
obj[k].push(v);
} else {
obj[k] = [obj[k], v];
}
}
return obj;
};

View File

@@ -0,0 +1,64 @@
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
var stringifyPrimitive = function (v) {
switch (typeof v) {
case 'string':
return v;
case 'boolean':
return v ? 'true' : 'false';
case 'number':
return isFinite(v) ? v : '';
default:
return '';
}
};
module.exports = function (obj, sep, eq, name) {
sep = sep || '&';
eq = eq || '=';
if (obj === null) {
obj = undefined;
}
if (typeof obj === 'object') {
return Object.keys(obj).map(function (k) {
var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
if (Array.isArray(obj[k])) {
return obj[k].map(function (v) {
return ks + encodeURIComponent(stringifyPrimitive(v));
}).join(sep);
} else {
return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
}
}).filter(Boolean).join(sep);
}
if (!name) return '';
return encodeURIComponent(stringifyPrimitive(name)) + eq +
encodeURIComponent(stringifyPrimitive(obj));
};

View File

@@ -0,0 +1,4 @@
'use strict';
exports.decode = exports.parse = require('./decode');
exports.encode = exports.stringify = require('./encode');

View File

@@ -0,0 +1,747 @@
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
var punycode = require('punycode');
// @ts-ignore
var util = {
isString: function (arg) {
return typeof (arg) === 'string';
},
isObject: function (arg) {
return typeof (arg) === 'object' && arg !== null;
},
isNull: function (arg) {
return arg === null;
},
isNullOrUndefined: function (arg) {
return arg == null;
}
}
exports.parse = urlParse;
exports.resolve = urlResolve;
exports.resolveObject = urlResolveObject;
exports.format = urlFormat;
exports.Url = Url;
function Url(this: any) {
this.protocol = null;
this.slashes = null;
this.auth = null;
this.host = null;
this.port = null;
this.hostname = null;
this.hash = null;
this.search = null;
this.query = null;
this.pathname = null;
this.path = null;
this.href = null;
}
// Reference: RFC 3986, RFC 1808, RFC 2396
// define these here so at least they only have to be
// compiled once on the first module load.
var protocolPattern = /^([a-z0-9.+-]+:)/i,
portPattern = /:[0-9]*$/,
// Special case for a simple path URL
simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
// RFC 2396: characters reserved for delimiting URLs.
// We actually just auto-escape these.
delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
// RFC 2396: characters not allowed for various reasons.
unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
// Allowed by RFCs, but cause of XSS attacks. Always escape these.
autoEscape = ['\''].concat(unwise),
// Characters that are never ever allowed in a hostname.
// Note that any invalid chars are also handled, but these
// are the ones that are *expected* to be seen, so we fast-path
// them.
nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
hostEndingChars = ['/', '?', '#'],
hostnameMaxLen = 255,
hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
// protocols that can allow "unsafe" and "unwise" chars.
unsafeProtocol = {
'javascript': true,
'javascript:': true
},
// protocols that never have a hostname.
hostlessProtocol = {
'javascript': true,
'javascript:': true
},
// protocols that always contain a // bit.
slashedProtocol = {
'http': true,
'https': true,
'ftp': true,
'gopher': true,
'file': true,
'http:': true,
'https:': true,
'ftp:': true,
'gopher:': true,
'file:': true
},
querystring = require('querystring');
function urlParse(url, parseQueryString?, slashesDenoteHost?) {
if (url && util.isObject(url) && url instanceof Url) return url;
var u = new Url;
u.parse(url, parseQueryString, slashesDenoteHost);
return u;
}
Url.prototype.parse = function (url, parseQueryString, slashesDenoteHost) {
if (!util.isString(url)) {
throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
}
// Copy chrome, IE, opera backslash-handling behavior.
// Back slashes before the query string get converted to forward slashes
// See: https://code.google.com/p/chromium/issues/detail?id=25916
var queryIndex = url.indexOf('?'),
splitter =
(queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
uSplit = url.split(splitter),
slashRegex = /\\/g;
uSplit[0] = uSplit[0].replace(slashRegex, '/');
url = uSplit.join(splitter);
var rest = url;
// trim before proceeding.
// This is to support parse stuff like " http://foo.com \n"
rest = rest.trim();
if (!slashesDenoteHost && url.split('#').length === 1) {
// Try fast path regexp
var simplePath = simplePathPattern.exec(rest);
if (simplePath) {
this.path = rest;
this.href = rest;
this.pathname = simplePath[1];
if (simplePath[2]) {
this.search = simplePath[2];
if (parseQueryString) {
this.query = querystring.parse(this.search.substr(1));
} else {
this.query = this.search.substr(1);
}
} else if (parseQueryString) {
this.search = '';
this.query = {};
}
return this;
}
}
var proto: any = protocolPattern.exec(rest);
if (proto) {
proto = proto[0];
var lowerProto = proto.toLowerCase();
this.protocol = lowerProto;
rest = rest.substr(proto.length);
}
// figure out if it's got a host
// user@server is *always* interpreted as a hostname, and url
// resolution will treat //foo/bar as host=foo,path=bar because that's
// how the browser resolves relative URLs.
if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
var slashes = rest.substr(0, 2) === '//';
if (slashes && !(proto && hostlessProtocol[proto])) {
rest = rest.substr(2);
this.slashes = true;
}
}
if (!hostlessProtocol[proto] &&
(slashes || (proto && !slashedProtocol[proto]))) {
// there's a hostname.
// the first instance of /, ?, ;, or # ends the host.
//
// If there is an @ in the hostname, then non-host chars *are* allowed
// to the left of the last @ sign, unless some host-ending character
// comes *before* the @-sign.
// URLs are obnoxious.
//
// ex:
// http://a@b@c/ => user:a@b host:c
// http://a@b?@c => user:a host:c path:/?@c
// v0.12 TODO(isaacs): This is not quite how Chrome does things.
// Review our test case against browsers more comprehensively.
// find the first instance of any hostEndingChars
var hostEnd = -1;
for (var i = 0; i < hostEndingChars.length; i++) {
var hec = rest.indexOf(hostEndingChars[i]);
if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
hostEnd = hec;
}
// at this point, either we have an explicit point where the
// auth portion cannot go past, or the last @ char is the decider.
var auth, atSign;
if (hostEnd === -1) {
// atSign can be anywhere.
atSign = rest.lastIndexOf('@');
} else {
// atSign must be in auth portion.
// http://a@b/c@d => host:b auth:a path:/c@d
atSign = rest.lastIndexOf('@', hostEnd);
}
// Now we have a portion which is definitely the auth.
// Pull that off.
if (atSign !== -1) {
auth = rest.slice(0, atSign);
rest = rest.slice(atSign + 1);
this.auth = decodeURIComponent(auth);
}
// the host is the remaining to the left of the first non-host char
hostEnd = -1;
for (var i = 0; i < nonHostChars.length; i++) {
var hec = rest.indexOf(nonHostChars[i]);
if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
hostEnd = hec;
}
// if we still have not hit it, then the entire thing is a host.
if (hostEnd === -1)
hostEnd = rest.length;
this.host = rest.slice(0, hostEnd);
rest = rest.slice(hostEnd);
// pull out port.
this.parseHost();
// we've indicated that there is a hostname,
// so even if it's empty, it has to be present.
this.hostname = this.hostname || '';
// if hostname begins with [ and ends with ]
// assume that it's an IPv6 address.
var ipv6Hostname = this.hostname[0] === '[' &&
this.hostname[this.hostname.length - 1] === ']';
// validate a little.
if (!ipv6Hostname) {
var hostparts = this.hostname.split(/\./);
for (var i = 0, l = hostparts.length; i < l; i++) {
var part = hostparts[i];
if (!part) continue;
if (!part.match(hostnamePartPattern)) {
var newpart = '';
for (var j = 0, k = part.length; j < k; j++) {
if (part.charCodeAt(j) > 127) {
// we replace non-ASCII char with a temporary placeholder
// we need this to make sure size of hostname is not
// broken by replacing non-ASCII by nothing
newpart += 'x';
} else {
newpart += part[j];
}
}
// we test again with ASCII char only
if (!newpart.match(hostnamePartPattern)) {
var validParts = hostparts.slice(0, i);
var notHost = hostparts.slice(i + 1);
var bit = part.match(hostnamePartStart);
if (bit) {
validParts.push(bit[1]);
notHost.unshift(bit[2]);
}
if (notHost.length) {
rest = '/' + notHost.join('.') + rest;
}
this.hostname = validParts.join('.');
break;
}
}
}
}
if (this.hostname.length > hostnameMaxLen) {
this.hostname = '';
} else {
// hostnames are always lower case.
this.hostname = this.hostname.toLowerCase();
}
if (!ipv6Hostname) {
// IDNA Support: Returns a punycoded representation of "domain".
// It only converts parts of the domain name that
// have non-ASCII characters, i.e. it doesn't matter if
// you call it with a domain that already is ASCII-only.
this.hostname = punycode.toASCII(this.hostname);
}
var p = this.port ? ':' + this.port : '';
var h = this.hostname || '';
this.host = h + p;
this.href += this.host;
// strip [ and ] from the hostname
// the host field still retains them, though
if (ipv6Hostname) {
this.hostname = this.hostname.substr(1, this.hostname.length - 2);
if (rest[0] !== '/') {
rest = '/' + rest;
}
}
}
// now rest is set to the post-host stuff.
// chop off any delim chars.
if (!unsafeProtocol[lowerProto]) {
// First, make 100% sure that any "autoEscape" chars get
// escaped, even if encodeURIComponent doesn't think they
// need to be.
for (var i = 0, m = autoEscape.length; i < m; i++) {
var ae = autoEscape[i];
if (rest.indexOf(ae) === -1)
continue;
var esc = encodeURIComponent(ae);
if (esc === ae) {
esc = escape(ae);
}
rest = rest.split(ae).join(esc);
}
}
// chop off from the tail first.
var hash = rest.indexOf('#');
if (hash !== -1) {
// got a fragment string.
this.hash = rest.substr(hash);
rest = rest.slice(0, hash);
}
var qm = rest.indexOf('?');
if (qm !== -1) {
this.search = rest.substr(qm);
this.query = rest.substr(qm + 1);
if (parseQueryString) {
this.query = querystring.parse(this.query);
}
rest = rest.slice(0, qm);
} else if (parseQueryString) {
// no query string, but parseQueryString still requested
this.search = '';
this.query = {};
}
if (rest) this.pathname = rest;
if (slashedProtocol[lowerProto] &&
this.hostname && !this.pathname) {
this.pathname = '/';
}
//to support http.request
if (this.pathname || this.search) {
var q = this.pathname || '';
var s = this.search || '';
this.path = q + s;
}
// finally, reconstruct the href based on what has been validated.
this.href = this.format();
return this;
};
// format a parsed object into a url string
function urlFormat(obj) {
// ensure it's an object, and not a string url.
// If it's an obj, this is a no-op.
// this way, you can call url_format() on strings
// to clean up potentially wonky urls.
if (util.isString(obj)) obj = urlParse(obj);
if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
// @ts-ignore
return obj.format();
}
Url.prototype.format = function () {
var auth = this.auth || '';
if (auth) {
auth = encodeURIComponent(auth);
auth = auth.replace(/%3A/i, ':');
auth += '@';
}
var protocol = this.protocol || '',
pathname = this.pathname || '',
hash = this.hash || '',
host: any = false,
query = '';
if (this.host) {
host = auth + this.host;
} else if (this.hostname) {
host = auth + (this.hostname.indexOf(':') === -1 ?
this.hostname :
'[' + this.hostname + ']');
if (this.port) {
host += ':' + this.port;
}
}
if (this.query &&
util.isObject(this.query) &&
Object.keys(this.query).length) {
query = querystring.stringify(this.query);
}
var search = this.search || (query && ('?' + query)) || '';
if (protocol && protocol.substr(-1) !== ':') protocol += ':';
// only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
// unless they had them to begin with.
if (this.slashes ||
(!protocol || slashedProtocol[protocol]) && host !== false) {
host = '//' + (host || '');
if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
} else if (!host) {
host = '';
}
if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
if (search && search.charAt(0) !== '?') search = '?' + search;
pathname = pathname.replace(/[?#]/g, function (match) {
return encodeURIComponent(match);
});
search = search.replace('#', '%23');
return protocol + host + pathname + search + hash;
};
function urlResolve(source, relative) {
return urlParse(source, false, true).resolve(relative);
}
Url.prototype.resolve = function (relative) {
return this.resolveObject(urlParse(relative, false, true)).format();
};
function urlResolveObject(source, relative) {
if (!source) return relative;
return urlParse(source, false, true).resolveObject(relative);
}
Url.prototype.resolveObject = function (relative) {
if (util.isString(relative)) {
var rel = new Url();
rel.parse(relative, false, true);
relative = rel;
}
var result = new Url();
var tkeys = Object.keys(this);
for (var tk = 0; tk < tkeys.length; tk++) {
var tkey = tkeys[tk];
result[tkey] = this[tkey];
}
// hash is always overridden, no matter what.
// even href="" will remove it.
result.hash = relative.hash;
// if the relative url is empty, then there's nothing left to do here.
if (relative.href === '') {
result.href = result.format();
return result;
}
// hrefs like //foo/bar always cut to the protocol.
if (relative.slashes && !relative.protocol) {
// take everything except the protocol from relative
var rkeys = Object.keys(relative);
for (var rk = 0; rk < rkeys.length; rk++) {
var rkey = rkeys[rk];
if (rkey !== 'protocol')
result[rkey] = relative[rkey];
}
//urlParse appends trailing / to urls like http://www.example.com
if (slashedProtocol[result.protocol] &&
result.hostname && !result.pathname) {
result.path = result.pathname = '/';
}
result.href = result.format();
return result;
}
if (relative.protocol && relative.protocol !== result.protocol) {
// if it's a known url protocol, then changing
// the protocol does weird things
// first, if it's not file:, then we MUST have a host,
// and if there was a path
// to begin with, then we MUST have a path.
// if it is file:, then the host is dropped,
// because that's known to be hostless.
// anything else is assumed to be absolute.
if (!slashedProtocol[relative.protocol]) {
var keys = Object.keys(relative);
for (var v = 0; v < keys.length; v++) {
var k = keys[v];
result[k] = relative[k];
}
result.href = result.format();
return result;
}
result.protocol = relative.protocol;
if (!relative.host && !hostlessProtocol[relative.protocol]) {
var relPath = (relative.pathname || '').split('/');
while (relPath.length && !(relative.host = relPath.shift()));
if (!relative.host) relative.host = '';
if (!relative.hostname) relative.hostname = '';
if (relPath[0] !== '') relPath.unshift('');
if (relPath.length < 2) relPath.unshift('');
result.pathname = relPath.join('/');
} else {
result.pathname = relative.pathname;
}
result.search = relative.search;
result.query = relative.query;
result.host = relative.host || '';
result.auth = relative.auth;
result.hostname = relative.hostname || relative.host;
result.port = relative.port;
// to support http.request
if (result.pathname || result.search) {
var p = result.pathname || '';
var s = result.search || '';
result.path = p + s;
}
result.slashes = result.slashes || relative.slashes;
result.href = result.format();
return result;
}
var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
isRelAbs = (
relative.host ||
relative.pathname && relative.pathname.charAt(0) === '/'
),
mustEndAbs = (isRelAbs || isSourceAbs ||
(result.host && relative.pathname)),
removeAllDots = mustEndAbs,
srcPath = result.pathname && result.pathname.split('/') || [],
relPath = relative.pathname && relative.pathname.split('/') || [],
psychotic = result.protocol && !slashedProtocol[result.protocol];
// if the url is a non-slashed url, then relative
// links like ../.. should be able
// to crawl up to the hostname, as well. This is strange.
// result.protocol has already been set by now.
// Later on, put the first path part into the host field.
if (psychotic) {
result.hostname = '';
result.port = null;
if (result.host) {
if (srcPath[0] === '') srcPath[0] = result.host;
else srcPath.unshift(result.host);
}
result.host = '';
if (relative.protocol) {
relative.hostname = null;
relative.port = null;
if (relative.host) {
if (relPath[0] === '') relPath[0] = relative.host;
else relPath.unshift(relative.host);
}
relative.host = null;
}
mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
}
if (isRelAbs) {
// it's absolute.
result.host = (relative.host || relative.host === '') ?
relative.host : result.host;
result.hostname = (relative.hostname || relative.hostname === '') ?
relative.hostname : result.hostname;
result.search = relative.search;
result.query = relative.query;
srcPath = relPath;
// fall through to the dot-handling below.
} else if (relPath.length) {
// it's relative
// throw away the existing file, and take the new path instead.
if (!srcPath) srcPath = [];
srcPath.pop();
srcPath = srcPath.concat(relPath);
result.search = relative.search;
result.query = relative.query;
} else if (!util.isNullOrUndefined(relative.search)) {
// just pull out the search.
// like href='?foo'.
// Put this after the other two cases because it simplifies the booleans
if (psychotic) {
result.hostname = result.host = srcPath.shift();
//occationaly the auth can get stuck only in host
//this especially happens in cases like
//url.resolveObject('mailto:local1@domain1', 'local2@domain2')
var authInHost = result.host && result.host.indexOf('@') > 0 ?
result.host.split('@') : false;
if (authInHost) {
result.auth = authInHost.shift();
result.host = result.hostname = authInHost.shift();
}
}
result.search = relative.search;
result.query = relative.query;
//to support http.request
if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
result.path = (result.pathname ? result.pathname : '') +
(result.search ? result.search : '');
}
result.href = result.format();
return result;
}
if (!srcPath.length) {
// no path at all. easy.
// we've already handled the other stuff above.
result.pathname = null;
//to support http.request
if (result.search) {
result.path = '/' + result.search;
} else {
result.path = null;
}
result.href = result.format();
return result;
}
// if a url ENDs in . or .., then it must get a trailing slash.
// however, if it ends in anything else non-slashy,
// then it must NOT get a trailing slash.
var last = srcPath.slice(-1)[0];
var hasTrailingSlash = (
(result.host || relative.host || srcPath.length > 1) &&
(last === '.' || last === '..') || last === '');
// strip single dots, resolve double dots to parent dir
// if the path tries to go above the root, `up` ends up > 0
var up = 0;
for (var i = srcPath.length; i >= 0; i--) {
last = srcPath[i];
if (last === '.') {
srcPath.splice(i, 1);
} else if (last === '..') {
srcPath.splice(i, 1);
up++;
} else if (up) {
srcPath.splice(i, 1);
up--;
}
}
// if the path is allowed to go above the root, restore leading ..s
if (!mustEndAbs && !removeAllDots) {
for (; up--; up) {
srcPath.unshift('..');
}
}
if (mustEndAbs && srcPath[0] !== '' &&
(!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
srcPath.unshift('');
}
if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
srcPath.push('');
}
var isAbsolute = srcPath[0] === '' ||
(srcPath[0] && srcPath[0].charAt(0) === '/');
// put the host back
if (psychotic) {
result.hostname = result.host = isAbsolute ? '' :
srcPath.length ? srcPath.shift() : '';
//occationaly the auth can get stuck only in host
//this especially happens in cases like
//url.resolveObject('mailto:local1@domain1', 'local2@domain2')
var authInHost = result.host && result.host.indexOf('@') > 0 ?
result.host.split('@') : false;
if (authInHost) {
result.auth = authInHost.shift();
result.host = result.hostname = authInHost.shift();
}
}
mustEndAbs = mustEndAbs || (result.host && srcPath.length);
if (mustEndAbs && !isAbsolute) {
srcPath.unshift('');
}
if (!srcPath.length) {
result.pathname = null;
result.path = null;
} else {
result.pathname = srcPath.join('/');
}
//to support request.http
if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
result.path = (result.pathname ? result.pathname : '') +
(result.search ? result.search : '');
}
result.auth = relative.auth || result.auth;
result.slashes = result.slashes || relative.slashes;
result.href = result.format();
return result;
};
Url.prototype.parseHost = function () {
var host = this.host;
var port: any = portPattern.exec(host);
if (port) {
port = port[0];
if (port !== ':') {
this.port = port.substr(1);
}
host = host.substr(0, host.length - port.length);
}
if (host) this.hostname = host;
};

View File

@@ -0,0 +1,727 @@
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors ||
function getOwnPropertyDescriptors(obj) {
var keys = Object.keys(obj);
var descriptors = {};
for (var i = 0; i < keys.length; i++) {
descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]);
}
return descriptors;
};
var formatRegExp = /%[sdj%]/g;
exports.format = function (f) {
if (!isString(f)) {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
// @ts-ignore
var str = String(f).replace(formatRegExp, function (x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j':
try {
return JSON.stringify(args[i++]);
} catch (_) {
return '[Circular]';
}
default:
return x;
}
});
for (var x = args[i]; i < len; x = args[++i]) {
if (isNull(x) || !isObject(x)) {
str += ' ' + x;
} else {
str += ' ' + inspect(x);
}
}
return str;
};
// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function (fn, msg) {
// @ts-ignore
if (typeof process !== 'undefined' && process.noDeprecation === true) {
return fn;
}
// Allow for deprecating things in the process of starting up.
if (typeof process === 'undefined') {
return function () {
// @ts-ignore
return exports.deprecate(fn, msg).apply(this, arguments);
};
}
var warned = false;
function deprecated() {
if (!warned) {
// @ts-ignore
if (process.throwDeprecation) {
throw new Error(msg);
// @ts-ignore
} else if (process.traceDeprecation) {
console.trace(msg);
} else {
console.error(msg);
}
warned = true;
}
// @ts-ignore
return fn.apply(this, arguments);
}
return deprecated;
};
var debugs = {};
var debugEnvRegex = /^$/;
if (process.env.NODE_DEBUG) {
var debugEnv = process.env.NODE_DEBUG;
debugEnv = debugEnv.replace(/[|\\{}()[\]^$+?.]/g, '\\$&')
.replace(/\*/g, '.*')
.replace(/,/g, '$|^')
.toUpperCase();
debugEnvRegex = new RegExp('^' + debugEnv + '$', 'i');
}
exports.debuglog = function (set) {
set = set.toUpperCase();
if (!debugs[set]) {
if (debugEnvRegex.test(set)) {
var pid = process.pid;
debugs[set] = function () {
var msg = exports.format.apply(exports, arguments);
console.error('%s %d: %s', set, pid, msg);
};
} else {
debugs[set] = function () { };
}
}
return debugs[set];
};
/**
* Echos the value of a value. Trys to print the value out
* in the best way possible given the different types.
*
* @param {Object} obj The object to print out.
* @param {Object} opts Optional options object that alters the output.
*/
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts?) {
// default options
var ctx: any = {
seen: [],
stylize: stylizeNoColor
};
// legacy...
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) {
// legacy...
ctx.showHidden = opts;
} else if (opts) {
// got an "options" object
exports._extend(ctx, opts);
}
// set default options
if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
if (isUndefined(ctx.depth)) ctx.depth = 2;
if (isUndefined(ctx.colors)) ctx.colors = false;
if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
if (ctx.colors) ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
'bold': [1, 22],
'italic': [3, 23],
'underline': [4, 24],
'inverse': [7, 27],
'white': [37, 39],
'grey': [90, 39],
'black': [30, 39],
'blue': [34, 39],
'cyan': [36, 39],
'green': [32, 39],
'magenta': [35, 39],
'red': [31, 39],
'yellow': [33, 39]
};
// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
'special': 'cyan',
'number': 'yellow',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red'
};
function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
if (style) {
return '\u001b[' + inspect.colors[style][0] + 'm' + str +
'\u001b[' + inspect.colors[style][1] + 'm';
} else {
return str;
}
}
function stylizeNoColor(str, styleType) {
return str;
}
function arrayToHash(array) {
var hash = {};
array.forEach(function (val, idx) {
hash[val] = true;
});
return hash;
}
function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (ctx.customInspect &&
value &&
isFunction(value.inspect) &&
// Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
}
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
// Look up the keys of the object.
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
}
// IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (isError(value)
&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
return formatError(value);
}
// Some type of object without properties can be shortcutted.
if (keys.length === 0) {
if (isFunction(value)) {
var name = value.name ? ': ' + value.name : '';
return ctx.stylize('[Function' + name + ']', 'special');
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date');
}
if (isError(value)) {
return formatError(value);
}
}
var base = '', array = false, braces = ['{', '}'];
// Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = ['[', ']'];
}
// Make functions say that they are functions
if (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']';
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
if (isError(value)) {
base = ' ' + formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function (key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
}
function formatPrimitive(ctx, value) {
if (isUndefined(value))
return ctx.stylize('undefined', 'undefined');
if (isString(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value))
return ctx.stylize('' + value, 'number');
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.
if (isNull(value))
return ctx.stylize('null', 'null');
}
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(i), true));
} else {
output.push('');
}
}
keys.forEach(function (key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true));
}
});
return output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str, desc;
desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
if (desc.get) {
if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special');
} else {
str = ctx.stylize('[Getter]', 'special');
}
} else {
if (desc.set) {
str = ctx.stylize('[Setter]', 'special');
}
}
if (!hasOwnProperty(visibleKeys, key)) {
name = '[' + key + ']';
}
if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null);
} else {
str = formatValue(ctx, desc.value, recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (array) {
str = str.split('\n').map(function (line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function (line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = ctx.stylize('[Circular]', 'special');
}
}
if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = ctx.stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
name = ctx.stylize(name, 'string');
}
}
return name + ': ' + str;
}
function reduceToSingleString(output, base, braces) {
var numLinesEst = 0;
var length = output.reduce(function (prev, cur) {
numLinesEst++;
if (cur.indexOf('\n') >= 0) numLinesEst++;
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
}, 0);
if (length > 60) {
return braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
}
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
exports.types = require('./support/types');
function isArray(ar) {
return Array.isArray(ar);
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
exports.types.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
exports.types.isDate = isDate;
function isError(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
exports.types.isNativeError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = require('./support/isBuffer');
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'];
// 26 Feb 16:19:34
function timestamp() {
var d = new Date();
var time = [pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
}
// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function () {
console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};
/**
* Inherit the prototype methods from one constructor into another.
*
* The Function.prototype.inherits from lang.js rewritten as a standalone
* function (not on Function.prototype). NOTE: If this file is to be loaded
* during bootstrapping this function needs to be rewritten using some native
* functions as prototype setup using normal JavaScript does not work as
* expected during bootstrapping (see mirror.js in r114903).
*
* @param {function} ctor Constructor function which needs to inherit the
* prototype.
* @param {function} superCtor Constructor function to inherit prototype from.
*/
exports.inherits = require('inherits');
exports._extend = function (origin, add) {
// Don't do anything if add isn't an object
if (!add || !isObject(add)) return origin;
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
// @ts-ignore
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
var kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined;
exports.promisify = function promisify(original) {
if (typeof original !== 'function')
throw new TypeError('The "original" argument must be of type Function');
if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) {
// @ts-ignore
var fn = original[kCustomPromisifiedSymbol];
if (typeof fn !== 'function') {
throw new TypeError('The "util.promisify.custom" argument must be of type Function');
}
Object.defineProperty(fn, kCustomPromisifiedSymbol, {
value: fn, enumerable: false, writable: false, configurable: true
});
return fn;
}
// @ts-ignore
function fn() {
var promiseResolve, promiseReject;
var promise = new Promise(function (resolve, reject) {
promiseResolve = resolve;
promiseReject = reject;
});
var args = [];
for (var i = 0; i < arguments.length; i++) {
args.push(arguments[i]);
}
args.push(function (err, value) {
if (err) {
promiseReject(err);
} else {
promiseResolve(value);
}
});
try {
// @ts-ignore
original.apply(this, args);
} catch (err) {
promiseReject(err);
}
return promise;
}
Object.setPrototypeOf(fn, Object.getPrototypeOf(original));
if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, {
value: fn, enumerable: false, writable: false, configurable: true
});
return Object.defineProperties(
fn,
getOwnPropertyDescriptors(original)
);
}
exports.promisify.custom = kCustomPromisifiedSymbol
function callbackifyOnRejected(reason, cb) {
// `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M).
// Because `null` is a special error value in callbacks which means "no error
// occurred", we error-wrap so the callback consumer can distinguish between
// "the promise rejected with null" or "the promise fulfilled with undefined".
if (!reason) {
var newReason = new Error('Promise was rejected with a falsy value');
// @ts-ignore
newReason.reason = reason;
reason = newReason;
}
return cb(reason);
}
function callbackify(original) {
if (typeof original !== 'function') {
throw new TypeError('The "original" argument must be of type Function');
}
// We DO NOT return the promise as it gives the user a false sense that
// the promise is actually somehow related to the callback's execution
// and that the callback throwing will reject the promise.
function callbackified() {
var args = [];
for (var i = 0; i < arguments.length; i++) {
args.push(arguments[i]);
}
var maybeCb = args.pop();
if (typeof maybeCb !== 'function') {
throw new TypeError('The last argument must be of type Function');
}
// @ts-ignore
var self = this;
var cb = function () {
return maybeCb.apply(self, arguments);
};
// In true node style we process the callback on `nextTick` with all the
// implications (stack, `uncaughtException`, `async_hooks`)
// @ts-ignore
original.apply(this, args)
.then(function (ret) { process.nextTick(cb.bind(null, null, ret)) },
function (rej) { process.nextTick(callbackifyOnRejected.bind(null, rej, cb)) });
}
Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original));
Object.defineProperties(callbackified,
getOwnPropertyDescriptors(original));
return callbackified;
}
exports.callbackify = callbackify;

View File

@@ -0,0 +1,3 @@
module.exports = function isBuffer(arg) {
return arg instanceof Buffer;
}

View File

@@ -0,0 +1,6 @@
module.exports = function isBuffer(arg) {
return arg && typeof arg === 'object'
&& typeof arg.copy === 'function'
&& typeof arg.fill === 'function'
&& typeof arg.readUInt8 === 'function';
}

View File

@@ -0,0 +1,424 @@
// Currently in sync with Node.js lib/internal/util/types.js
// https://github.com/nodejs/node/commit/112cc7c27551254aa2b17098fb774867f05ed0d9
'use strict';
var isBuffer = require('./isBuffer');
var isArgumentsObject = require('is-arguments');
var isGeneratorFunction = require('is-generator-function');
function uncurryThis(f) {
return f.call.bind(f);
}
var BigIntSupported = typeof BigInt !== 'undefined';
var SymbolSupported = typeof Symbol !== 'undefined';
var SymbolToStringTagSupported = SymbolSupported && typeof Symbol.toStringTag !== 'undefined';
var Uint8ArraySupported = typeof Uint8Array !== 'undefined';
var ArrayBufferSupported = typeof ArrayBuffer !== 'undefined';
if (Uint8ArraySupported && SymbolToStringTagSupported) {
var TypedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);
var TypedArrayProto_toStringTag =
uncurryThis(
Object.getOwnPropertyDescriptor(TypedArrayPrototype,
Symbol.toStringTag).get);
}
var ObjectToString = uncurryThis(Object.prototype.toString);
var numberValue = uncurryThis(Number.prototype.valueOf);
var stringValue = uncurryThis(String.prototype.valueOf);
var booleanValue = uncurryThis(Boolean.prototype.valueOf);
if (BigIntSupported) {
var bigIntValue = uncurryThis(BigInt.prototype.valueOf);
}
if (SymbolSupported) {
var symbolValue = uncurryThis(Symbol.prototype.valueOf);
}
function checkBoxedPrimitive(value, prototypeValueOf) {
if (typeof value !== 'object') {
return false;
}
try {
prototypeValueOf(value);
return true;
} catch (e) {
return false;
}
}
exports.isArgumentsObject = isArgumentsObject;
exports.isGeneratorFunction = isGeneratorFunction;
// Taken from here and modified for better browser support
// https://github.com/sindresorhus/p-is-promise/blob/cda35a513bda03f977ad5cde3a079d237e82d7ef/index.js
function isPromise(input) {
return (
(
typeof Promise !== 'undefined' &&
input instanceof Promise
) ||
(
input !== null &&
typeof input === 'object' &&
typeof input.then === 'function' &&
typeof input.catch === 'function'
)
);
}
exports.isPromise = isPromise;
function isArrayBufferView(value) {
if (ArrayBufferSupported && ArrayBuffer.isView) {
return ArrayBuffer.isView(value);
}
return (
isTypedArray(value) ||
isDataView(value)
);
}
exports.isArrayBufferView = isArrayBufferView;
function isTypedArray(value) {
if (Uint8ArraySupported && SymbolToStringTagSupported) {
return TypedArrayProto_toStringTag(value) !== undefined;
} else {
return (
isUint8Array(value) ||
isUint8ClampedArray(value) ||
isUint16Array(value) ||
isUint32Array(value) ||
isInt8Array(value) ||
isInt16Array(value) ||
isInt32Array(value) ||
isFloat32Array(value) ||
isFloat64Array(value) ||
isBigInt64Array(value) ||
isBigUint64Array(value)
);
}
}
exports.isTypedArray = isTypedArray;
function isUint8Array(value) {
if (Uint8ArraySupported && SymbolToStringTagSupported) {
return TypedArrayProto_toStringTag(value) === 'Uint8Array';
} else {
return (
ObjectToString(value) === '[object Uint8Array]' ||
// If it's a Buffer instance _and_ has a `.buffer` property,
// this is an ArrayBuffer based buffer; thus it's an Uint8Array
// (Old Node.js had a custom non-Uint8Array implementation)
isBuffer(value) && value.buffer !== undefined
);
}
}
exports.isUint8Array = isUint8Array;
function isUint8ClampedArray(value) {
if (Uint8ArraySupported && SymbolToStringTagSupported) {
return TypedArrayProto_toStringTag(value) === 'Uint8ClampedArray';
} else {
return ObjectToString(value) === '[object Uint8ClampedArray]';
}
}
exports.isUint8ClampedArray = isUint8ClampedArray;
function isUint16Array(value) {
if (Uint8ArraySupported && SymbolToStringTagSupported) {
return TypedArrayProto_toStringTag(value) === 'Uint16Array';
} else {
return ObjectToString(value) === '[object Uint16Array]';
}
}
exports.isUint16Array = isUint16Array;
function isUint32Array(value) {
if (Uint8ArraySupported && SymbolToStringTagSupported) {
return TypedArrayProto_toStringTag(value) === 'Uint32Array';
} else {
return ObjectToString(value) === '[object Uint32Array]';
}
}
exports.isUint32Array = isUint32Array;
function isInt8Array(value) {
if (Uint8ArraySupported && SymbolToStringTagSupported) {
return TypedArrayProto_toStringTag(value) === 'Int8Array';
} else {
return ObjectToString(value) === '[object Int8Array]';
}
}
exports.isInt8Array = isInt8Array;
function isInt16Array(value) {
if (Uint8ArraySupported && SymbolToStringTagSupported) {
return TypedArrayProto_toStringTag(value) === 'Int16Array';
} else {
return ObjectToString(value) === '[object Int16Array]';
}
}
exports.isInt16Array = isInt16Array;
function isInt32Array(value) {
if (Uint8ArraySupported && SymbolToStringTagSupported) {
return TypedArrayProto_toStringTag(value) === 'Int32Array';
} else {
return ObjectToString(value) === '[object Int32Array]';
}
}
exports.isInt32Array = isInt32Array;
function isFloat32Array(value) {
if (Uint8ArraySupported && SymbolToStringTagSupported) {
return TypedArrayProto_toStringTag(value) === 'Float32Array';
} else {
return ObjectToString(value) === '[object Float32Array]';
}
}
exports.isFloat32Array = isFloat32Array;
function isFloat64Array(value) {
if (Uint8ArraySupported && SymbolToStringTagSupported) {
return TypedArrayProto_toStringTag(value) === 'Float64Array';
} else {
return ObjectToString(value) === '[object Float64Array]';
}
}
exports.isFloat64Array = isFloat64Array;
function isBigInt64Array(value) {
if (Uint8ArraySupported && SymbolToStringTagSupported) {
return TypedArrayProto_toStringTag(value) === 'BigInt64Array';
} else {
return ObjectToString(value) === '[object BigInt64Array]';
}
}
exports.isBigInt64Array = isBigInt64Array;
function isBigUint64Array(value) {
if (Uint8ArraySupported && SymbolToStringTagSupported) {
return TypedArrayProto_toStringTag(value) === 'BigUint64Array';
} else {
return ObjectToString(value) === '[object BigUint64Array]';
}
}
exports.isBigUint64Array = isBigUint64Array;
function isMapToString(value) {
return ObjectToString(value) === '[object Map]';
}
isMapToString.working = (
typeof Map !== 'undefined' &&
isMapToString(new Map())
);
function isMap(value) {
if (typeof Map === 'undefined') {
return false;
}
return isMapToString.working
? isMapToString(value)
: value instanceof Map;
}
exports.isMap = isMap;
function isSetToString(value) {
return ObjectToString(value) === '[object Set]';
}
isSetToString.working = (
typeof Set !== 'undefined' &&
isSetToString(new Set())
);
function isSet(value) {
if (typeof Set === 'undefined') {
return false;
}
return isSetToString.working
? isSetToString(value)
: value instanceof Set;
}
exports.isSet = isSet;
function isWeakMapToString(value) {
return ObjectToString(value) === '[object WeakMap]';
}
isWeakMapToString.working = (
typeof WeakMap !== 'undefined' &&
isWeakMapToString(new WeakMap())
);
function isWeakMap(value) {
if (typeof WeakMap === 'undefined') {
return false;
}
return isWeakMapToString.working
? isWeakMapToString(value)
: value instanceof WeakMap;
}
exports.isWeakMap = isWeakMap;
function isWeakSetToString(value) {
return ObjectToString(value) === '[object WeakSet]';
}
isWeakSetToString.working = (
typeof WeakSet !== 'undefined' &&
isWeakSetToString(new WeakSet())
);
function isWeakSet(value) {
return isWeakSetToString(value);
if (typeof WeakSet === 'undefined') {
return false;
}
return isWeakSetToString.working
? isWeakSetToString(value)
: value instanceof WeakSet;
}
exports.isWeakSet = isWeakSet;
function isArrayBufferToString(value) {
return ObjectToString(value) === '[object ArrayBuffer]';
}
isArrayBufferToString.working = (
typeof ArrayBuffer !== 'undefined' &&
// @ts-ignore
isArrayBufferToString(new ArrayBuffer())
);
function isArrayBuffer(value) {
if (typeof ArrayBuffer === 'undefined') {
return false;
}
return isArrayBufferToString.working
? isArrayBufferToString(value)
: value instanceof ArrayBuffer;
}
exports.isArrayBuffer = isArrayBuffer;
function isDataViewToString(value) {
return ObjectToString(value) === '[object DataView]';
}
isDataViewToString.working = (
typeof ArrayBuffer !== 'undefined' &&
typeof DataView !== 'undefined' &&
isDataViewToString(new DataView(new ArrayBuffer(1), 0, 1))
);
function isDataView(value) {
if (typeof DataView === 'undefined') {
return false;
}
return isDataViewToString.working
? isDataViewToString(value)
: value instanceof DataView;
}
exports.isDataView = isDataView;
function isSharedArrayBufferToString(value) {
return ObjectToString(value) === '[object SharedArrayBuffer]';
}
isSharedArrayBufferToString.working = (
typeof SharedArrayBuffer !== 'undefined' &&
// @ts-ignore
isSharedArrayBufferToString(new SharedArrayBuffer())
);
function isSharedArrayBuffer(value) {
if (typeof SharedArrayBuffer === 'undefined') {
return false;
}
return isSharedArrayBufferToString.working
? isSharedArrayBufferToString(value)
: value instanceof SharedArrayBuffer;
}
exports.isSharedArrayBuffer = isSharedArrayBuffer;
function isAsyncFunction(value) {
return ObjectToString(value) === '[object AsyncFunction]';
}
exports.isAsyncFunction = isAsyncFunction;
function isMapIterator(value) {
return ObjectToString(value) === '[object Map Iterator]';
}
exports.isMapIterator = isMapIterator;
function isSetIterator(value) {
return ObjectToString(value) === '[object Set Iterator]';
}
exports.isSetIterator = isSetIterator;
function isGeneratorObject(value) {
return ObjectToString(value) === '[object Generator]';
}
exports.isGeneratorObject = isGeneratorObject;
function isWebAssemblyCompiledModule(value) {
return ObjectToString(value) === '[object WebAssembly.Module]';
}
exports.isWebAssemblyCompiledModule = isWebAssemblyCompiledModule;
function isNumberObject(value) {
return checkBoxedPrimitive(value, numberValue);
}
exports.isNumberObject = isNumberObject;
function isStringObject(value) {
return checkBoxedPrimitive(value, stringValue);
}
exports.isStringObject = isStringObject;
function isBooleanObject(value) {
return checkBoxedPrimitive(value, booleanValue);
}
exports.isBooleanObject = isBooleanObject;
function isBigIntObject(value) {
return BigIntSupported && checkBoxedPrimitive(value, bigIntValue);
}
exports.isBigIntObject = isBigIntObject;
function isSymbolObject(value) {
return SymbolSupported && checkBoxedPrimitive(value, symbolValue);
}
exports.isSymbolObject = isSymbolObject;
function isBoxedPrimitive(value) {
return (
isNumberObject(value) ||
isStringObject(value) ||
isBooleanObject(value) ||
isBigIntObject(value) ||
isSymbolObject(value)
);
}
exports.isBoxedPrimitive = isBoxedPrimitive;
function isAnyArrayBuffer(value) {
return Uint8ArraySupported && (
isArrayBuffer(value) ||
isSharedArrayBuffer(value)
);
}
exports.isAnyArrayBuffer = isAnyArrayBuffer;
['isProxy', 'isExternal', 'isModuleNamespaceObject'].forEach(function (method) {
Object.defineProperty(exports, method, {
enumerable: false,
value: function () {
throw new Error(method + ' is not supported in userland');
}
});
});

View File

@@ -0,0 +1,7 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"baseUrl": "src",
"outDir": "dist"
}
}

View File

@@ -0,0 +1,34 @@
{
"name": "@ms/nukkit",
"version": "0.4.1",
"description": "MiaoScript nukkit package",
"keywords": [
"miaoscript",
"minecraft",
"bukkit",
"sponge"
],
"author": "MiaoWoo <admin@yumc.pw>",
"homepage": "https://github.com/circlecloud/ms.git",
"license": "ISC",
"main": "dist/index.js",
"publishConfig": {
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
},
"scripts": {
"clean": "rimraf dist",
"watch": "tsc --watch",
"build": "yarn clean && tsc",
"test": "echo \"Error: run tests from root\" && exit 1"
},
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.8.3"
},
"dependencies": {
"@ms/api": "^0.4.1",
"@ms/common": "^0.4.0",
"@ms/container": "^0.4.0"
}
}

View 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
}
}

View 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(' '));
}
}

View 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);
}
}

View 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);
}

View File

@@ -0,0 +1,48 @@
import { server } from '@ms/api'
import { provideSingleton } from '@ms/container';
let Nukkit: cn.nukkit.Server = base.getInstance().getServer();
const File = Java.type("java.io.File");
@provideSingleton(server.Server)
export class NukkitServer implements server.Server {
private pluginsFolder: string;
constructor() {
this.pluginsFolder = new File(base.getInstance().getClass().getProtectionDomain().getCodeSource().getLocation().getPath()).getParentFile().getCanonicalPath()
}
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)
}
getPluginsFolder(): string {
return this.pluginsFolder;
}
getNativePluginManager() {
return Nukkit.getPluginManager() as any;
}
sendJson(sender: string | any, json: object | string): void {
throw new Error("Method not implemented.");
}
}

View 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;
}
}

View File

@@ -0,0 +1,7 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"baseUrl": "src",
"outDir": "dist"
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@ms/ployfill",
"version": "0.1.0",
"version": "0.4.1",
"description": "MiaoScript ployfill package",
"author": "MiaoWoo <admin@yumc.pw>",
"homepage": "https://github.com/circlecloud/ms.git",
@@ -12,16 +12,18 @@
},
"scripts": {
"clean": "rimraf dist",
"watch": "npx tsc --watch",
"build": "yarn clean && npx tsc",
"watch": "tsc --watch",
"build": "yarn clean && tsc",
"test": "echo \"Error: run tests from root\" && exit 1"
},
"dependencies": {
"@ms/nashorn": "^0.1.0"
"@ms/i18n": "^0.4.1",
"@ms/nashorn": "^0.4.0",
"core-js": "^3.6.4"
},
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.0",
"typescript": "^3.6.2"
"rimraf": "^3.0.2",
"typescript": "^3.8.3"
}
}

View 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
})

View File

@@ -1,7 +1,12 @@
import { XMLHttpRequest as xhr } from './xml-http-request'
/// <reference types="@ms/nashorn" />
var XMLHttpRequest = xhr;
export {
XMLHttpRequest
}
import i18n from '@ms/i18n'
let ployfillStartTime = new Date().getTime();
i18n.initialize();
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 });

View 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]
})
}
}

View File

@@ -0,0 +1,141 @@
(function nashornEventLoopMain(context) {
'use strict';
var Thread = Java.type('java.lang.Thread');
var Phaser = Java.type('java.util.concurrent.Phaser');
var ArrayDeque = Java.type('java.util.ArrayDeque');
var HashMap = Java.type('java.util.HashMap');
var TimeUnit = Java.type("java.util.concurrent.TimeUnit");
var Runnable = Java.type('java.lang.Runnable');
var globalTimerId;
var timerMap;
var eventLoop;
var phaser = new Phaser();
// __NASHORN_POLYFILL_TIMER__ type is ScheduledExecutorService
var scheduler = context.__NASHORN_POLYFILL_TIMER__;
resetEventLoop();
// console.log('main javasript thread ' + Thread.currentThread().getName());
function resetEventLoop() {
globalTimerId = 1;
if (timerMap) {
timerMap.forEach(function(key, value) {
value.cancel(true);
})
}
timerMap = new HashMap();
eventLoop = new ArrayDeque();
}
function waitForMessages() {
phaser.register();
var wait = !(eventLoop.size() === 0);
phaser.arriveAndDeregister();
return wait;
}
function processNextMessages() {
var remaining = 1;
while (remaining) {
phaser.register();
var message = eventLoop.removeFirst();
remaining = eventLoop.size();
phaser.arriveAndDeregister();
var fn = message.fn;
var args = message.args;
try {
fn.apply(context, args);
} catch (e) {
console.trace(e);
console.trace(fn);
console.trace(args);
}
}
}
context.nashornEventLoop = {
process: function() {
while (waitForMessages()) {
processNextMessages()
}
},
reset: resetEventLoop
};
function createRunnable(fn, timerId, args, repeated) {
return new Runnable({
run: function() {
try {
var phase = phaser.register();
eventLoop.addLast({
fn: fn,
args: args
});
} catch (e) {
console.trace(e);
} finally {
if (!repeated) timerMap.remove(timerId);
phaser.arriveAndDeregister();
}
}
})
}
var setTimeout = function(fn, millis /* [, args...] */) {
var args = [].slice.call(arguments, 2, arguments.length);
var timerId = globalTimerId++;
var runnable = createRunnable(fn, timerId, args, false);
var task = scheduler.schedule(runnable, millis, TimeUnit.MILLISECONDS);
timerMap.put(timerId, task);
return timerId;
};
var setImmediate = function(fn /* [, args...] */) {
var args = [].slice.call(arguments, 1, arguments.length);
// @ts-ignore
return setTimeout(fn, 0, args);
}
var clearImmediate = function(timerId) {
clearTimeout(timerId);
}
var clearTimeout = function(timerId) {
var task = timerMap.get(timerId);
if (task) {
task.cancel(true);
timerMap.remove(timerId);
}
};
var setInterval = function(fn, delay /* [, args...] */) {
var args = [].slice.call(arguments, 2, arguments.length);
var timerId = globalTimerId++;
var runnable = createRunnable(fn, timerId, args, true);
var task = scheduler.scheduleWithFixedDelay(runnable, delay, delay, TimeUnit.MILLISECONDS);
timerMap.put(timerId, task);
return timerId;
};
var clearInterval = function(timerId) {
clearTimeout(timerId);
};
context.setTimeout = setTimeout;
context.clearTimeout = clearTimeout;
context.setImmediate = setImmediate;
context.clearImmediate = clearImmediate;
context.setInterval = setInterval;
context.clearInterval = clearInterval;
// @ts-ignore
})(typeof global !== "undefined" && global || typeof self !== "undefined" && self || this);

View File

@@ -114,7 +114,7 @@ export class XMLHttpRequest {
return this._statusText;
}
get response() {
return JSON.parse(this._response);
return this._response ? JSON.parse(this._response) : this._response;
}
get responseText() {
return this._response;
@@ -174,6 +174,16 @@ export class XMLHttpRequest {
if (!this._async) { future.get() }
return future;
}
get() {
switch (this._responseType) {
case "json":
return this.response;
case "text":
return this.responseText;
default:
throw Error(`Unsupport ResponseType: ${this._responseType} !`)
}
}
abort() {
this._connection.disconnect();
this.onabort();
@@ -182,7 +192,6 @@ export class XMLHttpRequest {
private _send(body?: string | object) {
try {
this._connection.connect();
this.onloadstart();
if (body) {
let bodyType = Object.prototype.toString.call(body);
@@ -204,14 +213,6 @@ export class XMLHttpRequest {
this._response = this.readOutput(this._connection.getErrorStream());
}
this.onloadend();
switch (this._responseType) {
case "json":
return this.response;
case "text":
return this.responseText;
default:
throw Error(`Unsupport ResponseType: ${this._responseType} !`)
}
} catch (ex) {
if (ex instanceof SocketTimeoutException && this.ontimeout) {
return this.ontimeout(ex)

View File

@@ -1,6 +1,6 @@
{
"name": "@ms/plugin",
"version": "0.1.1",
"version": "0.4.1",
"description": "MiaoScript api package",
"keywords": [
"miaoscript",
@@ -17,18 +17,21 @@
},
"scripts": {
"clean": "rimraf dist",
"watch": "npx tsc --watch",
"build": "yarn clean && npx tsc",
"watch": "tsc --watch",
"build": "yarn clean && tsc",
"test": "echo \"Error: run tests from root\" && exit 1"
},
"devDependencies": {
"@types/js-yaml": "^3.12.2",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.0",
"typescript": "^3.6.2"
"rimraf": "^3.0.2",
"typescript": "^3.8.3"
},
"dependencies": {
"@ms/api": "^0.1.1",
"@ms/common": "^0.1.0",
"@ms/container": "^0.1.0"
"@ms/api": "^0.4.1",
"@ms/common": "^0.4.0",
"@ms/container": "^0.4.0",
"@ms/i18n": "^0.4.1",
"js-yaml": "^3.13.1"
}
}

View 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()

View File

@@ -3,4 +3,5 @@ export const METADATA_KEY = {
cmd: "@ms/plugin:cmd",
tab: "@ms/plugin:tab",
listener: "@ms/plugin:listener",
config: "@ms/plugin:config",
};

View File

@@ -1,7 +1,7 @@
import { injectable, decorate } from "@ms/container";
import { interfaces } from './interfaces'
import { METADATA_KEY } from './constants'
import { getPluginMetadatas, getPluginCommandMetadata, getPluginListenerMetadata, getPluginTabCompleterMetadata } from './utils'
import { getPluginMetadatas, getPluginCommandMetadata, getPluginListenerMetadata, getPluginTabCompleterMetadata, getPluginConfigMetadata } from './utils'
/**
* MiaoScript plugin
@@ -9,10 +9,9 @@ import { getPluginMetadatas, getPluginCommandMetadata, getPluginListenerMetadata
*/
export function plugin(metadata: interfaces.PluginMetadata) {
return function(target: any) {
target.description = metadata;
metadata.target = target;
decorate(injectable(), target);
Reflect.defineMetadata(METADATA_KEY.plugin, metadata, target.constructor);
Reflect.defineMetadata(METADATA_KEY.plugin, metadata, target);
const previousMetadata: Map<string, interfaces.PluginMetadata> = getPluginMetadatas();
previousMetadata.set(metadata.name, metadata);
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);
};
}
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);
}
}

View File

@@ -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 {
@injectable()
@@ -6,11 +9,27 @@ export namespace interfaces {
public description: PluginMetadata;
public logger: Console;
constructor(@inject(server.Console) Console: MiaoScriptConsole) {
this.description = getPluginMetadata(this)
// @ts-ignore
this.logger = new Console(this.description.prefix || this.description.name)
}
public load() { }
public enable() { }
public disable() { }
}
export interface PluginMetadata {
interface BaseMetadata {
/**
* 名称 为空则为对象名称
*/
name?: string;
/**
* 支持的服务器列表 为空则代表所有
*/
servers?: string[];
}
export interface PluginMetadata extends BaseMetadata {
/**
* 插件名称
*/
@@ -36,20 +55,39 @@ export namespace interfaces {
*/
target?: any;
}
export interface CommandMetadata {
name?: string;
interface ExecMetadata extends BaseMetadata {
/**
* 执行器
*/
executor?: string;
}
export interface CommandMetadata extends ExecMetadata {
/**
* 参数列表
*/
paramtypes?: string[];
}
export interface TabCompleterMetadata {
name?: string;
executor?: string;
export interface TabCompleterMetadata extends ExecMetadata {
/**
* 参数列表
*/
paramtypes?: string[];
}
export interface ListenerMetadata {
name?: string;
executor?: string;
servertype?: string;
export interface ListenerMetadata extends ExecMetadata {
}
export interface ConfigMetadata extends BaseMetadata {
/**
* 配置文件版本号
*/
version?: number;
/**
* 实体变量名称
*/
variable?: string;
/**
* 配置文件格式 默认 yml
*/
format?: string;
}
export type PluginLike = Plugin | string;
}

View File

@@ -1,18 +1,22 @@
import { plugin, server, command, event, MiaoScriptConsole } from '@ms/api'
import { injectable, inject, postConstruct, Container, DefaultContainer as container } from '@ms/container'
import i18n from '@ms/i18n'
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 { getPluginMetadatas, getPluginCommandMetadata, getPluginListenerMetadata, getPlugin, getPluginTabCompleterMetadata } from './utils'
import { getPluginMetadatas, getPluginCommandMetadata, getPluginListenerMetadata, getPlugin, getPluginTabCompleterMetadata, getPluginConfigMetadata } from './utils'
import { interfaces } from './interfaces'
import { getConfigLoader } from './config'
@injectable()
@provideSingleton(plugin.PluginManager)
export class PluginManagerImpl implements plugin.PluginManager {
@inject(ContainerInstance)
private container: Container
@inject(plugin.PluginInstance)
private pluginInstance: any
@inject(plugin.PluginFolder)
private pluginFolder: string;
@inject(server.ServerType)
private serverType: string
@inject(server.Console)
private Console: MiaoScriptConsole
@inject(command.Command)
private CommandManager: command.Command
@inject(event.Event)
@@ -21,12 +25,12 @@ export class PluginManagerImpl implements plugin.PluginManager {
private pluginMap: Map<string, interfaces.Plugin>
@postConstruct()
init() {
initialize() {
if (this.pluginInstance !== null) {
// 如果plugin不等于null 则代表是正式环境
console.info(`Initialization MiaoScript Plugin System: ${this.pluginInstance} ...`)
console.i18n('ms.plugin.initialize', { plugin: this.pluginInstance })
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,38 +38,46 @@ export class PluginManagerImpl implements plugin.PluginManager {
var plugin = fs.file(root, folder)
var files = []
// load common plugin
.concat(this.scanFloder(plugin))
.concat(this.scanFolder(plugin))
// load space plugin
.concat(this.scanFloder(fs.file(plugin, this.serverType)))
.concat(this.scanFolder(fs.file(plugin, this.serverType)))
this.loadPlugins(files)
}
build(container: Container): void {
this.buildPlugins(container)
build(): void {
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 {
this.checkAndGet(args[0]).forEach(pl => {
this.runCatch(pl, 'load')
this.runCatch(pl, `${this.serverType}load`)
this.checkAndGet(args[0]).forEach((plugin: interfaces.Plugin) => {
this.logStage(plugin, i18n.translate("ms.plugin.manager.stage.load"))
this.loadConfig(plugin)
this.runCatch(plugin, 'load')
this.runCatch(plugin, `${this.serverType}load`)
})
}
enable(...args: any[]): void {
this.checkAndGet(args[0]).forEach(plugin => {
this.runCatch(plugin, 'enable')
this.runCatch(plugin, `${this.serverType}enable`)
this.checkAndGet(args[0]).forEach((plugin: interfaces.Plugin) => {
this.logStage(plugin, i18n.translate("ms.plugin.manager.stage.enable"))
this.registryCommand(plugin)
this.registryListener(plugin)
this.runCatch(plugin, 'enable')
this.runCatch(plugin, `${this.serverType}enable`)
})
}
disable(...args: any[]): void {
this.checkAndGet(args[0]).forEach(pl => {
this.runCatch(pl, 'disable')
this.runCatch(pl, `${this.serverType}disable`)
this.unregistryCommand(pl)
this.unregistryListener(pl)
this.checkAndGet(args[0]).forEach((plugin: interfaces.Plugin) => {
this.logStage(plugin, i18n.translate("ms.plugin.manager.stage.disable"))
this.unregistryCommand(plugin)
this.unregistryListener(plugin)
this.runCatch(plugin, 'disable')
this.runCatch(plugin, `${this.serverType}disable`)
})
}
@@ -87,7 +99,7 @@ export class PluginManagerImpl implements plugin.PluginManager {
try {
if (pl[func]) pl[func].call(pl)
} 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)
}
}
@@ -99,11 +111,12 @@ export class PluginManagerImpl implements plugin.PluginManager {
throw new Error(`Plugin ${JSON.stringify(name)} not exist!`)
}
private scanFloder(plugin: any): string[] {
private scanFolder(folder: any): string[] {
var files = []
console.info(`Scanning Plugins in ${plugin} ...`)
this.checkUpdateFolder(plugin)
fs.list(plugin).forEach((file: any) => files.push(file.toFile()))
console.i18n('ms.plugin.manager.scan', { folder })
this.checkUpdateFolder(folder)
// 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
}
@@ -111,7 +124,7 @@ export class PluginManagerImpl implements plugin.PluginManager {
* 更新插件
* @param path
*/
private checkUpdateFolder(path) {
private checkUpdateFolder(path: any) {
var update = fs.file(path, "update")
if (!update.exists()) {
update.mkdirs()
@@ -134,7 +147,7 @@ export class PluginManagerImpl implements plugin.PluginManager {
this.updatePlugin(file)
this.createPlugin(file)
} 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)
}
}
@@ -142,68 +155,96 @@ export class PluginManagerImpl implements plugin.PluginManager {
private updatePlugin(file: any) {
var update = fs.file(fs.file(file.parentFile, 'update'), file.name)
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)
}
}
private createPlugin(file) {
//@ts-ignore
require(file, {
cache: false
})
private allowProcess(servers: string[]) {
// Not set servers allow
if (!servers) return true
// include !type deny
let denyServers = servers.filter(svr => svr.startsWith("!"))
if (denyServers.length !== 0) {
return !denyServers.includes(`!${this.serverType}`)
} else {
return servers.includes(this.serverType)
}
}
private buildPlugins(container: Container) {
private createPlugin(file: string) {
//@ts-ignore
require(file, { cache: false })
}
private buildPlugins() {
let pluginMetadatas = getPluginMetadatas()
pluginMetadatas.forEach(metadata => {
for (const [_, metadata] of pluginMetadatas) {
if (!this.allowProcess(metadata.servers)) { continue }
this.buildPlugin(metadata)
})
}
}
private buildPlugin(metadata: interfaces.PluginMetadata) {
this.bindPlugin(metadata)
let pluginInstance = container.getNamed<interfaces.Plugin>(plugin.Plugin, metadata.name)
if (!(pluginInstance instanceof interfaces.Plugin)) {
console.console(`§4found error plugin §b${metadata.source} §4it's not extends interfaces.Plugin, the plugin will be ignore!`)
return
try {
this.bindPlugin(metadata)
let pluginInstance = this.container.getNamed<interfaces.Plugin>(plugin.Plugin, metadata.name)
if (!(pluginInstance instanceof interfaces.Plugin)) {
console.i18n('ms.plugin.manager.build.not.extends', { source: metadata.source })
return
}
this.pluginMap.set(metadata.name, pluginInstance)
return pluginInstance;
} catch (ex) {
console.i18n("ms.plugin.manager.initialize.error", { name: metadata.name, ex })
console.ex(ex)
}
this.pluginMap.set(metadata.name, pluginInstance)
pluginInstance.description = metadata
// @ts-ignore
pluginInstance.logger = new this.Console(metadata.prefix || metadata.name)
return pluginInstance
}
private bindPlugin(metadata: interfaces.PluginMetadata) {
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 + '') {
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{
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) {
let cmds = getPluginCommandMetadata(pluginInstance)
let tabs = getPluginTabCompleterMetadata(pluginInstance)
cmds.forEach(cmd => {
for (const [_, cmd] of cmds) {
let tab = tabs.get(cmd.name)
if (!this.allowProcess(cmd.servers)) { continue }
this.CommandManager.on(pluginInstance, cmd.name, {
cmd: pluginInstance[cmd.executor].bind(pluginInstance),
tab: tab ? pluginInstance[tab.executor].bind(pluginInstance) : undefined
})
})
}
}
private registryListener(pluginInstance: interfaces.Plugin) {
let events = getPluginListenerMetadata(pluginInstance)
for (const event of events) {
// ignore space listener
if (event.servertype && event.servertype != this.serverType) { continue }
if (!this.allowProcess(event.servers)) { continue }
// here must bind this to pluginInstance
this.EventManager.listen(pluginInstance, event.name, pluginInstance[event.executor].bind(pluginInstance))
}

View File

@@ -49,6 +49,14 @@ function getPluginListenerMetadata(target: any) {
return listnerMetadata;
}
function getPluginConfigMetadata(target: any) {
let configMetadata: Map<string, interfaces.ConfigMetadata> = Reflect.getMetadata(
METADATA_KEY.config,
target.constructor
) || new Map<string, interfaces.ConfigMetadata>();
return configMetadata;
}
export {
getPlugin,
getPlugins,
@@ -57,4 +65,5 @@ export {
getPluginCommandMetadata,
getPluginTabCompleterMetadata,
getPluginListenerMetadata,
getPluginConfigMetadata
}

View File

@@ -1,7 +1,7 @@
{
"private": true,
"name": "@ms/plugins",
"version": "0.1.1",
"version": "0.4.1",
"description": "MiaoScript plugins package",
"keywords": [
"miaoscript",
@@ -18,18 +18,18 @@
},
"scripts": {
"clean": "rimraf dist",
"watch": "npx tsc --watch",
"build": "yarn clean && npx tsc",
"watch": "tsc --watch",
"build": "yarn clean && tsc",
"test": "echo \"Error: run tests from root\" && exit 1"
},
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.0",
"typescript": "^3.6.2"
"rimraf": "^3.0.2",
"typescript": "^3.8.3"
},
"dependencies": {
"@ms/plugin": "^0.1.1",
"es6-map": "^0.1.5",
"inversify": "^5.0.1"
"@ms/api": "^0.4.1",
"@ms/container": "^0.4.0",
"@ms/plugin": "^0.4.1"
}
}

Some files were not shown because too many files have changed in this diff Show More