Compare commits

..

151 Commits

Author SHA1 Message Date
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
9fa3ed704a feat: move type def to other package 2019-11-07 15:02:05 +08:00
a76858d626 feat: add illegal plugin check
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-11-05 17:03:49 +08:00
55a6b33110 feat: support async task
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-11-05 17:02:58 +08:00
b87b94aade feat: update plugin register
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-11-04 20:28:52 +08:00
4110ed2c20 feat: update config and add XHR
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-11-04 20:26:22 +08:00
3cbc101eff fix: command remove error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-11-04 20:21:31 +08:00
221b821085 feat: add xhr
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-11-04 20:20:08 +08:00
7331cfaa55 refactor: update http use XHR
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-11-04 20:19:50 +08:00
40d020ef67 feat: add server interface
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-11-04 20:18:30 +08:00
eea2a225e8 feat: complate websocket plugin 2019-10-30 20:45:59 +08:00
48f7f0fdbb feat: update ignore file
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-10-29 15:38:55 +08:00
99ed76f9bb style: format file
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-27 18:40:35 +08:00
7f21fa67ee feat: share decorators container
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-27 18:39:40 +08:00
8584709828 feat: add XMLHttpRequest
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-27 18:39:03 +08:00
d1f58e7482 feat: supoort mod server scan event
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-27 09:49:45 +08:00
1bd35aef6d fix: type instance error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-25 10:10:35 +08:00
fdf1088564 fix: not exist type mapping
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-25 10:10:22 +08:00
7bb4d1f6a3 feat: add sponge typings
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-25 09:55:00 +08:00
b8c3d0d19d feat: add type extend and interface
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-24 17:20:18 +08:00
a616a07553 feat: update type defiend
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-24 15:02:03 +08:00
781524f83e v0.1.1 2019-09-24 10:15:06 +08:00
c7a812c003 feat: split test plugin
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-24 10:12:57 +08:00
325f2c8cf9 feat: modify import to reference type
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-24 10:12:40 +08:00
562e2d0017 v0.1.0 2019-09-23 00:41:04 +08:00
b7871e8d33 feat: update registry in every package
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-23 00:39:13 +08:00
060cffd8e7 feat: add cli sh and add hosted url in package.json
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-23 00:34:38 +08:00
4b1fb07cc9 feat: update deps
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-23 00:19:43 +08:00
0931d69188 feat: add example plugins
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-22 23:31:52 +08:00
7d33368ebd feat: add hello world plugin
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-22 18:02:59 +08:00
c95fc5fcff doc: add jsdoc
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-22 18:02:28 +08:00
a7479f60c8 fix: bukkit task error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-22 18:01:50 +08:00
ac75356778 feat: add start time
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-22 18:01:35 +08:00
7f32382dbc feat: modify sponge event mapping handle
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-22 18:01:13 +08:00
b3c2def36d feat: add remove plugin on disable
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-22 18:00:18 +08:00
1ea93dfb9f feat: add build:plugins
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-22 17:59:25 +08:00
e5ffa70ed9 feat: add readme and update ts config
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-21 15:06:17 +08:00
2a60b36e23 feat: support multi stage load
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-21 15:05:37 +08:00
c4c2c0ab0f feat: complate command event and task
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-21 15:04:47 +08:00
bf5628a646 feat: add task and optimize command
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-21 15:04:25 +08:00
13e9f0a5af feat: update command and complate task
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-21 14:58:00 +08:00
cdd5f2d250 fix: command registry error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-20 09:09:29 +08:00
dfd7182008 feat: add build script
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-19 19:00:35 +08:00
533859808f feat: complate event and command module
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-19 18:59:32 +08:00
15cea1dfc8 feat: optimize api
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-19 18:59:00 +08:00
dfa43d58f0 feat: complete event module fix tab completer 2019-09-19 18:58:01 +08:00
2bf239d8ea feat: add bukkit class type
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-12 17:54:17 +08:00
cbe87cc378 feat: add plugins packages and add Test Plugin
Signed-off-by: MiaoWoo <admin@yumc.pw>
2019-09-10 17:22:56 +08:00
6829 changed files with 381942 additions and 26756 deletions

View File

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

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

@@ -1,4 +1,3 @@
src
test
typings
bundled
@@ -21,5 +20,3 @@ wallaby.js
.vscode
.theia
type_definitions
tsconfig.tsbuildinfo
*.tsbuildinfo

View File

@@ -7,6 +7,7 @@
### Project Path
```txt
└─packages
└─packages
├─api 全平台兼容的接口
├─core 核心代码 用于引导加载
@@ -19,6 +20,7 @@
├─bukkit BukkitAPI内部实现
├─sponge SpongeAPI内部实现
├─nukkit NukkitAPI内部实现
├─ployfill JS环境的相关环境补全
├─plugin 插件管理器
├─websocket Netty的WebSocket注入
├─type Java的类型定义

View File

@@ -1,11 +1,416 @@
- 构建状态 [![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)
- 为了方便阅读 我对帖子进行了分页 请点击目录阅读!
### 腐竹版本(开发中)
### 更新日志
- 先上几张图
- 2019-09-25
- 完善 `Sponge` 类型自动补全
- 2019-09-24
- 完善 `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
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);
}
```
## 插件列表
暂无
> 注意: 一楼的列表是老版本的 新版本无法加载!

View File

@@ -1,5 +1,5 @@
{
"version": "0.23.0",
"version": "0.3.1",
"useWorkspaces": true,
"npmClient": "yarn",
"packages": [
@@ -8,9 +8,9 @@
"command": {
"run": {
"stream": true
},
"publish": {
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
}
},
"publishConfig": {
"access": "public"
}
}

View File

@@ -8,18 +8,16 @@
"scripts": {
"bs": "lerna bootstrap",
"clean": "lerna run clean",
"watch": "lerna run watch --parallel",
"build": "lerna run build",
"watch": "lerna run watch --parallel --scope=\"@ms/!(manager)\"",
"build": "lerna run build --scope=\"@ms/!(plugins|manager)\"",
"build:plugins": "lerna run build --scope=\"@ms/plugins\"",
"ug": "yarn upgrade-interactive --latest",
"np": "./script/push.sh",
"lsp": "npm login --registry=https://registry.npmjs.org --scope=@ccms",
"lp": "lerna publish --registry https://registry.npmjs.org",
"lpb": "lerna publish --registry https://registry.npmjs.org --canary --preid beta --pre-dist-tag beta"
"lp": "lerna publish"
},
"workspaces": [
"packages/*"
],
"devDependencies": {
"lerna": "^4.0.0"
"lerna": "^3.20.2"
}
}
}

View File

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

View File

@@ -1,35 +0,0 @@
{
"name": "@ccms/amqp",
"version": "0.23.0",
"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.23.0",
"@ccms/common": "^0.23.0",
"@ccms/container": "^0.23.0"
},
"devDependencies": {
"@ccms/nashorn": "^0.23.0",
"@javatypes/amqp-client": "^0.0.3",
"@javatypes/spring-amqp": "^0.0.3",
"@javatypes/spring-rabbit": "^0.0.3",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^4.6.3"
}
}

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
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: any) {
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: any) {
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, org.springframework.amqp.core.Binding.DestinationType.QUEUE, exchange, routerKey, argument)
this.amqpAdmin.declareBinding(binding)
return this
}
declareQueueAndBindExchange(queue: string, exchange: string, routerKey: string) {
return this.declareQueue(queue).declareExchange(exchange).declareBinding(queue, exchange, routerKey)
}
createContainer<T>(queue: string, listener: MessageHandler<T>, acknowledgeMode = AcknowledgeMode.AUTO) {
let connection = this.amqpAdmin.getRabbitTemplate().getConnectionFactory()
return new MessageListenerContainerAdapter({
connectionFactory: connection,
queueNames: [queue],
messageListener: new SimpleMessageHandler(listener),
acknowledgeMode: acknowledgeMode
}).getHandler()
}
send()
send() {
}
getTemplate() {
return this.amqpAdmin.getRabbitTemplate()
}
close() {
this.getTemplate().stop()
}
}
export class SimpleMessageHandler extends ChannelAwareMessageListenerAdapter {
constructor(private handler: MessageHandler<any>) {
super()
}
onMessage(content: any, message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel) {
return this.handler(content, message, channel)
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/api",
"version": "0.23.0",
"name": "@ms/api",
"version": "0.3.1",
"description": "MiaoScript api package",
"keywords": [
"miaoscript",
@@ -12,6 +12,9 @@
"homepage": "https://github.com/circlecloud/ms.git",
"license": "ISC",
"main": "dist/index.js",
"publishConfig": {
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
},
"scripts": {
"clean": "rimraf dist",
"watch": "tsc --watch",
@@ -19,16 +22,13 @@
"test": "echo \"Error: run tests from root\" && exit 1"
},
"dependencies": {
"@ccms/common": "^0.23.0",
"@ccms/container": "^0.23.0",
"@ccms/polyfill": "^0.23.0",
"base64-js": "^1.5.1",
"@ms/container": "^0.3.1",
"@ms/ployfill": "^0.3.1",
"source-map-builder": "^0.0.7"
},
"devDependencies": {
"@types/base64-js": "^1.3.0",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^4.6.3"
"typescript": "^3.8.3"
}
}

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,4 +1,4 @@
import { injectable } from "@ccms/container"
import { injectable } from "@ms/container";
export namespace channel {
/**
@@ -10,41 +10,33 @@ export namespace channel {
@injectable()
export abstract class Channel {
private listenerMap = [];
/**
* 注册通道
* @param plugin 插件
* @param channel 通道
* @param exec 执行器
*/
listen(plugin: any, channel: string, exec: ChannelListener) {
if (!plugin || !plugin.description || !plugin.description.name) throw new TypeError('Plugin can\'t be undefiend!')
let name = plugin.description.name
if (!plugin || !plugin.description || !plugin.description.name) throw new TypeError('Plugin can\'t be undefiend!');
let name = plugin.description.name;
let listener = this.register(channel, exec)
if (!this.listenerMap[name]) this.listenerMap[name] = []
if (!this.listenerMap[name]) this.listenerMap[name] = [];
let offExec = () => {
this.unregister(channel, listener)
console.debug(`[${name}] unregister channel ${channel}`)
}
this.unregister(channel, listener);
console.debug(`[${name}] unregister channel ${channel}`);
};
var off = {
channel,
listener,
off: offExec
}
this.listenerMap[name].push(off)
console.debug(`[${name}] register channel ${channel} => ${exec.name || '[anonymous]'}`)
return off
};
this.listenerMap[name].push(off);
console.debug(`[${name}] register channel ${channel} => ${exec.name || '[anonymous]'}`);
return off;
}
/**
* 关闭插件注册的通道
* @param plugin 插件
*/
disable(plugin: any) {
var channelCache = this.listenerMap[plugin.description.name]
var channelCache = this.listenerMap[plugin.description.name];
if (channelCache) {
channelCache.forEach(t => t.off())
delete this.listenerMap[plugin.description.name]
channelCache.forEach(t => t.off());
delete this.listenerMap[plugin.description.name];
}
}
/**
* Send Channel Message
* @param player recover target

View File

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

View File

@@ -1,135 +1,68 @@
import i18n from '@ccms/i18n'
import { injectable } from "@ccms/container"
import { plugin } from './plugin'
import i18n from '@ms/i18n'
import { injectable } from "@ms/container";
export namespace command {
@injectable()
export abstract class Command {
/**
* 注册插件命令
* @param plugin 插件
* @param name 命令
* @param exec 执行器
*/
on(plugin: plugin.Plugin, name: string, exec: { cmd: Function, tab?: Function }) {
var cmd = this.create(plugin, name)
if (!cmd) { throw Error(`Plugin ${plugin.description.name} can't create Command ${name}!`) }
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);
}
}
public tabComplete(sender: any, input: string, index?: number): string[] {
throw new Error("Method not implemented.")
off(plugin: any, name: string) {
console.debug(i18n.translate("ms.api.command.unregister", { plugin: plugin.description.name, name }))
this.remove(plugin, name);
}
/**
* 取消命令注册
* @param plugin 插件
* @param name 命令
* Create Server Command Object
*/
off(plugin: plugin.Plugin, name: string) {
console.debug(i18n.translate("ms.api.command.unregister", { plugin: plugin.description.name, name }))
this.remove(plugin, name)
protected abstract create(plugin: any, command: string);
protected abstract remove(plugin: any, command: string);
protected abstract onCommand(plugin: any, command: any, executor: Function);
protected abstract onTabComplete(plugin: any, command: any, tabCompleter: Function);
protected setExecutor(plugin: any, command: any, executor: Function) {
return (sender: any, _: any, command: string, args: string[]) => {
try {
return executor(sender, command, Java.from(args));
} catch (ex) {
console.i18n("ms.api.command.execute.error", { sender: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex })
console.ex(ex);
console.sender(sender, [i18n.translate("ms.api.command.execute.error", { sender: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex }), ...console.stack(ex)])
return true;
}
}
}
protected 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 setTabCompleter(plugin: any, command: any, tabCompleter: Function) {
return (sender: any, _: any, command: string, args: string[]) => {
try {
let time = Date.now()
let result = executor(sender, command, Java.from(args))
let cost = Date.now() - time
if (cost > global.ScriptSlowExecuteTime) {
console.i18n("ms.api.command.execute.slow", {
player: sender.name,
plugin: plugin.description.name,
command,
args: Java.from(args).join(' '),
cost
})
}
return result
} catch (ex: any) {
console.i18n("ms.api.command.execute.error", {
player: sender.name,
plugin: plugin.description.name,
command,
args: Java.from(args).join(' '),
ex
})
console.ex(ex)
if (sender.name != 'CONSOLE') {
console.sender(sender, [i18n.translate("ms.api.command.execute.error", {
player: sender.name,
plugin: plugin.description.name,
command,
args: Java.from(args).join(' '),
ex
}),
...console.stack(ex)])
}
return true
}
}
}
protected setTabCompleter(plugin: plugin.Plugin, command: any, tabCompleter: Function) {
return (sender: any, _: any, command: string, args: string[]) => {
try {
let time = Date.now()
var token = args[args.length - 1]
var complete = tabCompleter(sender, command, Java.from(args)) || []
let result = this.copyPartialMatches(complete, token)
let cost = Date.now() - time
if (cost > global.ScriptSlowExecuteTime) {
console.i18n("ms.api.command.tab.completer.slow", {
player: sender.name,
plugin: plugin.description.name,
command,
args: Java.from(args).join(' '),
cost
})
}
return result
} catch (ex: any) {
console.i18n("ms.api.command.tab.completer.error", {
player: sender.name,
plugin: plugin.description.name,
command,
args: Java.from(args).join(' '),
ex
})
console.ex(ex)
if (sender.name != 'CONSOLE') {
console.sender(sender, [
i18n.translate("ms.api.command.tab.completer.error", {
player: sender.name,
plugin: plugin.description.name,
command,
args: Java.from(args).join(' '),
ex
}),
...console.stack(ex)
])
}
return []
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 [];
}
}
}
protected copyPartialMatches(complete: string[], token: string, array: string[] = []): string[] {
if (!token) { return complete }
complete.forEach(function (e) {
complete.forEach(function(e) {
if (typeof e === "string" && e.toLowerCase().startsWith(token.toLowerCase())) {
array.push(e)
}
})
});
return array
}
}

View File

@@ -1,11 +1,12 @@
import i18m from '@ccms/i18n'
import i18m from '@ms/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.internal.dynalink.', 'jdk.nashorn.', 'org.openjdk.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 JavaString = Java.type('java.lang.String');
const Files = Java.type('java.nio.file.Files');
const Paths = Java.type('java.nio.file.Paths');
const ignoreLogPrefix = ['java.', 'net.minecraft.', 'org.bukkit.', 'jdk.nashorn.', 'io.netty.', 'org.spongepowered.'];
enum LogLevel {
ALL,
@@ -18,124 +19,19 @@ enum LogLevel {
OFF
}
const sourceMaps: { [key: string]: SourceMapBuilder } = {}
const sourceFileMaps: { [key: string]: string } = {}
global.setGlobal('MiaoScriptSourceMaps', sourceMaps)
global.setGlobal('MiaoScriptSourceFileMaps', sourceFileMaps)
export namespace jsconsole {
export function readSourceMap(fileName: string, lineNumber: any) {
try {
if (fileName.endsWith('js') || fileName.endsWith('ms')) {
if (sourceMaps[fileName] === undefined) {
sourceMaps[fileName] = null
let sourceLine = base.read(fileName).split('\n')
let lastLine = sourceLine[sourceLine.length - 1] || sourceLine[sourceLine.length - 2]
// lastLine is similar //# sourceMappingURL=data:application/json;base64,
if (lastLine.startsWith('//# sourceMappingURL=')) {
let sourceContent = null
let sourceMappingURL = lastLine.split('sourceMappingURL=', 2)[1]
if (sourceMappingURL.startsWith('data:application/json;base64,')) {
sourceContent = String.fromCharCode(...Array.from(base64.toByteArray(sourceMappingURL.split(',', 2)[1])))
} else if (sourceMappingURL.startsWith('http://') || sourceMappingURL.startsWith('https://')) {
// TODO
} else {
let file = Paths.get(Paths.get(fileName, '..', sourceMappingURL).toFile().getCanonicalPath()).toFile()
if (file.exists()) {
sourceContent = base.read(file)
} else if (global.debug) {
console.debug('readSourceMap can\'t found', fileName, 'source map file', sourceMappingURL)
}
}
if (sourceContent) {
sourceMaps[fileName] = new SourceMapBuilder(JSON.parse(sourceContent))
sourceFileMaps[fileName] = Paths.get(fileName, '..', sourceMaps[fileName].sources[0]).toFile().getCanonicalPath()
}
}
}
if (sourceMaps[fileName]) {
let sourceMapping = sourceMaps[fileName].getSource(lineNumber, 25, true, true)
if (sourceMapping) {
fileName = Paths.get(fileName, '..', sourceMapping.sourcePath).toFile().getCanonicalPath()
lineNumber = sourceMapping.mapping.sourceLine
}
}
}
} catch (error: any) {
console.debug('search source map', fileName, 'line', lineNumber, 'error:', error)
if (global.debug) {
console.ex(error)
}
}
return {
fileName,
lineNumber
}
}
export function getStackTrace(ex: Error, color: boolean = true): string[] {
if (!ex) return []
let stack = ex.getStackTrace()
let cache = [(color ? '§c' : '') + ex]
//@ts-ignore
if (stack.class) {
stack = Arrays.asList(stack)
}
stack.forEach(trace => {
if (!trace.fileName || trace.fileName.startsWith('jar:file:') || trace.fileName.startsWith('file:')) { return }
if (trace.className.startsWith('<')) {
let { fileName, lineNumber } = readSourceMap(trace.fileName, trace.lineNumber)
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
if (color) {
cache.push(` §e->§c ${fileName}:${lineNumber} => §4${trace.methodName}`)
} else {
cache.push(` -> ${fileName}:${lineNumber} => ${trace.methodName}`)
}
} else {
let className = trace.className
var fileName = trace.fileName as string
var lineNumber = trace.lineNumber
if (className.startsWith('jdk.nashorn.internal.scripts') || className.startsWith('org.openjdk.nashorn.internal.scripts')) {
className = className.substr(className.lastIndexOf('$') + 1)
var { fileName, lineNumber } = readSourceMap(fileName, lineNumber)
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
} else {
if (!global.debug) {
for (let prefix in ignoreLogPrefix) {
if (className.startsWith(ignoreLogPrefix[prefix])) {
return
}
}
} else if (className.startsWith('jdk.nashorn.internal.') || className.startsWith('org.openjdk.nashorn.internal.')) {
return
}
}
if (color) {
cache.push(` §e->§c ${className}.${trace.methodName}(§4${fileName}:${lineNumber}§c)`)
} else {
cache.push(` -> ${className}.${trace.methodName}(${fileName}:${lineNumber})`)
}
}
})
return cache
}
}
export class MiaoScriptConsole implements Console {
Console: any
memory: any
Console: NodeJS.ConsoleConstructor;
private _name: string = ''
private _level: LogLevel = LogLevel.INFO
private sourceMaps: { [key: string]: SourceMapBuilder } = {};
private _name: string = '';
private _level: LogLevel = LogLevel.INFO;
protected logger: any
public 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
}
@@ -145,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.prefix = `§6[§cMS§6][§b${name}§6]§r `
this._name = `[${name}] `;
// noinspection JSUnusedGlobalSymbols
this.prefix = `§6[§cMS§6][§b${name}§6]§r `;
}
}
log(...args: any[]): void {
this.logger.info(this.name + args.join(' '))
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) {
@@ -187,74 +83,129 @@ export class MiaoScriptConsole implements Console {
this.console(i18m.translate(name, param))
}
object(obj) {
for (const i in obj) {
for (var i in obj) {
this.info(i, '=>', obj[i])
}
}
ex(ex: Error) {
this.stack(ex).forEach(line => this.console(line))
}
stack(ex: Error, color: boolean = true): string[] {
return jsconsole.getStackTrace(ex, color)
readSourceMap(fileName: string, lineNumber: number) {
try {
if (fileName.endsWith('js')) {
var file = Paths.get(fileName + '.map');
if (this.sourceMaps[fileName] === undefined) {
if (file.toFile().exists()) {
var sourceMapObj = JSON.parse(new JavaString(Files.readAllBytes(file), "UTF-8"))
this.sourceMaps[fileName] = new SourceMapBuilder(sourceMapObj)
} else {
this.sourceMaps[fileName] = null;
}
}
if (this.sourceMaps[fileName]) {
var sourceMapping = this.sourceMaps[fileName].getSource(lineNumber, lineNumber);
if (sourceMapping) {
if (lineNumber != sourceMapping.mapping.sourceLine) {
fileName = fileName.replace(".js", ".ts");
lineNumber = sourceMapping.mapping.sourceLine;
}
}
}
}
} catch (error) {
console.debug('search source map', fileName, 'line', lineNumber, 'error:', error)
}
return {
fileName,
lineNumber
}
}
stack(ex: Error): string[] {
var stack = ex.getStackTrace();
var cache = ['§4' + ex];
//@ts-ignore
if (stack.class) {
stack = Arrays.asList(stack)
}
stack.forEach(trace => {
if (trace.className.startsWith('<')) {
var { fileName, lineNumber } = this.readSourceMap(trace.fileName, trace.lineNumber)
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
cache.push(` §e->§c ${fileName} => §4${trace.methodName}:${lineNumber}`)
} else {
var className = trace.className;
var fileName = trace.fileName as string;
if (className.startsWith('jdk.nashorn.internal.scripts')) {
className = className.substr(className.lastIndexOf('$') + 1)
var { fileName, lineNumber } = this.readSourceMap(trace.fileName, trace.lineNumber)
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
} else {
for (var prefix in ignoreLogPrefix) {
if (className.startsWith(ignoreLogPrefix[prefix])) {
return;
}
}
}
cache.push(` §e->§c ${className}.${trace.methodName}(§4${fileName}:${trace.lineNumber}§c)`);
}
});
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?: any): void {
throw new Error("Method not implemented.")
dir(obj: any, options?: NodeJS.InspectOptions): void {
throw new Error("Method not implemented.");
}
dirxml(...data: any[]): void {
throw new Error("Method not implemented.")
}
exception(message?: string, ...optionalParams: any[]): void {
throw new Error('Method not implemented.')
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

@@ -1,38 +0,0 @@
export namespace constants {
export namespace ServiceIdentifier {
/**
* Runtime Server NettyPipeline
*/
export const NettyPipeline = Symbol("NettyPipeline")
/**
* Runtime Server RootLogger
*/
export const RootLogger = Symbol("RootLogger")
}
export namespace Reflect {
export const Method = {
getServerConnection: [
/*spigot 1.8.8*/'aq',
/*spigot 1.12.2*/ 'an',
/*spigot 1.14.4+*/'getServerConnection',
/*spigot 1.19+*/'ad',
/*catserver 1.12.2*/'func_147137_ag'
]
}
export const Field = {
listeningChannels: [
/*spigot 1.8.8-1.12.2*/'g',
/*spigot 1.14.4*/'f',
/*spigot 1.15.2+*/'listeningChannels',
/*catserver 1.12.2*/'field_151274_e'
]
}
}
export enum ServerType {
Bukkit = 'bukkit',
Sponge = 'sponge',
Nukkit = 'nukkit',
Bungee = 'bungee',
Spring = 'spring'
}
}

View File

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

View File

@@ -1,15 +1,12 @@
/**
* MiaoScript Event处理类
*/
import i18n from '@ccms/i18n'
import { injectable, unmanaged } from '@ccms/container'
import i18n from '@ms/i18n'
import { injectable, unmanaged } from '@ms/container'
const Thread = Java.type('java.lang.Thread')
const Thread = Java.type('java.lang.Thread');
export namespace event {
/**
* 事件监听优先级
*/
export enum EventPriority {
LOWEST = "LOWEST",
LOW = "LOW",
@@ -21,16 +18,13 @@ export namespace event {
@injectable()
export abstract class Event {
// export EventPriority to blockly
public EventPriority = EventPriority;
private mapEvent = [];
private listenerMap = [];
protected baseEventDir = '';
constructor(@unmanaged() baseEventDir: string) {
this.baseEventDir = baseEventDir
this.baseEventDir = baseEventDir;
}
/**
@@ -39,74 +33,74 @@ export namespace event {
* org.spongepowered.api.event.game.GameRegistryEvent.Register => gameregistryevent$register
*/
mapEventName() {
if (this.baseEventDir === "") { throw new Error(i18n.translate('ms.api.event.empty.event.dir')) }
let count = 0
let jar = this.getJarFile(this.baseEventDir)
let entries = jar.entries()
if (this.baseEventDir === "") { throw new Error(i18n.translate('ms.api.event.empty.event.dir')); }
let count = 0;
let jar = this.getJarFile(this.baseEventDir);
let entries = jar.entries();
while (entries.hasMoreElements()) {
let entry = entries.nextElement()
let name = entry.name
let entry = entries.nextElement();
let name = entry.name;
if (name.startsWith(this.baseEventDir) && name.endsWith(".class")) {
// replace name to qualifiedName
let qualifiedName = name.replaceAll('/', '.')
let qualifiedName = name.replaceAll('/', '.');
try {
let clazz = base.getClass(qualifiedName.substring(0, qualifiedName.length - 6))
let clazz = base.getClass(qualifiedName.substring(0, qualifiedName.length - 6));
if (this.isValidEvent(clazz)) {
let simpleName = this.class2Name(clazz).toLowerCase()
console.trace(i18n.translate("ms.api.event.mapping", { canonicalName: clazz.canonicalName, simpleName }))
this.mapEvent[simpleName] = clazz
count++
let simpleName = this.class2Name(clazz).toLowerCase();
console.trace(i18n.translate("ms.api.event.mapping", { canonicalName: clazz.canonicalName, simpleName }));
this.mapEvent[simpleName] = clazz;
count++;
}
} catch (ex: any) {
} catch (ex) {
//ignore already loaded class
}
}
}
return count
return count;
}
getJarFile(resource: string, loader?: any) {
let dirs = (loader || Thread.currentThread().getContextClassLoader()).getResources(resource)
getJarFile(resource: string) {
let dirs = Thread.currentThread().getContextClassLoader().getResources(resource);
if (dirs.hasMoreElements()) {
let url = dirs.nextElement()
if (url.protocol === "jar") { return url.openConnection().jarFile }
let url = dirs.nextElement();
if (url.protocol === "jar") { return url.openConnection().jarFile; }
}
throw new Error(i18n.translate("ms.api.event.resource.not.found", { resource }))
}
class2Name(clazz: any) {
return clazz.simpleName
return clazz.simpleName;
}
name2Class(name: any, event: string) {
let eventCls = this.mapEvent[event.toLowerCase()] || this.mapEvent[event.toLowerCase() + 'event']
let eventCls = this.mapEvent[event.toLowerCase()] || this.mapEvent[event.toLowerCase() + 'event'];
if (!eventCls) {
try {
eventCls = base.getClass(event)
this.mapEvent[event] = eventCls
} catch (ex: any) {
eventCls = base.getClass(eventCls);
this.mapEvent[event] = eventCls;
} catch (ex) {
console.i18n("ms.api.event.not.found", { name, event })
return
return;
}
}
return eventCls
return eventCls;
}
execute(name, exec, eventCls) {
return (...args: any[]) => {
try {
let event = args[args.length - 1]
let event = args[args.length - 1];
if (eventCls.isAssignableFrom(event.getClass())) {
let time = Date.now()
exec(event)
let cost = Date.now() - time
if (cost > global.ScriptSlowExecuteTime) {
exec(event);
let cost = Date.now() - time;
if (cost > 20) {
console.i18n("ms.api.event.execute.slow", { name, event: this.class2Name(eventCls), cost })
}
}
} catch (ex: any) {
} catch (ex) {
console.i18n("ms.api.event.execute.error", { name, event: this.class2Name(eventCls), ex })
console.ex(ex)
console.ex(ex);
}
}
}
@@ -120,80 +114,46 @@ export namespace event {
* @param ignoreCancel
*/
listen(plugin: any, event: string, exec: (event: any) => void, priority: EventPriority = EventPriority.NORMAL, ignoreCancel = false) {
if (!plugin || !plugin.description || !plugin.description.name) throw new TypeError(i18n.translate("ms.api.event.listen.plugin.name.empty"))
var name = plugin.description.name
var eventCls = this.name2Class(name, event)
if (!eventCls) { return }
if (!plugin || !plugin.description || !plugin.description.name) throw new TypeError(i18n.translate("ms.api.event.listen.plugin.name.empty"));
var name = plugin.description.name;
var eventCls = this.name2Class(name, event);
if (!eventCls) { return; }
if (typeof priority === 'boolean') {
ignoreCancel = priority
priority = EventPriority.NORMAL
ignoreCancel = priority;
priority = EventPriority.NORMAL;
}
priority = priority || EventPriority.NORMAL
ignoreCancel = ignoreCancel || false
// @ts-ignore
let executor = exec.name || exec.executor || '[anonymous]'
priority = priority || EventPriority.NORMAL;
ignoreCancel = ignoreCancel || false;
// noinspection JSUnusedGlobalSymbols
var listener = this.register(
eventCls,
this.execute(name, exec, eventCls),
priority,
ignoreCancel
)
var listenerMap = this.listenerMap
var listener = this.register(eventCls, this.execute(name, exec, eventCls), priority, ignoreCancel);
var listenerMap = this.listenerMap;
// add to cache Be used for close plugin to close event
if (!listenerMap[name]) listenerMap[name] = []
var off = () => {
if (off['offed']) return
off['offed'] = true
this.unregister(eventCls, listener)
console.debug(i18n.translate("ms.api.event.unregister", {
name,
event: this.class2Name(eventCls),
exec: executor
}))
}
listenerMap[name].push(off)
if (!listenerMap[name]) listenerMap[name] = [];
var offExec = () => {
this.unregister(eventCls, listener);
console.debug(i18n.translate("ms.api.event.unregister", { name, event: this.class2Name(eventCls) }));
};
var off = {
event: eventCls,
listener: listener,
off: offExec
};
listenerMap[name].push(off);
// noinspection JSUnresolvedVariable
console.debug(i18n.translate("ms.api.event.register", {
name,
event: this.class2Name(eventCls),
exec: executor,
priority,
ignore: ignoreCancel
}))
return off
console.debug(i18n.translate("ms.api.event.register", { name, event: this.class2Name(eventCls) }));
return off;
}
/**
* 关闭插件监听任务
* @param plugin 插件
*/
disable(plugin: any) {
var eventCache = this.listenerMap[plugin.description.name]
var eventCache = this.listenerMap[plugin.description.name];
if (eventCache) {
eventCache.forEach(off => off())
delete this.listenerMap[plugin.description.name]
eventCache.forEach(t => t.off());
delete this.listenerMap[plugin.description.name];
}
}
/**
* 判断
* @param clazz 事件类
*/
abstract isValidEvent(clazz: any): boolean
/**
* 注册事件
* @param eventCls 事件类
* @param exec 执行器
* @param priority 优先级
* @param ignoreCancel 是否忽略已取消的事件
*/
abstract register(eventCls: any, exec: Function, priority: any, ignoreCancel: boolean): any
/**
* 取消监听事件
* @param event 事件
* @param listener 监听器
*/
abstract unregister(event: any, listener: any): void
abstract isValidEvent(clazz: any): boolean;
abstract register(eventCls: any, exec: Function, priority: any, ignoreCancel: boolean): any;
abstract unregister(event: any, listener: any): void;
}
}

View File

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

View File

@@ -0,0 +1,2 @@
export * from './plugin'
export * from './server'

View File

@@ -0,0 +1,30 @@
export namespace plugin {
/**
* MiaoScript Plugin
*/
export const Plugin = Symbol("Plugin");
/**
* MiaoScript Plugin Folder
*/
export const PluginFolder = Symbol("PluginFolder");
/**
* Runtime Plugin Instance
*/
export const PluginInstance = Symbol("PluginInstance");
/**
* MiaoScript Plugin Manager Symbol
*/
export const PluginManager = Symbol("PluginManager");
/**
* MiaoScript Plugin Manager Interface
*/
export interface PluginManager {
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

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

View File

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

View File

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

View File

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

View File

@@ -1,198 +0,0 @@
import { injectable } from '@ccms/container'
export namespace plugin {
/**
* MiaoScript Plugin
*/
export const Plugin = Symbol("Plugin")
/**
* MiaoScript Plugin Folder
*/
export const PluginFolder = Symbol("PluginFolder")
/**
* Runtime Plugin Instance
*/
export const PluginInstance = Symbol("PluginInstance")
/**
* MiaoScript Plugin Manager Interface
*/
@injectable()
export abstract class PluginManager {
abstract scan(folder: string): void
abstract build(): void
abstract loadFromFile(file: string, ext?: any): Plugin
abstract load(...args: any[]): void
abstract enable(...args: any[]): void
abstract disable(...args: any[]): void
abstract reload(...args: any[]): void
abstract getPlugin(name: string): plugin.Plugin
abstract getPlugins(): Map<string, plugin.Plugin>
}
export const PluginScanner = Symbol("PluginScanner")
/**
* 插件加载元信息
*/
export interface PluginLoadMetadata {
/**
* 插件加载类型
*/
type: 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
/**
* 插件中文名称
*/
cname?: string
/**
* 插件等级 付费插件自动注入
*/
level?: number
/**
* 前缀
*/
prefix?: string
/**
* 插件版本 不填默认为 1.0.0
*/
version?: string
/**
* 插件作者 不填默认为 Unknow
*/
author?: string | string[]
/**
* 脚本依赖
*/
depends?: string[]
/**
* 插件依赖
*/
nativeDepends?: string[]
/**
* 插件源文件 必须指定为 __filename
*/
source: string
/**
* 插件类型 默认为 ioc 执行 MiaoScript 加载逻辑
*/
type?: string
/**
* 插件加载信息
*/
loadMetadata?: PluginLoadMetadata
/**
* 插件本体
*/
target?: any
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/bukkit",
"version": "0.23.0",
"name": "@ms/bukkit",
"version": "0.3.1",
"description": "MiaoScript bukkit package",
"keywords": [
"miaoscript",
@@ -12,6 +12,9 @@
"homepage": "https://github.com/circlecloud/ms.git",
"license": "ISC",
"main": "dist/index.js",
"publishConfig": {
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
},
"scripts": {
"clean": "rimraf dist",
"watch": "tsc --watch",
@@ -19,14 +22,13 @@
"test": "echo \"Error: run tests from root\" && exit 1"
},
"devDependencies": {
"@javatypes/spigot-api": "^0.0.3",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^4.6.3"
"typescript": "^3.8.3"
},
"dependencies": {
"@ccms/api": "^0.23.0",
"@ccms/common": "^0.23.0",
"@ccms/container": "^0.23.0"
"@ms/api": "^0.3.1",
"@ms/common": "^0.3.1",
"@ms/container": "^0.3.1"
}
}

View File

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

View File

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

View File

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

View File

@@ -1,20 +1,20 @@
import { MiaoScriptConsole } from '@ccms/api'
import { MiaoScriptConsole } from '@ms/api'
const Bukkit: typeof org.bukkit.Bukkit = Java.type('org.bukkit.Bukkit')
let Bukkit = org.bukkit.Bukkit;
export class BukkitConsole extends MiaoScriptConsole {
sender(sender, ...args) {
if (!(sender instanceof Java.type('org.bukkit.command.CommandSender'))) {
this.error(`First parameter ${sender} not instanceof org.bukkit.command.CommandSender can't send message!`)
return
return;
}
if (Object.prototype.toString.call(args[0]) === "[object Array]") {
args[0].forEach(line => sender.sendMessage(this.prefix + line))
} else {
sender.sendMessage(this.prefix + args.join(' '))
sender.sendMessage(this.prefix + args.join(' '));
}
}
console(...args: string[]): void {
this.sender(Bukkit.getConsoleSender(), args.join(' '))
this.sender(Bukkit.getConsoleSender(), args.join(' '));
}
}

View File

@@ -0,0 +1,114 @@
/*global Java, base, module, exports, require*/
var nmsChatSerializerClass;
var nmsChatSerializerMethod;
var packetTypeConstructor;
var nmsChatMessageTypeClass;
var chatMessageTypes;
var RemapUtils;
var playerConnectionFieldName;
var sendPacketMethod;
var downgrade = false;
/**
* 获取NMS版本
*/
//@ts-ignore
var nmsVersion = org.bukkit.Bukkit.server.class.name.split('.')[3];
/**
* 获取NMS类
*/
function nmsCls(name) {
return base.getClass(['net.minecraft.server', nmsVersion, name].join('.'))
}
function remapMethod(clazz: any, origin: string, test: string, params) {
try {
return clazz.getMethod(origin, params)
} catch (ex) {
if (RemapUtils) {
return clazz.getMethod(RemapUtils.mapMethod(clazz, origin, params), params)
} else {
return clazz.getMethod(test, params)
}
}
}
function remapFieldName(clazz: any, origin: string, test: string) {
try {
return clazz.getField(origin)
} catch (ex) {
if (RemapUtils) {
return clazz.getField(RemapUtils.mapFieldName(clazz, origin))
} else {
return clazz.getField(test)
}
}
}
function init() {
try {
RemapUtils = Java.type('catserver.server.remapper.RemapUtils');
} catch (ex) {
}
nmsChatSerializerClass = nmsCls(nmsVersion.split("_")[1] > 7 ? "IChatBaseComponent$ChatSerializer" : "ChatSerializer");
nmsChatSerializerMethod = remapMethod(nmsChatSerializerClass, 'a', 'func_150699_a', base.getClass('java.lang.String'))
var packetTypeClass = nmsCls("PacketPlayOutChat");
Java.from(packetTypeClass.constructors).forEach(function(c) {
if (c.parameterTypes.length === 2) {
packetTypeConstructor = c
}
});
nmsChatMessageTypeClass = packetTypeConstructor.parameterTypes[1];
if (nmsChatMessageTypeClass.isEnum()) {
chatMessageTypes = nmsChatMessageTypeClass.getEnumConstants();
} else {
switch (nmsChatMessageTypeClass.name) {
case "int":
//@ts-ignore
nmsChatMessageTypeClass = java.lang.Integer;
break;
case "byte":
//@ts-ignore
nmsChatMessageTypeClass = java.lang.Byte;
break;
}
}
var entityPlayerClass = nmsCls('EntityPlayer');
var packetClass = nmsCls('Packet');
var playerConnectionField = remapFieldName(entityPlayerClass, 'playerConnection', 'field_71135_a')
playerConnectionFieldName = playerConnectionField.getName()
sendPacketMethod = remapMethod(playerConnectionField.getType(), 'sendPacket', 'func_179290_a', packetClass)
}
function json(sender, json) {
if (downgrade) {
return '/tellraw ' + sender.name + ' ' + json
} else {
send(sender, json, 0);
return false;
}
}
function send(sender, json, type) {
//@ts-ignore
sendPacket(sender, packetTypeConstructor.newInstance(nmsChatSerializerMethod.invoke(null, json), chatMessageTypes == null ? nmsChatMessageTypeClass.valueOf(java.lang.String.valueOf(type)) : chatMessageTypes[type]))
}
function sendPacket(player, p) {
sendPacketMethod.invoke(player.handle[playerConnectionFieldName], p)
}
try {
init();
} catch (ex) {
org.bukkit.Bukkit.getConsoleSender().sendMessage(`§6[§cMS§6][§bbukkit§6][§achat§6] §cNMS Inject Error §4${ex} §cDowngrade to Command Mode...`)
downgrade = true;
}
let chat = {
json
}
export default chat

View File

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

View File

@@ -1,20 +1,15 @@
/// <reference types="@javatypes/spigot-api" />
/// <reference types="@ms/types/dist/typings/bukkit" />
import { server } from '@ccms/api'
import { Container } from '@ccms/container'
import { server } from '@ms/api'
import { Container } from '@ms/container'
import { BukkitConsole } from './console'
import './item'
import './chat'
import './task'
import './event'
import './server'
import { BukkitNativePluginManager } from './plugin'
import './command'
import './channel'
import './particle'
import { BukkitConsole } from './console';
import './event';
import './server';
import './command';
import './channel';
import './task';
export default function BukkitImpl(container: Container) {
container.bind(server.Console).toConstantValue(BukkitConsole)
container.rebind(server.NativePluginManager).toConstantValue(new BukkitNativePluginManager())
container.bind(server.Console).toConstantValue(BukkitConsole);
}

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

@@ -1,31 +0,0 @@
import { provideSingleton } from '@ccms/container'
import { particle } from '@ccms/api'
@provideSingleton(particle.ParticleManager)
export class BukkitParticleManager extends particle.ParticleManager {
private globalSpawner = new BukkitParticleSpawner()
constructor() {
super()
particle.ParticleManager.globalSpawner = this.globalSpawner
}
protected getGlobalSpawner() {
return this.globalSpawner
}
}
export class BukkitParticleSpawner extends particle.ParticleSpawner {
spawnParticle(location: any, particle: any, count: number = 1) {
location.getWorld().spawnParticle(particle, location, count)
}
spawn(location: any, particle: particle.Particle) {
location.getWorld().spawnParticle(
particle.getParticle(),
location,
particle.getCount(),
particle.getOffsetX(),
particle.getOffsetY(),
particle.getOffsetZ(),
particle.getExtra(),
particle.getData()
)
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/bungee",
"version": "0.23.0",
"name": "@ms/bungee",
"version": "0.3.1",
"description": "MiaoScript bungee package",
"keywords": [
"miaoscript",
@@ -12,6 +12,9 @@
"homepage": "https://github.com/circlecloud/ms.git",
"license": "ISC",
"main": "dist/index.js",
"publishConfig": {
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
},
"scripts": {
"clean": "rimraf dist",
"watch": "tsc --watch",
@@ -19,14 +22,13 @@
"test": "echo \"Error: run tests from root\" && exit 1"
},
"devDependencies": {
"@javatypes/bungee-api": "^0.0.3",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^4.6.3"
"typescript": "^3.8.3"
},
"dependencies": {
"@ccms/api": "^0.23.0",
"@ccms/common": "^0.23.0",
"@ccms/container": "^0.23.0"
"@ms/api": "^0.3.1",
"@ms/common": "^0.3.1",
"@ms/container": "^0.3.1"
}
}

View File

@@ -1,25 +1,25 @@
import { channel, event } from '@ccms/api'
import { provideSingleton, inject } from '@ccms/container'
import { channel, event } from '@ms/api'
import { provideSingleton, inject } from '@ms/container'
const Bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy()
@provideSingleton(channel.Channel)
export class BungeeChannel extends channel.Channel {
@inject(event.Event)
private eventManager: event.Event
private eventManager: event.Event;
send(player: any, channel: string, data: any) {
throw new Error("Method not implemented.")
throw new Error("Method not implemented.");
}
register(channel: string, listener: channel.ChannelListener) {
Bungee.registerChannel(channel)
Bungee.registerChannel(channel);
// console.console('§6[§eWARN§6] §eMiaoScript channel in BungeeCord only register. you need self hanler PluginMessageEvent!')
return this.eventManager.listen({ description: { name: channel } }, "PluginMessageEvent", (event: net.md_5.bungee.api.event.PluginMessageEvent) => {
listener(event.getData(), event)
})
}
unregister(channel: string, off: any) {
Bungee.unregisterChannel(channel)
off()
unregister(channel: string, listener: any) {
Bungee.unregisterChannel(channel);
listener.off();
}
}

View File

@@ -1,5 +1,5 @@
import { command, plugin } from "@ccms/api";
import { inject, provideSingleton } from "@ccms/container";
import { command, plugin } from "@ms/api";
import { inject, provideSingleton } from "@ms/container";
const Arrays = Java.type('java.util.Arrays')
const Command = Java.extend(Java.type('net.md_5.bungee.api.plugin.Command'), Java.type('net.md_5.bungee.api.plugin.TabExecutor'));

View File

@@ -1,6 +1,6 @@
import '@ccms/nashorn'
import { plugin, MiaoScriptConsole } from '@ccms/api'
import { inject, injectable } from "@ccms/container";
import '@ms/nashorn'
import { plugin, MiaoScriptConsole } from '@ms/api'
import { inject, injectable } from "@ms/container";
let CommandSender = Java.type("net.md_5.bungee.api.CommandSender")

View File

@@ -1,6 +1,6 @@
import { event } from '@ccms/api'
import { provideSingleton, postConstruct } from '@ccms/container'
import * as reflect from '@ccms/common/dist/reflect'
import { event } from '@ms/api'
import { provideSingleton, postConstruct } from '@ms/container'
import * as reflect from '@ms/common/dist/reflect'
const Bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy();
const Event = Java.type("net.md_5.bungee.api.plugin.Event");
@@ -79,7 +79,7 @@ export class BungeeEvent extends event.Event {
currentPriorityMap.put(listener, methods);
this.bakeHandlers.invoke(this.eventBus, eventCls);
return listener;
} catch (ex: any) {
} catch (ex) {
console.ex(ex)
} finally {
this.lock.unlock()
@@ -108,7 +108,7 @@ export class BungeeEvent extends event.Event {
}
this.bakeHandlers.invoke(this.eventBus, eventCls);
}
} catch (ex: any) {
} catch (ex) {
console.ex(ex)
} finally {
this.lock.unlock()

View File

@@ -1,17 +1,15 @@
/// <reference types="@javatypes/bungee-api" />
/// <reference types="@ms/types/dist/typings/bungee" />
import { server } from '@ccms/api'
import { Container } from '@ccms/container'
import { server } from '@ms/api'
import { Container } from '@ms/container'
import { BungeeConsole } from './console'
import './task'
import './event'
import './server'
import { BungeeNativePluginManager } from './plugin'
import './command'
import './channel'
import { BungeeConsole } from './console';
import './event';
import './server';
import './command';
import './channel';
import './task';
export default function BungeeImpl(container: Container) {
container.bind(server.Console).toConstantValue(BungeeConsole)
container.rebind(server.NativePluginManager).toConstantValue(new BungeeNativePluginManager())
container.bind(server.Console).toConstantValue(BungeeConsole);
}

View File

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

View File

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

View File

@@ -1,32 +1,33 @@
import { task, plugin } from '@ccms/api'
import { inject, provideSingleton } from '@ccms/container'
import { task, plugin } from '@ms/api'
import { inject, provideSingleton } from '@ms/container';
var Runnable = Java.type('java.lang.Runnable')
let TimeUnit = Java.type('java.util.concurrent.TimeUnit')
@provideSingleton(task.TaskManager)
export class BungeeTaskManager extends task.TaskManager {
create0(owner: plugin.Plugin, func: Function, id: number): task.Task {
return new BungeeTask(owner, func, id)
export class BungeeTaskManager implements task.TaskManager {
@inject(plugin.PluginInstance)
private pluginInstance: any;
create(func: Function): task.Task {
if (Object.prototype.toString.call(func) !== "[object Function]") { throw TypeError('第一个参数 Task 必须为 function !'); };
return new BungeeTask(this.pluginInstance, func);
}
callSyncMethod(func: Function): any {
return func()
}
disable0() {
base.getInstance().getProxy().getScheduler().cancel(base.getInstance())
return func();
}
}
export class BungeeTask extends task.Task {
submit0(...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 base.getInstance().getProxy().getScheduler().runAsync(base.getInstance(), run)
return this.plugin.getProxy().getScheduler().runAsync(this.plugin, run)
}
if (this.interval) {
return base.getInstance().getProxy().getScheduler().schedule(base.getInstance(), run, this.laterTime * 50, this.interval * 50, TimeUnit.MILLISECONDS)
return this.plugin.getProxy().getScheduler().schedule(this.plugin, run, this.laterTime, this.interval, TimeUnit.MILLISECONDS)
} else {
return base.getInstance().getProxy().getScheduler().schedule(base.getInstance(), run, this.laterTime * 50, TimeUnit.MILLISECONDS)
return this.plugin.getProxy().getScheduler().schedule(this.plugin, run, this.laterTime, TimeUnit.MILLISECONDS)
}
}
}

View File

@@ -1 +0,0 @@
src/emp.ts

View File

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

View File

@@ -1,7 +1,7 @@
{
"private": true,
"name": "@ccms/client",
"version": "0.23.0",
"name": "@ms/client",
"version": "0.3.1",
"description": "MiaoScript client package",
"keywords": [
"miaoscript",
@@ -13,25 +13,23 @@
"homepage": "https://github.com/circlecloud/ms.git",
"license": "ISC",
"main": "dist/index.js",
"publishConfig": {
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
},
"scripts": {
"dev": "ts-node-dev --respawn --debounce=1500 src/index.ts",
"clean": "rimraf dist",
"watch": "tsc --watch",
"build": "yarn clean && tsc",
"start": "node dist/index.js",
"debug": "DEBUG=minecraft-protocol node dist/index.js",
"emp": "node dist/emp.js",
"test": "echo \"Error: run tests from root\" && exit 1"
},
"dependencies": {
"axios": "^0.27.2",
"minecraft-protocol": "^1.34.0",
"minecraft-protocol-forge": "^1.0.0",
"proxy-agent": "^5.0.0"
"minecraft-protocol": "^1.11.0"
},
"devDependencies": {
"@types/node": "^17.0.25",
"@nestjs/cli": "^6.14.2",
"rimraf": "^3.0.2",
"typescript": "^4.6.3"
"typescript": "^3.8.3"
}
}

View File

@@ -3,12 +3,12 @@ import { $ } from './color'
export function attachEvents(client) {
client.on('chat', (packet) => {
// Listen for chat messages and echo them back.
var jsonMsg = JSON.parse(packet.message)
var jsonMsg = JSON.parse(packet.message);
console.log($(jsonMsg))
})
client.on('state', (newState, oldState) => {
console.log('Client Change State', oldState, 'to', newState)
let targetServer = process.argv[6]
let targetServer = process.argv[3]
if (newState == "play" && targetServer) {
setTimeout(() => {
client.write('chat', {
@@ -24,10 +24,4 @@ export function attachEvents(client) {
} else if (packet.health > 0) {
}
})
client.on('kick_disconnect', (packet) => {
console.log($(packet.reason))
})
client.on('disconnect', (packet) => {
console.log($(packet.reason))
})
}

View File

@@ -1,81 +1,34 @@
import { createInterface } from 'readline'
import { Client, createClient } from 'minecraft-protocol'
import { createClient } from 'minecraft-protocol'
import { attachForge } from './forge'
import { attachEvents } from './event'
let readUserInfo = process.argv[2] || 'Mr_jtb'
let realUserInfo = readUserInfo.split(":")
let username = realUserInfo[0]
let password = realUserInfo[1] || ''
let version = process.argv[3] || '1.12.2'
let readAddress = process.argv[4] || '192.168.2.25:25565'
let realAddress = readAddress.split(":")
let address = realAddress[0]
let port = parseInt(realAddress[1] || "25565")
let client = commandLineCreateClient()
let username = process.argv[2] || 'Mr_jtb'
let client = createConnection('192.168.2.5', 25577, username)
function commandLineCreateClient() {
return createConnection(address, port, username, password)
}
function createConnection(host: string, port: number, username: string, password: string) {
let clientOptions: any = {
version,
function createConnection(host: string, port: number, username: string) {
let client = createClient({
version: '1.12.2',
host,
port,
username,
password,
// clientToken: 'd02c7f39-2376-45da-a5a5-50e24fa8b185',
//@ts-ignore
// authServer: 'https://skin.yumc.pw/api/yggdrasil/authserver',
// sessionServer: 'https://skin.yumc.pw/api/yggdrasil/sessionserver'
}
if (clientOptions.password) {
clientOptions.clientToken = 'd02c7f39-2376-45da-a5a5-50e24fa8b185'
clientOptions.authServer = 'https://skin.yumc.pw/api/yggdrasil/authserver'
clientOptions.sessionServer = 'https://skin.yumc.pw/api/yggdrasil/sessionserver'
}
let client = createClient(clientOptions)
skipValidation: true
})
attachCommon(client)
attachForge(client)
attachEvents(client)
return client
return client;
}
function attachCommon(client: Client) {
client.on('login', () => {
// client.registerChannel('updater', ['string', []])
// client.registerChannel('updater-enabled', ['string', []])
// client.registerChannel('dragoncore', ['string', []])
// client.registerChannel('dragoncore:main', ['string', []])
client.on('REGISTER', (array) => {
for (const channel of array) {
client.on('channel', console.log)
}
})
// client.on('dragoncore:main', (data) => {
// console.log(data)
// })
})
client.on('custom_payload', (data) => {
console.log('custom_payload' + JSON.stringify(data))
})
client.on('error', (error) => {
console.log("Client Error", error)
})
client.on('end', (resone) => {
console.log("Client End Resone:", resone)
if (`${resone}` != "SocketClosed") {
setTimeout(() => {
client = commandLineCreateClient()
}, 500)
} else {
process.exit(0)
}
})
}
client.on('error', (error) => {
console.log("Client Error", error)
})
client.on('end', (resone) => {
console.log("Client End Resone:", resone)
client = createConnection('192.168.2.5', 25577, username)
})
const rl = createInterface({
input: process.stdin,
@@ -98,22 +51,22 @@ const rl = createInterface({
rl.on('line', function (line) {
switch (line) {
case "":
break
break;
case "eval":
break
break;
case "write":
break
break;
case "/respawn":
client.write('client_command', { payload: 0 })
break
break;
case "//reco":
client.end("")
client = commandLineCreateClient()
break
client = createConnection('192.168.2.5', 25577, username)
break;
case "//quit":
console.info('Disconnected')
client.end("")
break
break;
case "//end":
console.info('Forcibly ended client')
process.exit(0)

View File

@@ -1,5 +0,0 @@
while :; do
yarn emp
echo 进程退出 休眠120秒!
sleep 120
done

View File

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

View File

@@ -1,7 +1,7 @@
{
"name": "@ccms/common",
"version": "0.23.0",
"description": "MiaoScript common package",
"name": "@ms/common",
"version": "0.3.1",
"description": "MiaoScript api package",
"keywords": [
"miaoscript",
"minecraft",
@@ -12,6 +12,9 @@
"homepage": "https://github.com/circlecloud/ms.git",
"license": "ISC",
"main": "dist/index.js",
"publishConfig": {
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
},
"scripts": {
"clean": "rimraf dist",
"watch": "tsc --watch",
@@ -19,11 +22,12 @@
"test": "echo \"Error: run tests from root\" && exit 1"
},
"devDependencies": {
"@ccms/nashorn": "^0.23.0",
"@javatypes/jdk": "^0.0.3",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^4.6.3"
"typescript": "^3.8.3"
},
"dependencies": {
"@ms/nashorn": "^0.3.1"
},
"gitHead": "562e2d00175c9d3a99c8b672aa07e6d92706a027"
}

View File

@@ -1,4 +1,4 @@
import '@ccms/nashorn'
import '@ms/nashorn'
/*global Java, base, module, exports, require, __FILE__*/
const Path = Java.type("java.nio.file.Path");
@@ -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

@@ -1,9 +1,7 @@
import * as querystring from 'querystring'
const URL = Java.type('java.net.URL')
const Paths = Java.type('java.nio.file.Paths')
const Files = Java.type('java.nio.file.Files')
const StandardCopyOption = Java.type('java.nio.file.StandardCopyOption')
const Paths = Java.type('java.nio.file.Paths');
const Files = Java.type('java.nio.file.Files');
const StandardCopyOption = Java.type('java.nio.file.StandardCopyOption');
export type Method =
| 'get' | 'GET'
@@ -15,50 +13,36 @@ export type Method =
| 'patch' | 'PATCH'
interface RequestConfig {
url?: string
method?: Method
headers?: { [key: string]: string }
params?: { [key: string]: string }
data?: any
url?: string;
method?: Method;
headers?: { [key: string]: string };
params?: { [key: string]: string };
data?: any;
}
function request(config: RequestConfig) {
// @ts-ignore XMLHttpRequest class only exist nashorn polyfill
let xhr = new XMLHttpRequest()
xhr.open(config.method, config.url, false)
// @ts-ignore
let xhr = new XMLHttpRequest();
xhr.open(config.method, config.url, false);
for (const header in config.headers) {
xhr.setRequestHeader(header, config.headers[header])
xhr.setRequestHeader(header, config.headers[header]);
}
let body = config.data
if (body && typeof body !== "string") {
switch (config.headers['Content-Type']) {
case "application/json":
body = JSON.stringify(body)
break
case "application/x-www-form-urlencoded":
body = querystring.encode(body)
break
}
}
xhr.send(body)
if (xhr.getResponseHeader("Content-Type").indexOf('application/json') != -1) {
xhr.send(config.data);
if ((xhr.getResponseHeader("Content-Type") + '').indexOf('application/json') != -1) {
xhr.responseType = "json"
}
// @ts-ignore get only exist nashorn polyfill
return xhr.get()
return xhr.get();
}
function download(url: string, target: string) {
console.debug(`Start Download file ${target} from ${url}....`)
Files.copy(new URL(url).openStream(), Paths.get(target), StandardCopyOption.REPLACE_EXISTING)
Files.copy(new URL(url).openStream(), Paths.get(target), StandardCopyOption.REPLACE_EXISTING);
console.debug(`File ${target} Download Complate...`)
}
function _proxy(method: Method) {
return function (url: string, data?: any, config: RequestConfig = {}) {
if (!config.headers) { config.headers = {} }
config.headers['Content-Type'] = config.headers['Content-Type'] ?? 'application/json'
return request({ url, method, data, ...config })
return function (url: string, data?: any, config?: RequestConfig) {
return request({ url, method, data, ...config });
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,201 +1,196 @@
/// <reference types="@javatypes/jdk" />
const JavaClass = Java.type('java.lang.Class')
const JavaObject = Java.type('java.lang.Object')
const NoSuchFieldException = Java.type('java.lang.NoSuchFieldException')
const fieldCache = new Map<string, java.lang.reflect.Field>()
const methodCache = new Map<string, java.lang.reflect.Method>()
/**
* 反射工具类
* Created by MiaoWoo on 2017/2/9 0009.
*/
const JavaClass = Java.type('java.lang.Class');
const JavaObject = Java.type('java.lang.Object')
const NoSuchFieldException = Java.type('java.lang.NoSuchFieldException');
const methodCache = [];
class Reflect {
private obj: java.lang.Object
private class: java.lang.Class<any>
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(nameOrIndex: string | java.lang.String | number, declared = false): java.lang.reflect.Field {
if (nameOrIndex == undefined || nameOrIndex == null) throw new Error(`reflect field name can't be ${nameOrIndex} from ${this.class.getName()}!`)
let key = this.class.getName() + ':' + nameOrIndex + ':' + declared
if (fieldCache.has(key)) {
return fieldCache.get(key)
field(name): Reflect {
try {
// Try getting a public field
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));
}
let field = null
if (typeof nameOrIndex == "number") {
field = this.fields(declared)[nameOrIndex]
} else {
try {
// Try getting a public field
field = this.class.getField(nameOrIndex)
} catch (ex: any) {
// Try again, getting a non-public field
field = declaredField(this.class, nameOrIndex)
}
}
if (!field) throw new Error(`can't reflect field ${typeof nameOrIndex == "number" ? 'index' : 'name'} ${nameOrIndex} from ${this.class.getName()}!`)
return accessible(field)
}
};
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.get(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 (arguments.length === 0) return this.obj
return on(this.field(param, declared).get(this.obj))
}
get(...args): Reflect | any {
return args.length === 1 ? this.field(args[0]) : this.obj;
};
set(param: string | number, value: any, declared: boolean = true): Reflect {
this.field(param, declared).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 {
if (!accessible?.isAccessible()) {
accessible.setAccessible(true)
function accessible(accessible) {
if (accessible === null) {
return null;
}
return accessible
if (!accessible.isAccessible()) {
accessible.setAccessible(true);
}
return accessible;
}
function declaredConstructor(clazz, param) {
let constructor
let constructor;
try {
constructor = clazz.getDeclaredConstructor(types(param))
} catch (ex: any) {
constructor = clazz.getDeclaredConstructor(types(param));
} catch (ex) {
try {
constructor = clazz.getDeclaredConstructor(types(param, true))
} catch (ex: any) {
constructor = clazz.getDeclaredConstructors()[0]
constructor = clazz.getDeclaredConstructor(types(param, true));
} catch (ex) {
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) {
console.debug(`reflect field ${name} from ${target.getName()}`)
try {
field = target.getDeclaredField(name)
if (field !== null) { break }
} catch (error: any) {
if (target === undefined) { break }
target = target.getSuperclass()
console.debug(`切换到超类: ${target.getName()}`)
field = target.getDeclaredField(name);
if (field !== null) { break; }
} catch (e) {
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>, nameOrIndex: string | number, ...clazzs: java.lang.Class<any>[]): java.lang.reflect.Method {
let key = clazz.getName() + '.' + nameOrIndex + ':' + (clazzs || []).map(c => c.getName()).join(':')
if (methodCache.has(key)) { return methodCache.get(key) }
let target = clazz
if (typeof nameOrIndex === "number") {
methodCache.set(key, declaredMethods(clazz)[nameOrIndex])
} else {
while (target !== JavaObject.class && !methodCache.has(key)) {
function declaredMethod(clazz, name, clazzs) {
let key = clazz.name + '.' + name + ':' + (clazzs || []).join(':');
if (!methodCache[key]) {
try {
methodCache[key] = clazz.getMethod(name, clazzs);
} catch (ex) {
try {
console.debug(`reflect method ${typeof nameOrIndex == "number" ? 'index' : 'name'} ${nameOrIndex} from ${target.getName()}`)
try {
methodCache.set(key, target.getMethod(nameOrIndex, clazzs as any))
} catch (ex: any) {
try {
methodCache.set(key, target.getDeclaredMethod(nameOrIndex, clazzs as any))
} catch (ex: any) {
for (const m of Java.from(declaredMethods(target))) {
if (m.getName() == nameOrIndex) {
methodCache.set(key, m)
break
}
}
throw new Error(`method ${typeof nameOrIndex == "number" ? 'index' : 'name'} ${nameOrIndex} not found.`)
methodCache[key] = clazz.getDeclaredMethod(name, clazzs);
} catch (ex) {
for (const m of Java.from(declaredMethods(clazz))) {
if (m.name == name) {
methodCache[key] = m;
break;
}
}
} catch (error) {
if (target === undefined) { break }
target = target.getSuperclass()
console.debug(`切换到超类: ${target.getName()}`)
}
}
}
if (!methodCache.has(key)) throw new Error(`can't reflect method ${typeof nameOrIndex == "number" ? 'index' : 'name'} ${nameOrIndex} from ${clazz.getName()}!`)
return methodCache.get(key)
return methodCache[key];
}
function declaredMethods(clazz: java.lang.Class<any>) {
return clazz.getDeclaredMethods()
function declaredMethods(clazz) {
return clazz.declaredMethods;
}
let classMethodsCache: any[] = [];
function mapToObject(javaObj) {
if (!Java.isJavaObject(javaObj)) { throw new TypeError(`参数 ${javaObj} 不是一个Java对象!`) }
let target = Proxy.newProxy(javaObj, {
apply: (target, name, args) => { return args ? javaObj[name](args) : javaObj[name]() }
})
return target
if (!javaObj || !javaObj.class) { throw new TypeError(`参数 ${javaObj} 不是一个Java对象!`) }
let target = {};
getJavaObjectMethods(javaObj).forEach(t => mapMethod(target, javaObj, t));
return target;
}
function getJavaObjectMethods(javaObj) {
let className = javaObj.class.name;
if (!classMethodsCache[className]) {
let names: any[] = [];
let methods = javaObj.class.methods;
for (let i in methods) {
names.push(methods[i].name);
}
classMethodsCache[className] = names;
}
return classMethodsCache[className];
}
function mapMethod(target, source, name) {
target[name] = function __SimpleDynamicMethod__(...args) {
if (args.length > 0) {
return source[name](args);
} else {
return source[name]();
}
};
}
function on(obj) {
// if (!obj || !obj.class) { throw new TypeError(`参数 ${obj} 不是一个Java对象!`) }
return new Reflect(obj)
return new Reflect(obj);
}
export = {
@@ -203,4 +198,4 @@ export = {
accessible,
declaredMethods,
mapToObject
}
};

View File

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

View File

@@ -1,4 +1,4 @@
import '@ccms/nashorn'
import '@ms/nashorn'
let Files = Java.type("java.nio.file.Files");
let Paths = Java.type("java.nio.file.Paths");

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

View File

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

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/compile",
"version": "0.23.0",
"name": "@ms/compile",
"version": "0.3.1",
"description": "MiaoScript compile package",
"keywords": [
"miaoscript",
@@ -12,6 +12,9 @@
"homepage": "https://github.com/circlecloud/ms.git",
"license": "ISC",
"main": "dist/index.js",
"publishConfig": {
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
},
"scripts": {
"clean": "rimraf dist",
"watch": "tsc --watch",
@@ -21,6 +24,6 @@
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^4.6.3"
"typescript": "^3.8.3"
}
}

View File

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

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/container",
"version": "0.23.0",
"name": "@ms/container",
"version": "0.3.1",
"description": "MiaoScript container package",
"keywords": [
"miaoscript",
@@ -12,6 +12,9 @@
"homepage": "https://github.com/circlecloud/ms.git",
"license": "ISC",
"main": "dist/index.js",
"publishConfig": {
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
},
"scripts": {
"clean": "rimraf dist",
"watch": "tsc --watch",
@@ -19,13 +22,11 @@
"test": "echo \"Error: run tests from root\" && exit 1"
},
"devDependencies": {
"@ccms/nashorn": "^0.23.0",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^4.6.3"
"typescript": "^3.8.3"
},
"dependencies": {
"inversify": "^6.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,64 +1,93 @@
import { interfaces, Container } from "inversify"
import { _proxyGetter } from "./utils"
import { interfaces, Container } from "inversify";
let _container: Container
let _container: Container;
const ContainerInstance = Symbol.for("@ccms/ioc:Container")
const ContainerInstance = Symbol.for("@ms/ioc:Container");
const INJECTION = Symbol.for("INJECTION");
function _proxyGetter(
proto: any,
key: string,
resolve: () => any,
doCache: boolean
) {
function getter(this: object) {
if (doCache && !Reflect.hasMetadata(INJECTION, this, key)) {
Reflect.defineMetadata(INJECTION, resolve(), this, key);
}
if (Reflect.hasMetadata(INJECTION, this, key)) {
return Reflect.getMetadata(INJECTION, this, key);
} else {
return resolve();
}
}
function setter(this: object, newVal: any) {
Reflect.defineMetadata(INJECTION, newVal, this, key);
}
Object.defineProperty(proto, key, {
configurable: true,
enumerable: true,
get: getter,
set: setter
});
}
function initContainer(container: Container) {
Reflect.defineMetadata(ContainerInstance, container, Reflect)
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)
@@ -73,4 +102,4 @@ export {
lazyInjectNamed,
lazyInjectTagged,
lazyMultiInject
}
};

View File

@@ -1,170 +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, inject, named } from 'inversify'
import { fluentProvide } from 'inversify-binding-decorators'
import { ioc } from "./constants"
import { _proxyGetter } from "./utils"
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: object, propertyKey: string, index?: number) {
try { target[propertyKey] = Java.type(className).class; return } catch (error: any) { }
try { target[propertyKey] = base.getClass(className); return } catch (error: any) { }
console.warn('JavaClass', className, 'Inject target', target.constructor.name, 'propertyKey', propertyKey, 'failed!')
}
}
/**
* 获得一个JS的Java类
* @param className Java 全类名
*/
export const JSClass = (className: string) => {
return function (target: object, propertyKey: string, index?: number) {
_proxyGetter(target, propertyKey, () => {
try { return Java.type(className) } catch (error: any) { }
try { return base.getClass(className).static } catch (error: any) { }
console.warn('JSClass', className, 'Inject target', target.constructor.name, 'propertyKey', propertyKey, 'failed!')
}, true)
}
}
/**
* 自动注入实例由平台实现
* @param className 类名
*/
export const Autowired = (className?: any) => {
return function (target: any, propertyKey: string, index?: number) {
let container = getContainer()
if (className && (className instanceof Symbol || className instanceof Function)) {
return inject(className)(target, propertyKey, index)
}
let type = Reflect.getMetadata('design:type', target, propertyKey)
if (type && type !== Object && !Java.isJavaObject(type)) {
inject(type)(target, propertyKey, index)
named(className || propertyKey)(target, propertyKey, index)
} else if (container.isBound(ioc.Autowired)) {
console.debug('Autowired', 'ioc.Autowired', 'named', className || propertyKey)
target[propertyKey] = container.getNamed(ioc.Autowired, className || propertyKey)
} else {
throw new Error(`No matching bindings found for target: ${target.constructor.name} type: ${type} named: ${className || propertyKey}`)
}
}
}
/**
* 自动注入资源由平台实现
* @param className 类名
*/
export const Resource = (resourceName?: string | any) => {
return function (target: any, propertyKey: string, index?: number) {
target[propertyKey] = getContainer().getNamed(ioc.Resource, resourceName || propertyKey)
}
}
const DocumentBuilderFactory = Java.type('javax.xml.parsers.DocumentBuilderFactory')
export const MavenDepend = (groupId: string, artifactId: string, version: string, recursion = false) => {
return function (target: any) {
loadMavenDepend(groupId, artifactId, version, recursion)
}
}
const loadedMavenDepend = new Set<string>()
export function loadMavenDepend(groupId: string, artifactId: string, version: string, recursion = false) {
const key = `${groupId}:${artifactId}:${version}`
try {
if (loadedMavenDepend.has(key)) { return }
console.info('loading maven dependency', key)
let [pom, _] = base.loadMavenDepend(groupId, artifactId, version)
loadedMavenDepend.add(key)
if (recursion) {
let doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(pom)
let dependencies = doc.getElementsByTagName("dependency")
let size = dependencies.length
if (!size) { return }
console.debug(key, 'found', size, 'dependencies loading...')
for (let i = 0; i < size; i++) {
const dependency = dependencies.item(i)
const gav = dependency.getChildNodes()
const length = gav.length
const dependencyVersion = { groupId: '', artifactId: '', version: '' }
for (let j = 0; j < length; j++) {
const prop = gav.item(j)
switch (prop.getNodeName()) {
case "groupId":
dependencyVersion.groupId = prop.getTextContent()
break
case "artifactId":
dependencyVersion.artifactId = prop.getTextContent()
break
case "version":
dependencyVersion.version = prop.getTextContent()
break
}
}
loadMavenDepend(dependencyVersion.groupId, dependencyVersion.artifactId, dependencyVersion.version, recursion)
}
}
} catch (error: any) {
console.warn('load maven dependency', key, 'failed. Error:', error)
if (global.debug) {
console.ex(error)
}
}
}
export const reduceMetadata = (ctx: interfaces.Context): any => {
return ctx.currentRequest.target.metadata.reduce((result, entry, index) => {
result[entry.key] = entry.value
return result
}, {})
}
function initAutowired(container: Container) {
container.bind(ioc.Autowired).toDynamicValue((ctx) => {
var metadata: any = reduceMetadata(ctx)
let key = Object.toString.call(metadata.named)
if (key === "[object Function]" || key === "[object Symbol]") { return container.get(metadata.named) }
return undefined
})
}
export const DefaultContainer = new Container()
initContainer(DefaultContainer)
initAutowired(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,30 +0,0 @@
const INJECTION = Symbol.for("INJECTION")
export function _proxyGetter(
proto: any,
key: string,
resolve: () => any,
doCache: boolean
) {
function getter(this: object) {
if (doCache && !Reflect.hasMetadata(INJECTION, this, key)) {
Reflect.defineMetadata(INJECTION, resolve(), this, key)
}
if (Reflect.hasMetadata(INJECTION, this, key)) {
return Reflect.getMetadata(INJECTION, this, key)
} else {
return resolve()
}
}
function setter(this: object, newVal: any) {
Reflect.defineMetadata(INJECTION, newVal, this, key)
}
Object.defineProperty(proto, key, {
configurable: true,
enumerable: true,
get: getter,
set: setter
})
}

View File

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

View File

@@ -1,7 +1,7 @@
{
"name": "@ccms/core",
"version": "0.23.0",
"description": "MiaoScript core package",
"name": "@ms/core",
"version": "0.3.1",
"description": "MiaoScript api package",
"keywords": [
"miaoscript",
"minecraft",
@@ -12,6 +12,9 @@
"homepage": "https://github.com/circlecloud/ms.git",
"license": "ISC",
"main": "dist/index.js",
"publishConfig": {
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
},
"scripts": {
"clean": "rimraf dist",
"watch": "tsc --watch",
@@ -21,11 +24,11 @@
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^4.6.3"
"typescript": "^3.8.3"
},
"dependencies": {
"@ccms/api": "^0.23.0",
"@ccms/container": "^0.23.0"
"@ms/api": "^0.3.1",
"@ms/container": "^0.3.1"
},
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
}

View File

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

View File

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

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