Compare commits

..

439 Commits

Author SHA1 Message Date
d702d9e40d v0.28.0-beta.9 2023-11-09 13:44:38 +08:00
507431232b feat: 优化插件加载逻辑 2023-11-09 12:07:41 +08:00
3e8d1f7029 v0.28.0-beta.8 2023-10-25 17:47:25 +08:00
9fac585e5e chorn: change pack files 2023-10-25 17:44:27 +08:00
1d26a1e318 v0.28.0-beta.7 2023-10-25 16:27:57 +08:00
5f5df3452d fix: nodejs package publish error 2023-10-25 16:25:24 +08:00
fce3c1a284 v0.28.0-beta.6 2023-10-25 16:22:46 +08:00
21b35b0036 chorn: add @lerna-lite/run 2023-10-25 16:21:34 +08:00
2b7588cf04 chore: change lerna to lerna-lite 2023-10-25 14:39:09 +08:00
4435a239d4 v0.28.0-beta.5 2023-10-25 14:32:22 +08:00
4cc5e75f1d chorn: update build config 2023-10-25 12:07:15 +08:00
188641d57a chorn: remove npmignore use files limit 2023-10-25 12:04:43 +08:00
9a25362140 v0.28.0-beta.4 2023-10-25 11:48:18 +08:00
54eaae96bd feat: use pnpm & lock core-js shim 2023-10-25 11:29:01 +08:00
5bf4b1c09e feat: use files limit package file 2023-10-19 17:24:52 +08:00
54bea62735 bump: update deps version 2023-09-12 11:50:38 +08:00
0e4ae5d74f v0.28.0-beta.3 2023-08-16 11:50:54 +08:00
bdad4136ec fix: websocket close logic 2023-08-16 11:47:36 +08:00
a0866c1085 feat: add plugin self method 2023-08-12 17:14:57 +08:00
afd3f91a3f delete: amqp kv web spring package 2023-08-12 17:13:41 +08:00
e70c78a255 v0.28.0-beta.2 2023-08-08 18:11:44 +08:00
9cfac1672a feat: optimize websocket client 2023-08-08 18:06:34 +08:00
9126ec8035 v0.28.0-beta.1 2023-07-30 16:46:42 +08:00
23bc6068b5 feat: optimize websocket client 2023-07-30 16:46:34 +08:00
27b428fbe2 v0.28.0-beta.0 2023-07-26 17:37:26 +08:00
c07f1131c4 refactor: optimize plugin system 2023-07-26 17:35:33 +08:00
002f2c47c6 v0.27.6 2023-07-19 18:22:35 +08:00
8633d9ea95 fix: particle spawner error 2023-07-19 18:21:56 +08:00
07a5d0c8de feat: add plugin checker
Signed-off-by: MiaoWoo <admin@yumc.pw>
2023-02-18 16:01:15 +08:00
dd76e563c8 feat: add qrcode package
Signed-off-by: MiaoWoo <admin@yumc.pw>
2023-02-18 15:21:42 +08:00
7b85ff5b7c feat: 同步 socket.io 上游代码
Signed-off-by: MiaoWoo <admin@yumc.pw>
2023-02-09 13:49:48 +08:00
359aeb9d63 chore: remove client package
Signed-off-by: MiaoWoo <admin@yumc.pw>
2023-02-09 12:44:04 +08:00
3901d9fb5f feat: 更新依赖版本
Signed-off-by: MiaoWoo <admin@yumc.pw>
2023-02-08 17:03:17 +08:00
c2867da047 v0.26.0 2023-02-08 16:24:09 +08:00
65832c9fae feat: 完善粒子播放
Signed-off-by: MiaoWoo <admin@yumc.pw>
2023-02-08 16:23:05 +08:00
d9dffa704d v2.25.1 2022-11-28 17:30:45 +08:00
b39f29de6a v2.25.1-beta.1 2022-11-28 17:18:50 +08:00
56334c6f6e v0.25.1-beta.0 2022-11-28 17:15:39 +08:00
72673b2a67 feat: optimize event slow exec cache
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-11-28 17:14:29 +08:00
597bdb721a v0.25.0 2022-11-22 17:37:54 +08:00
6e0456d777 feat: 添加注释
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-11-22 17:35:13 +08:00
fb67b06230 v0.25.0-beta.0 2022-11-22 17:12:22 +08:00
203560dcf2 chore: add --verify-access
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-11-22 17:10:15 +08:00
3f58f5992c style: xml-http-request.ts
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-11-22 15:50:54 +08:00
ac16754c9c fix: buffer polyfill error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-11-22 13:48:41 +08:00
42d637dd63 fix: rename Buffer to BufferPolyfill
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-11-21 23:27:12 +08:00
df0d246136 feat: upgrade socket.io to v4
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-11-21 23:18:39 +08:00
e563e1b507 feat: update chat to 1.19.2
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-11-21 23:17:14 +08:00
3b822c613a dep: update dependencies
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-11-21 14:29:17 +08:00
2967c2a1fe v0.24.3 2022-10-14 14:12:02 +08:00
1c579c9789 feat: framework optimization
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-10-14 10:07:36 +08:00
2fe9bce2ea v0.24.2 2022-07-17 07:13:54 +08:00
496d278a93 fix: item fromJson error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-07-17 07:11:36 +08:00
bdf674b678 v0.24.1 2022-07-07 00:54:16 +08:00
67fe13deac fix: migrate config error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-07-07 00:51:10 +08:00
30846cdc87 v0.24.0 2022-07-06 22:01:09 +08:00
d8d03149df fix: some bug
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-07-06 21:57:36 +08:00
b6d7847a79 v0.23.0 2022-06-20 00:59:07 +08:00
58f59f8260 v0.23.0-beta.0 2022-06-20 00:57:37 +08:00
f3fa14990f v0.23.0-alpha.0 2022-06-20 00:52:40 +08:00
15d1f8392b release: v0.23.0
1. add item api
2. support rollup source map
3. fix database drvice error
4. support loliserver
5. support 1.19 bukkit chat
6. config add migrate options
7.

Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-06-20 00:48:00 +08:00
b5fac23c5c v0.22.0 2022-05-21 15:05:14 +08:00
148f6c28c4 feat enable faster load mode
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-05-21 11:54:40 +08:00
880065495e feat: add database web manager
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-05-21 11:54:09 +08:00
7fc70a92d5 v0.21.2 2022-05-14 16:44:25 +08:00
df6da12a8a feat: modify package description
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-05-14 16:43:50 +08:00
082f2b8f73 v0.21.0 2022-05-14 16:28:17 +08:00
7cd85f3f34 feat: add verify package signle
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-05-14 11:55:05 +08:00
073cf6aaac Revert "feat: lerna link convert"
This reverts commit 4ee8fc9a20.
2022-05-14 10:45:06 +08:00
43aa39b86f feat: remove verify package
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-05-14 09:54:15 +08:00
cb58fbdb6c feat: add verify package
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-05-13 23:50:02 +08:00
86aacf1a1f feat: optimize ioc loader
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-05-11 10:56:47 +08:00
47413c6766 feat: refactor database
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-05-11 10:54:44 +08:00
4ee8fc9a20 feat: lerna link convert
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-04-26 07:52:43 +08:00
8d0484eefb feat: add loadMavenDepend & optimize database
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-04-25 00:41:11 +08:00
579d89ae89 feat: update dependencies
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-04-21 07:25:55 +08:00
010f561766 v0.20.0 2022-04-19 10:04:56 +08:00
848aacd991 feat: add beta publish script
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-04-19 09:56:37 +08:00
ab5559b26f v0.20.0-alpha.0 2022-04-19 09:40:08 +08:00
46729b9cf0 feat: optimize config loader
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-04-19 09:29:57 +08:00
83cad2f52e v0.19.8 2022-04-04 05:17:27 +08:00
a5cb084767 feat: remove global initialize
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-04-04 05:13:24 +08:00
16ab108186 v0.19.7 2022-04-04 04:28:12 +08:00
a1df719dc9 fix: 修复子命令权限处理异常
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-04-04 04:27:47 +08:00
41e5754492 v0.19.6 2022-04-03 03:10:13 +08:00
866d1dd62c fix: api interface error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-04-03 03:07:18 +08:00
8056d3060d v0.19.5 2022-04-03 02:43:11 +08:00
b8440b83de feat: add exit event
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-04-03 02:41:17 +08:00
b55e662f81 feat: add more event emit
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-04-02 16:51:08 +08:00
db526e9444 fix: 修复自动化命令参数错误
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-04-02 15:02:21 +08:00
1b0ea9fa05 v0.19.0 2022-04-01 17:35:48 +08:00
143c960da5 feat: new mjs scanner
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-04-01 17:18:32 +08:00
30fd065bc5 v0.18.0 2022-02-13 00:13:57 +08:00
f4c04829b1 upgrade: dependencies version
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-02-12 23:00:24 +08:00
6816e51239 feat: add molang package
1. upgrade bukkit chat
2. fix config update error

Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-02-12 16:29:40 +08:00
5ed61829e1 feat: update typescript version
Signed-off-by: MiaoWoo <admin@yumc.pw>
2021-12-26 01:21:06 +08:00
72173b4778 v0.17.0 2021-11-04 09:28:18 +08:00
4ee300a22b feat: 优化WebSocket客户端 兼容1.7.10
Signed-off-by: MiaoWoo <admin@yumc.pw>
2021-11-04 09:07:48 +08:00
476d98b9c7 feat: 优化websocket
Signed-off-by: MiaoWoo <admin@yumc.pw>
2021-10-25 15:56:23 +08:00
cf9153c134 feat: 新增公告接口
Signed-off-by: MiaoWoo <admin@yumc.pw>
2021-10-25 15:54:38 +08:00
b3fa8790e3 chore: 依赖版本更新
Signed-off-by: MiaoWoo <admin@yumc.pw>
2021-08-14 12:45:38 +08:00
27dafe3307 feat: 配置文件调试日志限制500字符
Signed-off-by: MiaoWoo <admin@yumc.pw>
2021-08-14 12:44:58 +08:00
53502e12cf feat: 完善client相关功能 重构server部分
Signed-off-by: MiaoWoo <admin@yumc.pw>
2021-08-14 12:43:20 +08:00
774763be13 v0.16.3 2021-08-05 14:39:53 +08:00
cabf09e247 feat: 优化WebSocket客户端 支持WSS
Signed-off-by: MiaoWoo <admin@yumc.pw>
2021-08-05 14:35:17 +08:00
2fd10140cf v0.16.2 2021-08-03 17:59:49 +08:00
7afea75454 feat: 更新插件管理模块
Signed-off-by: MiaoWoo <admin@yumc.pw>
2021-08-03 17:56:11 +08:00
8a2b0d7c2e chore: 优化部分逻辑
Signed-off-by: MiaoWoo <admin@yumc.pw>
2021-08-03 17:30:53 +08:00
586b6acbbc feat: 更新WebSocket 优化逻辑
Signed-off-by: MiaoWoo <admin@yumc.pw>
2021-08-03 16:59:43 +08:00
def62e2940 v0.16.1 2021-07-14 15:48:56 +08:00
18329f0a4c chore: 更新依赖版本
Signed-off-by: MiaoWoo <admin@yumc.pw>
2021-07-14 15:48:42 +08:00
39612a1ff3 feat: 修改默认超时时间
Signed-off-by: MiaoWoo <admin@yumc.pw>
2021-07-14 15:46:32 +08:00
ea1dd6f9ae v0.16.0 2021-07-10 18:28:43 +08:00
66eaf6b8b0 chore: update depends 2021-07-10 18:28:22 +08:00
157782b43e feat: 优化XHR相关功能
Signed-off-by: MiaoWoo <admin@yumc.pw>
2021-07-10 18:14:55 +08:00
51fd13e734 v0.15.0 2021-06-22 15:58:29 +08:00
293c69a605 feat: remove some debug output
Signed-off-by: MiaoWoo <admin@yumc.pw>
2021-06-22 15:51:50 +08:00
88e59231da feat: add openjdk nashorn shim
Signed-off-by: MiaoWoo <admin@yumc.pw>
2021-06-22 15:51:28 +08:00
02dbf535bc refactor: optimize config & plugin load
Signed-off-by: MiaoWoo <admin@yumc.pw>
2021-06-22 15:51:13 +08:00
a4368cc9ba feat: bukkit chat support 1.17
Signed-off-by: MiaoWoo <admin@yumc.pw>
2021-06-22 15:24:08 +08:00
dbe9657b26 feat: update depends
Signed-off-by: MiaoWoo <admin@yumc.pw>
2021-06-22 15:23:47 +08:00
d486e2ab19 feat: add push script
Signed-off-by: MiaoWoo <admin@yumc.pw>
2021-03-27 15:29:22 +08:00
293b4e265b v0.14.1 2021-03-27 11:38:56 +08:00
bf34552321 fix: new ts version build error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2021-03-27 11:35:54 +08:00
4f41357953 v0.14.0 2021-03-26 17:20:41 +08:00
b2177683de chorn: update depends version
Signed-off-by: MiaoWoo <admin@yumc.pw>
2021-03-26 17:20:22 +08:00
081a934747 feat: update client
Signed-off-by: MiaoWoo <admin@yumc.pw>
2021-03-26 16:43:14 +08:00
4f5c9bafa1 fix: config value update error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2021-03-26 16:42:45 +08:00
1ff3a5ae62 refactor: optimize websocket server
Signed-off-by: MiaoWoo <admin@yumc.pw>
2021-03-26 16:42:02 +08:00
93f44e5a00 refactor: rename ployfill to polyfill
Signed-off-by: MiaoWoo <admin@yumc.pw>
2021-03-26 16:18:11 +08:00
67aa4302e0 v0.13.0 2020-12-17 17:04:30 +08:00
df1646dc15 feat: export server & client
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-12-17 17:01:09 +08:00
48cc6325b8 feat: add netty WebSocket client
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-12-17 17:00:27 +08:00
f42d5d12ed feat: js task limit exec time default 3s
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-12-17 17:00:00 +08:00
6617171472 fix: java file lineNumer lose
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-12-17 16:59:06 +08:00
f35c8cd3fb feat: add compile plugin info
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-12-17 16:58:37 +08:00
BuildTools
aa182fb169 v0.12.0 2020-12-07 11:19:12 +08:00
8a15a5398f fix: java thread need direct callback socket
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-12-07 11:13:30 +08:00
ad85c3bc9b feat: 新增Native插件管理
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-12-07 11:12:49 +08:00
a3cbe455a1 feat: 新增粒子相关API(未完成)
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-12-07 11:11:13 +08:00
BuildTools
f7a228975f v0.11.0 2020-11-20 14:26:15 +08:00
299a8e7791 fix: sponge task & command error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-11-20 14:22:28 +08:00
af1e64767a perf: optimize websocket logic
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-11-20 14:21:57 +08:00
f31726e98b feat: support full nodejs event loop
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-11-20 10:28:30 +08:00
4bb2337f39 refactor(core): core task function
move event loop task to @ccms/micro-task thread

BREAKING CHANGE: setTimeout & setInterval no longer run on main thread

Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-11-18 16:32:09 +08:00
c5fac44362 refactor(websocket): upgrade socket.io
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-11-18 16:21:56 +08:00
BuildTools
d7e757bcf8 v0.10.1 2020-11-13 10:02:21 +08:00
c013d0eec5 upgrade: dependencies version
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-11-13 09:52:32 +08:00
7f5929bc87 feat: optimize websocket
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-11-13 09:40:47 +08:00
d769a9c8ca fix: task disable error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-11-13 09:40:34 +08:00
c64d167893 v0.10.0 2020-10-31 11:41:26 +08:00
0776d0ddeb feat: optimize config save logic
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-10-31 11:40:38 +08:00
3f101ca250 feat: add protocol package
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-10-31 10:20:41 +08:00
85f2bd5a10 feat: optimize framework & support depends check
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-10-13 09:24:58 +08:00
c172bcfad7 v0.9.9 2020-10-02 20:00:31 +08:00
1d2a528bbb fix: continer Autowired error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-10-02 19:57:10 +08:00
d80e858a89 v0.9.8 2020-10-02 18:59:52 +08:00
24fc6dc464 feat: add .editorconfig
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-10-02 18:54:28 +08:00
e38666f12d feat: define config save & load
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-10-02 18:53:31 +08:00
c7079dd82e fix: Autowired Java class error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-10-02 18:48:37 +08:00
0fea6b5537 fix: server method error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-10-02 16:43:18 +08:00
00a84fb58a feat: hide internal function
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-10-02 16:21:09 +08:00
80fbc071ed refactor: update type define
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-10-02 16:20:33 +08:00
14f20897d6 feat: update javatypes version
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-09-26 14:50:04 +08:00
a84b82d206 v0.9.7 2020-09-25 10:13:59 +08:00
80111d5ada fix: config inject error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-09-25 10:12:28 +08:00
fb7e27af82 v0.9.6 2020-09-24 19:26:04 +08:00
e9a2aa9745 refactor: plugin system & config manager
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-09-24 18:36:10 +08:00
4741e341b7 v0.9.5 2020-09-24 15:36:45 +08:00
1b4b249859 fix: command tab complate error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-09-24 15:27:34 +08:00
78100e8696 v0.9.4 2020-09-24 13:51:39 +08:00
d0a0e2dd71 feat: compatible 1.8.8 chat
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-09-24 13:48:14 +08:00
7962aa5da0 fix: sponge command dispatch error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-09-24 10:51:31 +08:00
0667201605 feat: update client support mcsso
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-09-24 10:33:38 +08:00
afd04ed972 fix: command registry error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-09-24 10:33:16 +08:00
9c137574f5 refactor: extract proxy & fix bungee chaneel
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-09-24 10:31:20 +08:00
6597b261fd feat: update dependencies version
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-09-23 17:52:15 +08:00
8432f7fbab v0.9.3 2020-09-23 11:26:09 +08:00
e731de2162 fix: bungee task error 2020-09-23 11:25:53 +08:00
b87fb08d1c feat: optimize task impl
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-09-22 18:42:39 +08:00
e7077b1315 feat: add bungee proxy
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-09-22 17:36:32 +08:00
05e9feee9b feat: update Autowired & support command alias
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-09-22 17:36:04 +08:00
af85703bd9 refactor: chat & command tabComplete
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-09-22 15:29:12 +08:00
68a996f830 v0.9.2 2020-09-17 17:45:04 +08:00
8f944e0b14 feat: update ms system 2020-09-17 17:44:48 +08:00
6910ea3e26 v0.9.1 2020-08-14 16:09:46 +08:00
d01938487a fix: bukkit chat init error & config save error 2020-08-14 16:05:44 +08:00
606f097989 v0.9.0 2020-07-28 09:51:56 +08:00
a3cf4fa476 feat: optimize plugin event registry
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-07-28 09:41:10 +08:00
3c1ff6ea41 feat: impl bukkit chat api
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-07-28 09:39:52 +08:00
2990cdc4aa feat: add chat api
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-07-28 09:39:15 +08:00
f301d130f9 revent: qrcode.ts
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-07-27 01:08:45 +08:00
0ae4764c85 backup: new qrcodeSigned-off-by: MiaoWoo <admin@yumc.pw>
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-07-27 01:07:35 +08:00
8def6257df fix: readSourceMap split error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-07-26 21:33:58 +08:00
f62d198166 feat: add keyvalue package
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-07-24 18:45:56 +08:00
0c71bc3582 v0.8.4 2020-07-23 14:22:30 +08:00
ea99cbea1d feat: opitmize plugin manager
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-07-23 13:44:55 +08:00
b400ab81f0 feat: add qrcode lib
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-07-23 13:44:39 +08:00
63ff11def1 fix: reflect method error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-07-11 15:08:02 +08:00
b1a4c65adb fix: unregistry controller error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-07-06 17:41:50 +08:00
9b28cd4de0 feat: debug print error stack
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-07-06 17:41:15 +08:00
e55d48d713 feat: add plugin web stage
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-07-06 16:10:33 +08:00
3ea72f0aac feat: add ServerChecker
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-07-06 16:07:16 +08:00
fe1ee3883a fix: spring tab complate error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-07-06 16:07:00 +08:00
083a01f29f feat: split plugin ext stage exec
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-07-06 16:06:47 +08:00
0b0a3bb836 fix: reload plugin not effect
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-07-02 18:30:56 +08:00
9bb8278477 v0.8.3 2020-07-02 17:08:20 +08:00
92647fbea2 feat: enable compilerOptions importHelpers
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-07-02 16:57:16 +08:00
1928551023 feat: update typescript version
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-07-02 11:23:14 +08:00
018889b5eb v0.8.2 2020-07-01 14:41:21 +08:00
05244f9bef feat: update dep version
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-07-01 14:33:16 +08:00
36c9d4ad99 feat: complate @ccms/web package
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-06-30 16:02:39 +08:00
0bc513d580 feat: optimize process & plugin loader and scanner
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-06-30 15:58:51 +08:00
678f4ca8a4 fix: boardcast error when socket send packet
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-06-30 14:02:18 +08:00
f4aa568f0c v0.8.1 2020-06-23 16:15:17 +08:00
1bb938dcbd feat: update config & package.json
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-06-23 16:07:55 +08:00
dc4e554a35 feat: update script
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-06-23 15:53:24 +08:00
7c016f6ba6 feat: optimize plugin scan & load
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-06-23 15:51:55 +08:00
cfef52aecd v0.8.0 2020-06-22 18:58:05 +08:00
53ee92e20d feat: use @javatypes defiend java type
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-06-22 10:44:17 +08:00
9b5a303c21 feat: complate database & web
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-06-20 16:39:03 +08:00
4c0a77ed23 feat: add amqp & web interface
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-06-20 16:38:14 +08:00
46173ff549 feat: support loader & scanner
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-06-17 18:39:24 +08:00
2fb7ddd890 feat: add exit hook
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-06-17 18:36:25 +08:00
e2505597ff feat: add web package
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-06-17 18:34:20 +08:00
17ed9d7d52 feat: support Autowired and JSClass inject
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-06-17 18:34:01 +08:00
5a9e33e695 feat: add thread pool factory
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-06-17 18:28:12 +08:00
b98409abe7 feat: add amqp package
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-06-17 18:27:36 +08:00
5420ad460c feat: optimize type file generate
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-06-02 18:06:15 +08:00
9587a748eb feat: add scope login script
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-06-02 18:03:22 +08:00
ac2a4f3d6e feat: add nocolor stack
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-06-02 18:02:49 +08:00
d888d9ab4e feat: add node-shim & move plugin interface
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-06-02 18:01:56 +08:00
2582d51a98 feat: add @ccms/database
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-06-02 18:00:26 +08:00
843b65f13b feat: complate server & update spring
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-06-02 17:50:47 +08:00
c2857a0566 feat: update console
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-06-02 17:15:54 +08:00
684a033525 feat: compatible brower behavior
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-05-30 10:43:33 +08:00
503ca79dab fix: websocket session send synchronized
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-05-30 10:18:01 +08:00
46768e4cdd feat: modify ws on Message params
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-05-26 18:48:46 +08:00
f61360f739 v0.7.0 2020-05-26 16:04:34 +08:00
8fbf9ef29d feat: update docs
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-05-26 15:54:56 +08:00
d6138bc6f4 feat: add spring support
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-05-26 15:53:41 +08:00
c37a7cb772 feat: support tomcat websocket
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-05-26 15:45:40 +08:00
4e1a77cc50 v0.6.7 2020-05-15 18:24:24 +08:00
d614b3741e feat: add npm publish script 2020-05-15 16:50:12 +08:00
738bc50939 feat: link .npmignore file 2020-05-15 16:46:47 +08:00
167abfe3d9 v0.6.6 2020-05-15 16:20:21 +08:00
aab5c86588 feat: support nukkit getRootLogger
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-05-15 16:10:55 +08:00
5cd02ac08a feat: support get root Logger
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-05-15 15:48:38 +08:00
0b67ddce42 feat: support config auto save
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-05-15 14:28:40 +08:00
1e2c17456e feat: optimize import
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-05-14 19:04:19 +08:00
8731f5d9ef feat: support handshark & boardcast
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-05-14 19:03:41 +08:00
fb3803cae9 feat: update dep version
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-05-14 09:56:13 +08:00
84e4052871 feat: add global eventCenter & static console source map
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-05-13 18:41:05 +08:00
2dc662a4d4 v0.6.5 2020-05-12 14:35:26 +08:00
2b017d9208 feat: optimize framework
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-05-12 14:22:31 +08:00
0ca8ae944c feat: ignore if trace.fileName is empty
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-05-11 22:13:31 +08:00
1e03b104df feat: add node shim
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-05-11 22:13:03 +08:00
7ba34e7e01 v0.6.4 2020-05-11 17:52:13 +08:00
c016b1db34 feat: add npmignore
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-05-11 17:46:57 +08:00
3d1ed08473 v0.6.3 2020-05-11 17:32:02 +08:00
34ee276556 feat: support address arg
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-05-11 17:24:26 +08:00
53f20a9a8f feat: compatible blockly plugin
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-05-11 17:20:50 +08:00
76fd6b8318 feat: add i18n load tip
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-05-11 17:19:44 +08:00
dfff666284 feat: ignore jar:file stack info
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-05-10 16:25:04 +08:00
44fab858d3 feat: add incremental compiler config
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-05-10 16:24:19 +08:00
fea58a4dd6 feat: support basic plugin... 2020-05-08 18:41:56 +08:00
71308a13a1 feat: update init command... 2020-05-08 10:11:30 +08:00
34f9b088c7 feat: update gitpod init command... 2020-05-08 10:05:47 +08:00
70929d7ceb feat: add gitpod config... 2020-05-08 09:53:18 +08:00
2beca068a4 feat: complate deploy feature 2020-05-08 00:50:30 +08:00
e0ab8a5a7b v0.6.2 2020-05-07 18:38:28 +08:00
e6f9326ae3 fix: reload & download error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-05-07 18:33:10 +08:00
58cbacdc85 v0.6.1 2020-05-07 17:18:38 +08:00
dcbdbcfcdc feat: update docs & MSPM
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-05-07 17:13:48 +08:00
1662e8e0e9 feat: support source map & reload
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-05-07 17:12:15 +08:00
73fa62a23e v0.6.0 2020-05-03 00:15:06 +08:00
ca79161505 refactor: rename scope to @ccms
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-05-03 00:14:47 +08:00
be4fe82588 v0.5.0 2020-04-26 10:24:49 +08:00
8ec21a7f99 feat: merge stage exec & catch error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-04-26 10:19:44 +08:00
1431ce0a6e feat: update plugin & websocket
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-04-24 16:42:36 +08:00
e9c13e44b4 feat: support stage decorators and remove space plugin floder
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-04-24 15:38:00 +08:00
6b838ae55d fix: netty inject error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-04-24 13:05:46 +08:00
de99c0dd92 feat: support base64 source map
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-04-24 13:04:45 +08:00
b92cfccb84 v0.4.2 2020-04-07 13:39:50 +08:00
b03c311956 feat: add 1.8.8 reflect & export io namespace
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-04-07 13:31:20 +08:00
a164f08e1e feat: console执行异常只打印一次
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-04-03 13:32:54 +08:00
d850c4a16f feat: cancel all task when disable engine
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-04-03 11:36:06 +08:00
17fbfabff5 feat: use module export
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-04-01 17:53:12 +08:00
e84882e076 feat: add internal node moudle punycode
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-04-01 14:39:00 +08:00
f224b417bb feat: merge decorators meta interface
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-04-01 11:08:57 +08:00
f9458e66c1 feat: add pipeline reflect
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-04-01 11:08:15 +08:00
d22cb515f7 upgrade: js-yaml version
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-31 16:16:13 +08:00
595e11ddfd v0.4.1 2020-03-31 16:16:40 +08:00
328d93cd3f fix: disable server error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-31 14:53:23 +08:00
ccaa268362 feat: add new nodejs modules
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-31 14:51:44 +08:00
b04f4899ca feat: instance i18n object
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-30 18:49:08 +08:00
4677fba701 v0.4.0 2020-03-25 13:54:45 +08:00
cbfbc28504 feat: export error handle & merge config
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-24 18:30:50 +08:00
2042b49e0d feat: add api doc
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-24 17:59:18 +08:00
aee0457d9f fix: sourceMap sometime error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-24 15:02:20 +08:00
9b69b1221b fix: ack callback call twice
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-24 14:52:50 +08:00
cbb73b451f feat: optimize framework add error catch(only log)
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-24 13:27:11 +08:00
5844ca9e7d style: change error color
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-24 13:26:15 +08:00
b6318cb8c1 feat: complate sockt.io server
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-23 18:33:12 +08:00
efd1e5bd62 feat: add adapter and socket
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-23 00:58:53 +08:00
5549bdd804 feat: tracatch plugin build
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-21 15:48:45 +08:00
926fc3b17a feat: add nodejs package
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-21 15:47:59 +08:00
9dae44278d feat: complate socket.io base framework
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-21 15:47:42 +08:00
2fb62b26a0 v0.3.2 2020-03-18 11:19:08 +08:00
a1e50285a9 fix: source map print error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-18 11:15:49 +08:00
25dbefef6f refactor: move docs to MiaoDocs
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-10 13:19:48 +08:00
5ef16c5f21 update: README
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-04 02:23:37 +08:00
5f0075272c feat: modify stage order
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-04 02:11:55 +08:00
38469741fd feat: update readme and fix container package error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-04 02:04:35 +08:00
bbc6058347 feat: add docs package
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-04 02:04:02 +08:00
2254f22936 v0.3.1 2020-03-03 01:14:22 +08:00
9de4038788 feat: public types package
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-03 01:11:49 +08:00
0f8243a7ad feat: update readme
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-02 22:38:34 +08:00
95ac5d1800 feat: update MCBBS.MD
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-02 22:37:08 +08:00
5132019ce6 feat: add error handle
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-02 22:28:27 +08:00
d7061c0c9d remove: manager package
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-02 21:00:54 +08:00
f28a1e3c66 feat: add complate function
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-02 00:32:07 +08:00
cf3f840b3c feat: optimize types ref
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-01 20:28:16 +08:00
12b3973b38 fix: Dependency cycles
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-01 19:37:34 +08:00
b95b4f6928 feat: add i18n to ployfill
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-01 17:01:27 +08:00
f821998801 feat: add NativePluginManager
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-01 15:19:43 +08:00
27b5642047 feat: add download and getPluginsFolder
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-29 22:28:43 +08:00
85b3bba5d0 feat: upgrade typescript
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-29 18:21:02 +08:00
343f4ba04b feat: add command error i18n
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-29 00:44:11 +08:00
00b27e8999 feat: add normal env task
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-27 18:20:45 +08:00
97877832c4 feat: channel add ext data
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-27 18:14:17 +08:00
33d29271f9 fix: servers check error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-27 17:57:29 +08:00
9f0e732e37 v0.3.0 2020-02-27 12:27:19 +08:00
c2b3372d74 feat: optimize code
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-27 12:26:04 +08:00
8a0fcfae8b feat: improve i18n scope
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-27 12:11:18 +08:00
08ca3db67b feat: support i18n translate
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-27 01:58:23 +08:00
813f761e47 feat: add package i18n
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-27 01:57:44 +08:00
5728c48f16 feat: remove async check
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-26 10:43:47 +08:00
106abc76e1 feat: unmanaged baseEventDir
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-26 10:36:30 +08:00
6a5b1598d4 feat: use inversify autoProvide inject
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-26 10:15:33 +08:00
0ade2b2855 feat: exclude async event monitor
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-25 23:32:12 +08:00
6cf446e54b fix: event execute class type error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-25 23:15:39 +08:00
da07acc6b0 fix: nukkit unregister event error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-25 18:25:16 +08:00
f7207d99ba feat: add channel support for bungee bukkit sponge
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-24 18:36:08 +08:00
57f2b37401 feat: update ignore file
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-24 16:35:19 +08:00
8f864222ae v0.2.1 2020-02-24 16:27:49 +08:00
c33b78b029 feat: add nukkit support
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-24 16:25:54 +08:00
b5b9d3f230 feat: inject config folder
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-24 16:25:16 +08:00
93fa3e2460 feat: add config support
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-24 16:24:36 +08:00
c1ef761ec7 feat: update typescript version
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-24 15:28:47 +08:00
19e7692756 feat: add nukkit support
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-24 04:02:29 +08:00
0fbccbc05f feat: add nukkit package 2020-02-24 04:01:39 +08:00
b2a24943a4 v0.2.0 2020-02-24 00:21:48 +08:00
063fc51f40 feat: set manager and client to private
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-24 00:19:13 +08:00
126789d49a feat: add config decorator bate
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-24 00:12:32 +08:00
21394a3b4b feat: update mcbbs file
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-24 00:11:46 +08:00
11c91600da feat: add auto respawn support
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-23 22:35:05 +08:00
c13c4aefca fix: some bug at xhr and console
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-23 22:33:51 +08:00
4fa67549fb feat: update main script
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-19 19:03:09 +08:00
26f4c24659 feat: add source map support
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-19 19:00:26 +08:00
82cf6e6f53 feat: add mc console client package
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-19 18:59:02 +08:00
e3f3f9ca4e feat: remove script npx
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-19 18:56:02 +08:00
24d77ea34d feat: add source map support(only local)
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-15 19:39:45 +08:00
b28da75420 feat: enable sourceMap
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-15 18:49:18 +08:00
caa30083d3 feat: update dependencies version
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-15 18:48:46 +08:00
2ddd8c3879 fix: bungee unregister error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-14 04:02:37 +08:00
1eefb729d7 feat: chat compatible catserver
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-14 04:02:18 +08:00
b6f3a31eca feat: add bungee tab complate
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-09 22:07:00 +08:00
d1b6a4d4b2 feat: add core-js
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-09 22:06:45 +08:00
81fa66684a fix: compile error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-02 01:58:07 +08:00
0b6c174e42 feat: use dom types and set Proxy global
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-02 01:56:45 +08:00
bf33381e30 feat: update Proxy handle and optimize core index
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-01 03:37:56 +08:00
44422d4dcf feat: update Readme
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-01 02:54:03 +08:00
97b499c0b4 feat: add websocket package
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-01 02:47:39 +08:00
8ccfe499df feat: add plugin stage log
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-01 02:46:55 +08:00
f6df0a2c47 feat: move type bind and export impl function
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-01 02:46:06 +08:00
e2f32fd0bf feat: move global declare to @ms/ployfill
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-01 02:44:23 +08:00
1e00dc6530 fix: sponge task callSyncMethod
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-01-17 17:45:39 +08:00
de491bdd62 feat: optimiz plugin system
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-01-17 17:45:13 +08:00
30ec92fd65 feat: add tellraw string
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-01-17 17:44:08 +08:00
f869a524ff feat: plugin & cmd add server check
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-01-17 11:11:20 +08:00
72627c08bc feat: use inject container
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-01-17 11:10:30 +08:00
0595c3c046 fix: bungee event error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-01-17 11:09:16 +08:00
2063a2484d feat: add callSyncMethod
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-01-17 11:08:51 +08:00
a0304183c4 feat: add plugin controller
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-01-16 17:28:10 +08:00
e442da5b3b feat: update plugins
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-01-16 17:27:24 +08:00
54d12749dc feat: add bungee support
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-01-16 17:26:31 +08:00
7955f1663a feat: complete event and dispatch command
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-01-16 17:19:10 +08:00
032ef3e37d feat: add tellraw & Proxy utils
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-01-15 18:38:22 +08:00
d500546236 feat: formatting code & remove chinese
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-01-15 16:48:18 +08:00
c9d62cc617 feat: completion base func
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-01-15 16:44:14 +08:00
fb37d46acc feat: add bungee package
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-01-15 16:43:00 +08:00
5099430289 feat: add server module
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-01-14 17:44:20 +08:00
73690a2668 feat: upgrade version
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-01-08 09:48:37 +08:00
7ab3443351 feat: update gitignore 2019-11-09 18:35:26 +08:00
b60259c345 feat: add jdk support 2019-11-09 18:34:54 +08:00
7b67dc7719 feat: move type def to other package 2019-11-07 15:02:05 +08:00
5a29133561 feat: add illegal plugin check
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-11-05 17:03:49 +08:00
c0106e941b feat: support async task
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-11-05 17:02:58 +08:00
736760b2ee feat: update plugin register
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-11-04 20:28:52 +08:00
83cc4b6a54 feat: update config and add XHR
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-11-04 20:26:22 +08:00
24013bf240 fix: command remove error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-11-04 20:21:31 +08:00
a3cf7eb036 feat: add xhr
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-11-04 20:20:08 +08:00
0012da9855 refactor: update http use XHR
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-11-04 20:19:50 +08:00
364463dc6a feat: add server interface
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-11-04 20:18:30 +08:00
8e94683757 feat: update ignore file
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-10-29 15:38:55 +08:00
e1530c49ee style: format file
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-27 18:40:35 +08:00
4c0290bf21 feat: share decorators container
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-27 18:39:40 +08:00
10cb22c510 feat: add XMLHttpRequest
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-27 18:39:03 +08:00
b939c7c891 feat: supoort mod server scan event
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-27 09:49:45 +08:00
032f4d98ae fix: type instance error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-25 10:10:35 +08:00
ae1519ea4f fix: not exist type mapping
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-25 10:10:22 +08:00
a96756e1ac feat: add sponge typings
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-25 09:55:00 +08:00
35f2dbf162 feat: add type extend and interface
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-24 17:20:18 +08:00
c153f9babb feat: update type defiend
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-24 15:02:03 +08:00
0c8d3a04bd v0.1.1 2019-09-24 10:15:06 +08:00
0491e6fac9 feat: modify import to reference type
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-24 10:12:40 +08:00
7137325491 v0.1.0 2019-09-23 00:41:04 +08:00
8f183d1ca3 feat: update registry in every package
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-23 00:39:13 +08:00
db800a4038 feat: add cli sh and add hosted url in package.json
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-23 00:34:38 +08:00
a851bb543b feat: update deps
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-23 00:19:43 +08:00
81c76f4977 feat: add example plugins
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-22 23:31:52 +08:00
7ca81db573 doc: add jsdoc
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-22 18:02:28 +08:00
b0915648ea fix: bukkit task error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-22 18:01:50 +08:00
9121683e77 feat: add start time
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-22 18:01:35 +08:00
8f5882ff0a feat: modify sponge event mapping handle
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-22 18:01:13 +08:00
38bd2f5187 feat: add remove plugin on disable
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-22 18:00:18 +08:00
514ac27aca feat: add build:plugins
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-22 17:59:25 +08:00
60f6a4e18d feat: add readme and update ts config
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-21 15:06:17 +08:00
046c86681b feat: support multi stage load
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-21 15:05:37 +08:00
5ea4b6bdaf feat: complate command event and task
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-21 15:04:47 +08:00
500384326f feat: add task and optimize command
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-21 15:04:25 +08:00
eb1bab7e76 feat: update command and complate task
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-21 14:58:00 +08:00
928f73a4bf fix: command registry error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-20 09:09:29 +08:00
c3522aea64 feat: add build script
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-19 19:00:35 +08:00
e5bab5763c feat: complate event and command module
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-19 18:59:32 +08:00
34c598e6d8 feat: optimize api
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-19 18:59:00 +08:00
d06321d9b5 feat: complete event module fix tab completer 2019-09-19 18:58:01 +08:00
bee7e19fc3 feat: add bukkit class type
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-12 17:54:17 +08:00
361 changed files with 32617 additions and 7473 deletions

12
.editorconfig Normal file
View File

@@ -0,0 +1,12 @@
# http://editorconfig.org
root = true
[*]
indent_style = space
indent_size = 4
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false

6
.gitignore vendored
View File

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

View File

@@ -1,23 +0,0 @@
test
typings
bundled
build
coverage
docs
wiki
gulpfile.js
bower.json
karma.conf.js
tsconfig.json
typings.json
CONTRIBUTING.md
ISSUE_TEMPLATE.md
PULL_REQUEST_TEMPLATE.md
tslint.json
wallaby.js
.travis.yml
.gitignore
.vscode
.theia
type_definitions
tsconfig.tsbuildinfo

View File

@@ -8,27 +8,28 @@
```txt
└─packages
├─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的插件
└─nukkit 只兼容Nukkit的插件
├─api 全平台兼容的接口
├─core 核心代码 用于引导加载
├─common 公共类库代码 例如 http reflect 模块
├─compile 编译器相关功能
├─client NodeJS 的 Minecraft 客户端 已迁移至 ms-client
├─container IOC容器 用于注入具体实现
├─database 数据库相关功能
├─protocol 协议处理相关功能
├─service 服务相关功能
├─i18n 多语言环境相关支持
├─polyfill Nashorn 的一些自定义增强
├─nashorn Nashorn 的类型定义
├─nodejs NodeJS 的部分 Java 实现
├─bungee BungeeCordAPI 内部实现
├─bukkit BukkitAPI 内部实现
├─sponge SpongeAPI 内部实现
├─nukkit NukkitAPI 内部实现
├─molang MoLang 解析库
├─qrcode 二维码相关类库
├─plugin 插件管理器
├─websocket WebSocket 相关实现
| ├─client 基于 Netty 的 WebSocket 客户端
| └─server 基于 Netty 的 WebSocket 服务端
└─type 类型定义 已迁移到 @javatypes
```

View File

@@ -1,17 +1,12 @@
{
"version": "0.8.1",
"useWorkspaces": true,
"npmClient": "yarn",
"packages": [
"packages/*"
],
"command": {
"run": {
"stream": true
},
"publish": {
"access": "public",
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
}
"version": "0.28.0-beta.9",
"npmClient": "pnpm",
"command": {
"run": {
"stream": true
}
},
"publishConfig": {
"access": "public"
}
}

View File

@@ -6,20 +6,30 @@
"author": "MiaoWoo <admin@yumc.pw>",
"license": "MIT",
"scripts": {
"bs": "lerna bootstrap",
"bs": "pnpm install",
"clean": "lerna run clean",
"watch": "lerna run watch --parallel",
"build": "lerna run build --scope=\"@ccms/!(plugins)\"",
"build:plugins": "lerna run build --scope=\"@ccms/plugins\"",
"ug": "yarn upgrade-interactive --latest",
"np": "lerna exec \"npm publish --access=public --registry https://registry.npmjs.org\" --scope=\"@ccms/!(client|plugins)\"",
"lsp": "npm login --registry=https://registry.npmjs.org --scope=@ccms",
"lp": "lerna publish --registry https://registry.npmjs.org"
"build": "lerna run build",
"ug": "pnpm up -r -i",
"np": "./script/push.sh",
"lsp": "npm login -scope=@ccms",
"lp": "lerna publish --force-publish",
"lpb": "lerna publish prerelease --preid beta --dist-tag beta --force-publish",
"lpc": "lerna publish --canary --preid beta --pre-dist-tag beta --force-publish",
"lpf": "lerna publish from-package --dist-tag beta --yes",
"sync": "./script/sync.sh",
"postpublish": "pnpm sync"
},
"workspaces": [
"packages/*"
],
"devDependencies": {
"lerna": "^3.21.0"
"@ccms/nashorn": "^0.28.0-beta.3",
"@javatypes/jdk": "^0.0.3",
"@lerna-lite/cli": "^2.6.0",
"@lerna-lite/publish": "^2.6.0",
"@lerna-lite/run": "^2.6.0",
"@types/node": "^20.8.8",
"reflect-metadata": "^0.1.13",
"rimraf": "^5.0.5",
"tslib": "^2.6.2",
"typescript": "^5.2.2"
}
}
}

View File

@@ -1 +0,0 @@
../../.npmignore

View File

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

View File

@@ -1,17 +0,0 @@
import { ConnectionFactoryAdapter } from "./connection"
import { RabbitTemplateAdapter } from "./template"
import { JSClass } from "@ccms/container"
export const RabbitAdmin = Java.type('org.springframework.amqp.rabbit.core.RabbitAdmin')
export class RabbitAdminAdapter {
@JSClass('org.springframework.amqp.rabbit.core.RabbitAdmin')
private RabbitAdmin: org.springframework.amqp.rabbit.core.RabbitAdmin
private _Handler: org.springframework.amqp.rabbit.core.RabbitAdmin
constructor(config: RabbitTemplateAdapter | org.springframework.amqp.rabbit.core.RabbitTemplate | ConnectionFactoryAdapter | org.springframework.amqp.rabbit.connection.ConnectionFactory) {
this._Handler = new RabbitAdmin((config instanceof RabbitTemplateAdapter || config instanceof ConnectionFactoryAdapter) ? config.getHandler() : config)
}
getHandler(): org.springframework.amqp.rabbit.core.RabbitAdmin {
return this._Handler
}
}

View File

@@ -1,30 +0,0 @@
export const ConfirmCallback = Java.type('org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback')
export const ReturnCallback = Java.type('org.springframework.amqp.rabbit.core.RabbitTemplate.ReturnCallback')
export abstract class ConfirmCallbackAdapter {
private _Handler: org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback
constructor() {
let ConfirmCallbackImpl = Java.extend(ReturnCallback, {
confirm: (correlationData: org.springframework.amqp.rabbit.connection.CorrelationData, ack: boolean, cause: string) => this.confirm(correlationData, ack, cause)
})
this._Handler = new ConfirmCallbackImpl()
}
abstract confirm(correlationData: org.springframework.amqp.rabbit.connection.CorrelationData, ack: boolean, cause: string)
getHandler() {
return this._Handler
}
}
export abstract class ReturnCallbackAdapter {
private _Handler: org.springframework.amqp.rabbit.core.RabbitTemplate.ReturnCallback
constructor() {
let ReturnCallbackImpl = Java.extend(ReturnCallback, {
returnedMessage: (message: org.springframework.amqp.core.Message, replyCode: number, replyText: string, exchange: string, routingKey: string) => this.returnedMessage(message, replyCode, replyText, exchange, routingKey)
})
this._Handler = new ReturnCallbackImpl()
}
abstract returnedMessage(message: org.springframework.amqp.core.Message, replyCode: number, replyText: string, exchange: string, routingKey: string)
getHandler() {
return this._Handler
}
}

View File

@@ -1,31 +0,0 @@
import threadPool from '@ccms/common/dist/thread-pool'
export const ConnectionFactory = Java.type('org.springframework.amqp.rabbit.connection.ConnectionFactory')
const CachingConnectionFactory = Java.type('org.springframework.amqp.rabbit.connection.CachingConnectionFactory')
interface ConnectionConfig {
url: string,
username?: string,
password?: string,
publisherConfirms?: boolean
cacheSize?: number
}
export class ConnectionFactoryAdapter {
private _Handler: org.springframework.amqp.rabbit.connection.CachingConnectionFactory
constructor(config: ConnectionConfig) {
if (!config.url) { throw new Error('Connection UrI Can\'t be undefiend!') }
config = { publisherConfirms: true, cacheSize: 50, ...config }
this._Handler = new CachingConnectionFactory(new java.net.URI(config.url))
config.username && this._Handler.setUsername(config.username)
config.password && this._Handler.setPassword(config.password)
this._Handler.setPublisherConfirms(config.publisherConfirms)
this._Handler.setExecutor(threadPool.create({
groupName: '@ccms/amqp-rabbit'
}))
this._Handler.setChannelCacheSize(config.cacheSize)
}
getHandler() {
return this._Handler
}
}

View File

@@ -1,30 +0,0 @@
import { ConnectionFactoryAdapter, ConnectionFactory } from "./connection"
import { ChannelAwareMessageListenerAdapter, ChannelAwareMessageListener } from "./listener"
export const SimpleMessageListenerContainer = org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer
export const AcknowledgeMode: org.springframework.amqp.core.AcknowledgeMode = Java.type('org.springframework.amqp.core.AcknowledgeMode')
interface ContainerConfig {
connectionFactory: ConnectionFactoryAdapter | typeof ConnectionFactory
queueNames: string[]
messageListener: ChannelAwareMessageListenerAdapter | typeof ChannelAwareMessageListener
maxConcurrentConsumers?: number
concurrentConsumers?: number
acknowledgeMode?: org.springframework.amqp.core.AcknowledgeMode
}
export class MessageListenerContainerAdapter {
private _Handler: org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer
constructor(config: ContainerConfig) {
config = { concurrentConsumers: 5, maxConcurrentConsumers: 10, acknowledgeMode: AcknowledgeMode.AUTO, ...config }
this._Handler = new SimpleMessageListenerContainer(config.connectionFactory instanceof ConnectionFactoryAdapter ? config.connectionFactory.getHandler() : config.connectionFactory)
//@ts-ignore
this._Handler.setQueueNames(config.queueNames)
this._Handler.setMaxConcurrentConsumers(config.maxConcurrentConsumers)
this._Handler.setConcurrentConsumers(config.concurrentConsumers)
this._Handler.setAcknowledgeMode(config.acknowledgeMode)
this._Handler.setMessageListener(config.messageListener instanceof ChannelAwareMessageListenerAdapter ? config.messageListener.getHandler() : config.messageListener)
}
getHandler() {
return this._Handler
}
}

View File

@@ -1,37 +0,0 @@
const JavaString = Java.type('java.lang.String')
const MessageProperties = org.springframework.amqp.core.MessageProperties
const Message = org.springframework.amqp.core.Message
export const MessageConverter = Java.type('org.springframework.amqp.support.converter.MessageConverter')
export class MessageConverterAdapter {
private _Handler: org.springframework.amqp.support.converter.MessageConverter
constructor() {
var MessageConverterImpl = Java.extend(MessageConverter, {
toMessage: (object: any, messageProperties: org.springframework.amqp.core.MessageProperties) => this.toMessage(object, messageProperties),
fromMessage: (message: org.springframework.amqp.core.Message) => this.fromMessage(message)
})
this._Handler = new MessageConverterImpl()
}
toMessage(object: any, messageProperties: org.springframework.amqp.core.MessageProperties) {
if (typeof object == "string") {
messageProperties.setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN)
return new Message(new JavaString(object).getBytes(), messageProperties)
} else {
messageProperties.setContentType(MessageProperties.CONTENT_TYPE_JSON)
return new Message(new JavaString(JSON.stringify(object)).getBytes(), messageProperties)
}
}
fromMessage(message: org.springframework.amqp.core.Message) {
if (message.getMessageProperties().getContentType() == MessageProperties.CONTENT_TYPE_TEXT_PLAIN) {
return new JavaString(message.getBody(), message.getMessageProperties().getContentEncoding())
}
if (message.getMessageProperties().getContentType() == MessageProperties.CONTENT_TYPE_JSON) {
return JSON.parse(new JavaString(message.getBody(), message.getMessageProperties().getContentEncoding()))
}
return message
}
getHandler() {
return this._Handler
}
}

View File

@@ -1,7 +0,0 @@
export * from './admin'
export * from './callback'
export * from './connection'
export * from './container'
export * from './converter'
export * from './listener'
export * from './template'

View File

@@ -1,49 +0,0 @@
const JavaString = Java.type('java.lang.String')
export const MessageProperties = org.springframework.amqp.core.MessageProperties
export const ChannelAwareMessageListener = Java.type('org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener')
export const AmqpRejectAndDontRequeueException = org.springframework.amqp.AmqpRejectAndDontRequeueException
export const Channel: com.rabbitmq.client.Channel = Java.type('com.rabbitmq.client.Channel')
export const Message = org.springframework.amqp.core.Message
export type MessageHandler<T> = (content: T, message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel) => any
export abstract class ChannelAwareMessageListenerAdapter<T = any> {
private _Handler: org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener
constructor(manual: boolean = false) {
let ChannelAwareMessageListenerImpl = Java.extend(ChannelAwareMessageListener, {
onMessage: (message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel) => {
let content = new JavaString(message.getBody(), message.getMessageProperties().getContentEncoding() || "UTF-8")
try {
if (message.getMessageProperties().getContentType() == MessageProperties.CONTENT_TYPE_JSON) {
content = JSON.parse(content)
}
} catch (error) {
if (manual) {
channel.basicReject(message.getMessageProperties().getDeliveryTag(), true)
} else {
throw new AmqpRejectAndDontRequeueException(`${error}`, error)
}
}
manual ? this.manualOnMessage(content, message, channel) : this.onMessage(content, message, channel)
}
})
this._Handler = new ChannelAwareMessageListenerImpl()
}
abstract onMessage(content: T, message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel): any
onError(error: Error, message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel): any { }
getHandler() {
return this._Handler
}
private manualOnMessage(content: T, message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel) {
let deliveryTag = message.getMessageProperties().getDeliveryTag()
try {
if (this.onMessage(content, message, channel)) {
channel.basicAck(deliveryTag, false)
} else if (message.getMessageProperties().getRedelivered()) {
channel.basicReject(deliveryTag, true)
} else {
channel.basicNack(deliveryTag, false, true)
}
} catch (error) {
channel.basicReject(deliveryTag, this.onError(error, message, channel))
}
}
}

View File

@@ -1,27 +0,0 @@
import { MessageConverterAdapter } from "./converter"
import { ConnectionFactoryAdapter } from "./connection"
import { ConfirmCallbackAdapter, ReturnCallbackAdapter } from "./callback"
export const RabbitTemplate = Java.type('org.springframework.amqp.rabbit.core.RabbitTemplate')
interface TemplateConfig {
connectionFactory: ConnectionFactoryAdapter | org.springframework.amqp.rabbit.connection.ConnectionFactory
confirmCallback?: ConfirmCallbackAdapter
returnCallback?: ReturnCallbackAdapter
messageConverter?: MessageConverterAdapter
}
export class RabbitTemplateAdapter {
private _Handler: org.springframework.amqp.rabbit.core.RabbitTemplate
constructor(config: TemplateConfig) {
config = { messageConverter: new MessageConverterAdapter(), ...config }
console.debug(JSON.stringify(config))
this._Handler = new RabbitTemplate(config.connectionFactory instanceof ConnectionFactoryAdapter ? config.connectionFactory.getHandler() : config.connectionFactory)
config.returnCallback && this._Handler.setReturnCallback(config.returnCallback.getHandler())
config.confirmCallback && this._Handler.setConfirmCallback(config.confirmCallback.getHandler())
config.messageConverter && this._Handler.setMessageConverter(config.messageConverter.getHandler())
}
getHandler() {
return this._Handler
}
}

View File

@@ -1,89 +0,0 @@
import { JSClass } from "@ccms/container"
import { RabbitAdminAdapter, MessageListenerContainerAdapter, AcknowledgeMode, MessageHandler, ChannelAwareMessageListenerAdapter } from "./adapter"
export class AmqpAdmin {
@JSClass('org.springframework.amqp.core.TopicExchange')
private TopicExchange: typeof org.springframework.amqp.core.TopicExchange
@JSClass('org.springframework.amqp.core.Queue')
private Queue: typeof org.springframework.amqp.core.Queue
@JSClass('org.springframework.amqp.core.Binding')
private Binding: typeof org.springframework.amqp.core.Binding
@JSClass('org.springframework.amqp.rabbit.core.RabbitAdmin')
private RabbitAdmin: typeof org.springframework.amqp.rabbit.core.RabbitAdmin
@JSClass('org.springframework.amqp.core.Binding.DestinationType')
private DestinationType: org.springframework.amqp.core.Binding.DestinationType
private amqpAdmin: org.springframework.amqp.rabbit.core.RabbitAdmin
constructor(amqpAdmin: org.springframework.amqp.rabbit.core.RabbitAdmin | any) {
if (amqpAdmin instanceof this.RabbitAdmin) {
this.amqpAdmin = amqpAdmin
} else if (amqpAdmin instanceof RabbitAdminAdapter) {
this.amqpAdmin = amqpAdmin.getHandler()
} else {
this.amqpAdmin = new RabbitAdminAdapter(amqpAdmin).getHandler()
}
}
getHandler() {
return this.amqpAdmin
}
getQueueProperties(name: string) {
return this.amqpAdmin.getQueueProperties(name)
}
declareExchange(name: string) {
let exchange = new this.TopicExchange(name, true, false)
this.amqpAdmin.declareExchange(exchange)
return this
}
declareQueue(name: string) {
let queue = new this.Queue(name, true)
this.amqpAdmin.declareQueue(queue)
return this
}
declareBinding(queue: string, exchange: string, routerKey: string, argument: any = null) {
let binding = new this.Binding(queue, this.DestinationType.QUEUE, exchange, routerKey, argument)
this.amqpAdmin.declareBinding(binding)
return this
}
declareQueueAndBindExchange(queue: string, exchange: string, routerKey: string) {
return this.declareQueue(queue).declareExchange(exchange).declareBinding(queue, exchange, routerKey)
}
createContainer<T>(queue: string, listener: MessageHandler<T>, acknowledgeMode = AcknowledgeMode.AUTO) {
let connection = this.amqpAdmin.getRabbitTemplate().getConnectionFactory()
return new MessageListenerContainerAdapter({
connectionFactory: connection,
queueNames: [queue],
messageListener: new SimpleMessageHandler(listener),
acknowledgeMode: acknowledgeMode
}).getHandler()
}
send()
send() {
}
getTemplate() {
return this.amqpAdmin.getRabbitTemplate()
}
close() {
this.getTemplate().stop()
}
}
export class SimpleMessageHandler extends ChannelAwareMessageListenerAdapter {
constructor(private handler: MessageHandler<any>) {
super()
}
onMessage(content: any, message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel) {
return this.handler(content, message, channel)
}
}

View File

@@ -1,3 +0,0 @@
export const METADATA_KEY = {
}

View File

@@ -1,34 +0,0 @@
/// <reference types="@ccms/nashorn" />
/// <reference types="@javatypes/jdk" />
/// <reference types="@javatypes/spring-amqp" />
/// <reference types="@javatypes/spring-rabbit" />
/// <reference types="@javatypes/amqp-client" />
import { amqp } from '@ccms/api'
import { getContainer, reduceMetadata } from '@ccms/container'
function init() {
const beanFactory = base.getInstance().getAutowireCapableBeanFactory()
getContainer().bind(amqp.rabbit.Template).toDynamicValue((ctx) => {
let metadata = reduceMetadata(ctx)
if (!metadata.named) {
return beanFactory.getBean('rabbitTemplate')
} else {
return beanFactory.getBean(`${metadata.named}-rabbitTemplate`)
}
})
getContainer().bind(amqp.rabbit.Admin).toDynamicValue((ctx) => {
let metadata = reduceMetadata(ctx)
if (!metadata.named) {
return beanFactory.getBean('rabbitAdmin')
} else {
return beanFactory.getBean(`${metadata.named}-rabbitAdmin`)
}
})
}
init()
export * from './admin'
export * from './adapter'
export * from './manager'
export * from './constants'

View File

@@ -1,5 +0,0 @@
export class AmqpListener {
constructor() {
}
}

View File

@@ -1,18 +0,0 @@
import { amqp } from "@ccms/api"
import { provideSingleton } from "@ccms/container"
import { ConnectionFactoryAdapter, RabbitTemplateAdapter, RabbitAdminAdapter } from "./adapter"
import { AmqpAdmin } from "./admin"
@provideSingleton(amqp.Manager)
export class AmqpManager {
createConnection(url: string, username: string, password: string) {
return new ConnectionFactoryAdapter({ url, username, password })
}
createTemplate(adapter: ConnectionFactoryAdapter) {
return new RabbitTemplateAdapter({ connectionFactory: adapter })
}
createAdmin(adapter: RabbitTemplateAdapter | ConnectionFactoryAdapter) {
return new AmqpAdmin(new RabbitAdminAdapter(adapter))
}
}

View File

@@ -1 +0,0 @@
../../.npmignore

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/api",
"version": "0.8.1",
"version": "0.28.0-beta.9",
"description": "MiaoScript api package",
"keywords": [
"miaoscript",
@@ -12,23 +12,26 @@
"homepage": "https://github.com/circlecloud/ms.git",
"license": "ISC",
"main": "dist/index.js",
"files": [
"dist/**/*.js",
"dist/**/*.ts",
"dist/**/*.map"
],
"scripts": {
"clean": "rimraf dist",
"watch": "tsc --watch",
"build": "yarn clean && tsc",
"build": "pnpm clean && tsc",
"test": "echo \"Error: run tests from root\" && exit 1"
},
"dependencies": {
"@ccms/common": "^0.8.0",
"@ccms/container": "^0.8.0",
"@ccms/ployfill": "^0.8.1",
"base64-js": "^1.3.1",
"@ccms/common": "^0.28.0-beta.9",
"@ccms/container": "^0.28.0-beta.9",
"@ccms/i18n": "^0.28.0-beta.9",
"@ccms/polyfill": "^0.28.0-beta.9",
"base64-js": "^1.5.1",
"source-map-builder": "^0.0.7"
},
"devDependencies": {
"@types/base64-js": "^1.2.5",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.9.2"
"@types/base64-js": "^1.3.0"
}
}

View File

@@ -1,4 +1,4 @@
import { injectable } from "@ccms/container";
import { injectable } from "@ccms/container"
export namespace channel {
/**
@@ -17,32 +17,32 @@ export namespace 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;
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] = [];
if (!this.listenerMap[name]) this.listenerMap[name] = []
let offExec = () => {
this.unregister(channel, listener);
console.debug(`[${name}] unregister channel ${channel}`);
};
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;
}
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];
var channelCache = this.listenerMap[plugin.description.name]
if (channelCache) {
channelCache.forEach(t => t.off());
delete this.listenerMap[plugin.description.name];
channelCache.forEach(t => t.off())
delete this.listenerMap[plugin.description.name]
}
}
/**

31
packages/api/src/chat.ts Normal file
View File

@@ -0,0 +1,31 @@
import { injectable } from '@ccms/container'
export namespace chat {
@injectable()
export abstract class Chat {
/**
* sendJsonChat
* @param sender reciver
* @param json json
* @param type chat Type 0: chat 1: system 2: actionBar
*/
sendJson(sender: any, json: string | object, type = 0) {
throw new Error("Method not implemented.")
}
sendMessage(sender: any, message: string) {
throw new Error("Method not implemented.")
}
sendActionBar(sender: any, message: string) {
throw new Error("Method not implemented.")
}
clearActionBar(sender: any) {
this.sendActionBar(sender, '')
}
sendTitle(sender: any, title: string, subtitle: string = '', fadeIn: number = 20, time: number = 100, fadeOut: number = 20) {
throw new Error("Method not implemented.")
}
clearTitle(sender: any) {
this.sendTitle(sender, '', '', 0, 0, 0)
}
}
}

View File

@@ -1,10 +1,16 @@
import i18n from '@ccms/i18n'
import { injectable } from "@ccms/container"
import { plugin } from './interfaces'
import { plugin } from './plugin'
export namespace command {
@injectable()
export abstract class Command {
/**
* first time script engine need optimize jit code
* so ignore first slow exec notify
*/
private cacheSlowKeys = {};
/**
* 注册插件命令
* @param plugin 插件
@@ -13,7 +19,7 @@ export namespace command {
*/
on(plugin: plugin.Plugin, name: string, exec: { cmd: Function, tab?: Function }) {
var cmd = this.create(plugin, name)
if (!cmd) { throw Error("") }
if (!cmd) { throw Error(`Plugin ${plugin.description.name} can't create Command ${name}!`) }
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)
@@ -24,6 +30,9 @@ export namespace command {
this.onTabComplete(plugin, cmd, exec.tab)
}
}
public tabComplete(sender: any, input: string, index?: number): string[] {
throw new Error("Method not implemented.")
}
/**
* 取消命令注册
* @param plugin 插件
@@ -41,13 +50,15 @@ export namespace command {
protected setExecutor(plugin: plugin.Plugin, command: any, executor: Function) {
return (sender: any, _: any, command: string, args: string[]) => {
try {
return executor(sender, command, Java.from(args))
} catch (ex) {
console.i18n("ms.api.command.execute.error", { player: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex })
console.ex(ex)
if (sender.name != 'CONSOLE') {
console.sender(sender, [i18n.translate("ms.api.command.execute.error", { player: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex }), ...console.stack(ex)])
}
let time = Date.now()
let result = executor(sender, command, Java.from(args))
this.checkSlow(Date.now() - time,
"ms.api.command.execute.slow",
plugin, command, sender, args)
return result
} catch (ex: any) {
this.printError(ex, "ms.api.command.execute.error",
plugin, command, sender, args)
return true
}
}
@@ -55,17 +66,22 @@ export namespace command {
protected setTabCompleter(plugin: plugin.Plugin, command: any, tabCompleter: Function) {
return (sender: any, _: any, command: string, args: string[]) => {
try {
let time = Date.now()
var token = args[args.length - 1]
var complete = tabCompleter(sender, command, Java.from(args)) || []
return this.copyPartialMatches(complete, token)
} catch (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, [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)])
let result = this.copyPartialMatches(complete, token)
this.checkSlow(Date.now() - time,
"ms.api.command.tab.completer.slow",
plugin, command, sender, args)
return result
} catch (ex: any) {
this.printError(ex, "ms.api.command.tab.completer.error",
plugin, command, sender, args)
return []
}
}
}
protected copyPartialMatches(complete: string[], token: string, array: string[] = []): string[] {
if (!token) { return complete }
complete.forEach(function (e) {
@@ -75,5 +91,35 @@ export namespace command {
})
return array
}
private checkSlow(cost: number, key: string, plugin: plugin.Plugin, command: string, sender: any, args: any[]) {
if (cost > global.ScriptSlowExecuteTime) {
let completerKey = `${plugin.description.name}-${key}-${command}-${sender.name}`
if (!this.cacheSlowKeys[completerKey]) {
return this.cacheSlowKeys[completerKey] = cost
}
console.i18n(key, {
player: sender.name,
plugin: plugin.description.name,
command,
args: Java.from(args).join(' '),
cost
})
}
}
private printError(error: Error, key: string, plugin: plugin.Plugin, command: string, sender: any, args: any[]) {
let message = i18n.translate(key, {
player: sender.name,
plugin: plugin.description.name,
command,
args: Java.from(args).join(' '),
error
})
console.console(message)
console.ex(error)
if (sender.name != 'CONSOLE') {
console.sender(sender, [message, ...console.stack(error)])
}
}
}
}

View File

@@ -5,7 +5,7 @@ import * as base64 from 'base64-js'
const Arrays = Java.type('java.util.Arrays')
const Level = Java.type('java.util.logging.Level')
const Paths = Java.type('java.nio.file.Paths')
const ignoreLogPrefix = ['java.', 'javax.', 'sun.', 'net.minecraft.', 'org.bukkit.', 'jdk.nashorn.', 'io.netty.', 'org.spongepowered.', 'org.apache', 'org.springframework']
const ignoreLogPrefix = ['java.', 'javax.', 'sun.', 'net.minecraft.', 'org.bukkit.', 'jdk.internal.dynalink.', 'jdk.nashorn.', 'org.openjdk.nashorn', 'io.netty.', 'org.spongepowered.', 'org.apache', 'org.springframework']
enum LogLevel {
ALL,
@@ -18,16 +18,118 @@ enum LogLevel {
OFF
}
export class MiaoScriptConsole implements Console {
Console: NodeJS.ConsoleConstructor
const sourceMaps: { [key: string]: SourceMapBuilder } = {}
const sourceFileMaps: { [key: string]: string } = {}
global.setGlobal('MiaoScriptSourceMaps', sourceMaps)
global.setGlobal('MiaoScriptSourceFileMaps', sourceFileMaps)
export namespace jsconsole {
export function readSourceMap(fileName: string, lineNumber: any) {
if (lineNumber == 1) return { fileName, lineNumber }
try {
if (fileName.endsWith('js') || fileName.endsWith('ms')) {
if (sourceMaps[fileName] === undefined) {
sourceMaps[fileName] = null
let sourceLine = base.read(fileName).split('\n')
let lastLine = sourceLine[sourceLine.length - 1] || sourceLine[sourceLine.length - 2]
// lastLine is similar //# sourceMappingURL=data:application/json;base64,
if (lastLine.startsWith('//# sourceMappingURL=')) {
let sourceContent = null
let sourceMappingURL = lastLine.split('sourceMappingURL=', 2)[1]
if (sourceMappingURL.startsWith('data:application/json;base64,')) {
sourceContent = String.fromCharCode(...Array.from(base64.toByteArray(sourceMappingURL.split(',', 2)[1])))
} else if (sourceMappingURL.startsWith('http://') || sourceMappingURL.startsWith('https://')) {
// TODO
} else {
let file = Paths.get(Paths.get(fileName, '..', sourceMappingURL).toFile().getCanonicalPath()).toFile()
if (file.exists()) {
sourceContent = base.read(file)
sourceFileMaps[fileName] = file.getCanonicalPath()
} else if (global.debug) {
console.debug('readSourceMap can\'t found', fileName, 'source map file', sourceMappingURL)
}
}
if (sourceContent) {
sourceMaps[fileName] = new SourceMapBuilder(JSON.parse(sourceContent))
}
}
}
if (sourceMaps[fileName]) {
let sourceMapping = sourceMaps[fileName].getSource(lineNumber, 25, true, true)
if (sourceMapping) {
fileName = Paths.get(fileName, '..', sourceMapping.sourcePath).toFile().getCanonicalPath()
lineNumber = sourceMapping.mapping.sourceLine
}
}
}
} catch (error: any) {
console.debug('search source map', fileName, 'line', lineNumber, 'error:', error)
if (global.debug) {
console.ex(error)
}
}
return { fileName, lineNumber }
}
export function getStackTrace(ex: Error, color: boolean = true): string[] {
if (!ex) return []
let stack = ex.getStackTrace()
let cache = [(color ? '§c' : '') + ex]
//@ts-ignore
if (stack.class) {
stack = Arrays.asList(stack)
}
stack.forEach(trace => {
if (!trace.fileName || trace.fileName.startsWith('jar:file:') || trace.fileName.startsWith('file:')) { return }
if (trace.className.startsWith('<')) {
let { fileName, lineNumber } = readSourceMap(trace.fileName, trace.lineNumber)
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
if (color) {
cache.push(` §e->§c ${fileName}:${lineNumber}(${trace.lineNumber}) => §4${trace.methodName}`)
} else {
cache.push(` -> ${fileName}:${lineNumber}(${trace.lineNumber}) => ${trace.methodName}`)
}
} else {
let className = trace.className
var fileName = trace.fileName as string
var lineNumber = trace.lineNumber
if (className.startsWith('jdk.nashorn.internal.scripts') || className.startsWith('org.openjdk.nashorn.internal.scripts')) {
className = className.substr(className.lastIndexOf('$') + 1)
var { fileName, lineNumber } = readSourceMap(fileName, lineNumber)
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
} else {
if (!global.debug) {
for (let prefix in ignoreLogPrefix) {
if (className.startsWith(ignoreLogPrefix[prefix])) {
return
}
}
} else if (className.startsWith('jdk.nashorn.internal.') || className.startsWith('org.openjdk.nashorn.internal.')) {
return
}
}
if (color) {
cache.push(` §e->§c ${className}.${trace.methodName}(§4${fileName}:${lineNumber}§c)`)
} else {
cache.push(` -> ${className}.${trace.methodName}(${fileName}:${lineNumber})`)
}
}
})
return cache
}
}
export class MiaoScriptConsole implements Console {
Console: any
memory: any
private static sourceMaps: { [key: string]: SourceMapBuilder } = {}
private static sourceFileMaps: { [key: string]: string } = {}
private _name: string = ''
private _level: LogLevel = LogLevel.INFO
protected logger: any
protected prefix: string = '§6[§bMiaoScript§6]§r '
public prefix: string = '§6[§bMiaoScript§6]§r '
constructor(name?: string) {
this.name = name
@@ -47,10 +149,10 @@ export class MiaoScriptConsole implements Console {
set name(name: string) {
if (name) {
this._name = `[${name}] `
// noinspection JSUnusedGlobalSymbols
this.prefix = `§6[§cMS§6][§b${name}§6]§r `
}
}
log(...args: any[]): void {
this.logger.info(this.name + args.join(' '))
}
@@ -90,83 +192,8 @@ export class MiaoScriptConsole implements Console {
ex(ex: Error) {
this.stack(ex).forEach(line => this.console(line))
}
readSourceMap(fileName: string, lineNumber: number) {
try {
if (fileName.endsWith('js')) {
if (MiaoScriptConsole.sourceMaps[fileName] === undefined) {
MiaoScriptConsole.sourceMaps[fileName] = null
let sourceLine = base.read(fileName).split('\n')
let lastLine = sourceLine[sourceLine.length - 1]
if (lastLine.startsWith('//# sourceMappingURL=')) {
let sourceContent = null
let sourceMappingURL = lastLine.split('sourceMappingURL=', 2)[1]
if (sourceMappingURL.startsWith('data:application/jsonbase64,')) {
sourceContent = String.fromCharCode(...Array.from(base64.toByteArray(sourceMappingURL.split(',', 2)[1])))
} else if (sourceMappingURL.startsWith('http')) {
// TODO
} else {
let file = Paths.get(Paths.get(fileName, '..', sourceMappingURL).toFile().getCanonicalPath()).toFile()
if (file.exists()) { sourceContent = base.read(file) }
}
if (sourceContent) {
MiaoScriptConsole.sourceMaps[fileName] = new SourceMapBuilder(JSON.parse(sourceContent))
MiaoScriptConsole.sourceFileMaps[fileName] = Paths.get(fileName, '..', MiaoScriptConsole.sourceMaps[fileName].sources[0]).toFile().getCanonicalPath()
}
}
}
if (MiaoScriptConsole.sourceMaps[fileName]) {
let sourceMapping = MiaoScriptConsole.sourceMaps[fileName].getSource(lineNumber, 25, true, true)
fileName = MiaoScriptConsole.sourceFileMaps[fileName]
if (sourceMapping && lineNumber != sourceMapping.mapping.sourceLine) { lineNumber = sourceMapping.mapping.sourceLine }
}
}
} catch (error) {
console.debug('search source map', fileName, 'line', lineNumber, 'error:', error)
}
return {
fileName,
lineNumber
}
}
stack(ex: Error, color: boolean = true): string[] {
let stack = ex.getStackTrace()
let cache = [(color ? '§c' : '') + ex]
//@ts-ignore
if (stack.class) {
stack = Arrays.asList(stack)
}
stack.forEach(trace => {
if (!trace.fileName || trace.fileName.startsWith('jar:file:') || trace.fileName.startsWith('file:')) { return }
if (trace.className.startsWith('<')) {
let { fileName, lineNumber } = this.readSourceMap(trace.fileName, trace.lineNumber)
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
if (color) {
cache.push(` §e->§c ${fileName}:${lineNumber} => §4${trace.methodName}`)
} else {
cache.push(` -> ${fileName}:${lineNumber} => ${trace.methodName}`)
}
} else {
let className = trace.className
var fileName = trace.fileName as string
if (className.startsWith('jdk.nashorn.internal.scripts')) {
className = className.substr(className.lastIndexOf('$') + 1)
var { fileName, lineNumber } = this.readSourceMap(trace.fileName, trace.lineNumber)
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
} else {
for (let prefix in ignoreLogPrefix) {
if (className.startsWith(ignoreLogPrefix[prefix])) {
return
}
}
}
if (color) {
cache.push(` §e->§c ${className}.${trace.methodName}(§4${fileName}:${lineNumber}§c)`)
} else {
cache.push(` -> ${className}.${trace.methodName}(${fileName}:${lineNumber})`)
}
}
})
return cache
return jsconsole.getStackTrace(ex, color)
}
assert(value: any, message?: string, ...optionalParams: any[]): void {
throw new Error("Method not implemented.")
@@ -180,12 +207,15 @@ export class MiaoScriptConsole implements Console {
countReset(label?: string): void {
throw new Error("Method not implemented.")
}
dir(obj: any, options?: NodeJS.InspectOptions): void {
dir(obj: any, options?: any): void {
throw new Error("Method not implemented.")
}
dirxml(...data: any[]): void {
throw new Error("Method not implemented.")
}
exception(message?: string, ...optionalParams: any[]): void {
throw new Error('Method not implemented.')
}
group(...label: any[]): void {
throw new Error("Method not implemented.")
}

View File

@@ -1,10 +1,31 @@
export namespace constants {
export namespace ServiceIdentifier {
/**
* Runtime Server NettyPipeline
*/
export const NettyPipeline = Symbol("NettyPipeline")
/**
* Runtime Server RootLogger
*/
export const RootLogger = Symbol("RootLogger")
}
export namespace Reflect {
export const Method = {
getServerConnection: [/*spigot 1.8.8*/'aq',/*spigot 1.12.2*/ 'an', /*spigot 1.14.4+*/'getServerConnection', /*catserver 1.12.2*/'func_147137_ag']
getServerConnection: [
/*spigot 1.8.8*/'aq',
/*spigot 1.12.2*/ 'an',
/*spigot 1.14.4+*/'getServerConnection',
/*spigot 1.19+*/'ad',
/*catserver 1.12.2*/'func_147137_ag'
]
}
export const Field = {
listeningChannels: [/*spigot 1.8.8-1.12.2*/'g', /*spigot 1.14.4*/'f', /*spigot 1.15.2+*/'listeningChannels', /*catserver 1.12.2*/'field_151274_e']
listeningChannels: [
/*spigot 1.8.8-1.12.2*/'g',
/*spigot 1.14.4*/'f',
/*spigot 1.15.2+*/'listeningChannels',
/*catserver 1.12.2*/'field_151274_e'
]
}
}
export enum ServerType {

View File

@@ -0,0 +1,56 @@
import { injectable } from "@ccms/container"
export namespace database {
export const DataSource = Symbol("DataSource")
/**
* 数据库配置
*/
export interface DataBaseConfig {
/**
* 数据库类型
*/
type: 'h2' | 'mysql' | 'mongodb' | 'sqlite' | 'postgres' | 'redis'
/**
* 数据库连接串
*/
url: string | javax.sql.DataSource
/**
* 数据库驱动
*/
driverClassName?: string
/**
* 用户名
*/
username?: string
/**
* 密码
*/
password?: string
/**
* 链接属性
*/
properties?: { [key: string]: any }
/**
* 调试模式
*/
debug?: boolean
}
@injectable()
export abstract class DataBaseManager {
abstract setMainDatabase(mainDatabase: DataBase): void
abstract getMainDatabase(): DataBase
abstract createDatabase(name: string, config: DataBaseConfig): DataBase
abstract removeDatabase(name: string): boolean
abstract getDatabase(name: string): DataBase
abstract startWebManager(...args: string[])
abstract stopWebManager()
abstract shutdown()
}
@injectable()
export abstract class DataBase {
abstract query<T>(sql: string, ...args: any[]): Array<T>
abstract update(sql: string, ...args: any[]): number
abstract execute(sql: string): void
}
}

View File

@@ -4,7 +4,7 @@
import i18n from '@ccms/i18n'
import { injectable, unmanaged } from '@ccms/container'
const Thread = Java.type('java.lang.Thread');
const Thread = Java.type('java.lang.Thread')
export namespace event {
/**
@@ -25,12 +25,13 @@ export namespace event {
public EventPriority = EventPriority;
private mapEvent = [];
private listenerMap = [];
private pluginEventMap = [];
private cacheSlowEventKey = {};
protected baseEventDir = '';
constructor(@unmanaged() baseEventDir: string) {
this.baseEventDir = baseEventDir;
this.baseEventDir = baseEventDir
}
/**
@@ -39,115 +40,134 @@ export namespace event {
* org.spongepowered.api.event.game.GameRegistryEvent.Register => gameregistryevent$register
*/
mapEventName() {
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();
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;
let entry = entries.nextElement()
let name = entry.name
if (name.startsWith(this.baseEventDir) && name.endsWith(".class")) {
// replace name to qualifiedName
let qualifiedName = name.replaceAll('/', '.');
let qualifiedName = name.replaceAll('/', '.')
try {
let clazz = base.getClass(qualifiedName.substring(0, qualifiedName.length - 6));
let clazz = base.getClass(qualifiedName.substring(0, qualifiedName.length - 6))
if (this.isValidEvent(clazz)) {
let simpleName = this.class2Name(clazz).toLowerCase();
console.trace(i18n.translate("ms.api.event.mapping", { canonicalName: clazz.canonicalName, simpleName }));
this.mapEvent[simpleName] = clazz;
count++;
let simpleName = this.class2Name(clazz).toLowerCase()
console.trace(i18n.translate("ms.api.event.mapping", { canonicalName: clazz.canonicalName, simpleName }))
this.mapEvent[simpleName] = clazz
count++
}
} catch (ex) {
} catch (ex: any) {
//ignore already loaded class
}
}
}
return count;
return count
}
getJarFile(resource: string, loader?: any) {
let dirs = (loader || Thread.currentThread().getContextClassLoader()).getResources(resource);
let dirs = (loader || Thread.currentThread().getContextClassLoader()).getResources(resource)
if (dirs.hasMoreElements()) {
let url = dirs.nextElement();
if (url.protocol === "jar") { return url.openConnection().jarFile; }
let url = dirs.nextElement()
if (url.protocol === "jar") { return url.openConnection().jarFile }
}
throw new Error(i18n.translate("ms.api.event.resource.not.found", { resource }))
}
class2Name(clazz: any) {
return clazz.simpleName;
return clazz.simpleName
}
name2Class(name: any, event: string) {
let eventCls = this.mapEvent[event.toLowerCase()] || this.mapEvent[event.toLowerCase() + 'event'];
let eventCls = this.mapEvent[event.toLowerCase()] || this.mapEvent[event.toLowerCase() + 'event']
if (!eventCls) {
try {
eventCls = base.getClass(eventCls);
this.mapEvent[event] = eventCls;
} catch (ex) {
eventCls = base.getClass(event)
this.mapEvent[event] = eventCls
} catch (ex: any) {
console.i18n("ms.api.event.not.found", { name, event })
return;
return
}
}
return eventCls;
return eventCls
}
execute(name, exec, eventCls) {
/**
* 创建命令执行器
* @param name 插件名称
* @param exec 执行方法
* @param eventCls 事件类
* @returns
*/
createExecute(name, exec, eventCls) {
return (...args: any[]) => {
let event = args[args.length - 1]
try {
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 })
}
if (!eventCls.isAssignableFrom(event.getClass())) { return }
let time = Date.now(); exec(event); let cost = Date.now() - time
if (cost > global.ScriptSlowExecuteTime && !event.async) {
let eventKey = `${name}-${this.class2Name(eventCls)}`
if (!this.cacheSlowEventKey[eventKey]) { return this.cacheSlowEventKey[eventKey] = cost }
console.i18n("ms.api.event.execute.slow", { name, event: this.class2Name(eventCls), cost })
}
} catch (ex) {
} catch (ex: any) {
console.i18n("ms.api.event.execute.error", { name, event: this.class2Name(eventCls), ex })
console.ex(ex);
console.ex(ex)
}
}
}
/**
* 添加事件监听
* @param plugin {any}
* @param event {string}
* @param exec {function}
* @param priority {string} [LOWEST,LOW,NORMAL,HIGH,HIGHEST,MONITOR]
* @param ignoreCancel
* @param plugin {any} 插件
* @param event {string} 事件名称
* @param exec {function} 事件执行器
* @param priority {string} [LOWEST,LOW,NORMAL,HIGH,HIGHEST,MONITOR] 优先级
* @param ignoreCancel 是否忽略已取消事件
*/
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 (!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 () => { console.warn('event ' + event + ' not found ignore off listener.') } }
if (typeof priority === 'boolean') {
ignoreCancel = priority;
priority = EventPriority.NORMAL;
ignoreCancel = priority
priority = EventPriority.NORMAL
}
priority = priority || EventPriority.NORMAL;
ignoreCancel = ignoreCancel || false;
priority = priority || EventPriority.NORMAL
ignoreCancel = ignoreCancel || false
// @ts-ignore
let executor = exec.name || exec.executor || '[anonymous]'
// noinspection JSUnusedGlobalSymbols
var listener = this.register(eventCls, this.execute(name, exec, eventCls), priority, ignoreCancel);
var listenerMap = this.listenerMap;
let listener = this.register(
eventCls,
this.createExecute(name, exec, eventCls),
priority,
ignoreCancel
)
// add to cache Be used for close plugin to close event
if (!listenerMap[name]) listenerMap[name] = [];
var offExec = () => {
this.unregister(eventCls, listener);
console.debug(i18n.translate("ms.api.event.unregister", { name, event: this.class2Name(eventCls) }));
};
var off = {
event: eventCls,
listener: listener,
off: offExec
};
listenerMap[name].push(off);
if (!this.pluginEventMap[name]) this.pluginEventMap[name] = []
let off = () => {
if (off['offed']) return
off['offed'] = true
this.unregister(eventCls, listener)
console.debug(i18n.translate("ms.api.event.unregister", {
name,
event: this.class2Name(eventCls),
exec: executor
}))
}
this.pluginEventMap[name].push(off)
// noinspection JSUnresolvedVariable
console.debug(i18n.translate("ms.api.event.register", { name, event: this.class2Name(eventCls) }));
return off;
console.debug(i18n.translate("ms.api.event.register", {
name,
event: this.class2Name(eventCls),
exec: executor,
priority,
ignore: ignoreCancel
}))
return off
}
/**
@@ -155,10 +175,10 @@ export namespace event {
* @param plugin 插件
*/
disable(plugin: any) {
var eventCache = this.listenerMap[plugin.description.name];
var eventCache = this.pluginEventMap[plugin.description.name]
if (eventCache) {
eventCache.forEach(t => t.off());
delete this.listenerMap[plugin.description.name];
eventCache.forEach((off: () => any) => off())
delete this.pluginEventMap[plugin.description.name]
}
}
@@ -166,7 +186,7 @@ export namespace event {
* 判断
* @param clazz 事件类
*/
abstract isValidEvent(clazz: any): boolean;
abstract isValidEvent(clazz: any): boolean
/**
* 注册事件
* @param eventCls 事件类
@@ -174,12 +194,12 @@ export namespace event {
* @param priority 优先级
* @param ignoreCancel 是否忽略已取消的事件
*/
abstract register(eventCls: any, exec: Function, priority: any, ignoreCancel: boolean): any;
abstract register(eventCls: any, exec: Function, priority: any, ignoreCancel: boolean): any
/**
* 取消监听事件
* @param event 事件
* @param listener 监听器
*/
abstract unregister(event: any, listener: any): void;
abstract unregister(event: any, listener: any): void
}
}

View File

@@ -1,8 +1,16 @@
import "@ccms/nashorn"
export * from './chat'
export * from './task'
export * from './item'
export * from './event'
export * from './proxy'
export * from './plugin'
export * from './server'
export * from './console'
export { jsconsole as console } from './console'
export * from './channel'
export * from './command'
export * from './database'
export * from './particle'
export * from './constants'
export * from './interfaces'

View File

@@ -1,7 +0,0 @@
export namespace amqp {
export const Manager = Symbol('AmqpManager')
export namespace rabbit {
export const Admin = Symbol('RabbitAdmin')
export const Template = Symbol('RabbitTemplate')
}
}

View File

@@ -1,5 +0,0 @@
export namespace database {
export const DataBaseManager = Symbol("DataBaseManager");
export const DataSource = Symbol("DataSource");
export const DataBase = Symbol("DataBase");
}

View File

@@ -1,5 +0,0 @@
export * from './web'
export * from './amqp'
export * from './plugin'
export * from './server'
export * from './database'

View File

@@ -1,143 +0,0 @@
import * as reflect from '@ccms/common/dist/reflect'
import { injectable } from '@ccms/container'
import { NativePluginManager } from './native_plugin'
import { constants } from '../../constants'
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
getDedicatedServer?(): any
getNettyPipeline(): any
getRootLogger(): any
sendJson(sender: string | any, json: object | string): void
tabComplete?(sender: string | any, input: string, index?: number): string[]
}
@injectable()
export abstract class ReflectServer implements server.Server {
protected pipeline: any
protected rootLogger: any
constructor() {
this.reflect()
}
getVersion(): string {
throw new Error("Method not implemented.")
}
getPlayer(name: string) {
throw new Error("Method not implemented.")
}
getOnlinePlayers(): any[] {
throw new Error("Method not implemented.")
}
getConsoleSender() {
throw new Error("Method not implemented.")
}
getService(service: string) {
throw new Error("Method not implemented.")
}
dispatchCommand(sender: any, command: string): boolean {
throw new Error("Method not implemented.")
}
dispatchConsoleCommand(command: string): boolean {
throw new Error("Method not implemented.")
}
getPluginsFolder(): string {
throw new Error("Method not implemented.")
}
getNativePluginManager(): NativePluginManager {
throw new Error("Method not implemented.")
}
getDedicatedServer() {
throw new Error("Method not implemented.")
}
getNettyPipeline() {
throw new Error("Method not implemented.")
}
getRootLogger() {
throw new Error("Method not implemented.")
}
sendJson(sender: any, json: string | object): void {
throw new Error("Method not implemented.")
}
tabComplete?(sender: any, input: string, index?: number): string[] {
throw new Error("Method not implemented.")
}
protected reflect() {
try {
let consoleServer = this.getDedicatedServer()
this.reflectPipeline(consoleServer)
this.reflectRootLogger(consoleServer)
} catch (error) {
console.error('Error When Reflect MinecraftServer!', error)
console.ex(error)
}
}
protected reflectPipeline(consoleServer: any) {
let connection: any
let promise: any
for (const method of constants.Reflect.Method.getServerConnection) {
try {
connection = reflect.on(consoleServer).call(method).get()
if (connection.class.name.indexOf('ServerConnection') !== -1
|| connection.class.name.indexOf('NetworkSystem') !== -1) { break }
connection = undefined
} catch (error) { }
}
if (!connection) { console.error("Can't found ServerConnection!"); return }
for (const field of constants.Reflect.Field.listeningChannels) {
try {
promise = reflect.on(connection).get(field).get().get(0)
if (promise.class.name.indexOf('Promise') !== -1) { break }
promise = undefined
} catch (error) { }
}
if (!promise) { console.error("Can't found listeningChannels!"); return }
this.pipeline = reflect.on(promise).get('channel').get().pipeline()
}
protected reflectRootLogger(consoleServer: any) {
try {
this.rootLogger = reflect.on(consoleServer).get('LOGGER').get().parent
} catch (error) {
try { this.rootLogger = reflect.on(consoleServer).get(0).get().parent } catch (error) { }
}
if (this.rootLogger && this.rootLogger.class.name.indexOf('Logger') === -1) {
console.error('Error Logger Class: ' + this.rootLogger.class.name)
this.rootLogger = undefined
}
// get root logger
for (let index = 0; index < 5 && this.rootLogger.parent; index++) {
this.rootLogger = this.rootLogger.parent
}
if (!this.rootLogger) { console.error("Can't found rootLogger!") }
}
}
}

View File

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

View File

@@ -1,3 +0,0 @@
export namespace web {
export const Server = Symbol('Server')
}

20
packages/api/src/item.ts Normal file
View File

@@ -0,0 +1,20 @@
import { injectable } from '@ccms/container'
export namespace item {
@injectable()
export abstract class Item {
abstract builder(): ItemBuilder
abstract toJson(item: any): string
abstract fromJson(json: string): any
}
export interface ItemBuilder {
from(item: any): ItemBuilder
create(type: string | number): ItemBuilder
name(name: string): ItemBuilder
lore(...lores: string[]): ItemBuilder
amount(amount: number): ItemBuilder
durability(durability: number): ItemBuilder
clone(): any
build(): any
}
}

View File

@@ -0,0 +1,507 @@
import { Autowired, injectable } from '@ccms/container'
import { task, plugin } from './index'
const UUID = Java.type('java.util.UUID')
const Math = Java.type('java.lang.Math')
export namespace particle {
@injectable()
export abstract class ParticleSpawner {
abstract spawn(location: any, particle: Particle)
abstract spawnToPlayer(player: any, location: any, particle: Particle)
}
/**
* 表示一个特效对象
*
* @author Zoyn
*/
export abstract class Particle {
private spawner: ParticleSpawner
private readonly uuid: string
private particle: any /* Particle */
private count: number = 1;
private offsetX: number = 0;
private offsetY: number = 0;
private offsetZ: number = 0;
private extra: number = 0;
private data: Object = null;
/**
* Only Show To Player
*/
private player: any
constructor() {
this.uuid = UUID.randomUUID().toString()
}
abstract show(location: any)
getUUID() {
return this.uuid
}
getSpawner() {
return this.spawner
}
setSpawner(spawner: ParticleSpawner) {
this.spawner = spawner
return this
}
getParticle() {
return this.particle
}
setParticle(particle: any, data: any = null) {
this.particle = particle
this.data = data
return this
}
getCount() {
return this.count
}
setCount(count: number) {
this.count = count
return this
}
getOffsetX() {
return this.offsetX
}
setOffsetX(offsetX: number) {
this.offsetX = offsetX
return this
}
getOffsetY() {
return this.offsetY
}
setOffsetY(offsetY: number) {
this.offsetY = offsetY
return this
}
getOffsetZ() {
return this.offsetZ
}
setOffsetZ(offsetZ: number) {
this.offsetZ = offsetZ
return this
}
getExtra() {
return this.extra
}
setExtra(extra: number) {
this.extra = extra
return this
}
getData() {
return this.data
}
setData(data) {
this.data = data
return this
}
getPlayer() {
return this.player
}
setPlayer(player) {
this.player = player
return this
}
/**
* 通过给定一个坐标就可以使用已经指定的参数来播放粒子
*
* @param location 坐标
*/
spawn(location: any) {
if (!this.spawner) throw new Error(`particle ${this.uuid} not set spawner can't spawn!`)
if (this.player) {
this.spawner.spawnToPlayer(this.player, location, this)
} else {
this.spawner.spawn(location, this)
}
}
}
/**
* 表示一条线
*
* @author Zoyn
*/
export class Line extends Particle {
private vector: any
private start: any
private end: any
/**
* 步长
*/
private step: number
/**
* 向量长度
*/
private length: number
/**
* 构造一条线
*
* @param start 线的起点
* @param end 线的终点
*/
constructor(start: any, end: any)
/**
* 构造一条线
*
* @param start 线的起点
* @param end 线的终点
* @param step 每个粒子之间的间隔 (也即步长)
*/
constructor(start: any, end: any, step: number = 0.1) {
super()
this.start = start
this.end = end
this.step = step
// 对向量进行重置
this.resetVector()
}
show() {
for (let i = 0; i < this.length; i += this.step) {
this.spawn(this.start.clone().add(this.vector.clone().multiply(i)))
}
}
/**
* 获取线的起始坐标
*
* @return {@link Location}
*/
getStart() {
return this.start
}
/**
* 利用给定的坐标设置线的起始坐标
*
* @param start 起始坐标
* @return {@link Line}
*/
setStart(start) {
this.start = start
this.resetVector()
return this
}
/**
* 获取线的终点坐标
*
* @return {@link Location}
*/
getEnd() {
return this.end
}
/**
* 利用给定的坐标设置线的终点坐标
*
* @param end 终点
* @return {@link Line}
*/
setEnd(end) {
this.end = end
this.resetVector()
return this
}
/**
* 获取每个粒子之间的间隔
*
* @return 也就是循环的步长
*/
getStep() {
return this.step
}
/**
* 设置每个粒子之间的间隔
*
* @param step 间隔
* @return {@link Line}
*/
setStep(step) {
this.step = step
this.resetVector()
return this
}
/**
* 手动重设线的向量
*/
resetVector() {
this.vector = this.end.clone().subtract(this.start).toVector()
this.length = this.vector.length()
this.vector.normalize()
}
}
/**
* 表示一个弧
*
* @author Zoyn
*/
export class Arc extends Particle {
private angle: number
private radius: number
private step: number
/**
* 构造一个弧
*
* @param origin 弧所在的圆的圆点
* @param angle 弧所占的角度
* @param radius 弧所在的圆的半径
* @param step 每个粒子的间隔(也即步长)
*/
constructor(angle: number = 30, radius: number = 1, step: number = 1) {
super()
this.angle = angle
this.radius = radius
this.step = step
}
show(location: any) {
for (let i = 0; i < this.angle; i += this.step) {
let radians: number = Math.toRadians(i)
let x: number = this.radius * Math.cos(radians)
let z: number = this.radius * Math.sin(radians)
super.spawn(location.clone().add(x, 0, z))
}
}
getAngle(): number {
return this.angle
}
setAngle(angle: number): Arc {
this.angle = angle
return this
}
getRadius(): number {
return this.radius
}
setRadius(radius: number): Arc {
this.radius = radius
return this
}
getStep(): number {
return this.step
}
setStep(step: number): Arc {
this.step = step
return this
}
}
/**
* 表示一个圆
*
* @author Zoyn
*/
export class Circle extends Arc {
constructor(radius: number)
constructor(radius: number, step: number)
/**
* 构造一个圆
*
* @param origin 圆的圆点
* @param radius 圆的半径
* @param step 每个粒子的间隔(也即步长)
* @param period 特效周期(如果需要可以使用)
*/
constructor(radius: number = 1, step: number = 1) {
// Circle只需要控制这个fullArc就可以满足所有的要求
super(360, radius, step)
}
}
const AtomicInteger = Java.type("java.util.concurrent.atomic.AtomicInteger")
@injectable()
export abstract class ParticleManager {
@Autowired()
private taskManager: task.TaskManager
@Autowired()
private particleSpawner: particle.ParticleSpawner
protected taskId: java.util.concurrent.atomic.AtomicInteger
protected cacheTasks = new Map<string, ParticleTask>()
protected pluginCacheTasks = new Map<string, Map<number, ParticleTask>>()
constructor() {
this.taskId = new AtomicInteger(0)
}
/**
* 获得自增的任务ID
*/
public nextId() {
return this.taskId.incrementAndGet()
}
public getTaskManager() {
return this.taskManager
}
public getParticleSpawner() {
return this.particleSpawner
}
public create(particle: Particle, plugin?: plugin.Plugin) {
let uuid = particle.getUUID()
if (this.cacheTasks.has(uuid)) {
return this.cacheTasks.get(uuid)
}
let task = this.create0(plugin, particle)
this.cacheTasks.set(uuid, task)
if (plugin) {
if (!this.pluginCacheTasks.has(plugin.description.name)) {
this.pluginCacheTasks.set(plugin.description.name, new Map())
}
this.pluginCacheTasks.get(plugin.description.name).set(task.getTaskId(), task)
}
return task
}
public cancel(particle: Particle) {
let uuid = particle.getUUID()
if (this.cacheTasks.has(uuid)) {
this.cacheTasks.get(uuid).cancel()
this.cacheTasks.delete(uuid)
} else {
throw new Error(`particle ${uuid} not found!`)
}
}
disable(plugin: plugin.Plugin) {
if (this.pluginCacheTasks.has(plugin.description.name)) {
this.pluginCacheTasks
.get(plugin.description.name)
.forEach((task) => task.cancel())
this.pluginCacheTasks.delete(plugin.description.name)
}
}
protected create0(owner: plugin.Plugin, particle: Particle): ParticleTask {
particle.setSpawner(this.getParticleSpawner())
return new ParticleTask(owner, particle, this)
}
}
export class ParticleTask {
private particle: Particle
private isAsync: boolean = false
private interval: number = 0
private _location: any
private _follow: any
private owner: plugin.Plugin
private taskId: number
private task: task.Task
private taskManager: task.TaskManager
protected particleManager: ParticleManager
constructor(owner: plugin.Plugin, particle: Particle, particleManager: ParticleManager) {
this.owner = owner
this.taskId = particleManager.nextId()
this.particle = particle
this.taskManager = particleManager.getTaskManager()
this.particleManager = particleManager
}
getOwner() {
return this.task.getOwner()
}
getTaskId() {
return this.taskId
}
getParticle() {
return this.particle
}
async(isAsync: boolean = true) {
this.isAsync = isAsync
return this
}
timer(tick: number) {
this.interval = tick
return this
}
follow(entity: { getLocation: () => any }) {
this._follow = entity
this._location = undefined
return this
}
location(location: any) {
this._location = location
this._follow = undefined
return this
}
submit() {
this.cancel()
if (this._follow && !this.interval) throw new Error(`enable follow entity but interval is ${this.interval}!`)
this.taskManager.create(() => {
this.task = this.taskManager
.create(() => {
try {
if (this._follow) {
if (!this._follow.isOnline()) return this.cancel()
this.particle.show(this._follow.getLocation().clone().add(0, 1, 0))
} else if (this._location) {
this.particle.show(this._location)
} else {
console.warn(`ParticleTask ${this.taskId} particle ${this.particle.getUUID()} cancel because entity and location both undefined!`)
this.task.cancel()
}
} catch (error: any) {
console.error(`§6插件 §a${this.owner.description.name} §c播放粒子发送异常 §4粒子播放任务已终止!`)
console.ex(error)
this.cancel()
}
}, this.owner)
.async(this.isAsync)
.timer(this.interval)
.submit()
}, this.owner).later(2).submit()
return this
}
cancel() {
if (this.task != null) {
this.task.cancel()
}
}
}
}

View File

@@ -1,3 +1,5 @@
import { injectable } from '@ccms/container'
export namespace plugin {
/**
* MiaoScript Plugin
@@ -11,23 +13,29 @@ export namespace plugin {
* Runtime Plugin Instance
*/
export const PluginInstance = Symbol("PluginInstance")
/**
* MiaoScript Plugin Manager Symbol
*/
export const PluginManager = Symbol("PluginManager")
/**
* MiaoScript Plugin Manager Interface
*/
export interface PluginManager {
scan(folder: string): void
build(): void
loadFromFile(file: string, scanner?: plugin.PluginScanner): Plugin
load(...args: any[]): void
enable(...args: any[]): void
disable(...args: any[]): void
reload(...args: any[]): void
getPlugin(name: string): plugin.Plugin
getPlugins(): Map<string, plugin.Plugin>
@injectable()
export abstract class PluginManager {
abstract scan(folder: string): void
abstract loadFromFile(file: string, ext?: any): Plugin
abstract require(loadMetadata: PluginLoadMetadata): PluginMetadata
abstract build(metadata: PluginMetadata): Plugin
abstract rebuild(plugin: plugin.Plugin): void
abstract load(plugin: plugin.Plugin): void
abstract enable(plugin: plugin.Plugin): void
abstract disable(plugin: plugin.Plugin): void
abstract reload(plugin: plugin.Plugin): void
abstract has(name: string): boolean
abstract get(name: string): plugin.Plugin
abstract getPlugin(name: string): plugin.Plugin
abstract getPlugins(): Map<string, plugin.Plugin>
abstract buildPlugins(): void
abstract rebuildPlugins(): void
abstract loadPlugins(): void
abstract enablePlugins(): void
abstract disablePlugins(): void
}
export const PluginScanner = Symbol("PluginScanner")
/**
@@ -39,13 +47,13 @@ export namespace plugin {
*/
type: string
/**
*
* (java.io.File)
*/
name?: string
file?: any
/**
*
* canonicalPath
*/
file?: string
path?: string
/**
*
*/
@@ -83,7 +91,7 @@ export namespace plugin {
scan(target: any): PluginLoadMetadata[]
/**
*
* @param target
* @param target
*/
read(target: any): PluginLoadMetadata
/**
@@ -116,22 +124,17 @@ export namespace plugin {
* Load
* @param plugin
*/
load(plugin: Plugin): void
load?(plugin: Plugin): void
/**
* Enable
* @param plugin
*/
enable(plugin: Plugin): void
enable?(plugin: Plugin): void
/**
* Disable
* @param plugin
*/
disable(plugin: Plugin): void
/**
* Reload
* @param plugin
*/
reload(plugin: Plugin): void
disable?(plugin: Plugin): void
}
export interface Plugin {
description: PluginMetadata
@@ -152,21 +155,41 @@ export namespace plugin {
}
export interface PluginMetadata extends BaseMetadata {
/**
*
*
*/
name: string
/**
*
*/
cname?: string
/**
* ID
*/
pid?: number
/**
*
*/
level?: number
/**
*
*/
prefix?: string
/**
*
* 1.0.0
*/
version: string
version?: string
/**
*
* Unknow
*/
author: string | string[]
author?: string | string[]
/**
*
*/
depends?: string[]
/**
*
*/
nativeDepends?: string[]
/**
* __filename
*/

161
packages/api/src/proxy.ts Normal file
View File

@@ -0,0 +1,161 @@
import { provideSingleton, Autowired, optional } from '@ccms/container'
import { channel } from './channel'
export namespace proxy {
const ByteArrayOutputStream = Java.type('java.io.ByteArrayOutputStream')
const DataOutputStream = Java.type('java.io.DataOutputStream')
namespace bungeecord {
const CHANNEL_NAME = "BungeeCord"
export class SubChannelBuilder {
private channel: channel.Channel
private player: any
private params: string[]
constructor(channel: channel.Channel, player: any) {
this.channel = channel
this.player = player
this.params = []
}
connect(server: string) {
this.params.push("Connect")
this.params.push(server)
return this.finalSend()
}
connectOther(player: string, server: string) {
this.params.push("ConnectOther")
this.params.push(player)
this.params.push(server)
return this.finalSend()
}
ip() {
this.params.push("IP")
return this.finalSend()
}
ipOther(player: string) {
this.params.push("IPOther")
this.params.push(player)
return this.finalSend()
}
playerCount(server: string | "ALL") {
this.params.push("PlayerCount")
this.params.push(server)
return this.finalSend()
}
/**
* Get a list of players connected on a certain server, or on ALL the servers.
* @param server count server
* Response:
* String server = in.readUTF(); // The name of the server you got the player list of, as given in args.
* String[] playerList = in.readUTF().split(", ");
*/
playerList(server: string | "ALL") {
this.params.push("PlayerList")
this.params.push(server)
return this.finalSend()
}
/**
* Get a list of server name strings, as defined in BungeeCord's config.yml
* Response:
* String[] serverList = in.readUTF().split(", ");
*/
getServers() {
this.params.push("GetServers")
return this.finalSend()
}
/**
* Get this server's name, as defined in BungeeCord's config.yml
*/
getServer() {
this.params.push("GetServer")
return this.finalSend()
}
broadcast(message: string) {
this.message("ALL", message)
return this.finalSend()
}
/**
* Send a message (as in, a chat message) to the specified player.
* @param player who reciver message
* @param message message content
*/
message(player: string | "ALL", message: string) {
this.params.push("Message")
this.params.push(player)
this.params.push(message)
return this.finalSend()
}
/**
* Send a raw message (as in, a chat message) to the specified player. The advantage of this method over Message is that you can include click events and hover events.
* @param player who reciver message
* @param message message content
*/
messageRaw(player: string | "ALL", json: string) {
this.params.push("MessageRaw")
this.params.push(player)
this.params.push(json)
return this.finalSend()
}
forwardAll(channel: string, data: any) {
return this.forward("ALL", channel, data)
}
/**
* Send a custom plugin message to said server. This is one of the most useful channels ever.
* Remember, the sending and receiving server(s) need to have a player online.
* @param server reciver
* @param channel channelName
* @param data data
*/
forward(server: string | "ALL", channel: string, data: any) {
this.params.push("Forward")
this.params.push(server)
this.params.push(channel)
this.params.push(typeof data === "string" ? data : JSON.stringify(data))
return this.finalSend()
}
/**
* Send a custom plugin message to said server. This is one of the most useful channels ever.
* Remember, the sending and receiving server(s) need to have a player online.
* @param server reciver
* @param channel channelName
* @param data data
*/
forwardToPlayer(server: string | "ALL", channel: string, data: any) {
this.params.push("Forward")
this.params.push(server)
this.params.push(channel)
this.params.push(typeof data === "string" ? data : JSON.stringify(data))
return this.finalSend()
}
generic(...args: string[]) {
args && this.params.concat(...args)
return this.finalSend()
}
private send(...middlewares: ((out: java.io.DataOutputStream) => void)[]) {
let byteArray = new ByteArrayOutputStream()
let out = new DataOutputStream(byteArray)
this.params.forEach(utf => out.writeUTF(utf))
for (let middleware of middlewares) {
middleware(out)
}
return this.channel.send(this.player, CHANNEL_NAME, byteArray.toByteArray())
}
private finalSend() {
return {
send: this.send.bind(this)
}
}
}
}
@provideSingleton(BungeeCord)
export class BungeeCord {
@optional()
@Autowired()
private channel: channel.Channel
/**
* 获得代理
* @param player 玩家
*/
for(player: any): bungeecord.SubChannelBuilder {
return new bungeecord.SubChannelBuilder(this.channel, player)
}
}
}

229
packages/api/src/server.ts Normal file
View File

@@ -0,0 +1,229 @@
import * as reflect from '@ccms/common/dist/reflect'
import { injectable, Autowired, ContainerInstance, Container, postConstruct } from '@ccms/container'
import { constants } from './constants'
export namespace server {
/**
* Runtime ServerType
*/
export const ServerType = Symbol("ServerType")
/**
* Runtime Console
*/
export const Console = Symbol("Console")
/**
* Runtime Server Instance
*/
export const ServerInstance = Symbol("ServerInstance")
export interface NativePlugin {
name: string
version: string
authors?: string | string[]
enable: boolean
depends?: string[]
softDepends?: string[]
/**
* 插件本体
*/
origin: any
[key: string]: any
}
@injectable()
export abstract class NativePluginManager {
list(): NativePlugin[] {
throw new Error("Method not implemented.")
}
has(name: string): boolean {
return true
}
get(name: string): NativePlugin {
throw new Error("Method not implemented.")
}
enable(name: string): NativePlugin {
throw new Error("Method not implemented.")
}
disable(name: string): NativePlugin {
throw new Error("Method not implemented.")
}
reload(name: string): NativePlugin {
throw new Error("Method not implemented.")
}
delete(name: string): boolean {
throw new Error("Method not implemented.")
}
}
/**
* MiaoScript Server
*/
@injectable()
export abstract class Server {
getVersion(): string {
throw new Error("Method not implemented.")
}
getPlayer(name: string): any {
throw new Error("Method not implemented.")
}
getOnlinePlayers(): any[] {
throw new Error("Method not implemented.")
}
getConsoleSender(): any {
throw new Error("Method not implemented.")
}
getService(service: string): any {
throw new Error("Method not implemented.")
}
broadcast(message: string, permission: string) {
throw new Error("Method not implemented.")
}
broadcastMessage(message: string) {
throw new Error("Method not implemented.")
}
dispatchCommand(sender: string | any, command: string): boolean {
throw new Error("Method not implemented.")
}
dispatchConsoleCommand(command: string): boolean {
throw new Error("Method not implemented.")
}
getPluginsFolder(): string {
throw new Error("Method not implemented.")
}
getDedicatedServer?(): any {
throw new Error("Method not implemented.")
}
getNettyPipeline(): any {
throw new Error("Method not implemented.")
}
getRootLogger(): any {
throw new Error("Method not implemented.")
}
}
@injectable()
export class ServerChecker {
@Autowired(ServerType)
private serverType: string
check(servers: string[]) {
// Not set servers -> allow
if (!servers || !servers.length) return true
// include !type -> deny
let denyServers = servers.filter(svr => svr.startsWith("!"))
if (denyServers.length !== 0) {
return !denyServers.includes(`!${this.serverType}`)
} else {
// only include -> allow
return servers.includes(this.serverType)
}
}
}
@injectable()
export class NativePluginChecker {
@Autowired(NativePluginManager)
private nativePluginManager: NativePluginManager
check(plugins: string[]) {
// Not set plugins -> allow
if (!plugins || !plugins.length) return true
for (const plugin of plugins) {
if (!this.nativePluginManager.has(plugin)) { return false }
}
return true
}
}
@injectable()
export abstract class ReflectServer extends server.Server {
@Autowired(ContainerInstance)
private container: Container
protected pipeline: any
protected rootLogger: any
constructor() {
super()
}
@postConstruct()
protected reflect() {
try {
let consoleServer = this.getDedicatedServer()
this.reflectPipeline(consoleServer)
this.reflectRootLogger(consoleServer)
} catch (error: any) {
console.error('Error When Reflect MinecraftServer!', error)
console.ex(error)
}
}
protected reflectPipeline(consoleServer: any) {
let connection: any
let promise: any
for (const method of constants.Reflect.Method.getServerConnection) {
try {
connection = reflect.on(consoleServer).call(method).get()
if (connection.class.name.indexOf('ServerConnection') !== -1
|| connection.class.name.indexOf('NetworkSystem') !== -1) { break }
connection = undefined
} catch (error: any) {
if (global.debug) {
console.ex(error)
}
}
}
if (!connection) { console.error("Can't found ServerConnection!"); return }
for (const field of constants.Reflect.Field.listeningChannels) {
try {
promise = reflect.on(connection).get(field).get().get(0)
if (promise.class.name.indexOf('Promise') !== -1) { break }
promise = undefined
} catch (error: any) {
if (global.debug) {
console.ex(error)
}
}
}
if (!promise) { console.error("Can't found listeningChannels!"); return }
this.pipeline = reflect.on(promise).get('channel').get().pipeline()
this.container.bind(constants.ServiceIdentifier.NettyPipeline).toConstantValue(this.pipeline)
}
protected reflectRootLogger(consoleServer: any) {
try {
this.rootLogger = reflect.on(consoleServer).get('LOGGER').get()
} catch (error: any) {
if (global.debug) {
console.ex(error)
}
try {
this.rootLogger = reflect.on(consoleServer).get(0).get()
} catch (error: any) {
if (global.debug) {
console.ex(error)
}
}
}
if (this.rootLogger.class.name.indexOf('slf4j') !== -1) {
try {
let LogManager = Java.type('org.apache.logging.log4j.LogManager')
this.rootLogger = LogManager.getLogger('ROOT')
} catch (error: any) {
if (global.debug) {
console.ex(error)
}
}
}
if (this.rootLogger && this.rootLogger.class.name.indexOf('Logger') === -1) {
console.error('Error Logger Class: ' + this.rootLogger.class.name)
this.rootLogger = undefined
}
if (!this.rootLogger) { console.error("Can't found rootLogger!") }
// get root logger
for (let index = 0; index < 5 && this.rootLogger.parent; index++) {
this.rootLogger = this.rootLogger.parent
}
this.container.bind(constants.ServiceIdentifier.RootLogger).toConstantValue(this.rootLogger)
}
}
}

View File

@@ -1,34 +1,112 @@
import { EventEmitter } from 'events'
import { injectable } from '@ccms/container'
import { plugin } from './index'
const AtomicInteger = Java.type("java.util.concurrent.atomic.AtomicInteger")
export namespace task {
export const TaskManager = Symbol('TaskManager')
export interface TaskManager {
@injectable()
export abstract class TaskManager {
protected taskId: java.util.concurrent.atomic.AtomicInteger
protected cacheTasks = new Map<number, task.Task>()
protected pluginCacheTasks = new Map<string, Map<number, task.Task>>()
constructor() {
this.taskId = new AtomicInteger(0)
process.on('core.disable', () => { this.disable() })
process.on('task.finish', (task: task.Task) => {
let taskId = task.getTaskId()
this.cacheTasks.delete(taskId)
let ownerName = task.getOwner()?.description.name
if (ownerName && this.pluginCacheTasks.has(ownerName)) {
this.pluginCacheTasks.get(ownerName)?.delete(taskId)
}
})
}
/**
* 创建任务
* @param func 任务内容
*/
create(func: Function): task.Task;
create(func: Function, plugin?: plugin.Plugin): task.Task {
if (Object.prototype.toString.call(func) !== "[object Function]") { throw TypeError('第一个参数 Task 必须为 function !') };
let task = this.create0(plugin, func, this.nextId())
this.cacheTasks.set(task.getTaskId(), task)
if (plugin) { return this.pluginCreate(plugin, task) }
return task
}
cancel(taskId: number) {
if (!this.cacheTasks.has(taskId)) { throw new Error(`Task ${taskId} not found!`) }
this.cacheTasks.get(taskId).cancel()
}
/**
* 在主线程执行代码
* @param func 执行内容
*/
callSyncMethod(func: Function): any;
abstract callSyncMethod(func: Function): any
/**
* 关闭任务管理器
*/
disable();
disable(plugin?: plugin.Plugin) {
if (plugin) { return this.pluginDisable(plugin) }
this.disable0()
}
protected pluginCreate(plugin: plugin.Plugin, task: task.Task) {
if (!this.pluginCacheTasks.has(plugin.description.name)) {
this.pluginCacheTasks.set(plugin.description.name, new Map())
}
this.pluginCacheTasks.get(plugin.description.name).set(task.getTaskId(), task)
return task
}
protected pluginDisable(plugin: plugin.Plugin) {
if (this.pluginCacheTasks.has(plugin.description.name)) {
this.pluginCacheTasks.get(plugin.description.name).forEach((task) => task.cancel())
this.pluginCacheTasks.delete(plugin.description.name)
}
}
/**
* 获得自增的任务ID
*/
protected nextId() {
return this.taskId.incrementAndGet()
}
protected abstract create0(owner: plugin.Plugin, func: Function, id: number): task.Task
protected abstract disable0()
}
/**
* 任务抽象
*/
export abstract class Task {
protected plugin: any;
protected func: Function;
export abstract class Task extends EventEmitter implements Cancelable {
protected func: Function
protected isAsync: boolean = false;
protected laterTime: number = 0;
protected interval: number = 0;
protected owner: plugin.Plugin
protected taskId: number
protected innerTask: any
constructor(plugin: any, func: Function) {
this.plugin = plugin;
this.func = func;
private cancelled: boolean = false
constructor(owner: plugin.Plugin, func: Function, id: number) {
super()
this.owner = owner
this.func = func
this.taskId = id
this.on('finish', () => {
process.emit('task.finish', this)
})
}
getOwner() {
return this.owner
}
getTaskId() {
return this.taskId
}
/**
@@ -36,8 +114,8 @@ export namespace task {
* @param isAsync 是否异步
*/
async(isAsync: boolean = true): task.Task {
this.isAsync = isAsync;
return this;
this.isAsync = isAsync
return this
}
/**
@@ -45,8 +123,8 @@ export namespace task {
* @param tick 延时 Tick
*/
later(tick: number): task.Task {
this.laterTime = tick;
return this;
this.laterTime = tick
return this
}
/**
@@ -54,29 +132,69 @@ export namespace task {
* @param tick 循环时间 Tick
*/
timer(tick: number): task.Task {
this.interval = tick;
return this;
this.interval = tick
return this
}
/**
* 取消任务
*/
cancel(): boolean {
let result = this.cancel0()
this.finish()
this.cancelled = true
return result
}
protected run(...args: any[]): void {
try {
this.func(...args);
} catch (ex) {
console.console('§4插件执行任务时发生错误', ex)
console.ex(ex);
this.emit('before', this)
if (this.cancelled) { return }
this.func(...args)
this.emit('after', this)
} catch (error: any) {
try {
this.emit('error', error)
} catch (ignore) {
console.console('§4插件执行任务时发生错误', error)
console.ex(error)
this.cancel()
}
} finally {
this.emit('finally', this)
if (!this.interval && !this.cancelled) { this.finish() }
}
}
protected finish() {
this.emit('finish', this)
}
/**
* 提交任务
* @param args 任务参数
*/
abstract submit(...args: any[]): Cancelable;
submit(...args: any[]): task.Task {
this.innerTask = this.submit0(...args)
return this
}
/**
* 提交任务
* @param args 任务参数
*/
protected abstract submit0(...args: any[]): Cancelable
/**
* 取消任务
*/
protected cancel0(): boolean {
return this.innerTask?.cancel()
}
}
/**
* 返可取消的对象
*/
export interface Cancelable {
cancel(): boolean;
cancel(): boolean
}
}

View File

@@ -1 +0,0 @@
../../.npmignore

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/bukkit",
"version": "0.8.1",
"version": "0.28.0-beta.9",
"description": "MiaoScript bukkit package",
"keywords": [
"miaoscript",
@@ -12,20 +12,23 @@
"homepage": "https://github.com/circlecloud/ms.git",
"license": "ISC",
"main": "dist/index.js",
"files": [
"dist/**/*.js",
"dist/**/*.ts",
"dist/**/*.map"
],
"scripts": {
"clean": "rimraf dist",
"watch": "tsc --watch",
"build": "yarn clean && tsc",
"build": "pnpm clean && tsc",
"test": "echo \"Error: run tests from root\" && exit 1"
},
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.9.2"
"@javatypes/spigot-api": "^0.0.3"
},
"dependencies": {
"@ccms/api": "^0.8.1",
"@ccms/common": "^0.8.0",
"@ccms/container": "^0.8.0"
"@ccms/api": "^0.28.0-beta.9",
"@ccms/common": "^0.28.0-beta.9",
"@ccms/container": "^0.28.0-beta.9"
}
}

View File

@@ -1,28 +1,54 @@
import { channel, plugin } from '@ccms/api'
import { inject, provideSingleton } from '@ccms/container'
const Bukkit = org.bukkit.Bukkit
const Bukkit: typeof org.bukkit.Bukkit = Java.type('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);
private pluginInstance: any
private cacheChannel = new Map<string, any[]>()
/**
* 给玩家发送通道消息
* @param player 接受消息的玩家
* @param channel 通道
* @param data 数据
*/
send(player: any, channel: string, data: number[]) {
player.sendPluginMessage(this.pluginInstance, channel, data)
}
/**
* 注册通道监听器
* @param channel 通道
* @param listener 监听器
*/
register(channel: string, listener: channel.ChannelListener) {
Messenger.registerIncomingPluginChannel(this.pluginInstance, channel, new PluginMessageListener({
if (!this.cacheChannel.has(channel)) this.cacheChannel.set(channel, [])
this.cacheChannel.get(channel).push(listener)
let pluginMessageListener = new PluginMessageListener({
onPluginMessageReceived: (/**String */ channel, /**Player */ player, /**byte[] */data) => {
listener(data, { channel, player, data })
try {
listener(data, { channel, player, data })
} catch (error: any) {
console.ex(error)
}
}
}));
Messenger.registerOutgoingPluginChannel(this.pluginInstance, channel);
})
Messenger.registerIncomingPluginChannel(this.pluginInstance, channel, pluginMessageListener)
Messenger.registerOutgoingPluginChannel(this.pluginInstance, channel)
return pluginMessageListener
}
unregister(channel: string, listener: any) {
Messenger.unregisterIncomingPluginChannel(this.pluginInstance, channel)
Messenger.unregisterOutgoingPluginChannel(this.pluginInstance, channel)
if (!this.cacheChannel.has(channel)) return
let cacheListener = this.cacheChannel.get(channel)
cacheListener = cacheListener.filter(l => l != listener)
Messenger.unregisterIncomingPluginChannel(this.pluginInstance, channel, listener)
if (cacheListener.length == 0) {
this.cacheChannel.delete(channel)
Messenger.unregisterOutgoingPluginChannel(this.pluginInstance, channel)
}
}
}

View File

@@ -0,0 +1,26 @@
import { chat } from '@ccms/api'
import { provideSingleton } from '@ccms/container'
import bukkitChat from './internal/chat'
@provideSingleton(chat.Chat)
export class BukkitChat extends chat.Chat {
get handle(): any {
return bukkitChat
}
sendJson(sender: any, json: string | object, type = 0) {
bukkitChat.send(sender, typeof json === "string" ? json : JSON.stringify(json), type)
}
sendMessage(sender: any, message: string) {
this.sendJson(sender, { text: message }, 0)
}
sendActionBar(sender: any, message: string) {
this.sendJson(sender, { text: message }, 2)
}
sendTitle(sender: any, title: string, subtitle: string = '', fadeIn: number = 20, time: number = 100, fadeOut: number = 20) {
try {
sender.sendTitle(title, subtitle, fadeIn, time, fadeOut)
} catch (error: any) {
sender.sendTitle(title, subtitle)
}
}
}

View File

@@ -1,47 +1,53 @@
import '@ccms/nashorn'
import { command, plugin } from '@ccms/api'
import * as reflect from '@ccms/common/dist/reflect'
import { provideSingleton, postConstruct, inject } from '@ccms/container'
import * as reflect from '@ccms/common/dist/reflect'
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');
const Bukkit: typeof org.bukkit.Bukkit = Java.type('org.bukkit.Bukkit')
const TabCompleter = Java.type('org.bukkit.command.TabCompleter')
const PluginCommand = Java.type('org.bukkit.command.PluginCommand')
const CommandExecutor = Java.type('org.bukkit.command.CommandExecutor')
@provideSingleton(command.Command)
export class BukkitCommand extends command.Command {
@inject(plugin.PluginInstance)
private pluginInstance: any
private commandMap: any;
private commandMap: any
private knownCommands: any
@postConstruct()
init() {
this.commandMap = reflect.on(Bukkit.getPluginManager()).get('commandMap').get();
this.commandMap = reflect.on(Bukkit.getPluginManager()).get('commandMap').get()
this.knownCommands = reflect.on(this.commandMap).get('knownCommands').get()
}
create(plugin: any, command: string) {
var cmd = this.commandMap.getCommand(command)
if (cmd && cmd instanceof PluginCommand) { return cmd };
cmd = reflect.on(PluginCommand).create(command, this.pluginInstance).get();
this.commandMap.register(plugin.description.name, cmd);
return cmd;
if (cmd instanceof PluginCommand) { return cmd };
cmd = reflect.on(PluginCommand).create(command, this.pluginInstance).get()
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);
if (cmd instanceof PluginCommand) {
cmd.unregister(this.commandMap)
this.knownCommands.remove(command)
}
}
tabComplete(sender: any, input: string, index?: number): string[] {
return Java.from(this.commandMap.tabComplete(sender, input))
}
onCommand(plugin: any, command: any, executor: Function) {
// 必须指定需要实现的接口类型 否则MOD服会报错
command.setExecutor(new CommandExecutor({
onCommand: super.setExecutor(plugin, command, executor)
}));
}))
}
onTabComplete(plugin: any, command: any, tabCompleter: Function) {
// 必须指定需要实现的接口类型 否则MOD服会报错
command.setTabCompleter(new TabCompleter({
onTabComplete: super.setTabCompleter(plugin, command, tabCompleter)
}));
}))
}
}

View File

@@ -1,20 +1,20 @@
import { MiaoScriptConsole } from '@ccms/api'
let Bukkit = org.bukkit.Bukkit;
const Bukkit: typeof org.bukkit.Bukkit = Java.type('org.bukkit.Bukkit')
export class BukkitConsole extends MiaoScriptConsole {
sender(sender, ...args) {
if (!(sender instanceof Java.type('org.bukkit.command.CommandSender'))) {
this.error(`First parameter ${sender} not instanceof org.bukkit.command.CommandSender can't send message!`)
return;
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(' '));
sender.sendMessage(this.prefix + args.join(' '))
}
}
console(...args: string[]): void {
this.sender(Bukkit.getConsoleSender(), args.join(' '));
this.sender(Bukkit.getConsoleSender(), args.join(' '))
}
}

View File

@@ -1,114 +0,0 @@
/*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,13 +1,14 @@
import { event, plugin } from '@ccms/api'
import { inject, provideSingleton } from '@ccms/container';
import { inject, provideSingleton } from '@ccms/container'
import * as reflect from '@ccms/common/dist/reflect'
const Bukkit = Java.type("org.bukkit.Bukkit");
const Event = Java.type("org.bukkit.event.Event");
const Modifier = Java.type("java.lang.reflect.Modifier");
const Listener = Java.type("org.bukkit.event.Listener");
const EventPriority = Java.type("org.bukkit.event.EventPriority");
const EventExecutor = Java.type("org.bukkit.plugin.EventExecutor");
const URL = Java.type('java.net.URL')
const Bukkit = Java.type("org.bukkit.Bukkit")
const Event = Java.type("org.bukkit.event.Event")
const Modifier = Java.type("java.lang.reflect.Modifier")
const Listener = Java.type("org.bukkit.event.Listener")
const EventPriority = Java.type("org.bukkit.event.EventPriority")
const EventExecutor = Java.type("org.bukkit.plugin.EventExecutor")
@provideSingleton(event.Event)
export class BukkitEvent extends event.Event {
@@ -15,11 +16,19 @@ export class BukkitEvent extends event.Event {
private pluginInstance: any
constructor() {
super('org/bukkit/event');
super('org/bukkit/event')
}
getJarFile(resource: string) {
return super.getJarFile('org/bukkit/Bukkit.class', Bukkit.class.classLoader)
try {
return super.getJarFile('org/bukkit/Bukkit.class', Bukkit.class.classLoader)
} catch (error) {
// 兼容 LoliServer 的 Bukkit 包无法获取的问题
let ModList = Java.type('net.minecraftforge.fml.ModList').get()
let forgeFile = ModList.getModFileById("forge").getFile().getFilePath()
let jarPath = `jar:file:${forgeFile}!/org/bukkit/Bukkit.class`
return new URL(jarPath).openConnection().jarFile
}
}
isValidEvent(clazz: any): boolean {
// 继承于 org.bukkit.event.Event
@@ -27,10 +36,10 @@ export class BukkitEvent extends event.Event {
// 访问符为Public
Modifier.isPublic(clazz.getModifiers()) &&
// 不是抽象类
!Modifier.isAbstract(clazz.getModifiers());
!Modifier.isAbstract(clazz.getModifiers())
}
register(eventCls: any, exec: Function, priority: event.EventPriority, ignoreCancel: boolean) {
let listener = new Listener({});
let listener = new Listener({})
Bukkit.pluginManager.registerEvent(
eventCls,
listener,
@@ -39,10 +48,10 @@ export class BukkitEvent extends event.Event {
execute: exec
}),
this.pluginInstance,
ignoreCancel);
return listener;
ignoreCancel)
return listener
}
unregister(event: any, listener: any): void {
reflect.on(event).call('getHandlerList').get().unregister(listener);
reflect.on(event).call('getHandlerList').get().unregister(listener)
}
}

View File

@@ -3,13 +3,18 @@
import { server } from '@ccms/api'
import { Container } from '@ccms/container'
import { BukkitConsole } from './console';
import './event';
import './server';
import './command';
import './channel';
import './task';
import { BukkitConsole } from './console'
import './item'
import './chat'
import './task'
import './event'
import './server'
import { BukkitNativePluginManager } from './plugin'
import './command'
import './channel'
import './particle'
export default function BukkitImpl(container: Container) {
container.bind(server.Console).toConstantValue(BukkitConsole);
container.bind(server.Console).toConstantValue(BukkitConsole)
container.rebind(server.NativePluginManager).toConstantValue(new BukkitNativePluginManager())
}

View File

@@ -0,0 +1,206 @@
/*global Java, base, module, exports, require*/
let bukkitChatInvoke: BukkitChatInvoke
/**
* 获取NMS类
*/
abstract class BukkitChatInvoke {
private downgrade: boolean = false
protected RemapUtils: any
protected ComponentSerializer: any
protected ChatSerializer: any
protected nmsChatSerializerMethodName: string
protected PacketPlayOutChat: any
protected chatMessageTypes: any
protected playerConnectionFieldName: string
protected playerFieldName: string
protected sendPacketMethodName: string
constructor(private nmsVersion) {
}
init() {
try {
try {
this.ComponentSerializer = Java.type('net.md_5.bungee.chat.ComponentSerializer')
this.RemapUtils = Java.type('catserver.server.remapper.RemapUtils')
} catch (ex: any) {
}
let nmsChatSerializerClass = this.getNmsChatSerializerClass()
this.nmsChatSerializerMethodName = this.getNmsChatSerializerMethodName(nmsChatSerializerClass)
this.ChatSerializer = Java.type(nmsChatSerializerClass.getName())
let packetTypeClass = this.getPacketPlayOutChatClass()
this.PacketPlayOutChat = Java.type(packetTypeClass.getName())
let constructors = packetTypeClass.constructors
for (const constructor of Java.from(constructors)) {
let parameterTypes = constructor.parameterTypes
if (parameterTypes.length === 2 || parameterTypes.length === 3) {
let nmsChatMessageTypeClass = parameterTypes[1]
if (nmsChatMessageTypeClass.isEnum()) {
this.chatMessageTypes = nmsChatMessageTypeClass.getEnumConstants()
break
} else if (nmsChatMessageTypeClass.getName() == 'int') {
break
}
}
}
let playerConnectionField = this.getPlayerConnectionField()
this.playerConnectionFieldName = playerConnectionField.getName()
this.sendPacketMethodName = this.getSendPacketMethodName(playerConnectionField.getType())
} catch (ex: any) {
org.bukkit.Bukkit.getConsoleSender().sendMessage(`§6[§cMS§6][§bbukkit§6][§achat§6] §cNMS Inject Error §4${ex} §cDowngrade to Command Mode...`)
this.downgrade = true
}
}
abstract getNmsChatSerializerClass()
abstract getNmsChatSerializerMethodName(nmsChatSerializerClass: any)
abstract getPacketPlayOutChatClass()
abstract getPacketPlayOutChat(sender: any, json: any, type: number)
abstract getPlayerConnectionField()
abstract getPacketClass()
abstract getSendPacketMethodName(playerConnectionClass: any)
nmsCls(name: string) {
return base.getClass(['net.minecraft.server', this.nmsVersion, name].join('.'))
}
remapMethod(clazz: any, origin: string, test: string, params: any) {
try {
return clazz.getMethod(origin, params)
} catch (ex: any) {
if (this.RemapUtils) {
return clazz.getMethod(this.RemapUtils.mapMethod(clazz, origin, params), params)
} else {
return clazz.getMethod(test, params)
}
}
}
remapFieldName(clazz: any, origin: string, test: string) {
try {
return clazz.getField(origin)
} catch (ex: any) {
if (this.RemapUtils) {
return clazz.getField(this.RemapUtils.mapFieldName(clazz, origin))
} else {
return clazz.getField(test)
}
}
}
json(sender: any, json: string) {
if (this.downgrade) {
return sender.spigot().sendMessage(this.ComponentSerializer.parse(json))
} else {
this.send(sender, json, 0)
return false
}
}
send(sender: any, json: any, type: number) {
this.sendPacket(sender, this.getPacketPlayOutChat(sender, json, type))
}
sendPacket(player: { handle: { [x: string]: { [x: string]: (arg0: any) => void } } }, p: any) {
player.handle[this.playerConnectionFieldName][this.sendPacketMethodName](p)
}
}
class BukkitChatInvokeBase extends BukkitChatInvoke {
getSendPacketMethodName(playerConnectionClass: any) {
return this.remapMethod(playerConnectionClass, 'sendPacket', 'func_179290_a', this.getPacketClass()).getName()
}
getNmsChatSerializerMethodName(nmsChatSerializerClass: any) {
let nmsChatSerializerMethod = this.remapMethod(nmsChatSerializerClass, 'a', 'func_150699_a', base.getClass('java.lang.String'))
return nmsChatSerializerMethod.getName()
}
getPacketPlayOutChat(sender: any, json: any, type: number) {
return new this.PacketPlayOutChat(this.ChatSerializer[this.nmsChatSerializerMethodName](json), type)
}
getNmsChatSerializerClass() {
return this.nmsCls("ChatSerializer")
}
getPacketPlayOutChatClass() {
return this.nmsCls("PacketPlayOutChat")
}
getPlayerConnectionField() {
return this.remapFieldName(this.nmsCls('EntityPlayer'), 'playerConnection', 'field_71135_a')
}
getPacketClass() {
return this.nmsCls('Packet')
}
}
class BukkitChatInvoke_1_7_10 extends BukkitChatInvokeBase {
}
class BukkitChatInvoke_1_8 extends BukkitChatInvoke_1_7_10 {
getPacketPlayOutChat(sender: any, json: any, type: number) {
return new this.PacketPlayOutChat(this.ChatSerializer[this.nmsChatSerializerMethodName](json), this.chatMessageTypes[type])
}
getNmsChatSerializerClass() {
return this.nmsCls("IChatBaseComponent$ChatSerializer")
}
}
class BukkitChatInvoke_1_16_5 extends BukkitChatInvoke_1_8 {
getPacketPlayOutChat(sender: any, json: any, type: number) {
return new this.PacketPlayOutChat(this.ChatSerializer[this.nmsChatSerializerMethodName](json), this.chatMessageTypes[type], sender.getUniqueId())
}
}
class BukkitChatInvoke_1_17_1 extends BukkitChatInvoke_1_16_5 {
getPacketPlayOutChatClass() {
return base.getClass('net.minecraft.network.protocol.game.PacketPlayOutChat')
}
getNmsChatSerializerClass() {
return base.getClass('net.minecraft.network.chat.IChatBaseComponent$ChatSerializer')
}
getPlayerConnectionField() {
return base.getClass('net.minecraft.server.level.EntityPlayer').getField('b')
}
getPacketClass() {
return base.getClass('net.minecraft.network.protocol.Packet')
}
}
class BukkitChatInvoke_1_18_2 extends BukkitChatInvoke_1_17_1 {
getSendPacketMethodName(playerConnectionClass: any) {
return playerConnectionClass.getMethod('a', this.getPacketClass()).getName()
}
}
class BukkitChatInvoke_1_19 extends BukkitChatInvoke_1_18_2 {
getPacketPlayOutChatClass() {
return base.getClass('net.minecraft.network.protocol.game.ClientboundSystemChatPacket')
}
getPacketPlayOutChat(sender: any, json: any, type: number) {
return new this.PacketPlayOutChat(this.ChatSerializer[this.nmsChatSerializerMethodName](json), type)
}
}
try {
let Bukkit: typeof org.bukkit.Bukkit = Java.type('org.bukkit.Bukkit')
// @ts-ignore
let nmsVersion = Bukkit.getServer().class.name.split('.')[3]
let nmsSubVersion = nmsVersion.split("_")[1]
if (nmsSubVersion >= 19) {
bukkitChatInvoke = new BukkitChatInvoke_1_19(nmsVersion)
} else if (nmsSubVersion >= 18) {
bukkitChatInvoke = new BukkitChatInvoke_1_18_2(nmsVersion)
} else if (nmsSubVersion >= 17) {
bukkitChatInvoke = new BukkitChatInvoke_1_17_1(nmsVersion)
} else if (nmsSubVersion >= 16) {
bukkitChatInvoke = new BukkitChatInvoke_1_16_5(nmsVersion)
} else if (nmsSubVersion >= 8) {
bukkitChatInvoke = new BukkitChatInvoke_1_8(nmsVersion)
} else {
bukkitChatInvoke = new BukkitChatInvoke_1_7_10(nmsVersion)
}
bukkitChatInvoke.init()
} catch (ex: any) {
}
let chat = {
invoke: bukkitChatInvoke,
json: bukkitChatInvoke.json.bind(bukkitChatInvoke),
send: bukkitChatInvoke.send.bind(bukkitChatInvoke)
}
export default chat

File diff suppressed because it is too large Load Diff

128
packages/bukkit/src/item.ts Normal file
View File

@@ -0,0 +1,128 @@
import { item } from "@ccms/api"
import { provideSingleton } from "@ccms/container"
import { itemIds } from './internal/item'
const Material: typeof org.bukkit.Material = Java.type('org.bukkit.Material')
const ItemStack: typeof org.bukkit.inventory.ItemStack = Java.type('org.bukkit.inventory.ItemStack')
@provideSingleton(item.Item)
export class BukkitItem extends item.Item {
private CraftItemStack: any
private NBTTagCompound: any
private nmsSaveNBTMethodName: any
private MojangsonParser: any
private nmsItemStack: any
private mpParseMethodName: any
private nmsVersion: any
constructor() {
super()
this.reflect()
}
builder(): item.ItemBuilder {
return new BukkitItemBuilder()
}
toJson(item: any): string {
let nbt = new this.NBTTagCompound()
return this.CraftItemStack.asNMSCopy(item)[this.nmsSaveNBTMethodName](nbt).toString()
}
fromJson(json: string) {
return this.CraftItemStack.asBukkitCopy(new this.nmsItemStack(this.MojangsonParser[this.mpParseMethodName](json)))
}
private obcCls(name: string) {
return base.getClass(['org.bukkit.craftbukkit', this.nmsVersion, name].join('.'))
}
private nmsCls(name: string) {
return base.getClass(['net.minecraft.server', this.nmsVersion, name].join('.'))
}
private reflect() {
try {
let Bukkit: typeof org.bukkit.Bukkit = Java.type('org.bukkit.Bukkit')
// @ts-ignore
this.nmsVersion = Bukkit.getServer().class.name.split('.')[3]
let CraftItemStackClass = this.obcCls('inventory.CraftItemStack')
this.CraftItemStack = Java.type(CraftItemStackClass.getName())
// @ts-ignore
let asNMSCopyMethod = CraftItemStackClass.getMethod('asNMSCopy', ItemStack.class)
let nmsItemStackClass = asNMSCopyMethod.getReturnType()
this.nmsItemStack = Java.type(nmsItemStackClass.getName())
let nmsNBTTagCompoundClass = undefined
for (let method of Java.from(nmsItemStackClass.getMethods())) {
let rt = method.getReturnType()
if (method.getParameterTypes().length == 0 && "NBTTagCompound" == rt.getSimpleName()) {
nmsNBTTagCompoundClass = rt
}
}
this.NBTTagCompound = Java.type(nmsNBTTagCompoundClass.getName())
for (let method of Java.from(nmsItemStackClass.getMethods())) {
let params = method.getParameterTypes()
let rt = method.getReturnType()
if (params.length == 1 && "NBTTagCompound" == params[0].getSimpleName() && "NBTTagCompound" == rt.getSimpleName()) {
this.nmsSaveNBTMethodName = method.getName()
break
}
}
try {
this.MojangsonParser = this.nmsCls('MojangsonParser').static
} catch (error) {
this.MojangsonParser = Java.type('net.minecraft.nbt.MojangsonParser')
}
for (let method of Java.from(this.MojangsonParser.class.getMethods())) {
let params = method.getParameterTypes()
let rt = method.getReturnType()
if (params.length == 1 && "String" == params[0].getSimpleName() && "NBTTagCompound" == rt.getSimpleName()) {
this.mpParseMethodName = method.getName()
}
}
} catch (error: any) {
console.log('Bukkit 物品管理器初始化失败:', error)
if (global.debug) {
console.ex(error)
}
}
}
}
export class BukkitItemBuilder implements item.ItemBuilder {
private itemStack: org.bukkit.inventory.ItemStack
private itemMeta: org.bukkit.inventory.meta.ItemMeta
from(itemStack: any): item.ItemBuilder {
this.itemStack = itemStack
this.itemMeta = this.itemStack.getItemMeta()
return this
}
create(type: string | number): item.ItemBuilder {
let material = undefined
if (typeof type == 'number') {
type = itemIds[type]
}
material = Material[type] || Material[Material['LEGACY_PREFIX'] + type]
this.itemStack = new ItemStack(material)
this.itemMeta = this.itemStack.getItemMeta()
return this
}
name(name: string): item.ItemBuilder {
this.itemMeta.setDisplayName(name)
return this
}
lore(...lores: string[]): item.ItemBuilder {
this.itemMeta.setLore(lores)
return this
}
amount(amount: number): item.ItemBuilder {
this.itemStack.setAmount(amount)
return this
}
durability(durability: number): item.ItemBuilder {
this.itemStack.setDurability(durability)
return this
}
clone() {
return this.build().clone()
}
build() {
this.itemStack.setItemMeta(this.itemMeta)
return this.itemStack
}
}

View File

@@ -0,0 +1,33 @@
import { provideSingleton } from '@ccms/container'
import { particle } from '@ccms/api'
@provideSingleton(particle.ParticleManager)
export class BukkitParticleManager extends particle.ParticleManager {
}
@provideSingleton(particle.ParticleSpawner)
export class BukkitParticleSpawner extends particle.ParticleSpawner {
spawn(location: org.bukkit.Location, particle: particle.Particle) {
location.getWorld().spawnParticle(
particle.getParticle(),
location,
particle.getCount(),
particle.getOffsetX(),
particle.getOffsetY(),
particle.getOffsetZ(),
particle.getExtra(),
particle.getData()
)
}
spawnToPlayer(player: org.bukkit.entity.Player, location: org.bukkit.Location, particle: particle.Particle) {
player.spawnParticle(
particle.getParticle(),
location,
particle.getCount(),
particle.getOffsetX(),
particle.getOffsetY(),
particle.getOffsetZ(),
particle.getExtra(),
particle.getData())
}
}

View File

@@ -0,0 +1,52 @@
import { server } from '@ccms/api'
const Bukkit: typeof org.bukkit.Bukkit = Java.type('org.bukkit.Bukkit')
export class BukkitNativePluginManager extends server.NativePluginManager {
private bukkitPluginManager: org.bukkit.plugin.PluginManager
constructor() {
super()
this.bukkitPluginManager = Bukkit.getPluginManager()
}
list(): server.NativePlugin[] {
return Java.from(this.bukkitPluginManager.getPlugins()).map(plugin => this.convert(plugin))
}
has(name: string): boolean {
return !!this.bukkitPluginManager.getPlugin(name)
}
get(name: string): server.NativePlugin {
return this.convert(this.bukkitPluginManager.getPlugin(name))
}
enable(name: string): server.NativePlugin {
let origin = this.bukkitPluginManager.getPlugin(name)
if (!origin) { throw new Error(`Native Plugin ${name} not found.`) }
if (!origin.isEnabled()) {
this.bukkitPluginManager.enablePlugin(origin)
}
return this.convert(origin)
}
disable(name: string): server.NativePlugin {
let origin = this.bukkitPluginManager.getPlugin(name)
if (!origin) { throw new Error(`Native Plugin ${name} not found.`) }
if (origin.isEnabled()) {
this.bukkitPluginManager.disablePlugin(origin)
}
return this.convert(origin)
}
private convert(plugin: org.bukkit.plugin.Plugin): server.NativePlugin {
if (!plugin) return plugin as any
let desc = plugin.getDescription()
return {
name: plugin.getName(),
version: desc.getVersion(),
authors: Java.from(desc.getAuthors()),
depends: Java.from(desc.getDepend()),
softDepends: Java.from(desc.getSoftDepend()),
enable: plugin.isEnabled(),
origin: plugin
}
}
}

View File

@@ -1,28 +1,27 @@
import { server, constants } from '@ccms/api'
import { provideSingleton } from '@ccms/container';
import { server } from '@ccms/api'
import { provideSingleton } from '@ccms/container'
import * as reflect from '@ccms/common/dist/reflect'
import chat from './enhance/chat'
let Bukkit = org.bukkit.Bukkit;
const Bukkit: typeof org.bukkit.Bukkit = Java.type('org.bukkit.Bukkit')
@provideSingleton(server.Server)
export class BukkitServer extends server.ReflectServer {
private pluginsFolder: string;
private pluginsFolder: string
constructor() {
super();
this.pluginsFolder = Bukkit.getUpdateFolderFile().getParentFile().getCanonicalPath();
super()
this.pluginsFolder = Bukkit.getUpdateFolderFile().getParentFile().getCanonicalPath()
}
getPlayer(name: string) {
return Bukkit.getPlayer(name)
return Bukkit.getPlayerExact(name)
}
getVersion(): string {
return Bukkit.getVersion()
}
getOnlinePlayers() {
return Bukkit.getOnlinePlayers() as unknown as any[]
return Bukkit.getOnlinePlayers()
}
getConsoleSender() {
return Bukkit.getConsoleSender()
@@ -30,6 +29,12 @@ export class BukkitServer extends server.ReflectServer {
getService(service: string) {
return Bukkit.getServicesManager().getRegistration(base.getClass(service))?.getProvider()
}
broadcast(message: string, permission: string) {
return Bukkit.broadcast(message, permission)
}
broadcastMessage(message: string) {
return Bukkit.broadcastMessage(message)
}
dispatchCommand(sender: string | any, command: string): boolean {
if (typeof sender === 'string') {
sender = this.getPlayer(sender)
@@ -40,27 +45,18 @@ export class BukkitServer extends server.ReflectServer {
return Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command)
}
getPluginsFolder(): string {
return this.pluginsFolder;
return this.pluginsFolder
}
getNativePluginManager() {
return Bukkit.getPluginManager() as any;
return Bukkit.getPluginManager() as any
}
getDedicatedServer() {
return reflect.on(Bukkit.getServer()).get('console').get()
}
getNettyPipeline() {
return this.pipeline;
return this.pipeline
}
getRootLogger() {
return this.rootLogger;
}
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)
}
return this.rootLogger
}
}

View File

@@ -1,35 +1,31 @@
import { task, plugin } from '@ccms/api'
import { inject, provideSingleton } from '@ccms/container';
import { provideSingleton } from '@ccms/container'
const Bukkit = Java.type('org.bukkit.Bukkit');
const 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')
@provideSingleton(task.TaskManager)
export class BukkitTaskManager implements task.TaskManager {
@inject(plugin.PluginInstance)
private pluginInstance: any;
create(func: Function): task.Task {
if (Object.prototype.toString.call(func) !== "[object Function]") { throw TypeError('第一个参数 Task 必须为 function !'); };
return new BukkitTask(this.pluginInstance, func);
export class BukkitTaskManager extends task.TaskManager {
create0(owner: plugin.Plugin, func: Function, id: number): task.Task {
return new BukkitTask(owner, func, id)
}
callSyncMethod(func: Function): any {
return Bukkit.getScheduler().callSyncMethod(this.pluginInstance, new Callable({ call: () => func() })).get()
return Bukkit.getScheduler().callSyncMethod(base.getInstance(), new Callable({ call: () => func() })).get()
}
disable() {
Bukkit.getScheduler().cancelTasks(this.pluginInstance);
disable0() {
Bukkit.getScheduler().cancelTasks(base.getInstance())
}
}
export class BukkitTask extends task.Task {
submit(...args: any[]): task.Cancelable {
submit0(...args: any[]): task.Cancelable {
let run = new BukkitRunnable({ run: () => this.run(...args) })
let funcName = `runTask${this.interval ? 'Timer' : 'Later'}${this.isAsync ? 'Asynchronously' : ''}`
let suffix = this.isAsync ? 'Asynchronously' : ''
if (this.interval) {
return run[funcName](this.plugin, this.laterTime, this.interval)
return run[`runTaskTimer${suffix}`](base.getInstance(), this.laterTime, this.interval)
} else {
return run[funcName](this.plugin, this.laterTime)
return run[`runTaskLater${suffix}`](base.getInstance(), this.laterTime)
}
}
}

View File

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

View File

@@ -1 +0,0 @@
../../.npmignore

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/bungee",
"version": "0.8.1",
"version": "0.28.0-beta.9",
"description": "MiaoScript bungee package",
"keywords": [
"miaoscript",
@@ -12,20 +12,23 @@
"homepage": "https://github.com/circlecloud/ms.git",
"license": "ISC",
"main": "dist/index.js",
"files": [
"dist/**/*.js",
"dist/**/*.ts",
"dist/**/*.map"
],
"scripts": {
"clean": "rimraf dist",
"watch": "tsc --watch",
"build": "yarn clean && tsc",
"build": "pnpm clean && tsc",
"test": "echo \"Error: run tests from root\" && exit 1"
},
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.9.2"
"@javatypes/bungee-api": "^0.0.3"
},
"dependencies": {
"@ccms/api": "^0.8.1",
"@ccms/common": "^0.8.0",
"@ccms/container": "^0.8.0"
"@ccms/api": "^0.28.0-beta.9",
"@ccms/common": "^0.28.0-beta.9",
"@ccms/container": "^0.28.0-beta.9"
}
}

View File

@@ -6,20 +6,20 @@ 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;
private eventManager: event.Event
send(player: any, channel: string, data: any) {
throw new Error("Method not implemented.");
throw new Error("Method not implemented.")
}
register(channel: string, listener: channel.ChannelListener) {
Bungee.registerChannel(channel);
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();
unregister(channel: string, off: any) {
Bungee.unregisterChannel(channel)
off()
}
}

View File

@@ -79,7 +79,7 @@ export class BungeeEvent extends event.Event {
currentPriorityMap.put(listener, methods);
this.bakeHandlers.invoke(this.eventBus, eventCls);
return listener;
} catch (ex) {
} catch (ex: any) {
console.ex(ex)
} finally {
this.lock.unlock()
@@ -108,7 +108,7 @@ export class BungeeEvent extends event.Event {
}
this.bakeHandlers.invoke(this.eventBus, eventCls);
}
} catch (ex) {
} catch (ex: any) {
console.ex(ex)
} finally {
this.lock.unlock()

View File

@@ -3,13 +3,15 @@
import { server } from '@ccms/api'
import { Container } from '@ccms/container'
import { BungeeConsole } from './console';
import './event';
import './server';
import './command';
import './channel';
import './task';
import { BungeeConsole } from './console'
import './task'
import './event'
import './server'
import { BungeeNativePluginManager } from './plugin'
import './command'
import './channel'
export default function BungeeImpl(container: Container) {
container.bind(server.Console).toConstantValue(BungeeConsole);
container.bind(server.Console).toConstantValue(BungeeConsole)
container.rebind(server.NativePluginManager).toConstantValue(new BungeeNativePluginManager())
}

View File

@@ -0,0 +1,36 @@
import { server } from '@ccms/api'
let Bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy()
export class BungeeNativePluginManager extends server.NativePluginManager {
private bungeePluginManager: net.md_5.bungee.api.plugin.PluginManager
constructor() {
super()
this.bungeePluginManager = Bungee.getPluginManager()
}
list(): server.NativePlugin[] {
return Java.from(this.bungeePluginManager.getPlugins()).map(plugin => this.convert(plugin))
}
has(name: string): boolean {
return !!this.bungeePluginManager.getPlugin(name)
}
get(name: string): server.NativePlugin {
return this.convert(this.bungeePluginManager.getPlugin(name))
}
private convert(plugin: net.md_5.bungee.api.plugin.Plugin): server.NativePlugin {
if (!plugin) return plugin as any
let desc = plugin.getDescription()
return {
name: desc.getName(),
version: desc.getVersion(),
authors: [desc.getAuthor()],
depends: Java.from(desc.getDepends()) as any,
softDepends: Java.from(desc.getSoftDepends()) as any,
enable: true,
origin: plugin
}
}
}

View File

@@ -3,30 +3,30 @@ import { provideSingleton, inject, postConstruct } from '@ccms/container'
import * as reflect from '@ccms/common/dist/reflect'
let Bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy();
let Bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy()
@provideSingleton(server.Server)
export class BungeeServer implements server.Server {
private pluginsFolder: string;
private pipeline: any;
private rootLogger: any;
private pluginsFolder: string
private pipeline: any
private rootLogger: any
@inject(task.TaskManager)
private task: task.TaskManager
constructor() {
this.pluginsFolder = Bungee.getPluginsFolder().getCanonicalPath();
this.pluginsFolder = Bungee.getPluginsFolder().getCanonicalPath()
}
@postConstruct()
initialize() {
let count = 0;
let count = 0
let wait = this.task.create(() => {
try {
// @ts-ignore
this.pipeline = reflect.on(base.getInstance().getProxy()).get('listeners').get().toArray()[0].pipeline()
wait.cancel();
} catch (ex) {
wait.cancel()
} catch (ex: any) {
count++
if (count > 50) {
console.error('Reflect BungeeCord netty channel pipeline error time > 50times. Err: ' + ex)
@@ -38,13 +38,13 @@ export class BungeeServer implements server.Server {
}).later(10).timer(20).submit()
try {
this.rootLogger = Bungee.getLogger()
} catch (error) {
} catch (error: any) {
console.error("Can't found rootLogger!")
}
}
getPlayer(name: string) {
return Bungee.getPlayer(name);
return Bungee.getPlayer(name)
}
getVersion(): string {
return Bungee.getVersion()
@@ -56,7 +56,13 @@ export class BungeeServer implements server.Server {
return Bungee.getConsole()
}
getService(service: string) {
throw new Error("Method not implemented.");
throw new Error("Method not implemented.")
}
broadcast(message: string, permission: string) {
return Bungee.broadcast(message)
}
broadcastMessage(message: string) {
return Bungee.broadcast(message)
}
dispatchCommand(sender: string | any, command: string): boolean {
if (typeof sender === 'string') {
@@ -68,18 +74,15 @@ export class BungeeServer implements server.Server {
return Bungee.getPluginManager().dispatchCommand(Bungee.getConsole(), command)
}
getPluginsFolder(): string {
return this.pluginsFolder;
return this.pluginsFolder
}
getNativePluginManager() {
return Bungee.getPluginManager() as any
}
getNettyPipeline() {
return this.pipeline;
return this.pipeline
}
getRootLogger() {
return this.rootLogger;
}
sendJson(sender: string | any, json: string): void {
throw new Error("Method not implemented.");
return this.rootLogger
}
}

View File

@@ -1,36 +1,32 @@
import { task, plugin } from '@ccms/api'
import { inject, provideSingleton } from '@ccms/container';
import { inject, provideSingleton } from '@ccms/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);
export class BungeeTaskManager extends task.TaskManager {
create0(owner: plugin.Plugin, func: Function, id: number): task.Task {
return new BungeeTask(owner, func, id)
}
callSyncMethod(func: Function): any {
return func();
return func()
}
disable() {
this.pluginInstance.getProxy().getScheduler().cancel(this.pluginInstance)
disable0() {
base.getInstance().getProxy().getScheduler().cancel(base.getInstance())
}
}
export class BungeeTask extends task.Task {
submit(...args: any[]): task.Cancelable {
submit0(...args: any[]): task.Cancelable {
let run = new Runnable({ run: () => this.run(...args) })
if (this.isAsync) {
return this.plugin.getProxy().getScheduler().runAsync(this.plugin, run)
return base.getInstance().getProxy().getScheduler().runAsync(base.getInstance(), run)
}
if (this.interval) {
return this.plugin.getProxy().getScheduler().schedule(this.plugin, run, this.laterTime * 50, this.interval * 50, TimeUnit.MILLISECONDS)
return base.getInstance().getProxy().getScheduler().schedule(base.getInstance(), run, this.laterTime * 50, this.interval * 50, TimeUnit.MILLISECONDS)
} else {
return this.plugin.getProxy().getScheduler().schedule(this.plugin, run, this.laterTime * 50, TimeUnit.MILLISECONDS)
return base.getInstance().getProxy().getScheduler().schedule(base.getInstance(), run, this.laterTime * 50, TimeUnit.MILLISECONDS)
}
}
}

View File

@@ -1 +0,0 @@
../../.npmignore

View File

@@ -1,31 +0,0 @@
{
"private": true,
"name": "@ccms/client",
"version": "0.8.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",
"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": {
"rimraf": "^3.0.2",
"typescript": "^3.9.2"
}
}

View File

@@ -1,101 +0,0 @@
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

@@ -1,27 +0,0 @@
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

@@ -1,14 +0,0 @@
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

@@ -1,80 +0,0 @@
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 version = process.argv[3] || '1.12.2'
let address = process.argv[4] || '192.168.2.5:25577'
let realAddress = address.split(":");
let client = createConnection(realAddress[0], parseInt(realAddress[1] || "25565"), username)
function createConnection(host: string, port: number, username: string) {
let client = createClient({
version,
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

@@ -1 +0,0 @@
../../.npmignore

View File

@@ -1,7 +1,7 @@
{
"name": "@ccms/common",
"version": "0.8.0",
"description": "MiaoScript api package",
"version": "0.28.0-beta.9",
"description": "MiaoScript common package",
"keywords": [
"miaoscript",
"minecraft",
@@ -12,20 +12,20 @@
"homepage": "https://github.com/circlecloud/ms.git",
"license": "ISC",
"main": "dist/index.js",
"files": [
"dist/**/*.js",
"dist/**/*.ts",
"dist/**/*.map"
],
"scripts": {
"clean": "rimraf dist",
"watch": "tsc --watch",
"build": "yarn clean && tsc",
"build": "pnpm clean && tsc",
"test": "echo \"Error: run tests from root\" && exit 1"
},
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.9.2"
},
"dependencies": {
"@ccms/nashorn": "^0.8.0",
"@javatypes/jdk": "^1.14.0"
"@ccms/nashorn": "^0.28.0-beta.9",
"@javatypes/jdk": "^0.0.3"
},
"gitHead": "562e2d00175c9d3a99c8b672aa07e6d92706a027"
}

View File

@@ -1,7 +1,9 @@
import * as querystring from 'querystring'
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');
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'
@@ -13,36 +15,58 @@ export type Method =
| 'patch' | 'PATCH'
interface RequestConfig {
url?: string;
method?: Method;
headers?: { [key: string]: string };
params?: { [key: string]: string };
data?: any;
url?: string
method?: Method
headers?: { [key: string]: string }
params?: { [key: string]: string }
data?: any,
connectTimeout?: number,
readTimeout?: number,
}
function request(config: RequestConfig) {
// @ts-ignore
let xhr = new XMLHttpRequest();
xhr.open(config.method, config.url, false);
for (const header in config.headers) {
xhr.setRequestHeader(header, config.headers[header]);
// @ts-ignore XMLHttpRequest class only exist nashorn polyfill
let xhr = new XMLHttpRequest()
if (config.connectTimeout) {
xhr.connectTimeout = config.connectTimeout
}
xhr.send(typeof config.data === "string" ? config.data : JSON.stringify(config.data));
if ((xhr.getResponseHeader("Content-Type") + '').indexOf('application/json') != -1) {
if (config.readTimeout) {
xhr.readTimeout = config.readTimeout
}
xhr.open(config.method, config.url, false)
for (const header in config.headers) {
xhr.setRequestHeader(header, config.headers[header])
}
let body = config.data
if (body && typeof body !== "string") {
switch (config.headers['Content-Type']) {
case "application/json":
body = JSON.stringify(body)
break
case "application/x-www-form-urlencoded":
body = querystring.encode(body)
break
}
}
xhr.send(body)
if (xhr.getResponseHeader("Content-Type").indexOf('application/json') != -1) {
xhr.responseType = "json"
}
return xhr.get();
// @ts-ignore get only exist nashorn polyfill
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);
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 request({ url, method, data, ...config });
return function (url: string, data?: any, config: RequestConfig = {}) {
if (!config.headers) { config.headers = {} }
config.headers['Content-Type'] = config.headers['Content-Type'] ?? 'application/json'
return request({ url, method, data, ...config })
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,14 +1,15 @@
/// <reference types="@javatypes/jdk" />
const JavaClass = Java.type('java.lang.Class')
const JavaObject = Java.type('java.lang.Object')
const NoSuchFieldException = Java.type('java.lang.NoSuchFieldException')
const fieldCache = new Map<string, java.lang.reflect.Field>()
const methodCache = new Map<string, java.lang.reflect.Method>()
/**
* 反射工具类
* Created by MiaoWoo on 2017/2/9 0009.
*/
const JavaClass = Java.type('java.lang.Class')
const JavaObject = Java.type('java.lang.Object')
const NoSuchFieldException = Java.type('java.lang.NoSuchFieldException')
const methodCache = []
class Reflect {
private obj: java.lang.Object
private class: java.lang.Class<any>
@@ -34,15 +35,27 @@ class Reflect {
return Java.from(declaredMethods(this.class))
}
field(name: string | java.lang.String): Reflect {
try {
// Try getting a public field
let field = this.class.getField(name)
return on(field.get(this.obj))
} catch (ex) {
// Try again, getting a non-public field
return on(accessible(declaredField(this.class, name)).get(this.obj))
field(nameOrIndex: string | java.lang.String | number, declared = false): java.lang.reflect.Field {
if (nameOrIndex == undefined || nameOrIndex == null) throw new Error(`reflect field name can't be ${nameOrIndex} from ${this.class.getName()}!`)
let key = this.class.getName() + ':' + nameOrIndex + ':' + declared
if (fieldCache.has(key)) {
return fieldCache.get(key)
}
let field = null
if (typeof nameOrIndex == "number") {
field = this.fields(declared)[nameOrIndex]
} else {
try {
// Try getting a public field
field = this.class.getField(nameOrIndex)
} catch (ex: any) {
// Try again, getting a non-public field
field = declaredField(this.class, nameOrIndex)
}
}
if (!field) throw new Error(`can't reflect field ${typeof nameOrIndex == "number" ? 'index' : 'name'} ${nameOrIndex} from ${this.class.getName()}!`)
fieldCache.set(key, field)
return accessible(field)
}
fields(declared = false): java.lang.reflect.Field[] {
@@ -50,7 +63,7 @@ class Reflect {
}
values(declared = false) {
return this.fields(declared).reduce((cache, field) => { return cache[field.getName()] = this.field(field.getName()).get() }, {}) as any
return this.fields(declared).reduce((cache, field) => { return cache[field.getName()] = this.get(field.getName()).get() }, {}) as any
}
call(...args: any[]): Reflect {
@@ -64,17 +77,12 @@ class Reflect {
get(index: number, declared?: boolean): Reflect
get(prop: string): Reflect
get(param?: string | number, declared: boolean = true): Reflect | any {
if (param == undefined || param == null) return this.obj
if (typeof param == "number") {
return on(accessible(this.fields(declared)[param]).get(this.obj))
}
if (typeof param == "string") {
return this.field(param)
}
if (arguments.length === 0) return this.obj
return on(this.field(param, declared).get(this.obj))
}
set(name: any, value: any): Reflect {
accessible(declaredField(this.class, name)).set(this.obj, value)
set(param: string | number, value: any, declared: boolean = true): Reflect {
this.field(param, declared).set(this.obj, value)
return this
}
@@ -96,10 +104,7 @@ function types(values: any[], def?: any) {
}
function accessible<T extends java.lang.reflect.AccessibleObject>(accessible: T): T {
if (accessible === null) {
return null
}
if (!accessible.isAccessible()) {
if (!accessible?.isAccessible()) {
accessible.setAccessible(true)
}
return accessible
@@ -109,10 +114,10 @@ function declaredConstructor(clazz, param) {
let constructor
try {
constructor = clazz.getDeclaredConstructor(types(param))
} catch (ex) {
} catch (ex: any) {
try {
constructor = clazz.getDeclaredConstructor(types(param, true))
} catch (ex) {
} catch (ex: any) {
constructor = clazz.getDeclaredConstructors()[0]
}
}
@@ -125,12 +130,14 @@ function declaredField(clazz: java.lang.Class<any>, name: string | java.lang.Str
let field = null
// noinspection JSUnresolvedVariable
while (target !== JavaObject.class) {
console.debug(`reflect field ${name} from ${target.getName()}`)
try {
field = target.getDeclaredField(name)
if (field !== null) { break }
} catch (e) {
} catch (error: any) {
if (target === undefined) { break }
target = target.getSuperclass()
console.debug(`switch to super class: ${target.getName()}`)
}
}
if (field === null) {
@@ -139,63 +146,54 @@ function declaredField(clazz: java.lang.Class<any>, name: string | java.lang.Str
return field
}
function declaredMethod(clazz: java.lang.Class<any>, name: string, ...clazzs: java.lang.Class<any>[]): java.lang.reflect.Method {
let key = clazz.getName() + '.' + name + ':' + (clazzs || []).join(':')
if (!methodCache[key]) {
try {
methodCache[key] = clazz.getMethod(name, ...clazzs)
} catch (ex) {
function declaredMethod(clazz: java.lang.Class<any>, nameOrIndex: string | number, ...clazzs: java.lang.Class<any>[]): java.lang.reflect.Method {
let key = clazz.getName() + '.' + nameOrIndex + ':' + (clazzs || []).map(c => c.getName()).join(':')
if (methodCache.has(key)) { return methodCache.get(key) }
let target = clazz
if (typeof nameOrIndex === "number") {
methodCache.set(key, declaredMethods(clazz)[nameOrIndex])
} else {
while (target !== JavaObject.class && !methodCache.has(key)) {
try {
methodCache[key] = clazz.getDeclaredMethod(name, clazzs as any)
} catch (ex) {
for (const m of Java.from(declaredMethods(clazz))) {
if (m.getName() == name) {
methodCache[key] = m
break
console.debug(`reflect method ${typeof nameOrIndex == "number" ? 'index' : 'name'} ${nameOrIndex} from ${target.getName()}`)
try {
methodCache.set(key, target.getMethod(nameOrIndex, clazzs as any))
} catch (ex: any) {
try {
methodCache.set(key, target.getDeclaredMethod(nameOrIndex, clazzs as any))
} catch (ex: any) {
for (const m of Java.from(declaredMethods(target))) {
if (m.getName() == nameOrIndex) {
methodCache.set(key, m)
break
}
}
throw new Error(`method ${typeof nameOrIndex == "number" ? 'index' : 'name'} ${nameOrIndex} not found.`)
}
}
} catch (error) {
if (target === undefined) { break }
target = target.getSuperclass()
console.debug(`switch to super class: ${target.getName()}`)
}
}
}
return methodCache[key]
if (!methodCache.has(key)) throw new Error(`can't reflect method ${typeof nameOrIndex == "number" ? 'index' : 'name'} ${nameOrIndex} from ${clazz.getName()}!`)
return methodCache.get(key)
}
function declaredMethods(clazz: java.lang.Class<any>) {
return clazz.getDeclaredMethods()
}
let classMethodsCache: any[] = []
function mapToObject(javaObj) {
if (!javaObj || !javaObj.class) { throw new TypeError(`参数 ${javaObj} 不是一个Java对象!`) }
let target = {}
getJavaObjectMethods(javaObj).forEach(t => mapMethod(target, javaObj, t))
if (!Java.isJavaObject(javaObj)) { throw new TypeError(`argument ${javaObj} is not a java object.`) }
let target = Proxy.newProxy(javaObj, {
apply: (target, name, args) => { return args ? javaObj[name](args) : javaObj[name]() }
})
return target
}
function getJavaObjectMethods(javaObj) {
let className = javaObj.class.name
if (!classMethodsCache[className]) {
let names: any[] = []
let methods = javaObj.class.methods
for (let i in methods) {
names.push(methods[i].name)
}
classMethodsCache[className] = names
}
return classMethodsCache[className]
}
function mapMethod(target, source, name) {
target[name] = function __SimpleDynamicMethod__(...args) {
if (args.length > 0) {
return source[name](args)
} else {
return source[name]()
}
}
}
function on(obj) {
// if (!obj || !obj.class) { throw new TypeError(`参数 ${obj} 不是一个Java对象!`) }
return new Reflect(obj)

View File

@@ -17,14 +17,14 @@ class ChatMessagePart {
}
convert() {
return this.internal;
return this.internal
}
}
class Tellraw {
static duplicateChar = '§卐'
static create() {
return new Tellraw().then(Tellraw.duplicateChar);
return new Tellraw().then(Tellraw.duplicateChar)
}
private cache: string = '';
@@ -32,77 +32,81 @@ class Tellraw {
then(part: ChatMessagePart | string) {
if (typeof part === "string") {
var newPart = new ChatMessagePart();
var newPart = new ChatMessagePart()
newPart.text = part
this.then(newPart);
return this;
this.then(newPart)
return this
}
var last = this.latest();
var last = this.latest()
if (!last.text) {
last.text = part.text;
last.text = part.text
} else {
this.parts.push(part);
this.parts.push(part)
}
this.cache = null;
this.cache = null
}
text(text: string) {
this.latest().text = text;
return this;
this.latest().text = text
return this
}
tip(text: string) {
this.latest().hover("show_text", text);
return this;
tip(texts: string) {
return this.hover(texts)
}
item(text: string) {
this.latest().hover("show_item", text);
return this;
hover(texts: string) {
this.latest().hover("show_text", texts)
return this
}
item(item: string) {
this.latest().hover("show_item", item)
return this
}
command(command: string) {
this.latest().click("run_command", command);
return this;
this.latest().click("run_command", command)
return this
}
suggest(url: string) {
this.latest().click("suggest_command", url);
return this;
this.latest().click("suggest_command", url)
return this
}
file(path: string) {
this.latest().click("open_file", path);
return this;
this.latest().click("open_file", path)
return this
}
link(url: string) {
this.latest().click("open_url", url);
return this;
this.latest().click("open_url", url)
return this
}
latest() {
return this.parts[this.parts.length - 1];
return this.parts[this.parts.length - 1]
}
json() {
if (!this.cache) {
var temp = [];
var temp = []
this.parts.forEach(t => {
temp.push(t.convert());
});
this.cache = JSON.stringify(temp);
console.trace(this.cache);
temp.push(t.convert())
})
this.cache = JSON.stringify(temp)
console.trace(this.cache)
}
return this.cache;
return this.cache
}
string() {
var temp = '';
var temp = ''
this.parts.forEach(t => {
temp += t.text
});
return temp;
})
return temp
}
}

View File

@@ -0,0 +1,35 @@
export type Version = [string, string, string]
export class VersionUtils {
static isEqual(version: string, targetVersion: string): boolean {
return version == targetVersion
}
static isGreaterOrEqual(version: string, targetVersion: string): boolean {
const v1 = parseVersion(version)
const v2 = parseVersion(targetVersion)
return (
v1[0] > v2[0] ||
(v1[0] === v2[0] && v1[1] > v2[1]) ||
(v1[0] === v2[0] && v1[1] === v2[1] && v1[2] >= v2[2])
)
}
static isGreater(version: string, targetVersion: string): boolean {
const v1 = parseVersion(version)
const v2 = parseVersion(targetVersion)
return (
v1[0] > v2[0] ||
(v1[0] === v2[0] && v1[1] > v2[1]) ||
(v1[0] === v2[0] && v1[1] === v2[1] && v1[2] > v2[2])
)
}
}
function parseVersion(version: string = ""): Version {
const v: Version = ['0', '0', '0']
version.split(".").forEach((value, i) => (v[i] = value))
return v
}

View File

@@ -1 +0,0 @@
../../.npmignore

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/compile",
"version": "0.8.0",
"version": "0.28.0-beta.9",
"description": "MiaoScript compile package",
"keywords": [
"miaoscript",
@@ -12,15 +12,15 @@
"homepage": "https://github.com/circlecloud/ms.git",
"license": "ISC",
"main": "dist/index.js",
"files": [
"dist/**/*.js",
"dist/**/*.ts",
"dist/**/*.map"
],
"scripts": {
"clean": "rimraf dist",
"watch": "tsc --watch",
"build": "yarn clean && tsc",
"build": "pnpm clean && tsc",
"test": "echo \"Error: run tests from root\" && exit 1"
},
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.9.2"
}
}

View File

@@ -1 +0,0 @@
../../.npmignore

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/container",
"version": "0.8.0",
"version": "0.28.0-beta.9",
"description": "MiaoScript container package",
"keywords": [
"miaoscript",
@@ -12,20 +12,22 @@
"homepage": "https://github.com/circlecloud/ms.git",
"license": "ISC",
"main": "dist/index.js",
"files": [
"dist/**/*.js",
"dist/**/*.ts",
"dist/**/*.map"
],
"scripts": {
"clean": "rimraf dist",
"watch": "tsc --watch",
"build": "yarn clean && tsc",
"build": "pnpm clean && tsc",
"test": "echo \"Error: run tests from root\" && exit 1"
},
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.9.2"
"@ccms/nashorn": "^0.28.0-beta.9"
},
"dependencies": {
"@ccms/nashorn": "^0.8.0",
"inversify": "^5.0.1",
"inversify": "^6.0.1",
"inversify-binding-decorators": "^4.0.0"
}
}

View File

@@ -1,38 +1,9 @@
import { interfaces, Container } from "inversify"
import { _proxyGetter } from "./utils"
let _container: Container
const ContainerInstance = Symbol.for("@ccms/ioc:Container")
const INJECTION = Symbol.for("INJECTION")
function _proxyGetter(
proto: any,
key: string,
resolve: () => any,
doCache: boolean
) {
function getter(this: object) {
if (doCache && !Reflect.hasMetadata(INJECTION, this, key)) {
Reflect.defineMetadata(INJECTION, resolve(), this, key)
}
if (Reflect.hasMetadata(INJECTION, this, key)) {
return Reflect.getMetadata(INJECTION, this, key)
} else {
return resolve()
}
}
function setter(this: object, newVal: any) {
Reflect.defineMetadata(INJECTION, newVal, this, key)
}
Object.defineProperty(proto, key, {
configurable: true,
enumerable: true,
get: getter,
set: setter
})
}
function initContainer(container: Container) {
Reflect.defineMetadata(ContainerInstance, container, Reflect)

View File

@@ -2,9 +2,10 @@
import "reflect-metadata"
import { initContainer, getContainer } from './decorators'
import { interfaces, Container } from 'inversify'
import { interfaces, Container, inject, named } from 'inversify'
import { fluentProvide } from 'inversify-binding-decorators'
import { ioc } from "./constants"
import { _proxyGetter } from "./utils"
/**
* 注册一个命名对象
@@ -31,27 +32,37 @@ export const provideSingletonNamed = (identifier: interfaces.ServiceIdentifier<a
return fluentProvide(identifier).inSingletonScope().whenTargetNamed(name).done()
}
export function getJavaClass(className: string) {
try { return Java.type(className).class; return } catch (error: any) { }
try { return base.getClass(className); return } catch (error: any) { }
}
/**
* 获得一个 java.lang.Class
* @param className Java全类名
*/
export const JavaClass = (className: string) => {
return function (target: any, propertyKey: string, index?: number) {
try { target[propertyKey] = Java.type(className).class; return } catch (error) { }
try { target[propertyKey] = base.getClass(className); return } catch (error) { }
console.warn('JavaClass Inject target', target, 'propertyKey', propertyKey, 'failed!')
return function (target: object, propertyKey: string, index?: number) {
_proxyGetter(target, propertyKey, () => {
return getJavaClass(className) || console.warn('JavaClass', className, 'Inject target', target.constructor.name, 'propertyKey', propertyKey, 'failed!')
}, true)
}
}
export function getJSClass(className: string) {
try { return Java.type(className) } catch (error: any) { }
try { return base.getClass(className).static } catch (error: any) { }
}
/**
* 获得一个JS的Java类
* @param className Java 全类名
*/
export const JSClass = (className: string) => {
return function (target: any, propertyKey: string, index?: number) {
try { target[propertyKey] = Java.type(className); return } catch (error) { }
try { target[propertyKey] = base.getClass(className).static; return } catch (error) { }
console.warn('JSClass Inject target', target, 'propertyKey', propertyKey, 'failed!')
return function (target: object, propertyKey: string, index?: number) {
_proxyGetter(target, propertyKey, () => {
return getJSClass(className) || console.warn('JSClass', className, 'Inject target', target.constructor.name, 'propertyKey', propertyKey, 'failed!')
}, true)
}
}
@@ -59,9 +70,22 @@ export const JSClass = (className: string) => {
* 自动注入实例由平台实现
* @param className 类名
*/
export const Autowired = (className?: string | any) => {
return function (target: any, propertyKey: string) {
target[propertyKey] = getContainer().getNamed(ioc.Autowired, className || propertyKey)
export const Autowired = (className?: any) => {
return function (target: any, propertyKey: string, index?: number) {
let container = getContainer()
if (className && (className instanceof Symbol || className instanceof Function)) {
return inject(className)(target, propertyKey, index)
}
let type = Reflect.getMetadata('design:type', target, propertyKey)
if (type && type !== Object && !Java.isJavaObject(type)) {
inject(type)(target, propertyKey, index)
named(className || propertyKey)(target, propertyKey, index)
} else if (container.isBound(ioc.Autowired)) {
console.debug('Autowired', 'ioc.Autowired', 'named', className || propertyKey)
target[propertyKey] = container.getNamed(ioc.Autowired, className || propertyKey)
} else {
throw new Error(`No matching bindings found for target: ${target.constructor.name} type: ${type} named: ${className || propertyKey}`)
}
}
}
@@ -70,11 +94,64 @@ export const Autowired = (className?: string | any) => {
* @param className 类名
*/
export const Resource = (resourceName?: string | any) => {
return function (target: any, propertyKey: string) {
return function (target: any, propertyKey: string, index?: number) {
target[propertyKey] = getContainer().getNamed(ioc.Resource, resourceName || propertyKey)
}
}
const DocumentBuilderFactory = Java.type('javax.xml.parsers.DocumentBuilderFactory')
export const MavenDepend = (groupId: string, artifactId: string, version: string, recursion = false) => {
return function (target: any) {
loadMavenDepend(groupId, artifactId, version, recursion)
}
}
const loadedMavenDepend = new Set<string>()
export function loadMavenDepend(groupId: string, artifactId: string, version: string, recursion = false) {
const key = `${groupId}:${artifactId}:${version}`
try {
if (loadedMavenDepend.has(key)) { return }
console.info('loading maven dependency', key)
let [pom, _] = base.loadMavenDepend(groupId, artifactId, version)
loadedMavenDepend.add(key)
if (recursion) {
let doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(pom)
let dependencies = doc.getElementsByTagName("dependency")
let size = dependencies.length
if (!size) { return }
console.debug(key, 'found', size, 'dependencies loading...')
for (let i = 0; i < size; i++) {
const dependency = dependencies.item(i)
const gav = dependency.getChildNodes()
const length = gav.length
const dependencyVersion = { groupId: '', artifactId: '', version: '' }
for (let j = 0; j < length; j++) {
const prop = gav.item(j)
switch (prop.getNodeName()) {
case "groupId":
dependencyVersion.groupId = prop.getTextContent()
break
case "artifactId":
dependencyVersion.artifactId = prop.getTextContent()
break
case "version":
dependencyVersion.version = prop.getTextContent()
break
}
}
loadMavenDepend(dependencyVersion.groupId, dependencyVersion.artifactId, dependencyVersion.version, recursion)
}
}
} catch (error: any) {
console.warn('load maven dependency', key, 'failed. Error:', error)
if (global.debug) {
console.ex(error)
}
}
}
export const reduceMetadata = (ctx: interfaces.Context): any => {
return ctx.currentRequest.target.metadata.reduce((result, entry, index) => {
result[entry.key] = entry.value
@@ -82,8 +159,20 @@ export const reduceMetadata = (ctx: interfaces.Context): any => {
}, {})
}
function initAutowired(container: Container) {
container.bind(ioc.Autowired).toDynamicValue((ctx) => {
var metadata: any = reduceMetadata(ctx)
let key = Object.prototype.toString.call(metadata.named)
if (key === "[object Function]" || key === "[object Symbol]") { return container.get(metadata.named) }
console.warn('container Autowired', metadata.named, 'failed. Error: illegal serviceIdentifier type', key)
console.debug(metadata.named, 'metadata', JSON.stringify(metadata))
return undefined
})
}
export const DefaultContainer = new Container()
initContainer(DefaultContainer)
initAutowired(DefaultContainer)
export * from 'inversify'
export * from './constants'

View File

@@ -0,0 +1,30 @@
const INJECTION = Symbol.for("INJECTION")
export function _proxyGetter(
proto: any,
key: string,
resolve: () => any,
doCache: boolean
) {
function getter(this: object) {
if (doCache && !Reflect.hasMetadata(INJECTION, this, key)) {
Reflect.defineMetadata(INJECTION, resolve(), this, key)
}
if (Reflect.hasMetadata(INJECTION, this, key)) {
return Reflect.getMetadata(INJECTION, this, key)
} else {
return resolve()
}
}
function setter(this: object, newVal: any) {
Reflect.defineMetadata(INJECTION, newVal, this, key)
}
Object.defineProperty(proto, key, {
configurable: true,
enumerable: true,
get: getter,
set: setter
})
}

View File

@@ -1 +0,0 @@
../../.npmignore

View File

@@ -1,7 +1,7 @@
{
"name": "@ccms/core",
"version": "0.8.1",
"description": "MiaoScript api package",
"version": "0.28.0-beta.9",
"description": "MiaoScript core package",
"keywords": [
"miaoscript",
"minecraft",
@@ -12,20 +12,28 @@
"homepage": "https://github.com/circlecloud/ms.git",
"license": "ISC",
"main": "dist/index.js",
"files": [
"dist/**/*.js",
"dist/**/*.ts",
"dist/**/*.map"
],
"scripts": {
"clean": "rimraf dist",
"watch": "tsc --watch",
"build": "yarn clean && tsc",
"watch": "pnpm rollup -c rollup.config.js --watch",
"build": "pnpm clean && pnpm rollup -c rollup.config.js",
"test": "echo \"Error: run tests from root\" && exit 1"
},
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.9.2"
"@rollup/plugin-typescript": "^11.1.5",
"rollup": "^2.79.1",
"rollup-obfuscator": "^3.0.2",
"rollup-plugin-peer-deps-external": "^2.2.4"
},
"dependencies": {
"@ccms/api": "^0.8.1",
"@ccms/container": "^0.8.0"
"@ccms/api": "^0.28.0-beta.9",
"@ccms/common": "^0.28.0-beta.9",
"@ccms/container": "^0.28.0-beta.9",
"js-yaml": "^4.1.0"
},
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
}

View File

@@ -0,0 +1,49 @@
import typescript from '@rollup/plugin-typescript'
import peerDepsExternal from 'rollup-plugin-peer-deps-external'
import { obfuscator } from 'rollup-obfuscator'
import pkg from './package.json'
const external = ['path', 'fs', 'typescript', 'tslib']
/**
* @type {import('rollup').RollupOptions}
*/
export default {
input: 'src/index.ts',
plugins: [
peerDepsExternal(),
typescript(),
obfuscator({
compact: true,
deadCodeInjection: true,
deadCodeInjectionThreshold: 1,
identifierNamesGenerator: 'mangled-shuffled',
numbersToExpressions: true,
simplify: true,
stringArray: true,
stringArrayThreshold: 1,
stringArrayEncoding: ['rc4'],
stringArrayCallsTransform: true,
stringArrayCallsTransformThreshold: 1,
stringArrayWrappersChainedCalls: true,
stringArrayWrappersParametersMaxCount: 3,
sourceMap: true,
sourceMapSourcesMode: 'sources',
inputFileName: `${pkg.name}.ts`,
transformObjectKeys: true,
unicodeEscapeSequence: true,
target: 'browser-no-eval'
}),
],
external,
treeshake: false,
output: [
{
format: 'cjs',
interop: "auto",
exports: "named",
sourcemap: true,
file: pkg.main || `dist/${pkg.name}.js`
}
]
}

1
packages/core/src/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
script

View File

@@ -1,60 +1,62 @@
let containerStartTime = Date.now()
console.i18n("ms.core.ioc.initialize", { scope: global.scope })
import { plugin, server, task, constants } from '@ccms/api'
import { DefaultContainer as container, inject, provideSingleton, ContainerInstance, buildProviderModule } from '@ccms/container'
import { plugin, server, task, constants, console as jsconsole } from '@ccms/api'
import { DefaultContainer as container, provideSingleton, ContainerInstance, buildProviderModule, Autowired } from '@ccms/container'
console.i18n("ms.core.ioc.completed", { scope: global.scope, time: (Date.now() - containerStartTime) / 1000 })
import * as yaml from 'js-yaml'
import http from '@ccms/common/dist/http'
import { EventEmitter } from 'events'
import * as fs from '@ccms/common/dist/fs'
const UUID = Java.type('java.util.UUID')
const MiaoScriptAPI = Java.type('pw.yumc.MiaoScript.api.MiaoScriptAPI')
@provideSingleton(MiaoScriptCore)
class MiaoScriptCore {
@inject(server.Console)
@Autowired(server.Console)
private Console: Console
@inject(task.TaskManager)
private taskManager: task.TaskManager
@inject(plugin.PluginFolder)
private pluginFolder: string
@inject(plugin.PluginManager)
@Autowired()
private pluginManager: plugin.PluginManager
enable() {
process.emit('core.before.enable', this)
this.loadServerConsole()
this.loadTaskFunction()
global.level = "TRACE"
this.loadPlugins()
try {
MiaoScriptAPI.setPluginManager(this.pluginManager)
} catch (error) {
}
process.emit('core.enable', this)
process.emit('core.after.enable', this)
console.i18n("ms.core.engine.completed", {
loader: base.version,
version: 'v' + global.ScriptEngineVersion,
time: (Date.now() - global.ScriptEngineStartTime) / 1000
})
return () => this.disable()
}
loadServerConsole() {
process.emit('core.before.load.console', this)
//@ts-ignore
global.setGlobal('console', new this.Console(), { writable: false, configurable: false })
}
loadTaskFunction() {
global.setGlobal('setTimeout', (func: Function, tick: number, ...args: any[]) => {
return this.taskManager.create(func).later(tick).submit(...args)
}, { writable: false, configurable: false })
global.setGlobal('setInterval', (func: Function, tick: number, ...args: any[]) => {
return this.taskManager.create(func).timer(tick).submit(...args)
}, { writable: false, configurable: false })
}
loadPlugins() {
let loadPluginStartTime = new Date().getTime()
console.i18n("ms.core.plugin.initialize")
this.pluginManager.scan(this.pluginFolder)
this.pluginManager.build()
this.pluginManager.load(this.pluginManager.getPlugins())
this.pluginManager.enable(this.pluginManager.getPlugins())
console.i18n("ms.core.plugin.completed", { time: (new Date().getTime() - loadPluginStartTime) / 1000 })
process.emit('core.after.load.console', this)
}
disable() {
process.emit('core.before.disable', this)
let disableStartTime = Date.now()
console.i18n("ms.core.engine.disable")
this.pluginManager.disable(this.pluginManager.getPlugins())
this.taskManager.disable()
process.emit('exit', 0)
process.emit('core.disable', this)
process.emit('core.after.disable', this)
loadCoreScript('exit')
process.emit('core.before.exit', this)
process.exit(0)
process.emit('core.exit', this)
console.i18n("ms.core.engine.disable.finish", {
loader: base.version,
version: 'v' + global.ScriptEngineVersion,
time: (new Date().getTime() - disableStartTime) / 1000
})
process.emit('core.after.exit', this)
}
}
@@ -62,54 +64,99 @@ function detectServer(): constants.ServerType {
try {
Java.type("org.bukkit.Bukkit")
return constants.ServerType.Bukkit
} catch (ex) {
} catch (ex: any) {
}
try {
Java.type("org.spongepowered.api.Sponge")
return constants.ServerType.Sponge
} catch (ex) {
} catch (ex: any) {
}
try {
Java.type("cn.nukkit.Nukkit")
return constants.ServerType.Nukkit
} catch (ex) {
} catch (ex: any) {
}
try {
Java.type("net.md_5.bungee.api.ProxyServer")
return constants.ServerType.Bungee
} catch (ex) {
} catch (ex: any) {
}
try {
Java.type("org.springframework.boot.SpringApplication")
return constants.ServerType.Spring
} catch (ex) {
} catch (ex: any) {
}
throw Error('Unknow Server Type...')
}
function initialize() {
// @ts-ignore
try { engineLoad({ script: http.get("http://ms.yumc.pw/api/plugin/download/name/initialize"), name: 'core/initialize.js' }) } catch (error) { console.debug(error) }
function loadCoreScript(name) {
try {
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", { scope: global.scope, type })
container.bind(server.ServerType).toConstantValue(type)
console.i18n("ms.core.package.initialize", { scope: global.scope, type })
require(`${global.scope}/${type}`).default(container)
require(`${global.scope}/plugin`)
container.load(buildProviderModule())
console.i18n("ms.core.package.completed", { scope: global.scope, 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
} catch (error) {
console.i18n("ms.core.initialize.error", { error })
console.ex(error)
return () => console.i18n('ms.core.engine.disable.abnormal')
let scriptname = name + (global.debug ? '-debug' : '')
engineLoad({
script: http.get(`https://mscript.yumc.pw/api/plugin/download/name/${scriptname}`),
name: `core/${scriptname}.js`
})
} catch (error: any) {
if (global.debug) {
console.debug(error)
console.ex(error)
}
}
}
function loadMiaoScriptConfig() {
let configFile = fs.concat(root, 'config.yml')
if (!fs.exists(configFile)) {
global.ScriptEngineConfig = base.save(configFile, yaml.dump({
uuid: UUID.randomUUID().toString(),
slow_execute: 50
}))
} else {
global.ScriptEngineConfig = yaml.load(base.read(configFile))
}
global.ScriptSlowExecuteTime = global.ScriptEngineConfig.slow_execute || 50
}
function createCore() {
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()
process.emit('core.before.initialize.detect')
console.i18n("ms.core.initialize.detect", { scope: global.scope, type })
container.bind(server.ServerType).toConstantValue(type)
container.bind(server.ServerChecker).toSelf().inSingletonScope()
container.bind(server.NativePluginManager).toSelf().inSingletonScope()
container.bind(server.NativePluginChecker).toSelf().inSingletonScope()
process.emit('core.after.initialize.detect')
process.emit('core.before.package.initialize')
console.i18n("ms.core.package.initialize", { scope: global.scope, type })
require(`${global.scope}/${type}`).default(container)
require(`${global.scope}/plugin`)
container.load(buildProviderModule())
console.i18n("ms.core.package.completed", { scope: global.scope, type, time: (Date.now() - corePackageStartTime) / 1000 })
process.emit('core.after.package.initialize')
return container.get<MiaoScriptCore>(MiaoScriptCore)
}
function initialize() {
process.emit('core.before.initialize')
loadMiaoScriptConfig()
global.ScriptEngineVersion = require('../package.json').version
global.setGlobal('loadCoreScript', loadCoreScript)
loadCoreScript('initialize')
try {
return createCore()
} catch (error: any) {
console.i18n("core.initialize.error", { error })
jsconsole.getStackTrace(error, false).forEach(line => console.log(line))
process.emit('core.initialize.error')
return { enable: () => () => console.i18n('ms.core.engine.disable.abnormal') }
} finally {
process.emit('core.after.initialize')
}
}

View File

@@ -1 +0,0 @@
../../.npmignore

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/database",
"version": "0.8.1",
"version": "0.28.0-beta.9",
"description": "MiaoScript database package",
"keywords": [
"miaoscript",
@@ -12,19 +12,22 @@
"homepage": "https://github.com/circlecloud/ms.git",
"license": "ISC",
"main": "dist/index.js",
"files": [
"dist/**/*.js",
"dist/**/*.ts",
"dist/**/*.map"
],
"scripts": {
"clean": "rimraf dist",
"watch": "tsc --watch",
"build": "yarn clean && tsc",
"build": "pnpm clean && tsc",
"test": "echo \"Error: run tests from root\" && exit 1"
},
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.9.2"
"@javatypes/spring-jdbc": "^0.0.3"
},
"dependencies": {
"@ccms/api": "^0.8.1",
"@ccms/container": "^0.8.0"
"@ccms/api": "^0.28.0-beta.9",
"@ccms/container": "^0.28.0-beta.9"
}
}

View File

@@ -1,88 +1,109 @@
import { Model } from './model'
import { database } from '@ccms/api'
import { JSClass } from '@ccms/container'
const HikariDataSource = Java.type('com.zaxxer.hikari.HikariDataSource')
const HikariConfig = Java.type('com.zaxxer.hikari.HikariConfig')
const JdbcTemplate = Java.type('org.springframework.jdbc.core.JdbcTemplate')
/**
* 数据库配置
*/
export interface DataBaseConfig {
/**
* 数据库连接串
*/
url: string | javax.sql.DataSource
/**
* 数据库驱动
*/
driverClassName?: string
/**
* 用户名
*/
username?: string
/**
* 密码
*/
password?: string
}
const Thread = Java.type('java.lang.Thread')
const JavaString = Java.type('java.lang.String')
const Properties = Java.type('java.util.Properties')
/**
* 数据库封装类
*/
export class DataBase {
export class DataBase extends database.DataBase {
private dataSource: javax.sql.DataSource
private jdbcTemplate: org.springframework.jdbc.core.JdbcTemplate
constructor(dbConfig: DataBaseConfig) {
@JSClass('com.zaxxer.hikari.HikariDataSource')
private HikariDataSource: any
@JSClass('com.zaxxer.hikari.HikariConfig')
private HikariConfig: any
@JSClass('org.springframework.jdbc.core.JdbcTemplate')
private JdbcTemplate: typeof org.springframework.jdbc.core.JdbcTemplate
constructor(dbConfig: database.DataBaseConfig) {
super()
if (!dbConfig.url) { throw new Error('DataBase url can\'t be null!') }
this.createDataSource(dbConfig)
this.initialize()
}
private createDataSource(dbConfig: DataBaseConfig) {
private createDataSource(dbConfig: database.DataBaseConfig) {
if (typeof dbConfig.url === "string") {
if (!dbConfig.username || !dbConfig.password) {
throw new Error('DataBase username or password can\'t be null!')
}
let config = new HikariConfig()
let originClassLoader = Thread.currentThread().getContextClassLoader()
Thread.currentThread().setContextClassLoader(base.getInstance().class.classLoader)
let config = new this.HikariConfig()
if (dbConfig.driverClassName) {
config.setDriverClassName(dbConfig.driverClassName)
} else {
switch (dbConfig.type) {
case "h2":
config.setDriverClassName("org.h2.Driver")
break
case "sqlite":
config.setDriverClassName("org.sqlite.JDBC")
break
default:
}
}
if (dbConfig.username) {
config.setUsername(dbConfig.username)
}
if (dbConfig.password) {
config.setPassword(dbConfig.password)
}
config.setUsername(dbConfig.username)
config.setPassword(dbConfig.password)
config.setJdbcUrl(dbConfig.url)
this.dataSource = new HikariDataSource(config)
if (dbConfig.properties) {
let properties = new Properties()
for (const key in dbConfig.properties) {
properties.setProperty(key, dbConfig.properties[key])
}
config.setDataSourceProperties(properties)
}
console.debug('createDataSource from config ' + JSON.stringify(dbConfig))
this.dataSource = new this.HikariDataSource(config)
Thread.currentThread().setContextClassLoader(originClassLoader)
} else {
this.dataSource = dbConfig.url
}
this.jdbcTemplate = new this.JdbcTemplate(this.dataSource)
}
private initialize() {
this.jdbcTemplate = new JdbcTemplate(this.dataSource)
getDataSource() {
return this.dataSource
}
/**
* 执行SQL查询
* @param sql SQL语句
* @param args 参数
*/
query<T>(sql: string, ...args: any[]): Array<T> {
let startTime = Date.now()
let result = Java.from<any>(this.jdbcTemplate.queryForList(sql, args))
console.debug(java.lang.String.format(`\n[DB] query \nSQL : ${sql.replace(/\?/ig, '%s')} \nCOST : ${Date.now() - startTime}ms`, args))
console.debug(JavaString.format(`\n[DB] query \nSQL : ${sql.replace(/\?/ig, '%s')} \nCOST : ${Date.now() - startTime}ms`, args))
return result
}
/**
* 执行SQL更新
* @param sql SQL语句
* @param args 参数
*/
update(sql: string, ...args: any[]): number {
let startTime = Date.now()
let result = this.jdbcTemplate.update(sql, args)
console.debug(java.lang.String.format(`\n[DB] update \nSQL : ${sql.replace(/\?/ig, '%s')} \nCOST : ${Date.now() - startTime}ms`, args))
console.debug(JavaString.format(`\n[DB] update \nSQL : ${sql.replace(/\?/ig, '%s')} \nCOST : ${Date.now() - startTime}ms`, args))
return result
}
/**
* 执行SQL语句
* @param sql SQL语句
*/
execute(sql: string): void {
let startTime = Date.now()
this.jdbcTemplate.execute(sql)
console.debug(`\n[DB] execute \nSQL : ${sql} \nCOST : ${Date.now() - startTime}ms`)
}
close() {
//@ts-ignore
this.dataSource.close()

View File

@@ -1,7 +0,0 @@
import 'reflect-metadata'
export function id() {
return (target: Object, propertyKey: string | symbol) => void {
}
}

View File

@@ -2,5 +2,11 @@
/// <reference types="@javatypes/jdk" />
/// <reference types="@javatypes/spring-jdbc" />
import { loadMavenDepend } from '@ccms/container'
loadMavenDepend('com.h2database', 'h2', '2.1.212')
loadMavenDepend("com.zaxxer", "HikariCP", "4.0.3")
loadMavenDepend("org.springframework", "spring-jdbc", "5.3.19", true)
export * from './database'
export * from './manager'
export * from './manager'

View File

@@ -1,27 +1,46 @@
import { plugin, database } from '@ccms/api'
import { provideSingleton, inject, postConstruct } from '@ccms/container'
import { DataBase, DataBaseConfig } from './database'
import { database } from '@ccms/api'
import { JSClass, provideSingleton } from '@ccms/container'
import { DataBase } from './database'
@provideSingleton(database.DataBaseManager)
export class DataBaseManager {
@inject(plugin.PluginInstance)
private instance: any
private beanFactory: any
export class DataBaseManager extends database.DataBaseManager {
private mainDatabase: DataBase
private databases: { [key: string]: DataBase } = {}
private databases = new Map<string, DataBase>()
@postConstruct()
initialize() {
try {
this.beanFactory = this.instance.getAutowireCapableBeanFactory()
let mainDatasource = this.beanFactory.getBean(Packages.javax.sql.DataSource.class)
this.mainDatabase = new DataBase({ url: mainDatasource })
} catch (error) {
console.ex(error)
@JSClass('org.h2.tools.Server')
private Server: any
private webManager: any
constructor() {
super()
process.on('exit', () => this.shutdown())
}
startWebManager(...args: string[]) {
this.webManager = this.Server.createWebServer(args)
this.webManager.start()
}
stopWebManager() {
if (this.webManager) {
this.webManager.stop()
this.webManager.shutdown()
}
}
shutdown() {
this.stopWebManager()
this.disable()
}
/**
* 设置主数据库
* @param mainDatabase 主数据库
*/
setMainDatabase(mainDatabase: DataBase) {
this.mainDatabase = mainDatabase
}
/**
* 获得主数据库
* Get MainDatabase
@@ -36,18 +55,28 @@ export class DataBaseManager {
* @param name 数据库名称 用于代码 database Name use at code
* @param config 数据库配置
*/
createDatabase(name: string, config: DataBaseConfig) {
Java.synchronized(() => {
if (this.databases[name]) return this.databases[name]
return this.databases[name] = new DataBase(config)
createDatabase(name: string, config: database.DataBaseConfig) {
return Java.synchronized(() => {
if (!this.databases.has(name)) {
this.databases.set(name, new DataBase(config))
}
return this.databases.get(name)
}, this.databases)()
}
removeDatabase(name: string) {
if (this.databases.has(name)) {
this.databases.get(name).close()
}
return this.databases.delete(name)
}
getDatabase(name: string) {
return this.databases[name]
return this.databases.get(name)
}
disable() {
Object.values(this.databases).forEach((ds) => ds?.close())
this.databases.forEach((db) => db.close())
this.databases.clear()
}
}

View File

@@ -1,11 +0,0 @@
import { DataBase } from "./database"
export class Model<T> {
constructor(private database: DataBase) {
}
queryForList(): Array<T> {
return []
}
}

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