Compare commits

..

146 Commits

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

10
.gitpod.Dockerfile vendored
View File

@@ -1,10 +0,0 @@
FROM gitpod/workspace-full
USER gitpod
# Install custom tools, runtime, etc. using apt-get
# For example, the command below would install "bastet" - a command line tetris clone:
#
# RUN sudo apt-get -q update && # sudo apt-get install -yq bastet && # sudo rm -rf /var/lib/apt/lists/*
#
# More information: https://www.gitpod.io/docs/config-docker/

View File

@@ -1,5 +0,0 @@
tasks:
- init: yarn && yarn bs && yarn build
command: yarn watch
# image:
# file: .gitpod.Dockerfile

View File

@@ -20,4 +20,3 @@ wallaby.js
.vscode
.theia
type_definitions
tsconfig.tsbuildinfo

View File

@@ -1,11 +1,478 @@
- 构建状态 [![Build Status](https://ci.yumc.pw/job/Minecraft/job/MiaoScript/badge/icon?style=flat-square)](https://ci.yumc.pw/job/Minecraft/job/MiaoScript/)
- 当前版本 ![Build Status](https://ci.yumc.pw/job/Minecraft/job/MiaoScript/badge/icon?style=flat-square&subject=VERSION&status=0.1.0beta&color=darkturquoise)
- 下载地址 [![Build Status](https://ci.yumc.pw/job/Minecraft/job/MiaoScript/badge/icon?style=flat-square&subject=MiaoScript&status=DOWNLOAD&color=darkgreen)](http://w.yumc.pw/free.html#MiaoScript-download)
- 更新日志 [![Build Status](https://ci.yumc.pw/job/Minecraft/job/MiaoScript/badge/icon?style=flat-square&subject=MiaoScript&status=CHANGELOG&color=green)](https://docs.yumc.pw/MiaoScript/CHANGELOG.html)
- 安装文档 [![Build Status](https://ci.yumc.pw/job/Minecraft/job/MiaoScript/badge/icon?style=flat-square&subject=MiaoScript&status=MiaoDoc%20USER&color=red)](https://docs.yumc.pw/MiaoScript/1-user/1.1-check-env.html)
- 开发文档 [![Build Status](https://ci.yumc.pw/job/Minecraft/job/MiaoScript/badge/icon?style=flat-square&subject=MiaoScript&status=MiaoDoc%20DEVELOP&color=darkred)](https://docs.yumc.pw/MiaoScript/2-develop/1.1-check-env.html)
- 兼容服务端 Spigot CatServer Sponge BungeeCord Nukkit(没错 他还兼容Nukkit)
- 当前版本 ![Build Status](https://ci.yumc.pw/job/Minecraft/job/MiaoScript/badge/icon?style=flat-square&subject=version&status=0.1.0beta&color=darkturquoise)
- 下载地址 [![Build Status](https://ci.yumc.pw/job/Minecraft/job/MiaoScript/badge/icon?style=flat-square&subject=download&status=MiaoScript&color=darkgreen)](http://w.yumc.pw/free.html#MiaoScript-download)
- 为了方便阅读 我对帖子进行了分页 请点击目录阅读!
### 腐竹版本(开发中)
### 更新日志
- 先上几张图
- 2020-03-03
- 发布 `v0.3.1` 版本
- 2020-03-02
- 杂项 更新文档以及示例插件
- 2020-03-01
- 修复 多个包之间的循环依赖问题
- 优化 `@ms/types` 的引用逻辑
- 2020-02-29
- 更新 `TypeScript` 版本为 `3.8.3`
- 新增 `@ms/common` 的 `http` 下载功能
- 2020-02-27
- 发布 `v0.3.0` 版本
- 新增 `@ms/i18n` 国际化包的支持
- 修复 `@ms/plugin` 对 `servers` 相关处理异常
- 优化 `@ms/api` 的 `Channel` 处理增加 扩展原始数据
- 2020-02-26
- 优化 `@ms/container` 使用 `autoProvide` 自动注入依赖
- 2020-02-25
- 修复 `@ms/api` 对 `evnet` 的类型处理异常
- 2020-02-24
- 发布 `v0.2.1` 版本
- 完善 对 `Nukkit` 端的支持
- 新增 `@ms/api` 通道相关的支持
- 2020-02-23
- 新增 `@ms/nukkit` 包 对 `Nukkit` 端的支持
- 新增 `@ms/type` 的 `nukkit` 类型自动补全
- 2020-02-22
- 发布 `v0.2.0` 版本
- 新增 `@ms/plugin` 的 `@config` 注解 目前支持 `json` `yml` 格式的配置
- 2020-02-15
- 新增 `SourceMap` 的支持 用于跟踪源代码行数
- 2020-02-09
- 新增 `core-js` 用于支持大部分新ES语法
- 2020-01-31
- 优化 `@ms/ployfill` 全局处理
- 2020-01-15
- 新增 `@ms/bungee` 包 对 `BungeeCord` 端的支持
- 2020-01-14
- 新增 `@ms/type` 的 `bungee` 类型自动补全
- 2019-11-10
- 新增 `WebSocket` 的注入支持
- 2019-11-07
- 新增 `@ms/type` 的 `jdk` 类型自动补全
- 2019-09-27
- 新增 `CatServer` MOD端的支持
- 2019-09-25
- 新增 `@ms/type` 的 `sponge` 类型自动补全
- 2019-09-24
- 新增 `@ms/type` 的 `bukkit` 类型自动补全
## 插件简介
- 此插件可以实现跨端使用 `TypeScript` 开发 脚本插件
- 目前已经兼容 `Spigot` `Sponge` `Paper` `CatServer` `BungeeCord` `Nukkit`
- 后续计划兼容 暂无
## 起源 (可以略过)
### 简介
> 这个坑是我自己刨的 但是发现坑太大 需要更多的人一起填
### 起源
- 诞生于 `2016年08月25日` 这是 Git 上的第一个提交 具体啥时候我也忘了
- 起初 `MiaoScript` 只是用于服务器其他插件的变量执行 并且依赖于PAPI(不知道是啥的自己百度)
- 比如 [`MiaoMenu`](http://w.yumc.pw/zc/MiaoMenu.html) 的部分复杂脚本
- 比如 [`MiaoChat`](http://mcbbs.net/thread-631240-1-1.html) 的聊天变量
- 突然有一天 圈内的大佬 `QSB` @qiu1995 过来找我 说能不能用脚本监听玩家的事件
- PS: 这货自从用过 `DeluxeMenu` 之后就喜欢上了用JS写菜单
- 当初感觉没啥问题 就出了第一个简易的 `MiaoScript` 版本 还是用 yml 做的配置文件
- 但是由于设计 BukkitAPI 等内容 对Java要求太高 后来 邱也弃坑了 我也弃坑了
### 刨坑
- 时隔多年(也就一年) 看到了Sponge的兴起 (估摸着是MCPC系列的MOD端都弃坑了)
- 同时 这期间 收到很多腐竹的单子 但是又是非常基础的东西
- 比如 开服给玩家发一条消息啦
- 比如 修改玩家某些数据啦
- 这些东西实际上也就几行代码的事情
- 同时 很多想入坑 插件开发 但是又有一些被卡死在环境搭建上
- 比如 `Bukkit` 需要 `BukkitAPI`
- `Sponge` 需要 `SpongeAPI` 如果涉及 `MOD` 还要 `Forge` 环境
- 再或者 BungeeCord 的插件开发 我也是经常懒得搞
- 当然 最主要的是 某个 咕咕咕的群 天天有人问我 喵系插件能不能支持 Sponge
- 内心当然是拒绝的 现在要上班养老婆孩子(咳咳 不要以为我是大叔 我也才刚毕业而已) 那里还有时间免费给你们写插件
- 于是乎 我又想起了当初的 `MiaoScript`
- 突发奇想 一个插件的雏形出现在我的脑海中
- 可以兼容多种服务器
- 不需要开发环境 有记事本就可以开发
- 语法要简单 比如 JavaScript
- 能够自动搜索安装依赖(毕竟很多人天天问我为何喵系插件跑不起来 都是缺少PAPI)
- 能够不重启更新插件(当然得保证代码安全的前提下)
- 在 2017年9月14号(距离 第一个版本正式版发布(2016-09-21) 相差一年整)
- 一个全新的 `MiaoScript` 诞生了
- Java部分代码 只有一个启动类
- 核心全部由 JS 编写
- 兼容 `CommonJS` 规范
- 实时重载
- 2019年9月14号 emm 咸鱼2年之后
- TypeScript 重构版本横空出世
- 只保留 基础Java启动类 三个环境初始化js
- 完整的服务端Java类自动补全
- 全新的 IOC容器 注入功能
- 注解式 注册命令 注册事件
- 2020年3月2日 发布0.3.0版本
- 支持 Bukkit Nukkit BungeeCord Sponge
### 进展
- [项目发布](https://git.yumc.pw/502647092/MiaoScript/releases)
- [项目代码](https://git.yumc.pw/502647092/MiaoScript)
- [项目脑图](http://naotu.baidu.com/file/293b9a0fc7cef23c69de81c55e3617d5?token=1eee8fd759198eb7)
### 规划
- 初期只会支持JS类型的插件开发
- 二期会出一个建议版本的MS脚本 可以用简单的语法实现简单的功能
- 各个层级会有依赖控制 比如 `MS脚本 => JS脚本 => 调用Java原生API`
## 框架设计
### MiaoScript TS 实现
项目具体实现 由 TypeScript 进行编写 然后编译至 `es5` 用于兼容 Java8 的 `Nashorn`
### Project Structure
```txt
└─packages
├─api 全平台兼容的接口
├─core 核心代码 用于引导加载
├─common 公共类库代码 例如 http reflect 模块
├─client NodeJS的Minecraft客户端 用于调试插件
├─container IOC容器 用于注入具体实现
├─ployfill Nashorn 的一些自定义增强
├─nashorn Nashorn 的类型定义
├─bungee BungeeCordAPI内部实现
├─bukkit BukkitAPI内部实现
├─sponge SpongeAPI内部实现
├─nukkit NukkitAPI内部实现
├─ployfill JS环境的相关环境补全
├─plugin 插件管理器
├─websocket Netty的WebSocket注入
├─type Java的类型定义
| ├─bungee BungeeCord类型定义
| ├─bukkit Bukkit类型定义
| ├─sponge Sponge类型定义
| └─nukkit Nukkit类型定义
└─plugins 这里当然是插件啦
├─bungee 只兼容BungeeCord的插件
├─bukkit 只兼容Bukkit的插件
├─sponge 只兼容Sponge的插件
└─nukkit 只兼容Nukkit的插件
```
详细的内容就不逼逼了 自己看代码吧
Github: https://github.com/circlecloud/ms
YUMC: https://git.yumc.pw/circlecloud/ms
## 插件开发基础
### 开发IDE (推荐VSCode或者MiaoScrit在线IDE)
如果只是简单的开发 你可用记事本 (但是没有任何补全和错误提示)
### 开发环境准备(针对高级用户)
- 安装 `NodeJS` 和 `Yarn`
- 拉取代码
- `git clone https://github.com/circlecloud/ms.git`
- 进入目录 `ms`
- 安装 npm 包
- `yarn`
- 建立内部依赖链接
- `yarn bs`
- 编译一次生成对应的类库
- `yarn build`
- 编译插件
- `yarn build:plugins`
### 直接在 MiaoScript Online WebIDE 开发
填坑中...
## 基本插件框架
### HelloWorld 示例插件
先来一个 `HelloWorld.ts` 插件示范!
```ts
/// <reference types="@ms/types" />
import { server } from '@ms/api';
import { inject } from '@ms/container';
import { plugin, interfaces, cmd, listener, tab } from '@ms/plugin'
@plugin({ name: 'HelloWorld', version: '1.0.0', author: 'MiaoWoo', source: __filename })
export class HelloWorld extends interfaces.Plugin {
@inject(server.Server)
private Server: server.Server
@config()
private config = {
version: 1.0.0
}
load() {
this.logger.log('Plugin load from MiaoScript Plugin System...');
}
enable() {
this.logger.log('Plugin enable from MiaoScript Plugin System...');
}
disable() {
this.logger.log('Plugin disable from MiaoScript Plugin System...');
}
bukkitload() {
this.logger.log('Load When ServerType is Bukkit!')
}
bukkitenable() {
this.logger.log('Enable When ServerType is Bukkit!')
}
bukkitdisable() {
this.logger.log('Disable When ServerType is Bukkit!')
}
spongeload() {
this.logger.log('Load When ServerType is Sponge!')
}
spongeenable() {
this.logger.log('Enable When ServerType is Sponge!')
}
spongedisable() {
this.logger.log('Disable When ServerType is Sponge!')
}
bungeeload() {
this.logger.log('Load When ServerType is BungeeCord!')
}
bungeeenable() {
this.logger.log('Enable When ServerType is BungeeCord!')
}
bungeedisable() {
this.logger.log('Disable When ServerType is BungeeCord!')
}
nukkitload() {
this.logger.log('Load When ServerType is Nukkit!')
}
nukkitenable() {
this.logger.log('Enable When ServerType is Nukkit!')
}
nukkitdisable() {
this.logger.log('Disable When ServerType is Nukkit!')
}
@cmd()
hello(sender: any, command: string, args: string[]) {
this.logger.log(sender, command, args);
sender.sendMessage(JSON.stringify({ command, ...args }))
}
@tab()
tabhello(_sender: any, _command: string, _args: string[]) {
return ['world']
}
// bukkit nukkit 大部分API神似 可以直接用
@listener({ servers: ['bukkit', 'nukkit'] })
PlayerJoin(event: org.bukkit.event.player.PlayerJoinEvent) {
let plyaer = event.getPlayer();
this.logger.console(`§cBukkit §aPlayerJoinEvent: §b${plyaer.getName()}`)
setTimeout(() => this.sendWelcome(plyaer), 10);
}
@listener({ servers: ['sponge'] })
ClientConnectionEvent$Join(event: org.spongepowered.api.event.network.ClientConnectionEvent.Join) {
this.logger.console(`§cSponge §aClientConnectionEvent.Join: §b${event.getTargetEntity().getName()}`)
setTimeout(() => this.sendWelcome(event.getTargetEntity()), 10);
}
private sendWelcome(player: any) {
this.logger.sender(player, `§a欢迎来到 §bMiaoScript §a的世界!`)
this.logger.sender(player, `§6当前版本: §c${this.Server.getVersion()}`)
}
@listener({ servers: ['bungee'] })
ServerConnected(e: any) {
let event = e as net.md_5.bungee.api.event.ServerConnectedEvent
this.logger.console(`§cBungeeCord §aServerConnectedEvent: §b${event.getPlayer().getDisplayName()}`)
setTimeout(() => this.logger.sender(event.getPlayer(), `§a欢迎来到 §bMiaoScript §a的世界 §6来自 §cBungeeCord §6的问候!`), 10);
}
}
```
- 进入 `ms`目录
- 执行编译 `yarn build:plugins`
- 从 `packages/plugins/dist` 中复制 `HelloWorld.js` 和 `HelloWorld.js.map`(可选 用于显示插件原有行数) 文件 到对应的插件目录
- Bungee: plugins/MiaoScript/plugins/
- Bukkit: plugins/MiaoScript/plugins/
- Sponge: config/miaoscript/plugins/
- Nukkit: plugins/MiaoScript/plugins/
- 重载 `MiaoScript`
- 打开客户端进入游戏 预览一下效果
- 从 Spigot 服务端进入
![image.png](https://i.loli.net/2019/09/22/2BZuwF65WV1xGnv.png)
![image.png](https://i.loli.net/2019/09/22/m2CftwbalnXsxvg.png)
- 从 Sponge 服务端进入
![image.png](https://i.loli.net/2019/09/22/QD1jrShtJpPXyVl.png)
![image.png](https://i.loli.net/2019/09/22/GzLFVC3sjAJ4obm.png)
## 注册插件
- 从上面的示例可以看到 一个插件 通过注解 `@plugin` 即可启动
- 此注解接受一个 `PluginMetadata` 对象 定义如下
```ts
export interface PluginMetadata {
/**
* 插件名称
*/
name: string;
/**
* 支持的服务器列表 为空则代表所有
*/
servers?: string[];
/**
* 前缀
*/
prefix?: string;
/**
* 插件版本
*/
version: string;
/**
* 插件版本
*/
author: string | string[];
/**
* 插件源文件 必须指定为 __filename
*/
source: string;
/**
* 插件本体
*/
target?: any;
}
```
### 插件生命周期
MiaoScript 的生命周期遵循了 Bukkit 的生命周期
MiaoScript 针对不同的服务端 提供了扩展的周期
以服务端类型开头阶段名结束 例如 `bukkitload` `spongeenbale` `bungeedisable`
扩展的生命周期只会在特定的服务器执行
### load 加载阶段
此阶段通常用于初始化基础配置 数据库链接等
某些对外提供功能的插件 需要在此阶段初始化完成
### enable 启动阶段
此阶段通常用于注册命令 注册事件等
由于命令和事件 MiaoScript 已经托管了 所以开发者可以直接用注解实现
### disable 关闭阶段
此阶段通常用于注销命令 注销事件等
由于命令和事件 MiaoScript 已经托管了 所以开发者可以直接用注解实现
## 注册命令/补全
### cmd 命令
命令 就是玩家在Minecraft中执行命令 下面是一个示例的命令
- 命令是一个 `function` 通过 `@cmd` 注解注册
- 由于不同的服务端有不同的逻辑 所以支持通过 `servers` 指定注册的类型 加上 `!` 代表不注册 不指定 `servers` 则注册所有的类型
- 命令注册时默认使用方法名称为命令名称 当前你可以传入 name 参数指定命令名称 例如 `{name: 'test'}`
- 接受三个参数 `sender: any, command: string, args: string[]`
- 分别代表 命令发送者 命令名称 命令参数
```ts
@cmd({ servers: ["bukkit", "sponge", "!bungee"] })
hello(sender: any, command: string, args: string[]) {
this.logger.log(sender, command, args);
this.logger.sender(sender, JSON.stringify({ command, args }));
}
```
### tab 补全
补全就是 玩家在Minecraft执行命令时 使用 Tab键 补全
- 补全是一个 `function` 一般以 `tab` 开头 需要补全的命令结尾 通过 `@tab` 注解注册
- 补全注册时默认使用方法名称为补全名称 当前你可以传入 name 参数指定命令名称 例如 `{name: 'test'}`
- 接受三个参数 `sender: any, command: string, args: string[]`
- 分别代表 命令发送者 命令名称 命令参数
_注意: 当补全命令未注册时 补全无效! 且补全和命令必须在同一个Class内!_
```ts
@tab()
tabhello(_sender: any, _command: string, _args: string[]) {
return ['world']
}
```
## 监听事件
事件是指 Minecraft 中发生的各种事情
- 监听事件是一个 `function` 通过 `@listener` 注册
- 由于不同的服务端有不同的逻辑 所以支持通过 `servers` 指定注册的类型 加上 `!` 代表不注册 不指定 `servers` 则注册所有的类型
- 事件名称默认为方法名称
- 所有类型服务端的事件 MiaoScript 都会进行一次映射 方便使用
- 例如 `PlayerJoinEvent` 会映射为 `PlayerJoinEvent, playerjoinevent, playerjoin` 等
- 一般规则就是 类名直接小写 如果遇到子类 则保留 `$`
- 例如 `ClientConnectionEvent.Join` 会映射为 `clientconnectionevent$join`
- 事件的注可以传入 `servertype` 来指定这个事件类型的服务端加载 默认是所有服务端都加载
- 事件监听方法的第一个参数就是本次事件的具体内容 (这里就需要自己去查询对应的JavaDoc了)
```ts
// bukkit nukkit 大部分API神似 可以直接用
@listener({ servers: ['bukkit', 'nukkit'] })
PlayerJoin(event: org.bukkit.event.player.PlayerJoinEvent) {
let plyaer = event.getPlayer();
this.logger.console(`§cBukkit §aPlayerJoinEvent: §b${plyaer.getName()}`)
setTimeout(() => this.sendWelcome(plyaer), 10);
}
@listener({ servers: ['sponge'] })
ClientConnectionEvent$Join(event: org.spongepowered.api.event.network.ClientConnectionEvent.Join) {
this.logger.console(`§cSponge §aClientConnectionEvent.Join: §b${event.getTargetEntity().getName()}`)
setTimeout(() => this.sendWelcome(event.getTargetEntity()), 10);
}
private sendWelcome(player: any) {
this.logger.sender(player, `§a欢迎来到 §bMiaoScript §a的世界!`)
this.logger.sender(player, `§6当前版本: §c${this.Server.getVersion()}`)
}
@listener({ servers: ['bungee'] })
ServerConnected(e: any) {
let event = e as net.md_5.bungee.api.event.ServerConnectedEvent
this.logger.console(`§cBungeeCord §aServerConnectedEvent: §b${event.getPlayer().getDisplayName()}`)
setTimeout(() => this.logger.sender(event.getPlayer(), `§a欢迎来到 §bMiaoScript §a的世界 §6来自 §cBungeeCord §6的问候!`), 10);
}
```
## 配置文件
配置文件 默认读取的是 `MiaoScript根目录/plugins/插件名称/配置名称.配置格式`
例如下面文件 默认处理的是 `plugins/MiaoScript/plugins/HelloWorld/config.yml`
```ts
@config()
private config = {
version: 1.0.0
}
```
## 插件列表
暂无
> 注意: 一楼的列表是老版本的 新版本无法加载!

View File

@@ -1,5 +1,5 @@
{
"version": "0.8.1",
"version": "0.6.0",
"useWorkspaces": true,
"npmClient": "yarn",
"packages": [
@@ -10,7 +10,6 @@
"stream": true
},
"publish": {
"access": "public",
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
}
}

View File

@@ -11,15 +11,14 @@
"watch": "lerna run watch --parallel",
"build": "lerna run build --scope=\"@ccms/!(plugins)\"",
"build:plugins": "lerna run build --scope=\"@ccms/plugins\"",
"publish": "yarn lerna exec \"npm publish --access=public\" --scope=\"@ccms/!(plugins|client|types)\"",
"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"
"lp": "lerna publish"
},
"workspaces": [
"packages/*"
],
"devDependencies": {
"lerna": "^3.21.0"
"lerna": "^3.20.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,7 +0,0 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"baseUrl": "src",
"outDir": "dist"
}
}

View File

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

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/api",
"version": "0.8.1",
"version": "0.6.0",
"description": "MiaoScript api package",
"keywords": [
"miaoscript",
@@ -19,9 +19,8 @@
"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",
"@ccms/container": "^0.6.0",
"@ccms/ployfill": "^0.6.0",
"base64-js": "^1.3.1",
"source-map-builder": "^0.0.7"
},
@@ -29,6 +28,6 @@
"@types/base64-js": "^1.2.5",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.9.2"
"typescript": "^3.8.3"
}
}

View File

@@ -1,6 +1,5 @@
import i18n from '@ccms/i18n'
import { injectable } from "@ccms/container"
import { plugin } from './interfaces'
import { injectable } from "@ccms/container";
export namespace command {
@injectable()
@@ -11,17 +10,16 @@ export namespace command {
* @param name 命令
* @param exec 执行器
*/
on(plugin: plugin.Plugin, name: string, exec: { cmd: Function, tab?: Function }) {
var cmd = this.create(plugin, name)
if (!cmd) { throw Error("") }
on(plugin: any, name: string, exec: { cmd: Function, tab?: Function }) {
var cmd = this.create(plugin, 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)
this.onCommand(plugin, cmd, exec.cmd);
} else {
throw Error(i18n.translate("ms.api.command.register.input.error", { exec: exec.cmd }))
}
if (exec.tab && typeof exec.tab === "function") {
this.onTabComplete(plugin, cmd, exec.tab)
this.onTabComplete(plugin, cmd, exec.tab);
}
}
/**
@@ -29,40 +27,40 @@ export namespace command {
* @param plugin 插件
* @param name 命令
*/
off(plugin: plugin.Plugin, name: string) {
off(plugin: any, name: string) {
console.debug(i18n.translate("ms.api.command.unregister", { plugin: plugin.description.name, name }))
this.remove(plugin, name)
this.remove(plugin, name);
}
protected abstract create(plugin: plugin.Plugin, command: string): any
protected abstract remove(plugin: plugin.Plugin, command: string): void
protected abstract onCommand(plugin: plugin.Plugin, command: any, executor: Function)
protected abstract onTabComplete(plugin: plugin.Plugin, command: any, tabCompleter: Function)
protected setExecutor(plugin: plugin.Plugin, command: any, executor: Function) {
protected abstract create(plugin: any, command: string);
protected abstract remove(plugin: any, command: string);
protected abstract onCommand(plugin: any, command: any, executor: Function);
protected abstract onTabComplete(plugin: any, command: any, tabCompleter: Function);
protected setExecutor(plugin: any, command: any, executor: Function) {
return (sender: any, _: any, command: string, args: string[]) => {
try {
return executor(sender, command, Java.from(args))
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)
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)])
}
return true
return true;
}
}
}
protected setTabCompleter(plugin: plugin.Plugin, command: any, tabCompleter: Function) {
protected setTabCompleter(plugin: any, command: any, tabCompleter: Function) {
return (sender: any, _: any, command: string, args: string[]) => {
try {
var token = args[args.length - 1]
var complete = tabCompleter(sender, command, Java.from(args)) || []
return this.copyPartialMatches(complete, token)
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)])
return []
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)]);
return [];
}
}
}
@@ -72,7 +70,7 @@ export namespace command {
if (typeof e === "string" && e.toLowerCase().startsWith(token.toLowerCase())) {
array.push(e)
}
})
});
return array
}
}

View File

@@ -2,10 +2,10 @@ import i18m from '@ccms/i18n'
import { SourceMapBuilder } from 'source-map-builder'
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 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.', 'net.minecraft.', 'org.bukkit.', 'jdk.nashorn.', 'io.netty.', 'org.spongepowered.'];
enum LogLevel {
ALL,
@@ -19,19 +19,19 @@ enum LogLevel {
}
export class MiaoScriptConsole implements Console {
Console: NodeJS.ConsoleConstructor
Console: NodeJS.ConsoleConstructor;
private static sourceMaps: { [key: string]: SourceMapBuilder } = {}
private static sourceFileMaps: { [key: string]: string } = {}
private _name: string = ''
private _level: LogLevel = LogLevel.INFO
private sourceMaps: { [key: string]: SourceMapBuilder } = {};
private sourceFileMaps: { [key: string]: string } = {};
private _name: string = '';
private _level: LogLevel = LogLevel.INFO;
protected logger: any
protected prefix: string = '§6[§bMiaoScript§6]§r '
protected logger: any;
protected prefix: string = '§6[§bMiaoScript§6]§r ';
constructor(name?: string) {
this.name = name
this.logger = global.logger
this.name = name;
this.logger = global.logger;
if (global.debug) {
this._level = LogLevel.DEBUG
}
@@ -41,36 +41,36 @@ export class MiaoScriptConsole implements Console {
}
get name() {
return this._name
return this._name;
}
set name(name: string) {
if (name) {
this._name = `[${name}] `
this._name = `[${name}] `;
// noinspection JSUnusedGlobalSymbols
this.prefix = `§6[§cMS§6][§b${name}§6]§r `
this.prefix = `§6[§cMS§6][§b${name}§6]§r `;
}
}
log(...args: any[]): void {
this.logger.info(this.name + args.join(' '))
this.logger.info(this.name + args.join(' '));
}
info(...args: any[]) {
this.logger.info(this.name + args.join(' '))
this.logger.info(this.name + args.join(' '));
}
warn(...args: any[]) {
this.logger.warning(this.name + args.join(' '))
this.logger.warning(this.name + args.join(' '));
}
error(...args: any[]) {
this.logger.log(Level.SEVERE, this.name + args.join(' '))
this.logger.log(Level.SEVERE, this.name + args.join(' '));
}
debug(...args: any[]) {
if (global.debug) {
this.logger.info(this.name + '[DEBUG] ' + args.join(' '))
this.logger.info(this.name + '[DEBUG] ' + args.join(' '));
}
}
trace(...args: any[]): void {
if (this._level <= LogLevel.TRACE) {
this.logger.info(this.name + '[TRACE] ' + args.join(' '))
this.logger.info(this.name + '[TRACE] ' + args.join(' '));
}
}
sender(...args) {
@@ -93,31 +93,31 @@ export class MiaoScriptConsole implements Console {
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')
if (this.sourceMaps[fileName] === undefined) {
this.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,')) {
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')) {
// TODO
} else {
let file = Paths.get(Paths.get(fileName, '..', sourceMappingURL).toFile().getCanonicalPath()).toFile()
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()
this.sourceMaps[fileName] = new SourceMapBuilder(JSON.parse(sourceContent))
this.sourceFileMaps[fileName] = Paths.get(fileName, '..', this.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 }
if (this.sourceMaps[fileName]) {
let sourceMapping = this.sourceMaps[fileName].getSource(lineNumber, 25, true, true);
fileName = this.sourceFileMaps[fileName]
if (sourceMapping && lineNumber != sourceMapping.mapping.sourceLine) { lineNumber = sourceMapping.mapping.sourceLine; }
}
}
} catch (error) {
@@ -128,26 +128,21 @@ export class MiaoScriptConsole implements Console {
lineNumber
}
}
stack(ex: Error, color: boolean = true): string[] {
let stack = ex.getStackTrace()
let cache = [(color ? '§c' : '') + ex]
stack(ex: Error): string[] {
let stack = ex.getStackTrace();
let cache = ['§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}`)
}
cache.push(` §e->§c ${fileName} => §4${trace.methodName}:${lineNumber}`)
} else {
let className = trace.className
var fileName = trace.fileName as string
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)
@@ -155,74 +150,70 @@ export class MiaoScriptConsole implements Console {
} else {
for (let prefix in ignoreLogPrefix) {
if (className.startsWith(ignoreLogPrefix[prefix])) {
return
return;
}
}
}
if (color) {
cache.push(` §e->§c ${className}.${trace.methodName}(§4${fileName}:${lineNumber}§c)`)
} else {
cache.push(` -> ${className}.${trace.methodName}(${fileName}:${lineNumber})`)
}
cache.push(` §e->§c ${className}.${trace.methodName}(§4${fileName}:${lineNumber}§c)`);
}
})
return cache
});
return cache;
}
assert(value: any, message?: string, ...optionalParams: any[]): void {
throw new Error("Method not implemented.")
throw new Error("Method not implemented.");
}
clear(): void {
throw new Error("Method not implemented.")
throw new Error("Method not implemented.");
}
count(label?: string): void {
throw new Error("Method not implemented.")
throw new Error("Method not implemented.");
}
countReset(label?: string): void {
throw new Error("Method not implemented.")
throw new Error("Method not implemented.");
}
dir(obj: any, options?: NodeJS.InspectOptions): void {
throw new Error("Method not implemented.")
throw new Error("Method not implemented.");
}
dirxml(...data: any[]): void {
throw new Error("Method not implemented.")
throw new Error("Method not implemented.");
}
group(...label: any[]): void {
throw new Error("Method not implemented.")
throw new Error("Method not implemented.");
}
groupCollapsed(...label: any[]): void {
throw new Error("Method not implemented.")
throw new Error("Method not implemented.");
}
groupEnd(): void {
throw new Error("Method not implemented.")
throw new Error("Method not implemented.");
}
table(tabularData: any, properties?: string[]): void {
throw new Error("Method not implemented.")
throw new Error("Method not implemented.");
}
time(label?: string): void {
throw new Error("Method not implemented.")
throw new Error("Method not implemented.");
}
timeEnd(label?: string): void {
throw new Error("Method not implemented.")
throw new Error("Method not implemented.");
}
timeLog(label?: string, ...data: any[]): void {
throw new Error("Method not implemented.")
throw new Error("Method not implemented.");
}
markTimeline(label?: string): void {
throw new Error("Method not implemented.")
throw new Error("Method not implemented.");
}
profile(label?: string): void {
throw new Error("Method not implemented.")
throw new Error("Method not implemented.");
}
profileEnd(label?: string): void {
throw new Error("Method not implemented.")
throw new Error("Method not implemented.");
}
timeStamp(label?: string): void {
throw new Error("Method not implemented.")
throw new Error("Method not implemented.");
}
timeline(label?: string): void {
throw new Error("Method not implemented.")
throw new Error("Method not implemented.");
}
timelineEnd(label?: string): void {
throw new Error("Method not implemented.")
throw new Error("Method not implemented.");
}
}

View File

@@ -11,7 +11,6 @@ export namespace constants {
Bukkit = 'bukkit',
Sponge = 'sponge',
Nukkit = 'nukkit',
Bungee = 'bungee',
Spring = 'spring'
Bungee = 'bungee'
}
}

View File

@@ -21,9 +21,6 @@ export namespace event {
@injectable()
export abstract class Event {
// export EventPriority to blockly
public EventPriority = EventPriority;
private mapEvent = [];
private listenerMap = [];

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 +1,2 @@
export * from './web'
export * from './amqp'
export * from './plugin'
export * from './server'
export * from './database'

View File

@@ -2,186 +2,29 @@ export namespace plugin {
/**
* MiaoScript Plugin
*/
export const Plugin = Symbol("Plugin")
export const Plugin = Symbol("Plugin");
/**
* MiaoScript Plugin Folder
*/
export const PluginFolder = Symbol("PluginFolder")
export const PluginFolder = Symbol("PluginFolder");
/**
* Runtime Plugin Instance
*/
export const PluginInstance = Symbol("PluginInstance")
export const PluginInstance = Symbol("PluginInstance");
/**
* MiaoScript Plugin Manager Symbol
*/
export const PluginManager = Symbol("PluginManager")
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>
}
export const PluginScanner = Symbol("PluginScanner")
/**
* 插件加载元信息
*/
export interface PluginLoadMetadata {
/**
* 插件加载类型
*/
type: string
/**
* 插件名称
*/
name?: string
/**
* 插件文件
*/
file?: string
/**
* 插件实例
*/
instance?: any
/**
* 插件元信息
*/
metadata?: PluginMetadata
/**
* 插件扫描器
*/
scanner: PluginScanner
/**
* 插件加载器
*/
loader?: PluginLoader
/**
* 是否已加载
*/
loaded?: boolean
[key: string]: any
}
/**
* 插件扫描器
*/
export interface PluginScanner {
/**
* 扫描器类型
*/
type: string
/**
* 扫描插件目录 返回插件加载元信息列表
* @param target 扫描目标
*/
scan(target: any): PluginLoadMetadata[]
/**
* 读取插件 返回插件加载元信息
* @param target
*/
read(target: any): PluginLoadMetadata
/**
* 加载扫描到的目标
* @param target 加载目标
*/
load(target: PluginLoadMetadata): PluginLoadMetadata
}
export const PluginLoader = Symbol("PluginLoader")
/**
* 插件加载器
*/
export interface PluginLoader {
/**
* 加载器类型
*/
type: string
/**
* 加载插件 获取元数据
* @param target 加载目标
* @param result 扫描器加载的结果
*/
require(loadMetadata: PluginLoadMetadata): PluginLoadMetadata
/**
* 构建插件
* @param metadata 插件元信息
*/
build(metadata: PluginMetadata): Plugin
/**
* Load 阶段
* @param plugin 插件
*/
load(plugin: Plugin): void
/**
* Enable 阶段
* @param plugin 插件
*/
enable(plugin: Plugin): void
/**
* Disable 阶段
* @param plugin 插件
*/
disable(plugin: Plugin): void
/**
* Reload 阶段
* @param plugin 插件
*/
reload(plugin: Plugin): void
}
export interface Plugin {
description: PluginMetadata
logger: Console
load(): void
enable(): void
disable(): void
}
export interface BaseMetadata {
/**
* 名称 为空则为对象名称
*/
name?: string
/**
* 支持的服务器列表 为空则代表所有
*/
servers?: string[]
}
export interface PluginMetadata extends BaseMetadata {
/**
* 插件名称
*/
name: string
/**
* 前缀
*/
prefix?: string
/**
* 插件版本
*/
version: string
/**
* 插件版本
*/
author: string | string[]
/**
* 插件源文件 必须指定为 __filename
*/
source: string
/**
* 插件类型 默认为 ioc 执行 MiaoScript 加载逻辑
*/
type?: string
/**
* 插件加载信息
*/
loadMetadata?: PluginLoadMetadata
/**
* 插件本体
*/
target?: any
scan(folder: string): void;
build(): void;
load(...args: any[]): void;
enable(...args: any[]): void;
disable(...args: any[]): void;
reload(...args: any[]): void;
getPlugins(): Map<string, any>;
}
}

View File

@@ -1,143 +1,36 @@
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")
export const ServerType = Symbol("ServerType");
/**
* Runtime Console
*/
export const Console = Symbol("Console")
export const Console = Symbol("Console");
/**
* MiaoScript Server
*/
export const Server = Symbol("Server")
export const Server = Symbol("Server");
/**
* Runtime Server Instance
*/
export const ServerInstance = Symbol("ServerInstance")
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!") }
}
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;
getNettyPipeline(): any;
sendJson(sender: string | any, json: object | string): void;
}
}

View File

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

View File

@@ -58,9 +58,9 @@ export namespace task {
return this;
}
protected run(...args: any[]): void {
protected run(): void {
try {
this.func(...args);
this.func();
} catch (ex) {
console.console('§4插件执行任务时发生错误', ex)
console.ex(ex);
@@ -69,9 +69,8 @@ export namespace task {
/**
* 提交任务
* @param args 任务参数
*/
abstract submit(...args: any[]): Cancelable;
abstract submit(): Cancelable;
}
/**
* 返可取消的对象

View File

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

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/bukkit",
"version": "0.8.1",
"version": "0.6.0",
"description": "MiaoScript bukkit package",
"keywords": [
"miaoscript",
@@ -21,11 +21,11 @@
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.9.2"
"typescript": "^3.8.3"
},
"dependencies": {
"@ccms/api": "^0.8.1",
"@ccms/common": "^0.8.0",
"@ccms/container": "^0.8.0"
"@ccms/api": "^0.6.0",
"@ccms/common": "^0.6.0",
"@ccms/container": "^0.6.0"
}
}

View File

@@ -1,4 +1,4 @@
/// <reference types="@javatypes/spigot-api" />
/// <reference types="@ccms/types/dist/typings/bukkit" />
import { server } from '@ccms/api'
import { Container } from '@ccms/container'

View File

@@ -7,12 +7,13 @@ import chat from './enhance/chat'
let Bukkit = org.bukkit.Bukkit;
@provideSingleton(server.Server)
export class BukkitServer extends server.ReflectServer {
export class BukkitServer implements server.Server {
private pluginsFolder: string;
private pipeline: any;
constructor() {
super();
this.pluginsFolder = Bukkit.getUpdateFolderFile().getParentFile().getCanonicalPath();
this.reflectPipeline()
}
getPlayer(name: string) {
@@ -45,15 +46,9 @@ export class BukkitServer extends server.ReflectServer {
getNativePluginManager() {
return Bukkit.getPluginManager() as any;
}
getDedicatedServer() {
return reflect.on(Bukkit.getServer()).get('console').get()
}
getNettyPipeline() {
return this.pipeline;
}
getRootLogger() {
return this.rootLogger;
}
sendJson(sender: string | any, json: object | string): void {
if (typeof sender === "string") {
sender = this.getPlayer(sender)
@@ -63,4 +58,27 @@ export class BukkitServer extends server.ReflectServer {
this.dispatchConsoleCommand(result)
}
}
private reflectPipeline() {
let consoleServer = reflect.on(Bukkit.getServer()).get('console').get()
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) { 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()
}
}

View File

@@ -23,8 +23,10 @@ export class BukkitTaskManager implements task.TaskManager {
}
export class BukkitTask extends task.Task {
submit(...args: any[]): task.Cancelable {
let run = new BukkitRunnable({ run: () => this.run(...args) })
submit(): task.Cancelable {
let run = new BukkitRunnable({
run: () => this.run()
})
let funcName = `runTask${this.interval ? 'Timer' : 'Later'}${this.isAsync ? 'Asynchronously' : ''}`
if (this.interval) {
return run[funcName](this.plugin, this.laterTime, this.interval)

View File

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

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/bungee",
"version": "0.8.1",
"version": "0.6.0",
"description": "MiaoScript bungee package",
"keywords": [
"miaoscript",
@@ -21,11 +21,11 @@
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.9.2"
"typescript": "^3.8.3"
},
"dependencies": {
"@ccms/api": "^0.8.1",
"@ccms/common": "^0.8.0",
"@ccms/container": "^0.8.0"
"@ccms/api": "^0.6.0",
"@ccms/common": "^0.6.0",
"@ccms/container": "^0.6.0"
}
}

View File

@@ -1,4 +1,4 @@
/// <reference types="@javatypes/bungee-api" />
/// <reference types="@ccms/types/dist/typings/bungee" />
import { server } from '@ccms/api'
import { Container } from '@ccms/container'

View File

@@ -9,7 +9,6 @@ let Bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy();
export class BungeeServer implements server.Server {
private pluginsFolder: string;
private pipeline: any;
private rootLogger: any;
@inject(task.TaskManager)
private task: task.TaskManager
@@ -36,11 +35,6 @@ export class BungeeServer implements server.Server {
}
}
}).later(10).timer(20).submit()
try {
this.rootLogger = Bungee.getLogger()
} catch (error) {
console.error("Can't found rootLogger!")
}
}
getPlayer(name: string) {
@@ -76,9 +70,6 @@ export class BungeeServer implements server.Server {
getNettyPipeline() {
return this.pipeline;
}
getRootLogger() {
return this.rootLogger;
}
sendJson(sender: string | any, json: string): void {
throw new Error("Method not implemented.");
}

View File

@@ -22,8 +22,8 @@ export class BungeeTaskManager implements task.TaskManager {
}
export class BungeeTask extends task.Task {
submit(...args: any[]): task.Cancelable {
let run = new Runnable({ run: () => this.run(...args) })
submit(): task.Cancelable {
let run = new Runnable({ run: () => this.run() })
if (this.isAsync) {
return this.plugin.getProxy().getScheduler().runAsync(this.plugin, run)
}

View File

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

View File

@@ -1,7 +1,7 @@
{
"private": true,
"name": "@ccms/client",
"version": "0.8.0",
"version": "0.6.0",
"description": "MiaoScript client package",
"keywords": [
"miaoscript",
@@ -26,6 +26,6 @@
},
"devDependencies": {
"rimraf": "^3.0.2",
"typescript": "^3.9.2"
"typescript": "^3.8.3"
}
}

View File

@@ -6,9 +6,7 @@ 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)
let client = createConnection('192.168.2.5', 25577, username)
function createConnection(host: string, port: number, username: string) {
let client = createClient({

View File

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

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/common",
"version": "0.8.0",
"version": "0.6.0",
"description": "MiaoScript api package",
"keywords": [
"miaoscript",
@@ -21,11 +21,10 @@
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.9.2"
"typescript": "^3.8.3"
},
"dependencies": {
"@ccms/nashorn": "^0.8.0",
"@javatypes/jdk": "^1.14.0"
"@ccms/nashorn": "^0.6.0"
},
"gitHead": "562e2d00175c9d3a99c8b672aa07e6d92706a027"
}

View File

@@ -23,7 +23,9 @@ export function concat(...args: string[]) {
* @returns {*}
*/
export function file(...opts: any[]): any {
if (!opts[0]) { throw new Error("文件名称不得为 undefined 或者 null !") }
if (!opts[0]) {
console.warn("文件名称不得为 undefined 或者 null !");
}
switch (opts.length) {
case 1:
var f = opts[0];
@@ -141,7 +143,7 @@ export function del(file) {
return;
}
if (file.isDirectory()) {
Files.list(file.toPath()).collect(Collector.toList()).forEach(function (f) {
Files.list(file.toPath()).collect(Collector.toList()).forEach(function(f) {
del(f);
})
}

View File

@@ -27,7 +27,7 @@ function request(config: RequestConfig) {
for (const header in config.headers) {
xhr.setRequestHeader(header, config.headers[header]);
}
xhr.send(typeof config.data === "string" ? config.data : JSON.stringify(config.data));
xhr.send(config.data);
if ((xhr.getResponseHeader("Content-Type") + '').indexOf('application/json') != -1) {
xhr.responseType = "json"
}

View File

@@ -1,204 +1,196 @@
/// <reference types="@javatypes/jdk" />
/**
* 反射工具类
* Created by MiaoWoo on 2017/2/9 0009.
*/
const JavaClass = Java.type('java.lang.Class')
const JavaClass = Java.type('java.lang.Class');
const JavaObject = Java.type('java.lang.Object')
const NoSuchFieldException = Java.type('java.lang.NoSuchFieldException')
const methodCache = []
const NoSuchFieldException = Java.type('java.lang.NoSuchFieldException');
const methodCache = [];
class Reflect {
private obj: java.lang.Object
private class: java.lang.Class<any>
private obj: any;
private class: any
constructor(obj: any) {
// if (obj === undefined || obj === null) { throw Error(`reflect object can't be ${obj}!`) }
if (obj instanceof JavaClass) {
this.obj = null
this.class = obj
this.obj = null;
this.class = obj;
} else {
this.obj = obj
this.obj = obj;
if (obj !== null && obj !== undefined && obj.class) {
this.class = obj.class
this.class = obj.class;
}
}
}
method(name: string, ...args: java.lang.Class<any>[]) {
return declaredMethod(this.class, name, ...args)
method(...args: any[]) {
return declaredMethod(this.class, args[0], types(args.slice(1)));
}
methods() {
return Java.from(declaredMethods(this.class))
return Java.from(declaredMethods(this.class));
}
field(name: string | java.lang.String): Reflect {
field(name): Reflect {
try {
// Try getting a public field
let field = this.class.getField(name)
return on(field.get(this.obj))
let field = this.class.field(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))
return on(accessible(declaredField(this.class, name)).get(this.obj));
}
}
};
fields(declared = false): java.lang.reflect.Field[] {
return Java.from(declared ? this.class.getDeclaredFields() : this.class.getFields())
fields(declared = false) {
return Java.from(declared ? this.class.declaredFields : this.class.fields);
}
values(declared = false) {
return this.fields(declared).reduce((cache, field) => { return cache[field.getName()] = this.field(field.getName()).get() }, {}) as any
let cache = {};
this.fields(declared).forEach(fed => cache[fed.name] = this.field(fed.name).get())
return cache;
}
call(...args: any[]): Reflect {
let params = args.slice(1)
let method = accessible(declaredMethod(this.class, args[0], ...types(params)))
let result = method.invoke(this.get(), params)
return result && on(result)
}
call(...args): Reflect {
let params = args.slice(1);
let method = accessible(declaredMethod(this.class, args[0], types(params)));
let result = method.invoke(this.get(), params);
return result && on(result);
};
get(): any
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)
}
}
get(...args): Reflect | any {
return args.length === 1 ? this.field(args[0]) : this.obj;
};
set(name: any, value: any): Reflect {
accessible(declaredField(this.class, name)).set(this.obj, value)
return this
}
// noinspection JSUnusedGlobalSymbols
set(name, value): Reflect {
accessible(declaredField(this.class, name)).set(this.obj, value);
return this;
};
create(...args): Reflect {
return on(declaredConstructor(this.class, args).newInstance(args))
}
return on(declaredConstructor(this.class, args).newInstance(args));
};
}
/**
* Get an array of types for an array of objects
*/
function types(values: any[], def?: any) {
function types(values, def?) {
if (values === null) {
return []
return [];
}
let result: java.lang.Class<any>[] = []
values.forEach(t => result.push((t || def) ? JavaObject.class : t instanceof JavaClass ? t : t.class))
return result
let result: any[] = [];
values.forEach(t => result.push((t || def) ? JavaObject.class : t instanceof JavaClass ? t : t.class));
return result;
}
function accessible<T extends java.lang.reflect.AccessibleObject>(accessible: T): T {
function accessible(accessible) {
if (accessible === null) {
return null
return null;
}
if (!accessible.isAccessible()) {
accessible.setAccessible(true)
accessible.setAccessible(true);
}
return accessible
return accessible;
}
function declaredConstructor(clazz, param) {
let constructor
let constructor;
try {
constructor = clazz.getDeclaredConstructor(types(param))
constructor = clazz.getDeclaredConstructor(types(param));
} catch (ex) {
try {
constructor = clazz.getDeclaredConstructor(types(param, true))
constructor = clazz.getDeclaredConstructor(types(param, true));
} catch (ex) {
constructor = clazz.getDeclaredConstructors()[0]
constructor = clazz.getDeclaredConstructors()[0];
}
}
return accessible(constructor)
return accessible(constructor);
}
function declaredField(clazz: java.lang.Class<any>, name: string | java.lang.String) {
function declaredField(clazz, name) {
if (!clazz) { throw Error(`target class can't be ${clazz}!`) }
let target = clazz
let field = null
let target = clazz;
let field = null;
// noinspection JSUnresolvedVariable
while (target !== JavaObject.class) {
try {
field = target.getDeclaredField(name)
if (field !== null) { break }
field = target.getDeclaredField(name);
if (field !== null) { break; }
} catch (e) {
if (target === undefined) { break }
target = target.getSuperclass()
if (target === undefined) { break; }
target = target.getSuperclass();
}
}
if (field === null) {
throw new NoSuchFieldException(name + " is not found in " + clazz.getName())
throw new NoSuchFieldException(name + " is not found in " + clazz.name);
}
return field
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(':')
function declaredMethod(clazz, name, clazzs) {
let key = clazz.name + '.' + name + ':' + (clazzs || []).join(':');
if (!methodCache[key]) {
try {
methodCache[key] = clazz.getMethod(name, ...clazzs)
methodCache[key] = clazz.getMethod(name, clazzs);
} catch (ex) {
try {
methodCache[key] = clazz.getDeclaredMethod(name, clazzs as any)
methodCache[key] = clazz.getDeclaredMethod(name, clazzs);
} catch (ex) {
for (const m of Java.from(declaredMethods(clazz))) {
if (m.getName() == name) {
methodCache[key] = m
break
if (m.name == name) {
methodCache[key] = m;
break;
}
}
}
}
}
return methodCache[key]
return methodCache[key];
}
function declaredMethods(clazz: java.lang.Class<any>) {
return clazz.getDeclaredMethods()
function declaredMethods(clazz) {
return clazz.declaredMethods;
}
let classMethodsCache: any[] = []
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))
return target
let target = {};
getJavaObjectMethods(javaObj).forEach(t => mapMethod(target, javaObj, t));
return target;
}
function getJavaObjectMethods(javaObj) {
let className = javaObj.class.name
let className = javaObj.class.name;
if (!classMethodsCache[className]) {
let names: any[] = []
let methods = javaObj.class.methods
let names: any[] = [];
let methods = javaObj.class.methods;
for (let i in methods) {
names.push(methods[i].name)
names.push(methods[i].name);
}
classMethodsCache[className] = names
classMethodsCache[className] = names;
}
return classMethodsCache[className]
return classMethodsCache[className];
}
function mapMethod(target, source, name) {
target[name] = function __SimpleDynamicMethod__(...args) {
if (args.length > 0) {
return source[name](args)
return source[name](args);
} else {
return source[name]()
return source[name]();
}
}
};
}
function on(obj) {
// if (!obj || !obj.class) { throw new TypeError(`参数 ${obj} 不是一个Java对象!`) }
return new Reflect(obj)
return new Reflect(obj);
}
export = {

View File

@@ -1,32 +0,0 @@
const Thread = Java.type('java.lang.Thread')
const ThreadGroup = Java.type("java.lang.ThreadGroup")
const AtomicInteger = Java.type("java.util.concurrent.atomic.AtomicInteger")
const ThreadPoolExecutor = Java.type('java.util.concurrent.ThreadPoolExecutor')
const LinkedBlockingQueue = Java.type("java.util.concurrent.LinkedBlockingQueue")
interface ThreadPoolConfig {
corePoolSize?: number
maximumPoolSize?: number
keepAliveTime?: number
workQueueSize?: number
groupName: string
}
export default {
create(config: ThreadPoolConfig): java.util.concurrent.ThreadPoolExecutor {
let threadCount = new AtomicInteger(0)
config = {
corePoolSize: 10,
maximumPoolSize: 100,
keepAliveTime: 60,
workQueueSize: 500,
...config
}
return new ThreadPoolExecutor(
config.corePoolSize, config.maximumPoolSize, config.keepAliveTime, Packages.java.util.concurrent.TimeUnit.SECONDS,
new LinkedBlockingQueue(config.workQueueSize),
(run: any) => new Thread(new ThreadGroup(config.groupName), run, config.groupName + "-" + threadCount.incrementAndGet()),
new ThreadPoolExecutor.CallerRunsPolicy()
)
}
}

View File

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

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/compile",
"version": "0.8.0",
"version": "0.6.0",
"description": "MiaoScript compile package",
"keywords": [
"miaoscript",
@@ -21,6 +21,6 @@
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.9.2"
"typescript": "^3.8.3"
}
}

View File

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

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/container",
"version": "0.8.0",
"version": "0.6.0",
"description": "MiaoScript container package",
"keywords": [
"miaoscript",
@@ -21,10 +21,9 @@
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.9.2"
"typescript": "^3.8.3"
},
"dependencies": {
"@ccms/nashorn": "^0.8.0",
"inversify": "^5.0.1",
"inversify-binding-decorators": "^4.0.0"
}

View File

@@ -1,7 +0,0 @@
export namespace ioc {
export const Autowired = Symbol('Autowired')
export const Resource = Symbol('Resource')
export const JavaClass = Symbol('JavaClass')
export const JavaInstance = Symbol('JavaInstance')
export const JavaStaticClass = Symbol('JavaStaticClass')
}

View File

@@ -1,9 +1,9 @@
import { interfaces, Container } from "inversify"
import { interfaces, Container } from "inversify";
let _container: Container
let _container: Container;
const ContainerInstance = Symbol.for("@ccms/ioc:Container")
const INJECTION = Symbol.for("INJECTION")
const ContainerInstance = Symbol.for("@ccms/ioc:Container");
const INJECTION = Symbol.for("INJECTION");
function _proxyGetter(
proto: any,
@@ -13,17 +13,17 @@ function _proxyGetter(
) {
function getter(this: object) {
if (doCache && !Reflect.hasMetadata(INJECTION, this, key)) {
Reflect.defineMetadata(INJECTION, resolve(), this, key)
Reflect.defineMetadata(INJECTION, resolve(), this, key);
}
if (Reflect.hasMetadata(INJECTION, this, key)) {
return Reflect.getMetadata(INJECTION, this, key)
return Reflect.getMetadata(INJECTION, this, key);
} else {
return resolve()
return resolve();
}
}
function setter(this: object, newVal: any) {
Reflect.defineMetadata(INJECTION, newVal, this, key)
Reflect.defineMetadata(INJECTION, newVal, this, key);
}
Object.defineProperty(proto, key, {
@@ -31,63 +31,63 @@ function _proxyGetter(
enumerable: true,
get: getter,
set: setter
})
});
}
function initContainer(container: Container) {
Reflect.defineMetadata(ContainerInstance, container, Reflect)
return _container = container
Reflect.defineMetadata(ContainerInstance, container, Reflect);
_container = container;
}
function getContainer(): Container {
return _container || initContainer(new Container())
return _container || Reflect.getMetadata(ContainerInstance, Reflect)
}
function makePropertyInjectDecorator(doCache: boolean) {
return function (serviceIdentifier: interfaces.ServiceIdentifier<any>) {
return function (proto: any, key: string): void {
return function(serviceIdentifier: interfaces.ServiceIdentifier<any>) {
return function(proto: any, key: string): void {
let resolve = () => {
return getContainer().get(serviceIdentifier)
}
_proxyGetter(proto, key, resolve, doCache)
}
}
return getContainer().get(serviceIdentifier);
};
_proxyGetter(proto, key, resolve, doCache);
};
};
}
function makePropertyInjectNamedDecorator(doCache: boolean) {
return function (serviceIdentifier: interfaces.ServiceIdentifier<any>, named: string) {
return function (proto: any, key: string): void {
return function(serviceIdentifier: interfaces.ServiceIdentifier<any>, named: string) {
return function(proto: any, key: string): void {
let resolve = () => {
return getContainer().getNamed(serviceIdentifier, named)
}
_proxyGetter(proto, key, resolve, doCache)
}
}
return getContainer().getNamed(serviceIdentifier, named);
};
_proxyGetter(proto, key, resolve, doCache);
};
};
}
function makePropertyInjectTaggedDecorator(doCache: boolean) {
return function (serviceIdentifier: interfaces.ServiceIdentifier<any>, key: string, value: any) {
return function (proto: any, propertyName: string): void {
return function(serviceIdentifier: interfaces.ServiceIdentifier<any>, key: string, value: any) {
return function(proto: any, propertyName: string): void {
let resolve = () => {
return getContainer().getTagged(serviceIdentifier, key, value)
}
_proxyGetter(proto, propertyName, resolve, doCache)
}
}
return getContainer().getTagged(serviceIdentifier, key, value);
};
_proxyGetter(proto, propertyName, resolve, doCache);
};
};
}
function makePropertyMultiInjectDecorator(doCache: boolean) {
return function (serviceIdentifier: interfaces.ServiceIdentifier<any>) {
return function (proto: any, key: string): void {
return function(serviceIdentifier: interfaces.ServiceIdentifier<any>) {
return function(proto: any, key: string): void {
let resolve = () => {
return getContainer().getAll(serviceIdentifier)
}
_proxyGetter(proto, key, resolve, doCache)
}
}
return getContainer().getAll(serviceIdentifier);
};
_proxyGetter(proto, key, resolve, doCache);
};
};
}
let doCache = true
let doCache = true;
let lazyInject = makePropertyInjectDecorator(doCache)
let lazyInjectNamed = makePropertyInjectNamedDecorator(doCache)
@@ -102,4 +102,4 @@ export {
lazyInjectNamed,
lazyInjectTagged,
lazyMultiInject
}
};

View File

@@ -1,91 +1,25 @@
/// <reference types="@ccms/nashorn" />
import "reflect-metadata";
import { initContainer } from './decorators'
import { interfaces, Container } from 'inversify';
import { fluentProvide } from 'inversify-binding-decorators';
import "reflect-metadata"
import { initContainer, getContainer } from './decorators'
import { interfaces, Container } from 'inversify'
import { fluentProvide } from 'inversify-binding-decorators'
import { ioc } from "./constants"
const provideNamed = (identifier: interfaces.ServiceIdentifier<any>, name: string) => {
return fluentProvide(identifier).whenTargetNamed(name).done();
};
/**
* 注册一个命名对象
* @param identifier 标识符
* @param name 名称
*/
export const provideNamed = (identifier: interfaces.ServiceIdentifier<any>, name: string) => {
return fluentProvide(identifier).whenTargetNamed(name).done()
}
const provideSingleton = (identifier: interfaces.ServiceIdentifier<any>) => {
return fluentProvide(identifier).inSingletonScope().done();
};
/**
* 注册一个单例对象
* @param identifier 标识符
*/
export const provideSingleton = (identifier: interfaces.ServiceIdentifier<any>) => {
return fluentProvide(identifier).inSingletonScope().done()
}
/**
* 注册一个单例对象
* @param identifier 标识符
*/
export const provideSingletonNamed = (identifier: interfaces.ServiceIdentifier<any>, name: string) => {
return fluentProvide(identifier).inSingletonScope().whenTargetNamed(name).done()
}
/**
* 获得一个 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!')
}
}
/**
* 获得一个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!')
}
}
/**
* 自动注入实例由平台实现
* @param className 类名
*/
export const Autowired = (className?: string | any) => {
return function (target: any, propertyKey: string) {
target[propertyKey] = getContainer().getNamed(ioc.Autowired, className || propertyKey)
}
}
/**
* 自动注入资源由平台实现
* @param className 类名
*/
export const Resource = (resourceName?: string | any) => {
return function (target: any, propertyKey: string) {
target[propertyKey] = getContainer().getNamed(ioc.Resource, resourceName || propertyKey)
}
}
export const reduceMetadata = (ctx: interfaces.Context): any => {
return ctx.currentRequest.target.metadata.reduce((result, entry, index) => {
result[entry.key] = entry.value
return result
}, {})
}
export const DefaultContainer = new Container()
initContainer(DefaultContainer)
const DefaultContainer = new Container();
initContainer(DefaultContainer);
export * from 'inversify'
export * from './constants'
export * from './decorators'
export * from 'inversify-binding-decorators'
export {
fluentProvide,
provideNamed,
provideSingleton,
DefaultContainer
};

View File

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

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/core",
"version": "0.8.1",
"version": "0.6.0",
"description": "MiaoScript api package",
"keywords": [
"miaoscript",
@@ -21,11 +21,11 @@
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.9.2"
"typescript": "^3.8.3"
},
"dependencies": {
"@ccms/api": "^0.8.1",
"@ccms/container": "^0.8.0"
"@ccms/api": "^0.6.0",
"@ccms/container": "^0.6.0"
},
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
}

View File

@@ -1,116 +1,103 @@
let containerStartTime = Date.now()
console.i18n("ms.core.ioc.initialize", { scope: global.scope })
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'
console.i18n("ms.core.ioc.completed", { scope: global.scope, time: (Date.now() - containerStartTime) / 1000 })
import http from '@ccms/common/dist/http'
import { EventEmitter } from 'events'
@provideSingleton(MiaoScriptCore)
class MiaoScriptCore {
@inject(server.Console)
private Console: Console
private Console: Console;
@inject(task.TaskManager)
private taskManager: task.TaskManager
private taskManager: task.TaskManager;
@inject(plugin.PluginFolder)
private pluginFolder: string
private pluginFolder: string;
@inject(plugin.PluginManager)
private pluginManager: plugin.PluginManager
private pluginManager: plugin.PluginManager;
enable() {
this.loadServerConsole()
this.loadTaskFunction()
this.loadServerConsole();
this.loadTaskFunction();
global.level = "TRACE"
this.loadPlugins()
return () => this.disable()
this.loadPlugins();
return () => this.disable();
}
loadServerConsole() {
//@ts-ignore
global.setGlobal('console', new this.Console(), { writable: false, configurable: false })
global.setGlobal('console', new this.Console())
}
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 })
global.setGlobal('setTimeout', (func: Function, tick: number, async: boolean = false) => this.taskManager.create(func).later(tick).async(async).submit())
global.setGlobal('setInterval', (func: Function, tick: number, async: boolean = false) => this.taskManager.create(func).timer(tick).async(async).submit())
}
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())
this.pluginManager.scan(this.pluginFolder);
this.pluginManager.build();
this.pluginManager.load();
this.pluginManager.enable();
console.i18n("ms.core.plugin.completed", { time: (new Date().getTime() - loadPluginStartTime) / 1000 })
}
disable() {
console.i18n("ms.core.engine.disable")
this.pluginManager.disable(this.pluginManager.getPlugins())
this.taskManager.disable()
process.emit('exit', 0)
process.exit(0)
this.pluginManager.disable();
this.taskManager.disable();
//@ts-ignore
require.disable()
}
}
function detectServer(): constants.ServerType {
try {
Java.type("org.bukkit.Bukkit")
Java.type("org.bukkit.Bukkit");
return constants.ServerType.Bukkit
} catch (ex) {
}
try {
Java.type("org.spongepowered.api.Sponge")
Java.type("org.spongepowered.api.Sponge");
return constants.ServerType.Sponge
} catch (ex) {
}
try {
Java.type("cn.nukkit.Nukkit")
Java.type("cn.nukkit.Nukkit");
return constants.ServerType.Nukkit
} catch (ex) {
}
try {
Java.type("net.md_5.bungee.api.ProxyServer")
Java.type("net.md_5.bungee.api.ProxyServer");
return constants.ServerType.Bungee
} catch (ex) {
}
try {
Java.type("org.springframework.boot.SpringApplication")
return constants.ServerType.Spring
} catch (ex) {
}
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) }
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)
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 })
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
console.i18n("ms.core.engine.completed", { time: (Date.now() - global.NashornEngineStartTime) / 1000 });
return disable;
} catch (error) {
console.i18n("ms.core.initialize.error", { error })
console.i18n("ms.core.initialize.error", { error });
console.ex(error)
return () => console.i18n('ms.core.engine.disable.abnormal')
}
}
export default initialize()
export default initialize();

View File

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

View File

@@ -1,30 +0,0 @@
{
"name": "@ccms/database",
"version": "0.8.1",
"description": "MiaoScript database 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"
},
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.9.2"
},
"dependencies": {
"@ccms/api": "^0.8.1",
"@ccms/container": "^0.8.0"
}
}

View File

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

View File

@@ -1,90 +0,0 @@
import { Model } from './model'
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
}
/**
* 数据库封装类
*/
export class DataBase {
private dataSource: javax.sql.DataSource
private jdbcTemplate: org.springframework.jdbc.core.JdbcTemplate
constructor(dbConfig: DataBaseConfig) {
if (!dbConfig.url) { throw new Error('DataBase url can\'t be null!') }
this.createDataSource(dbConfig)
this.initialize()
}
private createDataSource(dbConfig: 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()
if (dbConfig.driverClassName) {
config.setDriverClassName(dbConfig.driverClassName)
}
config.setUsername(dbConfig.username)
config.setPassword(dbConfig.password)
config.setJdbcUrl(dbConfig.url)
this.dataSource = new HikariDataSource(config)
} else {
this.dataSource = dbConfig.url
}
}
private initialize() {
this.jdbcTemplate = new JdbcTemplate(this.dataSource)
}
/**
* 执行SQL查询
* @param sql SQL语句
*/
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))
return result
}
/**
* 执行SQL更新
* @param sql SQL语句
*/
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))
return result
}
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

@@ -1,6 +0,0 @@
/// <reference types="@ccms/nashorn" />
/// <reference types="@javatypes/jdk" />
/// <reference types="@javatypes/spring-jdbc" />
export * from './database'
export * from './manager'

View File

@@ -1,53 +0,0 @@
import { plugin, database } from '@ccms/api'
import { provideSingleton, inject, postConstruct } from '@ccms/container'
import { DataBase, DataBaseConfig } from './database'
@provideSingleton(database.DataBaseManager)
export class DataBaseManager {
@inject(plugin.PluginInstance)
private instance: any
private beanFactory: any
private mainDatabase: DataBase
private databases: { [key: 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)
}
}
/**
* 获得主数据库
* Get MainDatabase
*/
getMainDatabase() {
return this.mainDatabase
}
/**
* 创建数据库
* Create A Database Instance
* @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)
}, this.databases)()
}
getDatabase(name: string) {
return this.databases[name]
}
disable() {
Object.values(this.databases).forEach((ds) => ds?.close())
}
}

View File

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

View File

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

View File

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

View File

@@ -1,4 +1,3 @@
ms.i18n.completed: "Internationalization component initialization completed. Current Language: English"
ms.ployfill.initialize: "Initialization Java Nashorn ployfill. Please wait..."
ms.ployfill.completed: "Java Nashorn ployfill loading completed... Cost ({time}s)!"
@@ -39,10 +38,7 @@ ms.plugin.manager.stage.exec.error: "§6Plugin §b{plugin} §6exec §d{executor}
ms.plugin.manager.stage.load: "Loading"
ms.plugin.manager.stage.enable: "Enabling"
ms.plugin.manager.stage.disable: "Disabling"
ms.plugin.manager.build.error: "§6Load Plugin From §b{file} §6failed. §4Error: §c{error}"
ms.plugin.manager.build.update: "Auto Update Plugin {name} ..."
ms.plugin.manager.build.not.extends: "§4Found error plugin §b{source} §4it's not extends interfaces.Plugin, the plugin will be ignore!"
ms.plugin.manager.build.exists: "§4Found duplicate plugin §b{exists} §4and §b{source}§4. the first plugin will be ignore!"
ms.plugin.manager.config.load.error: "[{plugin}] config {name}.{format} load failed. Error: {error}"
ms.plugin.manager.config.save.error: "[{plugin}] config {name}.{format} save failed. Error: {error}"
ms.plugin.manager.config.save.default: "[{plugin}] config {name}.{format} not exists. auto create from default variable..."

View File

@@ -1,4 +1,3 @@
ms.i18n.completed: "国际化组件 初始化完成 当前语言: 简体中文"
ms.ployfill.initialize: "加载 Java Nashorn 补丁. 请稍候..."
ms.ployfill.completed: "Java Nashorn 补丁 加载完成... 耗时 ({time}s)!"
@@ -39,10 +38,7 @@ ms.plugin.manager.stage.exec.error: "§6插件 §b{plugin} §6执行 §d{executo
ms.plugin.manager.stage.load: "加载"
ms.plugin.manager.stage.enable: "启用"
ms.plugin.manager.stage.disable: "关闭"
ms.plugin.manager.build.error: "§6从文件 §b{file} §6加载插件失败 §4错误: §c{error}"
ms.plugin.manager.build.update: "自动更新插件 {name} ..."
ms.plugin.manager.build.not.extends: "§4发现错误的插件 §b{source} §4未继承接口 interfaces.Plugin, 将不会被载入到服务器!"
ms.plugin.manager.build.duplicate: "§4发现已存在插件 §b{exists} §4和 §b{source}§4 存在冲突. 已存在插件将会被替换!"
ms.plugin.manager.config.load.error: "[{plugin}] 配置 {name}.{format} 加载失败. 错误: {error}"
ms.plugin.manager.config.save.error: "[{plugin}] 配置 {name}.{format} 保存失败. 错误: {error}"
ms.plugin.manager.config.save.default: "[{plugin}] 配置 {name}.{format} 不存在. 从默认值自动创建保存..."

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/i18n",
"version": "0.8.0",
"version": "0.6.0",
"description": "MiaoScript i18n package",
"keywords": [
"miaoscript",
@@ -22,10 +22,10 @@
"@types/js-yaml": "^3.12.3",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.9.2"
"typescript": "^3.8.3"
},
"dependencies": {
"@ccms/nashorn": "^0.8.0",
"@ccms/nashorn": "^0.6.0",
"js-yaml": "^3.13.1"
},
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"

View File

@@ -45,7 +45,6 @@ export class Translate {
console.i18n = (name: string, param?: TranslateParam) => {
console.log(this.translate(name, param))
}
console.i18n('ms.i18n.completed')
}
readYamlFile(dir: string, name: string) {

View File

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

12
packages/nashorn/build.sh Executable file
View File

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

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/nashorn",
"version": "0.8.0",
"version": "0.6.0",
"description": "MiaoScript api package",
"keywords": [
"miaoscript",
@@ -22,6 +22,6 @@
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.9.2"
"typescript": "^3.8.3"
}
}

View File

@@ -0,0 +1,200 @@
import * as fs from "fs";
function convertJson2TypeDefiend(infile: string, outDir: string) {
const file = infile.split(".json")[0];
const json = fs.readFileSync(`${inDir}/${file}.json`).toString();
const obj = JSON.parse(json);
const qnas: string[] = obj.qualifiedName.split(".");
let closeBuk = 0;
let temp = `declare namespace ${qnas[0]} {\n`;
closeBuk++;
const nms = qnas.slice(1, qnas.length - 1);
for (const nm of nms) {
temp += `${' '.repeat(closeBuk)}namespace ${nm.replace('function', 'function$')} {\n`;
closeBuk++;
}
let classModifier = formatClassModifier(obj.modifiers)
temp += `${' '.repeat(closeBuk)}// @ts-ignore\n`
temp += `${' '.repeat(closeBuk)}${classModifier}${qnas[qnas.length - 1]}`
let isInterface = classModifier.includes('interface')
let safeInterface = [];
for (const ifs of obj.interfaces) {
if (!ifs.qualifiedName.startsWith('java')) {
safeInterface.push(ifs)
}
}
if (isInterface) {
if (safeInterface.length > 0) {
temp += ' extends '
for (const ifs of safeInterface) {
temp += ifs.qualifiedName;
temp += ', '
}
temp = temp.substr(0, temp.length - 2);
}
} else {
temp += `${(obj.superclass) ? (' extends ' + (obj.superclass.qualifiedName == "<any>" ? "object" : obj.superclass.qualifiedName)) : ''}`;
if (safeInterface.length > 0) {
temp += ' implements '
for (const ifs of safeInterface) {
temp += ifs.qualifiedName;
temp += ', '
}
temp = temp.substr(0, temp.length - 2);
}
}
temp += ' {\n'
closeBuk++;
for (const constructor of obj.constructors) {
temp += `${formatDoc(constructor.docString, closeBuk)}${' '.repeat(closeBuk)}// @ts-ignore\n${' '.repeat(closeBuk)}constructor(${formatParameters(constructor.parameters)})\n`;
}
let members = [];
let methods = '';
for (const method of obj.methods) {
let methodModifier = isInterface ? '' : replaceModifiers(method.modifiers, classModifier.includes('abstract'))
if (!whiteKey.includes(method.name)) {
if (members[method.name] && methodModifier.includes('abstract')) {
continue;
}
members[method.name] = methodModifier;
}
methods += `${formatDoc(method.docString, closeBuk)}${' '.repeat(closeBuk)}// @ts-ignore\n${' '.repeat(closeBuk)}${methodModifier} ${method.name}(${formatParameters(method.parameters)}): ${mappingType(method.returnType.type)};\n`;
}
let fields = '';
for (const field of obj.fields) {
if (members[field.name]) {
continue;
}
fields += `${' '.repeat(closeBuk)}// @ts-ignore\n${' '.repeat(closeBuk)}${isInterface ? '' : replaceModifiers(field.modifiers)} ${field.name}: ${mappingType(field.type ? field.type.type : "any")};\n`;
}
temp += fields + methods;
for (let index = 0; index < closeBuk; index++) {
temp += `${' '.repeat(closeBuk - index - 1)}}\n`;
}
fs.writeFileSync(`${outDir}/${file}.${suffix}`, temp);
return `${file}.${suffix}`;
}
function formatClassModifier(modifiers: string) {
let tempm = modifiers.replace('public', '').replace('static', '').replace('final', '').trim();
if (!modifiers.includes('interface')) { tempm += ' class' }
return tempm.length > 0 ? (tempm + ' ') : '';
}
function formatDoc(doc: string, closeBuk: number) {
let middleDoc = '';
for (const line of doc.split('\n')) {
if (line.trim().length != 0) {
middleDoc += `${' '.repeat(closeBuk)} * ${line.trim()}\n`
}
}
return middleDoc.length > 0 ? `${' '.repeat(closeBuk)}/**\n${middleDoc}${' '.repeat(closeBuk)} */\n` : '';
}
function replaceModifiers(modifiers: string, absClass = false): string {
// modifiers = modifiers.replace(' final', ' readonly');
modifiers = modifiers.split(" final")[0];
modifiers = modifiers.split(" native")[0];
modifiers = modifiers.split(" volatile")[0];
modifiers = modifiers.split(" transient")[0];
modifiers = modifiers.split(" synchronized")[0];
if (!absClass) {
modifiers = modifiers.split(" abstract")[0];
}
return modifiers;
}
function formatParameters(params: any[]) {
let tempParam = '';
for (const p of params) {
tempParam += `${mappingName(p.name)}: ${mappingType(p.type ? p.type.qualifiedName : 'any')}, `
}
return tempParam.substr(0, tempParam.length - 2);
}
const nameMap = [];
nameMap['function'] = 'func'
nameMap['in'] = 'input'
nameMap['var'] = 'variable'
function mappingName(name: string) {
if (whiteKey.includes(name)) { return name }
let outName = nameMap[name] || name || '';
return outName;
}
let whiteKey = ['shift', "map", 'filter', 'values', 'valueOf', 'toString', 'length', 'includes', 'entries', 'keys', 'join', 'fill']
const typeMap = [];
typeMap['int'] = 'number';
typeMap['int[]'] = 'number[]';
typeMap['int[][]'] = 'number[][]';
typeMap['byte'] = 'number';
typeMap['byte[]'] = 'number[]';
typeMap['double'] = 'number';
typeMap['double[]'] = 'number[]';
typeMap['short'] = 'number';
typeMap['short[]'] = 'number[]';
typeMap['float'] = 'number';
typeMap['float[]'] = 'number[]';
typeMap['long'] = 'number';
typeMap['long[]'] = 'number[]';
typeMap['<any>'] = 'any';
typeMap['char'] = 'string';
typeMap['char[]'] = 'string[]';
typeMap['java.lang.String'] = "string";
// typeMap['java.util.Date'] = 'any /*java.util.Date*/'
// typeMap['java.util.List'] = 'any[] /*java.util.List*/'
// typeMap['java.util.Set'] = 'any[] /*java.util.Set*/'
// typeMap['java.util.Collection'] = 'any[] /*java.util.Collection*/'
// typeMap['java.util.Map'] = 'Map<any, any> /*java.util.Map*/'
// Sponge
typeMap['Vectori'] = 'any /*Vector3i*/'
typeMap['Vectord'] = 'any /*Vector3d*/'
typeMap['Vectorf'] = 'any /*Vector3f*/'
typeMap['Vector2i'] = 'any /*Vector2i*/'
typeMap['Vector2d'] = 'any /*Vector2d*/'
typeMap['Vector2f'] = 'any /*Vector2f*/'
typeMap['Vector3i'] = 'any /*Vector3i*/'
typeMap['Vector3d'] = 'any /*Vector3d*/'
typeMap['Vector3f'] = 'any /*Vector3f*/'
typeMap['Type'] = 'any /*Type*/'
typeMap['Gson'] = 'any /*Gson*/'
typeMap['Logger'] = 'any /*Logger*/'
typeMap['MethodVisitor'] = 'any /*MethodVisitor*/'
typeMap['ConfigurationNode'] = 'any /*ConfigurationNode*/'
typeMap['TypeSerializerCollection'] = 'any /*TypeSerializerCollection*/'
typeMap['Quaterniond'] = 'any /*Quaterniond*/'
typeMap['Matrix2d'] = 'any /*Matrix2d*/'
typeMap['Matrix3d'] = 'any /*Matrix3d*/'
typeMap['Matrix4d'] = 'any /*Matrix4d*/'
function mappingType(type: string): string {
let outType = typeMap[type] || type || 'any';
if (outType.indexOf('.') != -1) {
if (outType.startsWith('java.') || outType.startsWith('org.') || outType.startsWith('net.') || outType.startsWith('cn.')) {
} else {
outType = `any /*${outType}*/`
}
}
return outType.replace('function', 'function$');
}
var args = process.argv.splice(2)
const suffix = 'd.ts'
const inDir = `../docs/${args[0]}`
const outDir = "./temp";
const files = fs.readdirSync(inDir);
let index = '';
for (const file of files) {
index += `/// <reference path="./${convertJson2TypeDefiend(file, outDir)}" />\n`;
}
fs.writeFileSync(`${outDir}/index.${suffix}`, index);

View File

@@ -1,85 +1,75 @@
declare global {
const __FILE__: string
const __LINE__: number
const __DIR__: string
const Packages: any
const __FILE__: string;
const __LINE__: number;
const __DIR__: string;
let Packages: any;
function print(...message: any[]): void
function load(script: string | object)
function loadWithNewGlobal(script: string | object)
function exit(code?: number)
function quit(code?: number)
function JavaImporter(...className: string[])
function print(...message: any[]): void;
function load(script: string | object);
function loadWithNewGlobal(script: string | object);
function exit(code?: number);
function quit(code?: number);
function JavaImporter(...className: string[]);
namespace Java {
function type<T = any>(clazz: string): T
function from<T = any>(javaObj: T[]): T[]
function to<T = any>(array: T[], type?: T): T[]
function extend(...parentTypes: any[]): any
function synchronized(func: () => void, lock: any): Function
function asJSONCompatible<T = any>(obj: T): T
function type(clazz: string): any;
function from(javaObj: any): any[];
function to(array: any[]): any;
function extend(...parentTypes: any[]);
//@ts-ignore
// function super(type: any);
}
interface Error {
readonly class?: any
readonly lineNumber?: number
readonly columnNumber?: number
readonly fileName?: string
dumpStack?: Function
printStackTrace?: Function
getStackTrace?: () => any[]
readonly lineNumber?: number;
readonly columnNumber?: number;
readonly fileName?: string;
dumpStack?: Function;
printStackTrace?: Function;
getStackTrace?: () => any[];
}
interface String {
trimLeft(): string
trimRight(): string
trimLeft();
trimRight();
}
interface Object {
setPrototypeOf(obj: object, prototype: object): void
bindProperties(to: object, from: object): void
setPrototypeOf(obj: object, prototype: object);
bindProperties(to: object, from: object);
}
namespace NodeJS {
interface Global {
scope: string
logger: any
debug: boolean
level: string
NashornEngineStartTime: number
setGlobal: (key: string, value: any, config?: PropertyDescriptor & ThisType<any>) => void
noop: () => void
console: Console
}
interface Process {
on(event: string, listener: any): this
emit(event: string, ...message: any): this
scope: string;
logger: any;
debug: boolean;
level: string;
NashornEngineStartTime: number;
setGlobal: (key: string, value: any) => void;
noop: () => void;
console: Console;
}
}
const root: string
const base: Core
const ScriptEngineContextHolder: any
function engineLoad(str: string | { script: string, name: string }): any
var root: string;
var base: Core;
var ScriptEngineContextHolder: any;
function engineLoad(str: string): any;
interface Core {
getClass(name: String): any
getProxyClass(): any
getInstance(): any
read(path: string): string
save(path: string, content: string): void
delete(path: string): void
getClass(name: String): any;
getProxyClass(): any;
getInstance(): any;
read(path: string): string;
save(path: string, content: string): void;
delete(path: string): void;
}
interface Console {
ex(err: Error): void
stack(err: Error, color?: boolean): string[]
sender(...args: any): void
console(...args: any): void
i18n(name: string, ...params: any[]): void
}
interface ProxyConstructor {
newProxy<T extends object>(target: T, handler: ProxyHandler<T>): T
ex(err: Error): void;
stack(err: Error): string[];
sender(...args: any): void;
console(...args: any): void;
i18n(name: string, ...params: any[]);
}
}
export { }
export { };

View File

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

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/nodejs",
"version": "0.8.0",
"version": "0.6.0",
"description": "MiaoScript nodejs package",
"keywords": [
"miaoscript",
@@ -21,10 +21,10 @@
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.9.2"
"typescript": "^3.8.3"
},
"dependencies": {
"@ccms/nashorn": "^0.8.0"
"@ccms/nashorn": "^0.6.0"
},
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
}

View File

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

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/nukkit",
"version": "0.8.1",
"version": "0.6.0",
"description": "MiaoScript nukkit package",
"keywords": [
"miaoscript",
@@ -21,11 +21,11 @@
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.9.2"
"typescript": "^3.8.3"
},
"dependencies": {
"@ccms/api": "^0.8.1",
"@ccms/common": "^0.8.0",
"@ccms/container": "^0.8.0"
"@ccms/api": "^0.6.0",
"@ccms/common": "^0.6.0",
"@ccms/container": "^0.6.0"
}
}

View File

@@ -1,4 +1,4 @@
/// <reference types="@javatypes/nukkit-api" />
/// <reference types="@ccms/types/dist/typings/nukkit" />
import { server } from '@ccms/api'
import { Container } from '@ccms/container'

View File

@@ -45,9 +45,6 @@ export class NukkitServer implements server.Server {
getNettyPipeline() {
throw new Error("Method not implemented.");
}
getRootLogger() {
return Packages.org.apache.logging.log4j.LogManager.getRootLogger()
}
sendJson(sender: string | any, json: object | string): void {
throw new Error("Method not implemented.");
}

View File

@@ -21,8 +21,10 @@ export class NukkitTaskManager implements task.TaskManager {
}
export class NukkitTask extends task.Task {
submit(...args: any[]): task.Cancelable {
let run = new NukkitRunnable({ run: () => this.run(...args) })
submit(): task.Cancelable {
let run = new NukkitRunnable({
run: () => this.run()
})
let funcName = `runTask${this.interval ? 'Timer' : 'Later'}${this.isAsync ? 'Asynchronously' : ''}`
if (this.interval) {
run[funcName](this.plugin, this.laterTime, this.interval);

View File

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

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/ployfill",
"version": "0.8.1",
"version": "0.6.0",
"description": "MiaoScript ployfill package",
"author": "MiaoWoo <admin@yumc.pw>",
"homepage": "https://github.com/circlecloud/ms.git",
@@ -14,14 +14,13 @@
"test": "echo \"Error: run tests from root\" && exit 1"
},
"dependencies": {
"@ccms/i18n": "^0.8.0",
"@ccms/nashorn": "^0.8.0",
"@ccms/nodejs": "^0.8.0",
"core-js": "^3.6.5"
"@ccms/i18n": "^0.6.0",
"@ccms/nashorn": "^0.6.0",
"core-js": "^3.6.4"
},
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.9.2"
"typescript": "^3.8.3"
}
}

View File

@@ -1,15 +1,12 @@
/// <reference types="@ccms/nashorn" />
import '@ccms/nodejs'
import i18n from '@ccms/i18n'
let ployfillStartTime = new Date().getTime()
i18n.initialize()
console.i18n("ms.ployfill.initialize")
require('./es5-ext')
require('./node-shim')
require('core-js')
//@ts-ignore
process.on('exit', () => require.disable())
let ployfillStartTime = new Date().getTime();
i18n.initialize();
console.i18n("ms.ployfill.initialize");
require('./es5-ext');
require('core-js');
global.setGlobal('Proxy', require('./proxy').Proxy)
global.setGlobal('XMLHttpRequest', require('./xml-http-request').XMLHttpRequest)
global.setGlobal('Blob', require('blob-polyfill').Blob)
console.i18n("ms.ployfill.completed", { time: (new Date().getTime() - ployfillStartTime) / 1000 })
console.i18n("ms.ployfill.completed", { time: (new Date().getTime() - ployfillStartTime) / 1000 });

View File

@@ -1,36 +0,0 @@
import { EventEmitter } from 'events'
const Thread = Java.type('java.lang.Thread')
const ThreadGroup = Java.type("java.lang.ThreadGroup")
const AtomicInteger = Java.type("java.util.concurrent.atomic.AtomicInteger")
const ThreadPoolExecutor = Java.type('java.util.concurrent.ThreadPoolExecutor')
const LinkedBlockingQueue = Java.type("java.util.concurrent.LinkedBlockingQueue")
const threadCount = new AtomicInteger(0)
const threadGroup = new ThreadGroup("@ccms/ployfill-micro-task")
const microTaskPool = new ThreadPoolExecutor(
10, 100, 60, Packages.java.util.concurrent.TimeUnit.SECONDS,
new LinkedBlockingQueue(500),
(run: any) => new Thread(threadGroup, run, "@ccms/micro-task-" + threadCount.incrementAndGet()),
new ThreadPoolExecutor.CallerRunsPolicy()
)
class Process extends EventEmitter {
env = {
__noSuchProperty__: (prop) => {
return Packages.java.lang.System.getenv(prop)
}
}
platform = Packages.java.lang.System.getProperty("os.name")
nextTick(func: Function) {
microTaskPool.execute(func)
}
queueMicrotask(func: Function) {
microTaskPool.execute(func)
}
exit() {
microTaskPool.shutdown();
}
}
global.setGlobal('process', new Process(), {})
global.setGlobal('queueMicrotask', (func: any) => microTaskPool.execute(func), {})

View File

@@ -82,14 +82,12 @@ export class XMLHttpRequest {
private _url: string;
private _async: boolean;
private _mimeType: string;
private _requestHeaders: HttpHeader = {};
private _status: number = 0;
private _statusText: string = null;
private _response: any;
private _responseText: any;
private _responseURL: string;
private _responseHeaders: HttpHeader = {};
private _responseHeaders: HttpHeader;
private _connection = null;
@@ -116,10 +114,10 @@ export class XMLHttpRequest {
return this._statusText;
}
get response() {
return this._response || this.get();
return this._response ? JSON.parse(this._response) : this._response;
}
get responseText() {
return this._responseText;
return this._response;
}
get responseXML() {
return this._response;
@@ -128,17 +126,17 @@ export class XMLHttpRequest {
return this._responseURL;
}
public onload: () => void;
public onerror: (ex: Error) => void;
public onabort: () => void;
public onprogress: () => void;
public ontimeout: (ex: Error) => void;
public onloadend: () => void;
public onloadstart: () => void;
public onreadystatechange: () => void;
onload() { }
onerror(ex: Error) { }
onabort() { }
onprogress() { }
ontimeout(ex: Error) { }
onloadend() { }
onloadstart() { }
onreadystatechange() { }
setRequestHeader(key: string, val: string) {
this._requestHeaders[key] = val;
this._connection.setRequestProperty(key, val);
}
getResponseHeader(key: string): string {
return this._responseHeaders[key];
@@ -153,8 +151,6 @@ export class XMLHttpRequest {
this._mimeType = mimeType;
}
open(method: RequestMethod, url: string, async: boolean = true, user?: string, password?: string) {
if (this._readyState !== ReadyState.UNSENT) { throw new Error(`Error Status ${this._readyState}!`) }
this._method = method;
this._url = url;
this._async = async;
@@ -173,39 +169,33 @@ export class XMLHttpRequest {
this.setReadyState(ReadyState.OPENED);
}
send(body?: string | object): Future<string> {
for (const header in this._requestHeaders) {
this._connection.setRequestProperty(header, this._requestHeaders[header]);
}
if (this._readyState !== ReadyState.OPENED) { throw new Error(`Error Status ${this._readyState}!`) }
let future = executor.submit(new Callable({ call: () => this._send(body) }));
if (!this._async) { future.get() }
return future;
}
get() {
if (this._response === undefined) {
switch (this._responseType) {
case "json":
return this._response = JSON.parse(this._responseText);
case "text":
return this._response = this._responseText;
default:
throw Error(`Unsupport ResponseType: ${this._responseType} !`)
}
switch (this._responseType) {
case "json":
return this.response;
case "text":
return this.responseText;
default:
throw Error(`Unsupport ResponseType: ${this._responseType} !`)
}
return this._response;
}
abort() {
this._connection.disconnect();
this.onabort && this.onabort();
this.onabort();
}
private _send(body?: string | object) {
try {
this._connection.connect();
this.onloadstart && this.onloadstart();
this.onloadstart();
if (body) {
let bodyType = Object.prototype.toString.call(body);
if (typeof body !== "string") { throw new Error(`body(${bodyType}) must be string!`) }
if (bodyType !== '[object String]') { throw new Error(`body(${bodyType}) must be string!`) }
var out = this._connection.getOutputStream();
out.write(new JavaString(body).getBytes(UTF_8));
out.flush();
@@ -214,15 +204,15 @@ export class XMLHttpRequest {
this.setReadyState(ReadyState.LOADING);
this._status = this._connection.getResponseCode();
this._statusText = this._connection.getResponseMessage();
this.setResponseHeaders(this._connection.getHeaderFields());
if (this._status >= 0 && this._status < 300) {
this._responseText = this.readOutput(this._connection.getInputStream());
this._response = this.readOutput(this._connection.getInputStream());
} else if (this._status >= 300 && this._status < 400) {
this._responseURL = this.getResponseHeader('Location');
} else {
this._responseText = this.readOutput(this._connection.getErrorStream());
this._response = this.readOutput(this._connection.getErrorStream());
}
this.setResponseHeaders(this._connection.getHeaderFields());
this.onloadend && this.onloadend();
this.onloadend();
} catch (ex) {
if (ex instanceof SocketTimeoutException && this.ontimeout) {
return this.ontimeout(ex)
@@ -237,14 +227,15 @@ export class XMLHttpRequest {
}
private setResponseHeaders(header: any) {
header.forEach((key: string | number, value: string | any[]) => {
this._responseHeaders = {};
header.forEach((key, value) => {
this._responseHeaders[key] = value[value.length - 1]
});
}
private setReadyState(state: ReadyState) {
this._readyState = state;
this.onreadystatechange && this.onreadystatechange();
this.onreadystatechange();
}
private readOutput(input: any) {

View File

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

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/plugin",
"version": "0.8.1",
"version": "0.6.0",
"description": "MiaoScript api package",
"keywords": [
"miaoscript",
@@ -22,13 +22,13 @@
"@types/js-yaml": "^3.12.3",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.9.2"
"typescript": "^3.8.3"
},
"dependencies": {
"@ccms/api": "^0.8.1",
"@ccms/common": "^0.8.0",
"@ccms/container": "^0.8.0",
"@ccms/i18n": "^0.8.0",
"@ccms/api": "^0.6.0",
"@ccms/common": "^0.6.0",
"@ccms/container": "^0.6.0",
"@ccms/i18n": "^0.6.0",
"js-yaml": "^3.13.1"
}
}

View File

@@ -10,7 +10,7 @@ export class YamlPluginConfig implements PluginConfigLoader {
return yaml.safeLoad(content);
}
dump(variable: any): string {
return yaml.safeDump(variable, { skipInvalid: true });
return yaml.safeDump(variable);
}
}

View File

@@ -1,13 +1,12 @@
export const METADATA_KEY = {
plugin: Symbol.for("@ccms/plugin:plugin"),
souece: Symbol.for("@ccms/plugin:souece"),
cmd: Symbol.for("@ccms/plugin:cmd"),
tab: Symbol.for("@ccms/plugin:tab"),
listener: Symbol.for("@ccms/plugin:listener"),
config: Symbol.for("@ccms/plugin:config"),
plugin: "@ccms/plugin:plugin",
cmd: "@ccms/plugin:cmd",
tab: "@ccms/plugin:tab",
listener: "@ccms/plugin:listener",
config: "@ccms/plugin:config",
stage: {
load: Symbol.for("@ccms/plugin:stage:load"),
enable: Symbol.for("@ccms/plugin:stage:enable"),
disable: Symbol.for("@ccms/plugin:stage:disable")
load: "@ccms/plugin:stage:load",
enable: "@ccms/plugin:stage:enable",
disable: "@ccms/plugin:stage:disable"
}
};

View File

@@ -1,26 +1,21 @@
import { plugin as pluginApi } from "@ccms/api"
import { injectable, decorate } from "@ccms/container"
import { injectable, decorate } from "@ccms/container";
import { interfaces } from './interfaces'
import { METADATA_KEY } from './constants'
import { getPluginMetadatas, getPluginCommandMetadata, getPluginListenerMetadata, getPluginTabCompleterMetadata, getPluginConfigMetadata, getPluginStageMetadata, getPluginSources } from './utils'
import { getPluginMetadatas, getPluginCommandMetadata, getPluginListenerMetadata, getPluginTabCompleterMetadata, getPluginConfigMetadata, getPluginStageMetadata } from './utils'
/**
* MiaoScript plugin
* @param metadata PluginMetadata
*/
export function plugin(metadata: pluginApi.PluginMetadata) {
export function plugin(metadata: interfaces.PluginMetadata) {
return function (target: any) {
metadata.target = target
metadata.type = "ioc"
decorate(injectable(), target)
Reflect.defineMetadata(METADATA_KEY.plugin, metadata, target)
const previousMetadata: Map<string, pluginApi.PluginMetadata> = getPluginMetadatas()
previousMetadata.set(metadata.name, metadata)
Reflect.defineMetadata(METADATA_KEY.plugin, previousMetadata, Reflect)
const previousSources: Map<string, pluginApi.PluginMetadata> = getPluginSources()
previousSources.set(metadata.source.toString(), metadata)
Reflect.defineMetadata(METADATA_KEY.souece, previousSources, Reflect)
}
metadata.target = target;
decorate(injectable(), target);
Reflect.defineMetadata(METADATA_KEY.plugin, metadata, target);
const previousMetadata: Map<string, interfaces.PluginMetadata> = getPluginMetadatas();
previousMetadata.set(metadata.name, metadata);
Reflect.defineMetadata(METADATA_KEY.plugin, previousMetadata, Reflect);
};
}
/**
@@ -29,13 +24,13 @@ export function plugin(metadata: pluginApi.PluginMetadata) {
*/
export function cmd(metadata: interfaces.CommandMetadata = {}) {
return function (target: any, key: string, value: any) {
metadata.name = metadata.name || key
metadata.executor = key
metadata.name = metadata.name || key;
metadata.executor = key;
metadata.paramtypes = Reflect.getMetadata("design:paramtypes", target, key)
const previousMetadata: Map<string, interfaces.CommandMetadata> = getPluginCommandMetadata(target)
previousMetadata.set(metadata.name, metadata)
Reflect.defineMetadata(METADATA_KEY.cmd, previousMetadata, target.constructor)
}
previousMetadata.set(metadata.name, metadata);
Reflect.defineMetadata(METADATA_KEY.cmd, previousMetadata, target.constructor);
};
}
/**
@@ -44,14 +39,14 @@ export function cmd(metadata: interfaces.CommandMetadata = {}) {
*/
export function tab(metadata: interfaces.CommandMetadata = {}) {
return function (target: any, key: string, value: any) {
metadata.name = metadata.name || (key.startsWith('tab') ? key.split('tab', 2)[1] : key)
if (!metadata.name) { return }
metadata.executor = key
metadata.name = metadata.name || (key.startsWith('tab') ? key.split('tab', 2)[1] : key);
if (!metadata.name) { return; }
metadata.executor = key;
metadata.paramtypes = Reflect.getMetadata("design:paramtypes", target, key)
const previousMetadata: Map<string, interfaces.CommandMetadata> = getPluginTabCompleterMetadata(target)
previousMetadata.set(metadata.name, metadata)
Reflect.defineMetadata(METADATA_KEY.tab, previousMetadata, target.constructor)
}
Reflect.defineMetadata(METADATA_KEY.tab, previousMetadata, target.constructor);
};
}
/**
@@ -60,32 +55,30 @@ export function tab(metadata: interfaces.CommandMetadata = {}) {
*/
export function listener(metadata: interfaces.ListenerMetadata = {}) {
return function (target: any, key: string, value: any) {
metadata.name = metadata.name || key
metadata.executor = key
metadata.name = metadata.name || key;
metadata.executor = key;
const previousMetadata: interfaces.ListenerMetadata[] = getPluginListenerMetadata(target)
Reflect.defineMetadata(METADATA_KEY.listener, [metadata, ...previousMetadata], target.constructor)
}
Reflect.defineMetadata(METADATA_KEY.listener, [metadata, ...previousMetadata], target.constructor);
};
}
export function config(metadata: interfaces.ConfigMetadata = {}) {
export function config(metadata: interfaces.ConfigMetadata = { version: 1, format: 'yml' }) {
return function (target: any, key: string) {
metadata.name = metadata.name || key
metadata.variable = key
metadata.version = metadata.version ?? 1
metadata.format = metadata.format ?? 'yml'
metadata.name = metadata.name || key;
metadata.variable = key;
const previousMetadata: Map<string, interfaces.ConfigMetadata> = getPluginConfigMetadata(target)
previousMetadata.set(metadata.name, metadata)
Reflect.defineMetadata(METADATA_KEY.config, previousMetadata, target.constructor)
previousMetadata.set(metadata.name, metadata);
Reflect.defineMetadata(METADATA_KEY.config, previousMetadata, target.constructor);
}
}
function stage(metadata: interfaces.ExecMetadata = {}, stage: string) {
return function (target: any, key: string, value: any) {
metadata.name = metadata.name || key
metadata.executor = key
metadata.name = metadata.name || key;
metadata.executor = key;
const previousMetadata: interfaces.ExecMetadata[] = getPluginStageMetadata(target, stage)
Reflect.defineMetadata(METADATA_KEY.stage[stage], [metadata, ...previousMetadata], target.constructor)
}
Reflect.defineMetadata(METADATA_KEY.stage[stage], [metadata, ...previousMetadata], target.constructor);
};
}
export function load(metadata: interfaces.ExecMetadata = {}) {

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