Compare commits
419 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 0f418f39df | |||
| 75cb430230 | |||
| 6aedd8e680 | |||
| cd31f80805 | |||
| 08ba1c1a98 | |||
| d5c2a825fc | |||
| b36b63277f | |||
| 7d02194ac7 | |||
| ce4ad6f046 | |||
| 24691a9ce8 | |||
| 9fa13f49cd | |||
| 64a698089b | |||
| 53843b65d2 | |||
| 5f00431e8b | |||
| c947ff7a14 | |||
| be2988fc58 | |||
| 3beed64319 | |||
| 23c7cb955a | |||
| 3be1f78a14 | |||
| d919fa07fc | |||
| d8fd7b0a7d | |||
| 907f9ed03f | |||
| e28d881976 | |||
| 1bdb324fc4 | |||
| 5c90ac3b1f | |||
| 653d7268cf | |||
| efa5e6d110 | |||
| ceb354f11e | |||
| d97af356fd | |||
| 6fd7174ca5 | |||
| 784ea2d65a | |||
| 3ccc9b3d06 | |||
| beef57d85d | |||
| 166b17b527 | |||
| d6ca19a56f | |||
| c61f87a449 | |||
| ede3f83dd5 | |||
| 69ef3b3979 | |||
|
|
0a8574621d | ||
| 5426ec1eed | |||
| 831f6d0916 | |||
| 1a5175f466 | |||
|
|
2ad290bd48 | ||
| 611d4e5425 | |||
| 894d5d43e6 | |||
| cd57944cb8 | |||
| 75b34bfc48 | |||
| 47478e13aa | |||
|
|
17af1fd49b | ||
| b5423cd26c | |||
| aca864500f | |||
| f86e1a8c94 | |||
| a76f9e8b50 | |||
| 6dcc56b0e5 | |||
| 6f8ea8290b | |||
| 1f574695a1 | |||
| 090c0b2668 | |||
| db8f2d9bc2 | |||
| e02f673c82 | |||
| 47c85f70eb | |||
| da9e2063ca | |||
| 0568a7abbe | |||
| 7375e8e2e9 | |||
| 41d3923d94 | |||
| f111b9891c | |||
| 2e4fdcb798 | |||
| ab7ca932a3 | |||
| e8b3d43cdf | |||
| eaaa0ef139 | |||
| 94840ae59d | |||
| c31eaeb8f6 | |||
| 469a66a277 | |||
| cd6a2023dc | |||
| 498b0ee017 | |||
| 9bfaf984c1 | |||
| 3c33ebf4e6 | |||
| 8af69c98f3 | |||
| 72277f4d1a | |||
| d85f75ba1f | |||
| ed14d317f4 | |||
| fb8a11ea05 | |||
| eae80fa30b | |||
| 3e69fc42d9 | |||
| c5595a65fb | |||
| df266905f2 | |||
| f8046e38be | |||
| 51fb5aece3 | |||
| 7a1dd3e7b3 | |||
| 8f3c799531 | |||
| 3389dbd566 | |||
| 54604e10b8 | |||
| d7247bae19 | |||
| 3ee2dcad0b | |||
| bc19021c63 | |||
| e9a4f2f351 | |||
| 9be9c400ad | |||
| 8eaf789bce | |||
| 7d6f6124b1 | |||
| e06fcc29e9 | |||
| 79ece8db63 | |||
| 66c1d25888 | |||
| ca8d4778bb | |||
| 7dcc5ed45a | |||
| 91d2d836fc | |||
| e5e1bb70a1 | |||
| e93a53aa9f | |||
| e3bceda06b | |||
| 9367e8c2c9 | |||
| 31c7ea2a29 | |||
| 2589633069 | |||
| bc17e2f376 | |||
| 20749d3381 | |||
| 6261b85413 | |||
| da9d590374 | |||
| 0af3ca8c79 | |||
| 561d5b60e8 | |||
| 878a5368af | |||
| 018b972aea | |||
| 4138cf9448 | |||
| 646176b43c | |||
| 506184a104 | |||
| 392f01d509 | |||
| 75b892e1c0 | |||
| c2d825eed0 | |||
| 393e63c017 | |||
| 46d6748f31 | |||
| b6803ed01c | |||
| bbfc70fdd6 | |||
| e28af3fbbc | |||
| 14eef46e67 | |||
| 1c4f512c89 | |||
| a8ae60625b | |||
| e7bc14294e | |||
| 4750f31b6e | |||
| 18df821049 | |||
| ef98c49e1d | |||
| 5f0c3bbdd4 | |||
| bf3638dda0 | |||
| 842335edbe | |||
| f573d0c758 | |||
| 13b04a904e | |||
| 2c1eea5bc1 | |||
| 8a07e85fda | |||
| 32db0bba56 | |||
| b417d8ff08 | |||
| 6fd7038ffe | |||
| 321b21a947 | |||
| 0ae7346678 | |||
| 7114876046 | |||
| 01fcc1337a | |||
| 476f7acc39 | |||
| 5b11be11da | |||
| 80c6b123c1 | |||
| a7a40b374b | |||
| 9888f908e9 | |||
| 73ada5fd17 | |||
| 79f151de5c | |||
| 16fcbfa69c | |||
| 7e1111470c | |||
| d407631072 | |||
| 4d7b27188a | |||
| 7bd8302b24 | |||
| b065bcd843 | |||
| c8a31b6d5a | |||
| 75492c77e8 | |||
| 8dbbb369b2 | |||
| 24ba6bd353 | |||
| a02bd6dc95 | |||
| 21cf867f43 | |||
| 4290d1132e | |||
| 1ed5dd1d24 | |||
| d751dc8614 | |||
| c45bbb9821 | |||
| c9ca4ffd39 | |||
| 5943d6882f | |||
| d24d0d39a1 | |||
| 95cd8c4889 | |||
| 78fcbbe9a5 | |||
| baa6e95222 | |||
| 3a045bd335 | |||
| dd28d9fae5 | |||
| 72bd6b4c9c | |||
| 58478116c6 | |||
| d29efb2332 | |||
| 0899276530 | |||
| 5c3ed4e36d | |||
| b926951656 | |||
| b47acf69ea | |||
| 63aef1fe60 | |||
| 541a3bb96b | |||
| 873964575b | |||
| 54af491399 | |||
| 43d9b97347 | |||
| 25aef3ed62 | |||
| c622abecda | |||
| f527c225fe | |||
| 26eceac330 | |||
| f5702c5080 | |||
| 101f152da7 | |||
| 97db272041 | |||
| a5ca0c2346 | |||
| aab94fe5ea | |||
| d3d7a9cdbf | |||
| 9dee4b3a60 | |||
| f1863c3b39 | |||
| 0120e84f3f | |||
| 00130f549c | |||
| fafcd09cc1 | |||
| 2bd8f0c5ff | |||
| 695a490296 | |||
| 1a546470a5 | |||
| e68c17576a | |||
| eaee2f9c91 | |||
| 3596fc0804 | |||
| 5e89872477 | |||
| c12670bd9e | |||
| b9ef3f2e33 | |||
| 4b3176e98e | |||
| 4922f6a39d | |||
| 195c84e1ae | |||
| 7d63a57991 | |||
| 1931391cba | |||
| 2dda9bd0fc | |||
| 937b24ecda | |||
| c9eff3dae4 | |||
| 098a4f8557 | |||
| 8566c6a883 | |||
| 0584ec9d85 | |||
| 87f197fe06 | |||
| 860946a44b | |||
| f40eddd5e3 | |||
| b67474f7ff | |||
| 8e5588ca23 | |||
| acbeda9659 | |||
| a4c549d446 | |||
| c311d3fdb1 | |||
| 1c29a059d9 | |||
| d22b72f10a | |||
| e74cfda86b | |||
| 24fe3b9026 | |||
| ee9ae408ec | |||
| d679915062 | |||
| eaa11ac89e | |||
| 5ddfb1c40f | |||
| da68821a1f | |||
| ec65d00f28 | |||
| a2c3eff622 | |||
| 8d2422fd64 | |||
| 9bc6cc1ff2 | |||
| 6fc3592536 | |||
| 49b96b3ac4 | |||
| 73b9c2f163 | |||
| f5a7a269e4 | |||
| 662e70b72c | |||
| b71ce1b24d | |||
| 1ea8966f26 | |||
| 0ed3f1fbd5 | |||
| f4b461409b | |||
| ace2c48ae2 | |||
| 39861b2c46 | |||
| 6c9ea9fb74 | |||
| 15f09abce0 | |||
| eb832a0830 | |||
| 1d35c836fc | |||
| e53f2cea76 | |||
| 1395865d8a | |||
| bae5355c1b | |||
| 41d2edc719 | |||
| d608e2c066 | |||
| e7c22b5961 | |||
| 18b46cdcc7 | |||
| d057fd5464 | |||
| 247c566219 | |||
| ed9fec281c | |||
| 15197355c5 | |||
| 988bb3b914 | |||
| 47048a5b1b | |||
| b3539d419e | |||
| c10247e241 | |||
| 553632e6ba | |||
| 6b7a729e65 | |||
| 488eecba07 | |||
| ce431aded4 | |||
| 525fde9f51 | |||
| ca11db68a6 | |||
| 3f475a7dc1 | |||
| e7d44af48c | |||
| 0b416adfd2 | |||
| 429cece606 | |||
| c34b744994 | |||
| 4d64a5d264 | |||
| 13c0584749 | |||
| f5f50d0dd6 | |||
| 0176cabd41 | |||
| a3f8451842 | |||
| 9ea4a067f1 | |||
| 3143851969 | |||
| 7e4c44eadd | |||
| e323467ed8 | |||
| eba21c08dc | |||
| a872172fff | |||
| c996fa6873 | |||
| 8616c3fe22 | |||
| 407de98468 | |||
| c13668dbe2 | |||
| a0b334b151 | |||
| d7e8b05573 | |||
| 9fd4b51d98 | |||
| 246867b999 | |||
| 381ea25b46 | |||
| 6d81a72106 | |||
| f20171f898 | |||
| eaf491f74d | |||
| 49f886c5ba | |||
| 3cf83023eb | |||
| 9f64f89222 | |||
| bdecc96fcf | |||
| f660b4a4f8 | |||
| e8d41e8a43 | |||
| d9e2b50953 | |||
| 93c83cac94 | |||
| b506d06173 | |||
| 8d81d6938e | |||
| d90264194c | |||
| cc96519e80 | |||
| 982e14953c | |||
| b0409c46ba | |||
| fb3eb9704f | |||
| effa43d42f | |||
| 06684939bc | |||
| 9eb052addb | |||
| 9acd824656 | |||
| 61195accc9 | |||
| 568f723c06 | |||
| bca12d6f02 | |||
| 9b3d76b6dd | |||
| 84d9eb8881 | |||
| 6b4d0cc64c | |||
| 1d783ebd1f | |||
| 87ac658a22 | |||
| b793ec192f | |||
| 606bbb3991 | |||
| cacde0627b | |||
| 6f5254497f | |||
| 2639fbd818 | |||
| 93997cd695 | |||
| 268f5d2837 | |||
| 5642a93974 | |||
| 85fe0cf87a | |||
| f4ea32862f | |||
| eaf1456771 | |||
| 9546881691 | |||
| 94ebbf3cba | |||
| 9e650aa203 | |||
| 7ce0705d41 | |||
| 106e429a3f | |||
| 05d12b347a | |||
| 7bf5f53afd | |||
| e4bb878648 | |||
| d724feaec0 | |||
| 9cb614bebd | |||
| 7d6269b2d3 | |||
| eae0ff2c1e | |||
| 093a3dda00 | |||
| 93ec202894 | |||
| a780467d87 | |||
| 0102b172f3 | |||
| 64111732fb | |||
| ffa62ee243 | |||
| bd9af562f2 | |||
| 59108bab27 | |||
| 6258ae83d0 | |||
| 9fa3ed704a | |||
| a76858d626 | |||
| 55a6b33110 | |||
| b87b94aade | |||
| 4110ed2c20 | |||
| 3cbc101eff | |||
| 221b821085 | |||
| 7331cfaa55 | |||
| 40d020ef67 | |||
| eea2a225e8 | |||
| 48f7f0fdbb | |||
| 99ed76f9bb | |||
| 7f21fa67ee | |||
| 8584709828 | |||
| d1f58e7482 | |||
| 1bd35aef6d | |||
| fdf1088564 | |||
| 7bb4d1f6a3 | |||
| b8c3d0d19d | |||
| a616a07553 | |||
| 781524f83e | |||
| c7a812c003 | |||
| 325f2c8cf9 | |||
| 562e2d0017 | |||
| b7871e8d33 | |||
| 060cffd8e7 | |||
| 4b1fb07cc9 | |||
| 0931d69188 | |||
| 7d33368ebd | |||
| c95fc5fcff | |||
| a7479f60c8 | |||
| ac75356778 | |||
| 7f32382dbc | |||
| b3c2def36d | |||
| 1ea93dfb9f | |||
| e5ffa70ed9 | |||
| 2a60b36e23 | |||
| c4c2c0ab0f | |||
| bf5628a646 | |||
| 13e9f0a5af | |||
| cdd5f2d250 | |||
| dfd7182008 | |||
| 533859808f | |||
| 15cea1dfc8 | |||
| dfa43d58f0 | |||
| 2bf239d8ea | |||
| cbe87cc378 |
@@ -1,4 +1,3 @@
|
||||
src
|
||||
test
|
||||
typings
|
||||
bundled
|
||||
|
||||
27
lerna.json
27
lerna.json
@@ -1,16 +1,17 @@
|
||||
{
|
||||
"version": "0.27.5",
|
||||
"useWorkspaces": true,
|
||||
"npmClient": "yarn",
|
||||
"packages": [
|
||||
"packages/*"
|
||||
],
|
||||
"command": {
|
||||
"run": {
|
||||
"stream": true
|
||||
"version": "0.16.3",
|
||||
"useWorkspaces": true,
|
||||
"npmClient": "yarn",
|
||||
"packages": [
|
||||
"packages/*"
|
||||
],
|
||||
"command": {
|
||||
"run": {
|
||||
"stream": true
|
||||
},
|
||||
"publish": {
|
||||
"access": "public",
|
||||
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
|
||||
}
|
||||
}
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
}
|
||||
}
|
||||
|
||||
12
package.json
12
package.json
@@ -9,19 +9,17 @@
|
||||
"bs": "lerna bootstrap",
|
||||
"clean": "lerna run clean",
|
||||
"watch": "lerna run watch --parallel",
|
||||
"build": "lerna run build",
|
||||
"build": "lerna run build --scope=\"@ccms/!(plugins)\"",
|
||||
"build:plugins": "lerna run build --scope=\"@ccms/plugins\"",
|
||||
"ug": "yarn upgrade-interactive --latest",
|
||||
"np": "./script/push.sh",
|
||||
"lsp": "npm login -scope=@ccms",
|
||||
"lp": "lerna publish --verify-access --force-publish",
|
||||
"lpb": "lerna publish --preid beta --dist-tag beta --verify-access --force-publish",
|
||||
"lpc": "lerna publish --canary --preid beta --pre-dist-tag beta --verify-access --force-publish",
|
||||
"lpf": "lerna publish from-package --yes"
|
||||
"lsp": "npm login --registry=https://registry.npmjs.org --scope=@ccms",
|
||||
"lp": "lerna publish --registry https://registry.npmjs.org"
|
||||
},
|
||||
"workspaces": [
|
||||
"packages/*"
|
||||
],
|
||||
"devDependencies": {
|
||||
"lerna": "^6.4.1"
|
||||
"lerna": "^4.0.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/amqp",
|
||||
"version": "0.27.5",
|
||||
"version": "0.16.2",
|
||||
"description": "MiaoScript amqp package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,17 +19,17 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.27.5",
|
||||
"@ccms/common": "^0.27.5",
|
||||
"@ccms/container": "^0.27.5"
|
||||
"@ccms/api": "^0.16.2",
|
||||
"@ccms/common": "^0.16.0",
|
||||
"@ccms/container": "^0.16.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.27.5",
|
||||
"@ccms/nashorn": "^0.16.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": "^4.1.2",
|
||||
"typescript": "^4.9.5"
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.3.5"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ export abstract class ChannelAwareMessageListenerAdapter<T = any> {
|
||||
if (message.getMessageProperties().getContentType() == MessageProperties.CONTENT_TYPE_JSON) {
|
||||
content = JSON.parse(content)
|
||||
}
|
||||
} catch (error: any) {
|
||||
} catch (error) {
|
||||
if (manual) {
|
||||
channel.basicReject(message.getMessageProperties().getDeliveryTag(), true)
|
||||
} else {
|
||||
@@ -42,7 +42,7 @@ export abstract class ChannelAwareMessageListenerAdapter<T = any> {
|
||||
} else {
|
||||
channel.basicNack(deliveryTag, false, true)
|
||||
}
|
||||
} catch (error: any) {
|
||||
} catch (error) {
|
||||
channel.basicReject(deliveryTag, this.onError(error, message, channel))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/api",
|
||||
"version": "0.27.5",
|
||||
"version": "0.16.2",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,16 +19,16 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/common": "^0.27.5",
|
||||
"@ccms/container": "^0.27.5",
|
||||
"@ccms/polyfill": "^0.27.5",
|
||||
"@ccms/common": "^0.16.0",
|
||||
"@ccms/container": "^0.16.0",
|
||||
"@ccms/polyfill": "^0.16.2",
|
||||
"base64-js": "^1.5.1",
|
||||
"source-map-builder": "^0.0.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/base64-js": "^1.3.0",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^4.1.2",
|
||||
"typescript": "^4.9.5"
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.3.5"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,37 +44,12 @@ export namespace command {
|
||||
protected setExecutor(plugin: plugin.Plugin, command: any, executor: 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
|
||||
})
|
||||
return executor(sender, command, Java.from(args))
|
||||
} catch (ex) {
|
||||
console.i18n("ms.api.command.execute.error", { player: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex })
|
||||
console.ex(ex)
|
||||
if (sender.name != 'CONSOLE') {
|
||||
console.sender(sender, [i18n.translate("ms.api.command.execute.error", {
|
||||
player: sender.name,
|
||||
plugin: plugin.description.name,
|
||||
command,
|
||||
args: Java.from(args).join(' '),
|
||||
ex
|
||||
}),
|
||||
...console.stack(ex)])
|
||||
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
|
||||
}
|
||||
@@ -83,42 +58,13 @@ export namespace command {
|
||||
protected setTabCompleter(plugin: plugin.Plugin, command: any, tabCompleter: Function) {
|
||||
return (sender: any, _: any, command: string, args: string[]) => {
|
||||
try {
|
||||
let time = Date.now()
|
||||
var token = args[args.length - 1]
|
||||
var complete = tabCompleter(sender, command, Java.from(args)) || []
|
||||
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
|
||||
})
|
||||
return this.copyPartialMatches(complete, token)
|
||||
} catch (ex) {
|
||||
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)
|
||||
])
|
||||
}
|
||||
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 []
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ import * as base64 from 'base64-js'
|
||||
const Arrays = Java.type('java.util.Arrays')
|
||||
const Level = Java.type('java.util.logging.Level')
|
||||
const Paths = Java.type('java.nio.file.Paths')
|
||||
const ignoreLogPrefix = ['java.', 'javax.', 'sun.', 'net.minecraft.', 'org.bukkit.', 'jdk.internal.dynalink.', 'jdk.nashorn.', 'org.openjdk.nashorn', 'io.netty.', 'org.spongepowered.', 'org.apache', 'org.springframework']
|
||||
const ignoreLogPrefix = ['java.', 'javax.', 'sun.', 'net.minecraft.', 'org.bukkit.', 'jdk.nashorn.', 'org.openjdk.nashorn', 'io.netty.', 'org.spongepowered.', 'org.apache', 'org.springframework']
|
||||
|
||||
enum LogLevel {
|
||||
ALL,
|
||||
@@ -18,114 +18,12 @@ 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)
|
||||
sourceFileMaps[fileName] = file.getCanonicalPath()
|
||||
} else if (global.debug) {
|
||||
console.debug('readSourceMap can\'t found', fileName, 'source map file', sourceMappingURL)
|
||||
}
|
||||
}
|
||||
if (sourceContent) {
|
||||
sourceMaps[fileName] = new SourceMapBuilder(JSON.parse(sourceContent))
|
||||
}
|
||||
}
|
||||
}
|
||||
if (sourceMaps[fileName]) {
|
||||
let sourceMapping = sourceMaps[fileName].getSource(lineNumber, 25, true, true)
|
||||
if (sourceMapping) {
|
||||
fileName = Paths.get(fileName, '..', sourceMapping.sourcePath).toFile().getCanonicalPath()
|
||||
lineNumber = sourceMapping.mapping.sourceLine
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.debug('search source map', fileName, 'line', lineNumber, 'error:', error)
|
||||
if (global.debug) {
|
||||
console.ex(error)
|
||||
}
|
||||
}
|
||||
return {
|
||||
fileName,
|
||||
lineNumber
|
||||
}
|
||||
}
|
||||
|
||||
export function getStackTrace(ex: Error, color: boolean = true): string[] {
|
||||
if (!ex) return []
|
||||
let stack = ex.getStackTrace()
|
||||
let cache = [(color ? '§c' : '') + ex]
|
||||
//@ts-ignore
|
||||
if (stack.class) {
|
||||
stack = Arrays.asList(stack)
|
||||
}
|
||||
stack.forEach(trace => {
|
||||
if (!trace.fileName || trace.fileName.startsWith('jar:file:') || trace.fileName.startsWith('file:')) { return }
|
||||
if (trace.className.startsWith('<')) {
|
||||
let { fileName, lineNumber } = readSourceMap(trace.fileName, trace.lineNumber)
|
||||
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
|
||||
if (color) {
|
||||
cache.push(` §e->§c ${fileName}:${lineNumber}(${trace.lineNumber}) => §4${trace.methodName}`)
|
||||
} else {
|
||||
cache.push(` -> ${fileName}:${lineNumber}(${trace.lineNumber}) => ${trace.methodName}`)
|
||||
}
|
||||
} else {
|
||||
let className = trace.className
|
||||
var fileName = trace.fileName as string
|
||||
var lineNumber = trace.lineNumber
|
||||
if (className.startsWith('jdk.nashorn.internal.scripts') || className.startsWith('org.openjdk.nashorn.internal.scripts')) {
|
||||
className = className.substr(className.lastIndexOf('$') + 1)
|
||||
var { fileName, lineNumber } = readSourceMap(fileName, lineNumber)
|
||||
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
|
||||
} else {
|
||||
if (!global.debug) {
|
||||
for (let prefix in ignoreLogPrefix) {
|
||||
if (className.startsWith(ignoreLogPrefix[prefix])) {
|
||||
return
|
||||
}
|
||||
}
|
||||
} else if (className.startsWith('jdk.nashorn.internal.') || className.startsWith('org.openjdk.nashorn.internal.')) {
|
||||
return
|
||||
}
|
||||
}
|
||||
if (color) {
|
||||
cache.push(` §e->§c ${className}.${trace.methodName}(§4${fileName}:${lineNumber}§c)`)
|
||||
} else {
|
||||
cache.push(` -> ${className}.${trace.methodName}(${fileName}:${lineNumber})`)
|
||||
}
|
||||
}
|
||||
})
|
||||
return cache
|
||||
}
|
||||
}
|
||||
|
||||
export class MiaoScriptConsole implements Console {
|
||||
Console: any
|
||||
memory: any
|
||||
|
||||
private static sourceMaps: { [key: string]: SourceMapBuilder } = {}
|
||||
private static sourceFileMaps: { [key: string]: string } = {}
|
||||
private _name: string = ''
|
||||
private _level: LogLevel = LogLevel.INFO
|
||||
|
||||
@@ -194,8 +92,91 @@ export class MiaoScriptConsole implements Console {
|
||||
ex(ex: Error) {
|
||||
this.stack(ex).forEach(line => this.console(line))
|
||||
}
|
||||
readSourceMap(fileName: string, lineNumber: any) {
|
||||
try {
|
||||
if (fileName.endsWith('js')) {
|
||||
if (MiaoScriptConsole.sourceMaps[fileName] === undefined) {
|
||||
MiaoScriptConsole.sourceMaps[fileName] = null
|
||||
let sourceLine = base.read(fileName).split('\n')
|
||||
let lastLine = sourceLine[sourceLine.length - 1]
|
||||
// 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')) {
|
||||
// TODO
|
||||
} else {
|
||||
let file = Paths.get(Paths.get(fileName, '..', sourceMappingURL).toFile().getCanonicalPath()).toFile()
|
||||
if (file.exists()) { sourceContent = base.read(file) }
|
||||
}
|
||||
if (sourceContent) {
|
||||
MiaoScriptConsole.sourceMaps[fileName] = new SourceMapBuilder(JSON.parse(sourceContent))
|
||||
MiaoScriptConsole.sourceFileMaps[fileName] = Paths.get(fileName, '..', MiaoScriptConsole.sourceMaps[fileName].sources[0]).toFile().getCanonicalPath()
|
||||
}
|
||||
}
|
||||
}
|
||||
if (MiaoScriptConsole.sourceMaps[fileName]) {
|
||||
let sourceMapping = MiaoScriptConsole.sourceMaps[fileName].getSource(lineNumber, 25, true, true)
|
||||
fileName = MiaoScriptConsole.sourceFileMaps[fileName]
|
||||
if (sourceMapping && lineNumber != sourceMapping.mapping.sourceLine) { lineNumber = sourceMapping.mapping.sourceLine }
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.debug('search source map', fileName, 'line', lineNumber, 'error:', error)
|
||||
if (global.debug) {
|
||||
console.ex(error)
|
||||
}
|
||||
}
|
||||
return {
|
||||
fileName,
|
||||
lineNumber
|
||||
}
|
||||
}
|
||||
stack(ex: Error, color: boolean = true): string[] {
|
||||
return jsconsole.getStackTrace(ex, color)
|
||||
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 } = this.readSourceMap(trace.fileName, trace.lineNumber)
|
||||
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
|
||||
if (color) {
|
||||
cache.push(` §e->§c ${fileName}:${lineNumber} => §4${trace.methodName}`)
|
||||
} else {
|
||||
cache.push(` -> ${fileName}:${lineNumber} => ${trace.methodName}`)
|
||||
}
|
||||
} else {
|
||||
let className = trace.className
|
||||
var fileName = trace.fileName as string
|
||||
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 } = this.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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (color) {
|
||||
cache.push(` §e->§c ${className}.${trace.methodName}(§4${fileName}:${lineNumber}§c)`)
|
||||
} else {
|
||||
cache.push(` -> ${className}.${trace.methodName}(${fileName}:${lineNumber})`)
|
||||
}
|
||||
}
|
||||
})
|
||||
return cache
|
||||
}
|
||||
assert(value: any, message?: string, ...optionalParams: any[]): void {
|
||||
throw new Error("Method not implemented.")
|
||||
|
||||
@@ -11,21 +11,10 @@ export namespace constants {
|
||||
}
|
||||
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'
|
||||
]
|
||||
getServerConnection: [/*spigot 1.8.8*/'aq',/*spigot 1.12.2*/ 'an', /*spigot 1.14.4+*/'getServerConnection', /*catserver 1.12.2*/'func_147137_ag']
|
||||
}
|
||||
export const Field = {
|
||||
listeningChannels: [
|
||||
/*spigot 1.8.8-1.12.2*/'g',
|
||||
/*spigot 1.14.4*/'f',
|
||||
/*spigot 1.15.2+*/'listeningChannels',
|
||||
/*catserver 1.12.2*/'field_151274_e'
|
||||
]
|
||||
listeningChannels: [/*spigot 1.8.8-1.12.2*/'g', /*spigot 1.14.4*/'f', /*spigot 1.15.2+*/'listeningChannels', /*catserver 1.12.2*/'field_151274_e']
|
||||
}
|
||||
}
|
||||
export enum ServerType {
|
||||
|
||||
@@ -1,56 +1,5 @@
|
||||
import { injectable } from "@ccms/container"
|
||||
|
||||
export namespace database {
|
||||
export const DataSource = Symbol("DataSource")
|
||||
/**
|
||||
* 数据库配置
|
||||
*/
|
||||
export interface DataBaseConfig {
|
||||
/**
|
||||
* 数据库类型
|
||||
*/
|
||||
type: 'h2' | 'mysql' | 'mongodb' | 'sqlite' | 'postgres' | 'redis'
|
||||
/**
|
||||
* 数据库连接串
|
||||
*/
|
||||
url: string | javax.sql.DataSource
|
||||
/**
|
||||
* 数据库驱动
|
||||
*/
|
||||
driverClassName?: string
|
||||
/**
|
||||
* 用户名
|
||||
*/
|
||||
username?: string
|
||||
/**
|
||||
* 密码
|
||||
*/
|
||||
password?: string
|
||||
/**
|
||||
* 链接属性
|
||||
*/
|
||||
properties?: { [key: string]: any }
|
||||
/**
|
||||
* 调试模式
|
||||
*/
|
||||
debug?: boolean
|
||||
}
|
||||
|
||||
@injectable()
|
||||
export abstract class DataBaseManager {
|
||||
abstract setMainDatabase(mainDatabase: DataBase): void
|
||||
abstract getMainDatabase(): DataBase
|
||||
abstract createDatabase(name: string, config: DataBaseConfig): DataBase
|
||||
abstract removeDatabase(name: string): boolean
|
||||
abstract getDatabase(name: string): DataBase
|
||||
abstract startWebManager(...args: string[])
|
||||
abstract stopWebManager()
|
||||
abstract shutdown()
|
||||
}
|
||||
@injectable()
|
||||
export abstract class DataBase {
|
||||
abstract query<T>(sql: string, ...args: any[]): Array<T>
|
||||
abstract update(sql: string, ...args: any[]): number
|
||||
abstract execute(sql: string): void
|
||||
}
|
||||
export const DataBaseManager = Symbol("DataBaseManager");
|
||||
export const DataSource = Symbol("DataSource");
|
||||
export const DataBase = Symbol("DataBase");
|
||||
}
|
||||
|
||||
@@ -26,7 +26,6 @@ export namespace event {
|
||||
|
||||
private mapEvent = [];
|
||||
private listenerMap = [];
|
||||
private cacheSlowEventKey = {};
|
||||
|
||||
protected baseEventDir = '';
|
||||
|
||||
@@ -58,7 +57,7 @@ export namespace event {
|
||||
this.mapEvent[simpleName] = clazz
|
||||
count++
|
||||
}
|
||||
} catch (ex: any) {
|
||||
} catch (ex) {
|
||||
//ignore already loaded class
|
||||
}
|
||||
}
|
||||
@@ -83,9 +82,9 @@ export namespace event {
|
||||
let eventCls = this.mapEvent[event.toLowerCase()] || this.mapEvent[event.toLowerCase() + 'event']
|
||||
if (!eventCls) {
|
||||
try {
|
||||
eventCls = base.getClass(event)
|
||||
eventCls = base.getClass(eventCls)
|
||||
this.mapEvent[event] = eventCls
|
||||
} catch (ex: any) {
|
||||
} catch (ex) {
|
||||
console.i18n("ms.api.event.not.found", { name, event })
|
||||
return
|
||||
}
|
||||
@@ -93,25 +92,19 @@ export namespace event {
|
||||
return eventCls
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建命令执行器
|
||||
* @param name 插件名称
|
||||
* @param exec 执行方法
|
||||
* @param eventCls 事件类
|
||||
* @returns
|
||||
*/
|
||||
createExecute(name, exec, eventCls) {
|
||||
execute(name, exec, eventCls) {
|
||||
return (...args: any[]) => {
|
||||
let event = args[args.length - 1]
|
||||
try {
|
||||
if (!eventCls.isAssignableFrom(event.getClass())) { return }
|
||||
let time = Date.now(); exec(event); let cost = Date.now() - time
|
||||
if (cost > global.ScriptSlowExecuteTime && !event.async) {
|
||||
let eventKey = `${name}-${this.class2Name(eventCls)}`
|
||||
if (!this.cacheSlowEventKey[eventKey]) { return this.cacheSlowEventKey[eventKey] = cost }
|
||||
console.i18n("ms.api.event.execute.slow", { name, event: this.class2Name(eventCls), cost })
|
||||
let event = args[args.length - 1]
|
||||
if (eventCls.isAssignableFrom(event.getClass())) {
|
||||
let time = Date.now()
|
||||
exec(event)
|
||||
let cost = Date.now() - time
|
||||
if (cost > 20) {
|
||||
console.i18n("ms.api.event.execute.slow", { name, event: this.class2Name(eventCls), cost })
|
||||
}
|
||||
}
|
||||
} catch (ex: any) {
|
||||
} catch (ex) {
|
||||
console.i18n("ms.api.event.execute.error", { name, event: this.class2Name(eventCls), ex })
|
||||
console.ex(ex)
|
||||
}
|
||||
@@ -120,11 +113,11 @@ export namespace event {
|
||||
|
||||
/**
|
||||
* 添加事件监听
|
||||
* @param plugin {any} 插件
|
||||
* @param event {string} 事件名称
|
||||
* @param exec {function} 事件执行器
|
||||
* @param priority {string} [LOWEST,LOW,NORMAL,HIGH,HIGHEST,MONITOR] 优先级
|
||||
* @param ignoreCancel 是否忽略已取消事件
|
||||
* @param plugin {any}
|
||||
* @param event {string}
|
||||
* @param exec {function}
|
||||
* @param priority {string} [LOWEST,LOW,NORMAL,HIGH,HIGHEST,MONITOR]
|
||||
* @param ignoreCancel
|
||||
*/
|
||||
listen(plugin: any, event: string, exec: (event: any) => void, priority: EventPriority = EventPriority.NORMAL, ignoreCancel = false) {
|
||||
if (!plugin || !plugin.description || !plugin.description.name) throw new TypeError(i18n.translate("ms.api.event.listen.plugin.name.empty"))
|
||||
@@ -140,12 +133,7 @@ export namespace event {
|
||||
// @ts-ignore
|
||||
let executor = exec.name || exec.executor || '[anonymous]'
|
||||
// noinspection JSUnusedGlobalSymbols
|
||||
var listener = this.register(
|
||||
eventCls,
|
||||
this.createExecute(name, exec, eventCls),
|
||||
priority,
|
||||
ignoreCancel
|
||||
)
|
||||
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] = []
|
||||
@@ -153,21 +141,11 @@ export namespace event {
|
||||
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
|
||||
}))
|
||||
console.debug(i18n.translate("ms.api.event.unregister", { name, event: this.class2Name(eventCls), exec: executor }))
|
||||
}
|
||||
listenerMap[name].push(off)
|
||||
// noinspection JSUnresolvedVariable
|
||||
console.debug(i18n.translate("ms.api.event.register", {
|
||||
name,
|
||||
event: this.class2Name(eventCls),
|
||||
exec: executor,
|
||||
priority,
|
||||
ignore: ignoreCancel
|
||||
}))
|
||||
console.debug(i18n.translate("ms.api.event.register", { name, event: this.class2Name(eventCls), exec: executor }))
|
||||
return off
|
||||
}
|
||||
|
||||
@@ -178,7 +156,7 @@ export namespace event {
|
||||
disable(plugin: any) {
|
||||
var eventCache = this.listenerMap[plugin.description.name]
|
||||
if (eventCache) {
|
||||
eventCache.forEach((off: () => any) => off())
|
||||
eventCache.forEach(off => off())
|
||||
delete this.listenerMap[plugin.description.name]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,13 +4,11 @@ export * from './web'
|
||||
export * from './amqp'
|
||||
export * from './chat'
|
||||
export * from './task'
|
||||
export * from './item'
|
||||
export * from './event'
|
||||
export * from './proxy'
|
||||
export * from './plugin'
|
||||
export * from './server'
|
||||
export * from './console'
|
||||
export { jsconsole as console } from './console'
|
||||
export * from './channel'
|
||||
export * from './command'
|
||||
export * from './database'
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -23,11 +23,6 @@ export namespace particle {
|
||||
private extra: number = 0;
|
||||
private data: Object = null;
|
||||
|
||||
/**
|
||||
* Only Show To Player
|
||||
*/
|
||||
private player: any
|
||||
|
||||
constructor() {
|
||||
this.uuid = UUID.randomUUID().toString()
|
||||
}
|
||||
@@ -110,15 +105,6 @@ export namespace particle {
|
||||
return this
|
||||
}
|
||||
|
||||
getPlayer() {
|
||||
return this.player
|
||||
}
|
||||
|
||||
setPlayer(player) {
|
||||
this.player = player
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过给定一个坐标就可以使用已经指定的参数来播放粒子
|
||||
*
|
||||
@@ -126,14 +112,9 @@ export namespace particle {
|
||||
*/
|
||||
spawn(location: any) {
|
||||
if (!this.spawner) throw new Error(`particle ${this.uuid} not set spawner can't spawn!`)
|
||||
if (this.player) {
|
||||
this.spawner.spawnToPlayer(this.player, location, this)
|
||||
} else {
|
||||
this.spawner.spawn(location, this)
|
||||
}
|
||||
this.spawner.spawn(location, this)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 表示一条线
|
||||
*
|
||||
@@ -177,7 +158,8 @@ export namespace particle {
|
||||
|
||||
show() {
|
||||
for (let i = 0; i < this.length; i += this.step) {
|
||||
this.spawn(this.start.clone().add(this.vector.clone().multiply(i)))
|
||||
let vectorTemp = this.vector.clone().multiply(i)
|
||||
this.spawn(this.start.clone().add(vectorTemp))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -252,6 +234,15 @@ export namespace particle {
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 表示一个弧
|
||||
@@ -340,10 +331,9 @@ export namespace particle {
|
||||
|
||||
@injectable()
|
||||
export abstract class ParticleManager {
|
||||
public static globalSpawner: ParticleSpawner = undefined
|
||||
@Autowired()
|
||||
private taskManager: task.TaskManager
|
||||
@Autowired()
|
||||
private particleSpawner: particle.ParticleSpawner
|
||||
|
||||
protected taskId: java.util.concurrent.atomic.AtomicInteger
|
||||
protected cacheTasks = new Map<string, ParticleTask>()
|
||||
@@ -364,10 +354,6 @@ export namespace particle {
|
||||
return this.taskManager
|
||||
}
|
||||
|
||||
public getParticleSpawner() {
|
||||
return this.particleSpawner
|
||||
}
|
||||
|
||||
public create(particle: Particle, plugin?: plugin.Plugin) {
|
||||
let uuid = particle.getUUID()
|
||||
if (this.cacheTasks.has(uuid)) {
|
||||
@@ -403,12 +389,14 @@ export namespace particle {
|
||||
}
|
||||
}
|
||||
protected create0(owner: plugin.Plugin, particle: Particle): ParticleTask {
|
||||
particle.setSpawner(this.getParticleSpawner())
|
||||
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
|
||||
@@ -479,7 +467,7 @@ export namespace particle {
|
||||
console.warn(`ParticleTask ${this.taskId} particle ${this.particle.getUUID()} cancel because entity and location both undefined!`)
|
||||
this.task.cancel()
|
||||
}
|
||||
} catch (error: any) {
|
||||
} catch (error) {
|
||||
console.error(`§6插件 §a${this.owner.description.name} §c播放粒子发送异常 §4粒子播放任务已终止!`)
|
||||
console.ex(error)
|
||||
this.cancel()
|
||||
@@ -499,9 +487,8 @@ export namespace particle {
|
||||
}
|
||||
}
|
||||
|
||||
@injectable()
|
||||
export abstract class ParticleSpawner {
|
||||
abstract spawnParticle(location: any, particle: any, count: number)
|
||||
abstract spawn(location: any, particle: Particle)
|
||||
abstract spawnToPlayer(player: any, location: any, particle: Particle)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ export namespace plugin {
|
||||
export abstract class PluginManager {
|
||||
abstract scan(folder: string): void
|
||||
abstract build(): void
|
||||
abstract loadFromFile(file: string, ext?: any): Plugin
|
||||
abstract loadFromFile(file: string, scanner?: plugin.PluginScanner): Plugin
|
||||
abstract load(...args: any[]): void
|
||||
abstract enable(...args: any[]): void
|
||||
abstract disable(...args: any[]): void
|
||||
@@ -149,19 +149,7 @@ export namespace plugin {
|
||||
/**
|
||||
* 插件名称 不填默认为类名
|
||||
*/
|
||||
name: string
|
||||
/**
|
||||
* 插件中文名称
|
||||
*/
|
||||
cname?: string
|
||||
/**
|
||||
* 付费插件ID
|
||||
*/
|
||||
pid?: number
|
||||
/**
|
||||
* 付费插件等级 付费插件自动注入
|
||||
*/
|
||||
level?: number
|
||||
name?: string
|
||||
/**
|
||||
* 前缀
|
||||
*/
|
||||
|
||||
@@ -29,7 +29,6 @@ export namespace server {
|
||||
origin: any
|
||||
[key: string]: any
|
||||
}
|
||||
|
||||
@injectable()
|
||||
export abstract class NativePluginManager {
|
||||
list(): NativePlugin[] {
|
||||
@@ -41,20 +40,19 @@ export namespace server {
|
||||
get(name: string): NativePlugin {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
enable(name: string): NativePlugin {
|
||||
load(name: string): boolean {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
disable(name: string): NativePlugin {
|
||||
unload(name: string): boolean {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
reload(name: string): NativePlugin {
|
||||
reload(name: string): boolean {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
delete(name: string): boolean {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* MiaoScript Server
|
||||
*/
|
||||
@@ -75,12 +73,6 @@ export namespace server {
|
||||
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.")
|
||||
}
|
||||
@@ -100,7 +92,6 @@ export namespace server {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
}
|
||||
|
||||
@injectable()
|
||||
export class ServerChecker {
|
||||
@Autowired(ServerType)
|
||||
@@ -119,22 +110,6 @@ export namespace server {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@injectable()
|
||||
export class NativePluginChecker {
|
||||
@Autowired(NativePluginManager)
|
||||
private nativePluginManager: NativePluginManager
|
||||
|
||||
check(plugins: string[]) {
|
||||
// Not set plugins -> allow
|
||||
if (!plugins || !plugins.length) return true
|
||||
for (const plugin of plugins) {
|
||||
if (!this.nativePluginManager.has(plugin)) { return false }
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
@injectable()
|
||||
export abstract class ReflectServer extends server.Server {
|
||||
@Autowired(ContainerInstance)
|
||||
@@ -153,7 +128,7 @@ export namespace server {
|
||||
let consoleServer = this.getDedicatedServer()
|
||||
this.reflectPipeline(consoleServer)
|
||||
this.reflectRootLogger(consoleServer)
|
||||
} catch (error: any) {
|
||||
} catch (error) {
|
||||
console.error('Error When Reflect MinecraftServer!', error)
|
||||
console.ex(error)
|
||||
}
|
||||
@@ -167,7 +142,7 @@ export namespace server {
|
||||
if (connection.class.name.indexOf('ServerConnection') !== -1
|
||||
|| connection.class.name.indexOf('NetworkSystem') !== -1) { break }
|
||||
connection = undefined
|
||||
} catch (error: any) {
|
||||
} catch (error) {
|
||||
if (global.debug) {
|
||||
console.ex(error)
|
||||
}
|
||||
@@ -179,7 +154,7 @@ export namespace server {
|
||||
promise = reflect.on(connection).get(field).get().get(0)
|
||||
if (promise.class.name.indexOf('Promise') !== -1) { break }
|
||||
promise = undefined
|
||||
} catch (error: any) {
|
||||
} catch (error) {
|
||||
if (global.debug) {
|
||||
console.ex(error)
|
||||
}
|
||||
@@ -191,24 +166,14 @@ export namespace server {
|
||||
}
|
||||
protected reflectRootLogger(consoleServer: any) {
|
||||
try {
|
||||
this.rootLogger = reflect.on(consoleServer).get('LOGGER').get()
|
||||
} catch (error: any) {
|
||||
this.rootLogger = reflect.on(consoleServer).get('LOGGER').get().parent
|
||||
} catch (error) {
|
||||
if (global.debug) {
|
||||
console.ex(error)
|
||||
}
|
||||
try {
|
||||
this.rootLogger = reflect.on(consoleServer).get(0).get()
|
||||
} catch (error: any) {
|
||||
if (global.debug) {
|
||||
console.ex(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (this.rootLogger.class.name.indexOf('slf4j') !== -1) {
|
||||
try {
|
||||
let LogManager = Java.type('org.apache.logging.log4j.LogManager')
|
||||
this.rootLogger = LogManager.getLogger('ROOT')
|
||||
} catch (error: any) {
|
||||
this.rootLogger = reflect.on(consoleServer).get(0).get().parent
|
||||
} catch (error) {
|
||||
if (global.debug) {
|
||||
console.ex(error)
|
||||
}
|
||||
@@ -218,11 +183,11 @@ export namespace server {
|
||||
console.error('Error Logger Class: ' + this.rootLogger.class.name)
|
||||
this.rootLogger = undefined
|
||||
}
|
||||
if (!this.rootLogger) { console.error("Can't found rootLogger!") }
|
||||
// get root logger
|
||||
for (let index = 0; index < 5 && this.rootLogger.parent; index++) {
|
||||
this.rootLogger = this.rootLogger.parent
|
||||
}
|
||||
if (!this.rootLogger) { console.error("Can't found rootLogger!") }
|
||||
this.container.bind(constants.ServiceIdentifier.RootLogger).toConstantValue(this.rootLogger)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ export namespace task {
|
||||
this.cacheTasks.delete(taskId)
|
||||
let ownerName = task.getOwner()?.description.name
|
||||
if (ownerName && this.pluginCacheTasks.has(ownerName)) {
|
||||
this.pluginCacheTasks.get(ownerName)?.delete(taskId)
|
||||
this.pluginCacheTasks.get(ownerName).delete(taskId)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -142,7 +142,7 @@ export namespace task {
|
||||
try {
|
||||
this.func(...args)
|
||||
!this.interval && process.emit('task.finish', this)
|
||||
} catch (ex: any) {
|
||||
} catch (ex) {
|
||||
console.console('§4插件执行任务时发生错误', ex)
|
||||
console.ex(ex)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/bukkit",
|
||||
"version": "0.27.5",
|
||||
"version": "0.16.2",
|
||||
"description": "MiaoScript bukkit package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -21,12 +21,12 @@
|
||||
"devDependencies": {
|
||||
"@javatypes/spigot-api": "^0.0.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^4.1.2",
|
||||
"typescript": "^4.9.5"
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.3.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.27.5",
|
||||
"@ccms/common": "^0.27.5",
|
||||
"@ccms/container": "^0.27.5"
|
||||
"@ccms/api": "^0.16.2",
|
||||
"@ccms/common": "^0.16.0",
|
||||
"@ccms/container": "^0.16.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { channel, plugin } from '@ccms/api'
|
||||
import { inject, provideSingleton } from '@ccms/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()
|
||||
|
||||
@@ -32,7 +32,7 @@ export class BukkitChannel extends channel.Channel {
|
||||
onPluginMessageReceived: (/**String */ channel, /**Player */ player, /**byte[] */data) => {
|
||||
try {
|
||||
listener(data, { channel, player, data })
|
||||
} catch (error: any) {
|
||||
} catch (error) {
|
||||
console.ex(error)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
import { chat } from '@ccms/api'
|
||||
import { provideSingleton } from '@ccms/container'
|
||||
import bukkitChat from './internal/chat'
|
||||
import bukkitChat from './enhance/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)
|
||||
}
|
||||
@@ -19,7 +16,7 @@ export class BukkitChat extends chat.Chat {
|
||||
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) {
|
||||
} catch (error) {
|
||||
sender.sendTitle(title, subtitle)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,38 +1,35 @@
|
||||
import '@ccms/nashorn'
|
||||
|
||||
import { command, plugin } from '@ccms/api'
|
||||
import { provideSingleton, postConstruct, inject } from '@ccms/container'
|
||||
import * as reflect from '@ccms/common/dist/reflect'
|
||||
import { provideSingleton, postConstruct, inject } from '@ccms/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
|
||||
|
||||
@postConstruct()
|
||||
init() {
|
||||
this.commandMap = reflect.on(Bukkit.getPluginManager()).get('commandMap').get()
|
||||
this.knownCommands = reflect.on(this.commandMap).get('knownCommands').get()
|
||||
}
|
||||
create(plugin: any, command: string) {
|
||||
var cmd = this.commandMap.getCommand(command)
|
||||
if (cmd instanceof PluginCommand) { 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) {
|
||||
if (cmd && cmd instanceof PluginCommand) {
|
||||
cmd.unregister(this.commandMap)
|
||||
this.knownCommands.remove(command)
|
||||
}
|
||||
}
|
||||
tabComplete(sender: any, input: string, index?: number): string[] {
|
||||
|
||||
@@ -1,20 +1,20 @@
|
||||
import { MiaoScriptConsole } from '@ccms/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(' '));
|
||||
}
|
||||
}
|
||||
|
||||
132
packages/bukkit/src/enhance/chat.ts
Normal file
132
packages/bukkit/src/enhance/chat.ts
Normal file
@@ -0,0 +1,132 @@
|
||||
/*global Java, base, module, exports, require*/
|
||||
let ChatSerializer: any
|
||||
let nmsChatSerializerMethodName: string
|
||||
let PacketPlayOutChat: any
|
||||
let chatMessageTypes: any
|
||||
|
||||
let RemapUtils: any
|
||||
|
||||
let playerConnectionFieldName: string
|
||||
let sendPacketMethodName: string
|
||||
|
||||
let above_1_16 = false
|
||||
let downgrade = false
|
||||
/**
|
||||
* 获取NMS版本
|
||||
*/
|
||||
let nmsVersion = undefined
|
||||
let nmsSubVersion = undefined
|
||||
/**
|
||||
* 获取NMS类
|
||||
*/
|
||||
function nmsCls(name: string) {
|
||||
return base.getClass(['net.minecraft.server', nmsVersion, name].join('.'))
|
||||
}
|
||||
|
||||
function remapMethod(clazz: any, origin: string, test: string, params: any) {
|
||||
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() {
|
||||
//@ts-ignore
|
||||
nmsVersion = org.bukkit.Bukkit.server.class.name.split('.')[3]
|
||||
nmsSubVersion = nmsVersion.split("_")[1]
|
||||
try {
|
||||
RemapUtils = Java.type('catserver.server.remapper.RemapUtils')
|
||||
} catch (ex) {
|
||||
}
|
||||
let nmsChatSerializerClass = undefined
|
||||
if (nmsSubVersion < 8) {
|
||||
nmsChatSerializerClass = nmsCls("ChatSerializer")
|
||||
} else if (nmsSubVersion < 17) {
|
||||
nmsChatSerializerClass = nmsCls("IChatBaseComponent$ChatSerializer")
|
||||
} else {
|
||||
nmsChatSerializerClass = base.getClass('net.minecraft.network.chat.IChatBaseComponent$ChatSerializer')
|
||||
}
|
||||
let nmsChatSerializerMethod = remapMethod(nmsChatSerializerClass, 'a', 'func_150699_a', base.getClass('java.lang.String'))
|
||||
nmsChatSerializerMethodName = nmsChatSerializerMethod.getName()
|
||||
ChatSerializer = Java.type(nmsChatSerializerClass.getName())
|
||||
let packetTypeClass = nmsSubVersion < 17 ? nmsCls("PacketPlayOutChat") : base.getClass('net.minecraft.network.protocol.game.PacketPlayOutChat')
|
||||
PacketPlayOutChat = Java.type(packetTypeClass.getName())
|
||||
let packetTypeConstructor: { parameterTypes: any[] }
|
||||
let constructors = packetTypeClass.constructors
|
||||
Java.from(constructors).forEach(function (c) {
|
||||
if (c.parameterTypes.length === 2) {
|
||||
packetTypeConstructor = c
|
||||
}
|
||||
if (c.parameterTypes.length === 3) {
|
||||
packetTypeConstructor = c
|
||||
above_1_16 = true
|
||||
}
|
||||
})
|
||||
let parameterTypes = packetTypeConstructor.parameterTypes
|
||||
let nmsChatMessageTypeClass = parameterTypes[1]
|
||||
if (nmsChatMessageTypeClass.isEnum()) {
|
||||
chatMessageTypes = nmsChatMessageTypeClass.getEnumConstants()
|
||||
}
|
||||
let playerConnectionField = undefined
|
||||
if (nmsSubVersion < 17) {
|
||||
playerConnectionField = remapFieldName(nmsCls('EntityPlayer'), 'playerConnection', 'field_71135_a')
|
||||
} else {
|
||||
playerConnectionField = base.getClass('net.minecraft.server.level.EntityPlayer').getField('b')
|
||||
}
|
||||
playerConnectionFieldName = playerConnectionField.getName()
|
||||
sendPacketMethodName = remapMethod(playerConnectionField.getType(), 'sendPacket', 'func_179290_a', nmsSubVersion < 17 ? nmsCls('Packet') : base.getClass('net.minecraft.network.protocol.Packet')).getName()
|
||||
}
|
||||
|
||||
function json(sender: { name: string }, json: string) {
|
||||
if (downgrade) {
|
||||
return '/tellraw ' + sender.name + ' ' + json
|
||||
} else {
|
||||
send(sender, json, 0)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function send(sender: any, json: any, type: number) {
|
||||
let packet
|
||||
if (above_1_16) {
|
||||
packet = new PacketPlayOutChat(ChatSerializer[nmsChatSerializerMethodName](json), chatMessageTypes == null ? type : chatMessageTypes[type], sender.getUniqueId())
|
||||
} else {
|
||||
packet = new PacketPlayOutChat(ChatSerializer[nmsChatSerializerMethodName](json), chatMessageTypes == null ? type : chatMessageTypes[type])
|
||||
}
|
||||
sendPacket(sender, packet)
|
||||
}
|
||||
|
||||
function sendPacket(player: { handle: { [x: string]: { [x: string]: (arg0: any) => void } } }, p: any) {
|
||||
player.handle[playerConnectionFieldName][sendPacketMethodName](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,
|
||||
send
|
||||
}
|
||||
|
||||
export default chat
|
||||
@@ -1,14 +1,13 @@
|
||||
import { event, plugin } from '@ccms/api'
|
||||
import { inject, provideSingleton } from '@ccms/container'
|
||||
import { inject, provideSingleton } from '@ccms/container';
|
||||
import * as reflect from '@ccms/common/dist/reflect'
|
||||
|
||||
const 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', Bukkit.class.classLoader)
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ import { server } from '@ccms/api'
|
||||
import { Container } from '@ccms/container'
|
||||
|
||||
import { BukkitConsole } from './console'
|
||||
import './item'
|
||||
import './chat'
|
||||
import './task'
|
||||
import './event'
|
||||
|
||||
@@ -1,206 +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
|
||||
} else if (nmsChatMessageTypeClass.getName() == 'int') {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
let playerConnectionField = this.getPlayerConnectionField()
|
||||
this.playerConnectionFieldName = playerConnectionField.getName()
|
||||
this.sendPacketMethodName = this.getSendPacketMethodName(playerConnectionField.getType())
|
||||
} catch (ex: any) {
|
||||
org.bukkit.Bukkit.getConsoleSender().sendMessage(`§6[§cMS§6][§bbukkit§6][§achat§6] §cNMS Inject Error §4${ex} §cDowngrade to Command Mode...`)
|
||||
this.downgrade = true
|
||||
}
|
||||
}
|
||||
|
||||
abstract getNmsChatSerializerClass()
|
||||
abstract getNmsChatSerializerMethodName(nmsChatSerializerClass: any)
|
||||
abstract getPacketPlayOutChatClass()
|
||||
abstract getPacketPlayOutChat(sender: any, json: any, type: number)
|
||||
abstract getPlayerConnectionField()
|
||||
abstract getPacketClass()
|
||||
abstract getSendPacketMethodName(playerConnectionClass: any)
|
||||
|
||||
nmsCls(name: string) {
|
||||
return base.getClass(['net.minecraft.server', this.nmsVersion, name].join('.'))
|
||||
}
|
||||
|
||||
remapMethod(clazz: any, origin: string, test: string, params: any) {
|
||||
try {
|
||||
return clazz.getMethod(origin, params)
|
||||
} catch (ex: any) {
|
||||
if (this.RemapUtils) {
|
||||
return clazz.getMethod(this.RemapUtils.mapMethod(clazz, origin, params), params)
|
||||
} else {
|
||||
return clazz.getMethod(test, params)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
remapFieldName(clazz: any, origin: string, test: string) {
|
||||
try {
|
||||
return clazz.getField(origin)
|
||||
} catch (ex: any) {
|
||||
if (this.RemapUtils) {
|
||||
return clazz.getField(this.RemapUtils.mapFieldName(clazz, origin))
|
||||
} else {
|
||||
return clazz.getField(test)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
json(sender: any, json: string) {
|
||||
if (this.downgrade) {
|
||||
return sender.spigot().sendMessage(this.ComponentSerializer.parse(json))
|
||||
} else {
|
||||
this.send(sender, json, 0)
|
||||
return false
|
||||
}
|
||||
}
|
||||
send(sender: any, json: any, type: number) {
|
||||
this.sendPacket(sender, this.getPacketPlayOutChat(sender, json, type))
|
||||
}
|
||||
sendPacket(player: { handle: { [x: string]: { [x: string]: (arg0: any) => void } } }, p: any) {
|
||||
player.handle[this.playerConnectionFieldName][this.sendPacketMethodName](p)
|
||||
}
|
||||
}
|
||||
|
||||
class BukkitChatInvokeBase extends BukkitChatInvoke {
|
||||
getSendPacketMethodName(playerConnectionClass: any) {
|
||||
return this.remapMethod(playerConnectionClass, 'sendPacket', 'func_179290_a', this.getPacketClass()).getName()
|
||||
}
|
||||
getNmsChatSerializerMethodName(nmsChatSerializerClass: any) {
|
||||
let nmsChatSerializerMethod = this.remapMethod(nmsChatSerializerClass, 'a', 'func_150699_a', base.getClass('java.lang.String'))
|
||||
return nmsChatSerializerMethod.getName()
|
||||
}
|
||||
getPacketPlayOutChat(sender: any, json: any, type: number) {
|
||||
return new this.PacketPlayOutChat(this.ChatSerializer[this.nmsChatSerializerMethodName](json), type)
|
||||
}
|
||||
getNmsChatSerializerClass() {
|
||||
return this.nmsCls("ChatSerializer")
|
||||
}
|
||||
getPacketPlayOutChatClass() {
|
||||
return this.nmsCls("PacketPlayOutChat")
|
||||
}
|
||||
getPlayerConnectionField() {
|
||||
return this.remapFieldName(this.nmsCls('EntityPlayer'), 'playerConnection', 'field_71135_a')
|
||||
}
|
||||
getPacketClass() {
|
||||
return this.nmsCls('Packet')
|
||||
}
|
||||
}
|
||||
|
||||
class BukkitChatInvoke_1_7_10 extends BukkitChatInvokeBase {
|
||||
}
|
||||
|
||||
class BukkitChatInvoke_1_8 extends BukkitChatInvoke_1_7_10 {
|
||||
getPacketPlayOutChat(sender: any, json: any, type: number) {
|
||||
return new this.PacketPlayOutChat(this.ChatSerializer[this.nmsChatSerializerMethodName](json), this.chatMessageTypes[type])
|
||||
}
|
||||
getNmsChatSerializerClass() {
|
||||
return this.nmsCls("IChatBaseComponent$ChatSerializer")
|
||||
}
|
||||
}
|
||||
class BukkitChatInvoke_1_16_5 extends BukkitChatInvoke_1_8 {
|
||||
getPacketPlayOutChat(sender: any, json: any, type: number) {
|
||||
return new this.PacketPlayOutChat(this.ChatSerializer[this.nmsChatSerializerMethodName](json), this.chatMessageTypes[type], sender.getUniqueId())
|
||||
}
|
||||
}
|
||||
|
||||
class BukkitChatInvoke_1_17_1 extends BukkitChatInvoke_1_16_5 {
|
||||
getPacketPlayOutChatClass() {
|
||||
return base.getClass('net.minecraft.network.protocol.game.PacketPlayOutChat')
|
||||
}
|
||||
getNmsChatSerializerClass() {
|
||||
return base.getClass('net.minecraft.network.chat.IChatBaseComponent$ChatSerializer')
|
||||
}
|
||||
getPlayerConnectionField() {
|
||||
return base.getClass('net.minecraft.server.level.EntityPlayer').getField('b')
|
||||
}
|
||||
getPacketClass() {
|
||||
return base.getClass('net.minecraft.network.protocol.Packet')
|
||||
}
|
||||
}
|
||||
class BukkitChatInvoke_1_18_2 extends BukkitChatInvoke_1_17_1 {
|
||||
getSendPacketMethodName(playerConnectionClass: any) {
|
||||
return playerConnectionClass.getMethod('a', this.getPacketClass()).getName()
|
||||
}
|
||||
}
|
||||
class BukkitChatInvoke_1_19 extends BukkitChatInvoke_1_18_2 {
|
||||
getPacketPlayOutChatClass() {
|
||||
return base.getClass('net.minecraft.network.protocol.game.ClientboundSystemChatPacket')
|
||||
}
|
||||
getPacketPlayOutChat(sender: any, json: any, type: number) {
|
||||
return new this.PacketPlayOutChat(this.ChatSerializer[this.nmsChatSerializerMethodName](json), type)
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
let Bukkit: typeof org.bukkit.Bukkit = Java.type('org.bukkit.Bukkit')
|
||||
// @ts-ignore
|
||||
let nmsVersion = Bukkit.getServer().class.name.split('.')[3]
|
||||
let nmsSubVersion = nmsVersion.split("_")[1]
|
||||
if (nmsSubVersion >= 19) {
|
||||
bukkitChatInvoke = new BukkitChatInvoke_1_19(nmsVersion)
|
||||
} else if (nmsSubVersion >= 18) {
|
||||
bukkitChatInvoke = new BukkitChatInvoke_1_18_2(nmsVersion)
|
||||
} else if (nmsSubVersion >= 17) {
|
||||
bukkitChatInvoke = new BukkitChatInvoke_1_17_1(nmsVersion)
|
||||
} else if (nmsSubVersion >= 16) {
|
||||
bukkitChatInvoke = new BukkitChatInvoke_1_16_5(nmsVersion)
|
||||
} else if (nmsSubVersion >= 8) {
|
||||
bukkitChatInvoke = new BukkitChatInvoke_1_8(nmsVersion)
|
||||
} else {
|
||||
bukkitChatInvoke = new BukkitChatInvoke_1_7_10(nmsVersion)
|
||||
}
|
||||
bukkitChatInvoke.init()
|
||||
} catch (ex: any) {
|
||||
}
|
||||
|
||||
let chat = {
|
||||
invoke: bukkitChatInvoke,
|
||||
json: bukkitChatInvoke.json.bind(bukkitChatInvoke),
|
||||
send: bukkitChatInvoke.send.bind(bukkitChatInvoke)
|
||||
}
|
||||
|
||||
export default chat
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,128 +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 nmsItemStack: any
|
||||
private mpParseMethodName: any
|
||||
private nmsVersion: any
|
||||
constructor() {
|
||||
super()
|
||||
this.reflect()
|
||||
}
|
||||
builder(): item.ItemBuilder {
|
||||
return new BukkitItemBuilder()
|
||||
}
|
||||
toJson(item: any): string {
|
||||
let nbt = new this.NBTTagCompound()
|
||||
return this.CraftItemStack.asNMSCopy(item)[this.nmsSaveNBTMethodName](nbt).toString()
|
||||
}
|
||||
fromJson(json: string) {
|
||||
return this.CraftItemStack.asBukkitCopy(new this.nmsItemStack(this.MojangsonParser[this.mpParseMethodName](json)))
|
||||
}
|
||||
private obcCls(name: string) {
|
||||
return base.getClass(['org.bukkit.craftbukkit', this.nmsVersion, name].join('.'))
|
||||
}
|
||||
private nmsCls(name: string) {
|
||||
return base.getClass(['net.minecraft.server', this.nmsVersion, name].join('.'))
|
||||
}
|
||||
private reflect() {
|
||||
try {
|
||||
let Bukkit: typeof org.bukkit.Bukkit = Java.type('org.bukkit.Bukkit')
|
||||
// @ts-ignore
|
||||
this.nmsVersion = Bukkit.getServer().class.name.split('.')[3]
|
||||
let CraftItemStackClass = this.obcCls('inventory.CraftItemStack')
|
||||
this.CraftItemStack = Java.type(CraftItemStackClass.getName())
|
||||
// @ts-ignore
|
||||
let asNMSCopyMethod = CraftItemStackClass.getMethod('asNMSCopy', ItemStack.class)
|
||||
let nmsItemStackClass = asNMSCopyMethod.getReturnType()
|
||||
this.nmsItemStack = Java.type(nmsItemStackClass.getName())
|
||||
let nmsNBTTagCompoundClass = undefined
|
||||
for (let method of Java.from(nmsItemStackClass.getMethods())) {
|
||||
let rt = method.getReturnType()
|
||||
if (method.getParameterTypes().length == 0 && "NBTTagCompound" == rt.getSimpleName()) {
|
||||
nmsNBTTagCompoundClass = rt
|
||||
}
|
||||
}
|
||||
this.NBTTagCompound = Java.type(nmsNBTTagCompoundClass.getName())
|
||||
for (let method of Java.from(nmsItemStackClass.getMethods())) {
|
||||
let params = method.getParameterTypes()
|
||||
let rt = method.getReturnType()
|
||||
if (params.length == 1 && "NBTTagCompound" == params[0].getSimpleName() && "NBTTagCompound" == rt.getSimpleName()) {
|
||||
this.nmsSaveNBTMethodName = method.getName()
|
||||
break
|
||||
}
|
||||
}
|
||||
try {
|
||||
this.MojangsonParser = this.nmsCls('MojangsonParser').static
|
||||
} catch (error) {
|
||||
this.MojangsonParser = Java.type('net.minecraft.nbt.MojangsonParser')
|
||||
}
|
||||
for (let method of Java.from(this.MojangsonParser.class.getMethods())) {
|
||||
let params = method.getParameterTypes()
|
||||
let rt = method.getReturnType()
|
||||
if (params.length == 1 && "String" == params[0].getSimpleName() && "NBTTagCompound" == rt.getSimpleName()) {
|
||||
this.mpParseMethodName = method.getName()
|
||||
}
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.log('Bukkit 物品管理器初始化失败:', error)
|
||||
if (global.debug) {
|
||||
console.ex(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class BukkitItemBuilder implements item.ItemBuilder {
|
||||
private itemStack: org.bukkit.inventory.ItemStack
|
||||
private itemMeta: org.bukkit.inventory.meta.ItemMeta
|
||||
|
||||
from(itemStack: any): item.ItemBuilder {
|
||||
this.itemStack = itemStack
|
||||
this.itemMeta = this.itemStack.getItemMeta()
|
||||
return this
|
||||
}
|
||||
create(type: string | number): item.ItemBuilder {
|
||||
let material = undefined
|
||||
if (typeof type == 'number') {
|
||||
type = itemIds[type]
|
||||
}
|
||||
material = Material[type] || Material[Material['LEGACY_PREFIX'] + type]
|
||||
this.itemStack = new ItemStack(material)
|
||||
this.itemMeta = this.itemStack.getItemMeta()
|
||||
return this
|
||||
}
|
||||
name(name: string): item.ItemBuilder {
|
||||
this.itemMeta.setDisplayName(name)
|
||||
return this
|
||||
}
|
||||
lore(...lores: string[]): item.ItemBuilder {
|
||||
this.itemMeta.setLore(lores)
|
||||
return this
|
||||
}
|
||||
amount(amount: number): item.ItemBuilder {
|
||||
this.itemStack.setAmount(amount)
|
||||
return this
|
||||
}
|
||||
durability(durability: number): item.ItemBuilder {
|
||||
this.itemStack.setDurability(durability)
|
||||
return this
|
||||
}
|
||||
clone() {
|
||||
return this.build().clone()
|
||||
}
|
||||
build() {
|
||||
this.itemStack.setItemMeta(this.itemMeta)
|
||||
return this.itemStack
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,22 @@
|
||||
import { provideSingleton } from '@ccms/container'
|
||||
import { particle } from '@ccms/api'
|
||||
import { particle, plugin } 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
|
||||
}
|
||||
}
|
||||
|
||||
@provideSingleton(particle.ParticleSpawner)
|
||||
export class BukkitParticleSpawner extends particle.ParticleSpawner {
|
||||
spawn(location: org.bukkit.Location, particle: particle.Particle) {
|
||||
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,
|
||||
@@ -19,15 +28,4 @@ export class BukkitParticleSpawner extends particle.ParticleSpawner {
|
||||
particle.getData()
|
||||
)
|
||||
}
|
||||
spawnToPlayer(player: org.bukkit.entity.Player, location: org.bukkit.Location, particle: particle.Particle) {
|
||||
player.spawnParticle(
|
||||
particle.getParticle(),
|
||||
location,
|
||||
particle.getCount(),
|
||||
particle.getOffsetX(),
|
||||
particle.getOffsetY(),
|
||||
particle.getOffsetZ(),
|
||||
particle.getExtra(),
|
||||
particle.getData())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,22 +19,6 @@ export class BukkitNativePluginManager extends server.NativePluginManager {
|
||||
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
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { server } from '@ccms/api'
|
||||
import { server, constants } from '@ccms/api'
|
||||
import { provideSingleton } from '@ccms/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 {
|
||||
@@ -29,12 +30,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)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { task, plugin } from '@ccms/api'
|
||||
import { provideSingleton } from '@ccms/container'
|
||||
import { inject, provideSingleton } from '@ccms/container'
|
||||
|
||||
const Bukkit = Java.type('org.bukkit.Bukkit')
|
||||
const BukkitRunnable = Java.type('org.bukkit.scheduler.BukkitRunnable')
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"baseUrl": "src",
|
||||
"outDir": "dist",
|
||||
"resolveJsonModule": true
|
||||
"outDir": "dist"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/bungee",
|
||||
"version": "0.27.5",
|
||||
"version": "0.16.2",
|
||||
"description": "MiaoScript bungee package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -21,12 +21,12 @@
|
||||
"devDependencies": {
|
||||
"@javatypes/bungee-api": "^0.0.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^4.1.2",
|
||||
"typescript": "^4.9.5"
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.3.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.27.5",
|
||||
"@ccms/common": "^0.27.5",
|
||||
"@ccms/container": "^0.27.5"
|
||||
"@ccms/api": "^0.16.2",
|
||||
"@ccms/common": "^0.16.0",
|
||||
"@ccms/container": "^0.16.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -26,7 +26,7 @@ export class BungeeServer implements server.Server {
|
||||
// @ts-ignore
|
||||
this.pipeline = reflect.on(base.getInstance().getProxy()).get('listeners').get().toArray()[0].pipeline()
|
||||
wait.cancel()
|
||||
} catch (ex: any) {
|
||||
} catch (ex) {
|
||||
count++
|
||||
if (count > 50) {
|
||||
console.error('Reflect BungeeCord netty channel pipeline error time > 50times. Err: ' + ex)
|
||||
@@ -38,7 +38,7 @@ export class BungeeServer implements server.Server {
|
||||
}).later(10).timer(20).submit()
|
||||
try {
|
||||
this.rootLogger = Bungee.getLogger()
|
||||
} catch (error: any) {
|
||||
} catch (error) {
|
||||
console.error("Can't found rootLogger!")
|
||||
}
|
||||
}
|
||||
@@ -58,12 +58,6 @@ export class BungeeServer implements server.Server {
|
||||
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)
|
||||
}
|
||||
dispatchCommand(sender: string | any, command: string): boolean {
|
||||
if (typeof sender === 'string') {
|
||||
sender = this.getPlayer(sender)
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
{
|
||||
"name": "@ccms/qrcode",
|
||||
"version": "0.27.5",
|
||||
"description": "MiaoScript qrcode package",
|
||||
"private": true,
|
||||
"name": "@ccms/client",
|
||||
"version": "0.16.1",
|
||||
"description": "MiaoScript client package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
"minecraft",
|
||||
@@ -13,14 +14,19 @@
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"scripts": {
|
||||
"dev": "ts-node-dev --respawn --debounce=1500 src/index.ts",
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"start": "node dist/index.js",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"minecraft-protocol": "^1.25.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^4.1.2",
|
||||
"typescript": "^4.9.5"
|
||||
"@types/node": "^16.3.2",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.3.5"
|
||||
}
|
||||
}
|
||||
101
packages/client/src/color.ts
Normal file
101
packages/client/src/color.ts
Normal file
@@ -0,0 +1,101 @@
|
||||
class MessagePart {
|
||||
text: string
|
||||
color: string
|
||||
clickEvent: MessagePartEvent
|
||||
hoverEvent: MessagePartEvent
|
||||
translate: string
|
||||
with: MessagePart[]
|
||||
extra: MessagePart[]
|
||||
}
|
||||
|
||||
class MessagePartEvent {
|
||||
action: string
|
||||
value: string
|
||||
}
|
||||
|
||||
var colorMap = []
|
||||
colorMap['0'] = '38;5;0'
|
||||
colorMap['1'] = '38;5;4'
|
||||
colorMap['2'] = '38;5;2'
|
||||
colorMap['3'] = '38;5;6'
|
||||
colorMap['4'] = '38;5;1'
|
||||
colorMap['5'] = '38;5;5'
|
||||
colorMap['6'] = '38;5;3'
|
||||
colorMap['7'] = '38;5;7'
|
||||
colorMap['8'] = '38;5;8'
|
||||
colorMap['9'] = '38;5;12'
|
||||
colorMap['a'] = '38;5;10'
|
||||
colorMap['b'] = '38;5;14'
|
||||
colorMap['c'] = '38;5;9'
|
||||
colorMap['d'] = '38;5;13'
|
||||
colorMap['e'] = '38;5;11'
|
||||
colorMap['f'] = '38;5;15'
|
||||
colorMap['r'] = '0'
|
||||
colorMap['l'] = '1'
|
||||
colorMap['n'] = '4'
|
||||
var regexMap = []
|
||||
for (const c in colorMap) {
|
||||
regexMap[colorMap[c]] = new RegExp(`§${c}`, "g")
|
||||
}
|
||||
function mcColor2ANSI(str) {
|
||||
for (const regex in regexMap) {
|
||||
str = str.replace(regexMap[regex], `\u001b[${regex}m`)
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
let jsonColorMap = {
|
||||
"black": '0',
|
||||
"dark_blue": '1',
|
||||
"dark_green": '2',
|
||||
"dark_aqua": '3',
|
||||
"dark_red": '4',
|
||||
"dark_purple": '5',
|
||||
"gold": '6',
|
||||
"gray": '7',
|
||||
"dark_gray": '8',
|
||||
"blue": '9',
|
||||
"green": 'a',
|
||||
"aqua": 'b',
|
||||
"red": 'c',
|
||||
"light_purple": 'd',
|
||||
"yellow": 'e',
|
||||
"white": 'f',
|
||||
"obfuscated": 'k',
|
||||
"bold": 'l',
|
||||
"strikethrough": 'm',
|
||||
"underline": 'n',
|
||||
"italic": 'o',
|
||||
"reset": 'r',
|
||||
};
|
||||
|
||||
function json2text(json: MessagePart): string {
|
||||
let temp = "";
|
||||
if (json.color) {
|
||||
temp += `§${jsonColorMap[json.color]}`
|
||||
}
|
||||
temp += json.text || json.translate || ''
|
||||
if (json.extra) {
|
||||
json.extra.forEach((ext) => {
|
||||
temp += json2text(ext)
|
||||
})
|
||||
}
|
||||
return temp += '§r'
|
||||
}
|
||||
|
||||
function $(input: any) {
|
||||
if (typeof input === "string") {
|
||||
input = JSON.parse(input)
|
||||
}
|
||||
input = json2text(input) + '§r'
|
||||
if (input.startsWith('§卐')) {
|
||||
input = input.substring(2)
|
||||
}
|
||||
return mcColor2ANSI(input)
|
||||
}
|
||||
|
||||
export {
|
||||
json2text,
|
||||
mcColor2ANSI,
|
||||
$
|
||||
}
|
||||
33
packages/client/src/event.ts
Normal file
33
packages/client/src/event.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { $ } from './color'
|
||||
|
||||
export function attachEvents(client) {
|
||||
client.on('chat', (packet) => {
|
||||
// Listen for chat messages and echo them back.
|
||||
var jsonMsg = JSON.parse(packet.message)
|
||||
console.log($(jsonMsg))
|
||||
})
|
||||
client.on('state', (newState, oldState) => {
|
||||
console.log('Client Change State', oldState, 'to', newState)
|
||||
let targetServer = process.argv[6]
|
||||
if (newState == "play" && targetServer) {
|
||||
setTimeout(() => {
|
||||
client.write('chat', {
|
||||
message: '/server ' + targetServer
|
||||
})
|
||||
}, 3000)
|
||||
}
|
||||
})
|
||||
client.on('update_health', (packet) => {
|
||||
if (packet.health <= 0) {
|
||||
console.log("Player Dead Auto Respawn...")
|
||||
client.write('client_command', { payload: 0 })
|
||||
} else if (packet.health > 0) {
|
||||
}
|
||||
})
|
||||
client.on('kick_disconnect', (packet) => {
|
||||
console.log($(packet.reason))
|
||||
})
|
||||
client.on('disconnect', (packet) => {
|
||||
console.log($(packet.reason))
|
||||
})
|
||||
}
|
||||
14
packages/client/src/forge.ts
Normal file
14
packages/client/src/forge.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
export function attachForge(client) {
|
||||
client.on('custom_payload', function(packet) {
|
||||
if (packet.channel === 'FML|HS') {
|
||||
client.write('custom_payload', {
|
||||
channel: 'FML|HS',
|
||||
data: Buffer.of(0x01, 0x02)
|
||||
});
|
||||
client.write('custom_payload', {
|
||||
channel: 'FML|HS',
|
||||
data: Buffer.of(0x02, 0x00)
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
107
packages/client/src/index.ts
Normal file
107
packages/client/src/index.ts
Normal file
@@ -0,0 +1,107 @@
|
||||
import { createInterface } from 'readline'
|
||||
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()
|
||||
|
||||
function commandLineCreateClient() {
|
||||
return createConnection(address, port, username, password)
|
||||
}
|
||||
|
||||
function createConnection(host: string, port: number, username: string, password: string) {
|
||||
let clientOptions: any = {
|
||||
version,
|
||||
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)
|
||||
|
||||
attachCommon(client)
|
||||
attachForge(client)
|
||||
attachEvents(client)
|
||||
return client
|
||||
}
|
||||
|
||||
function attachCommon(client) {
|
||||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const rl = createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stdout,
|
||||
completer: (line, func) => {
|
||||
let args = line.split(' ')
|
||||
let comp = args[args.length - 1]
|
||||
client.once('tab_complete', (msg) => {
|
||||
let mcts = msg.matches.filter(s => s)
|
||||
func(null, [mcts, comp])
|
||||
})
|
||||
client.write('tab_complete', {
|
||||
text: line
|
||||
})
|
||||
},
|
||||
terminal: true,
|
||||
prompt: ''
|
||||
})
|
||||
|
||||
rl.on('line', function (line) {
|
||||
switch (line) {
|
||||
case "":
|
||||
break
|
||||
case "eval":
|
||||
break
|
||||
case "write":
|
||||
break
|
||||
case "/respawn":
|
||||
client.write('client_command', { payload: 0 })
|
||||
break
|
||||
case "//reco":
|
||||
client.end("")
|
||||
client = commandLineCreateClient()
|
||||
break
|
||||
case "//quit":
|
||||
console.info('Disconnected')
|
||||
client.end("")
|
||||
break
|
||||
case "//end":
|
||||
console.info('Forcibly ended client')
|
||||
process.exit(0)
|
||||
default:
|
||||
client.write('chat', { message: line })
|
||||
}
|
||||
rl.prompt()
|
||||
})
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@ccms/common",
|
||||
"version": "0.27.5",
|
||||
"description": "MiaoScript common package",
|
||||
"version": "0.16.0",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
"minecraft",
|
||||
@@ -19,11 +19,11 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.27.5",
|
||||
"@ccms/nashorn": "^0.16.0",
|
||||
"@javatypes/jdk": "^0.0.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^4.1.2",
|
||||
"typescript": "^4.9.5"
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.3.5"
|
||||
},
|
||||
"gitHead": "562e2d00175c9d3a99c8b672aa07e6d92706a027"
|
||||
}
|
||||
|
||||
@@ -19,20 +19,12 @@ interface RequestConfig {
|
||||
method?: Method
|
||||
headers?: { [key: string]: string }
|
||||
params?: { [key: string]: string }
|
||||
data?: any,
|
||||
connectTimeout?: number,
|
||||
readTimeout?: number,
|
||||
data?: any
|
||||
}
|
||||
|
||||
function request(config: RequestConfig) {
|
||||
// @ts-ignore XMLHttpRequest class only exist nashorn polyfill
|
||||
let xhr = new XMLHttpRequest()
|
||||
if (config.connectTimeout) {
|
||||
xhr.connectTimeout = config.connectTimeout
|
||||
}
|
||||
if (config.readTimeout) {
|
||||
xhr.readTimeout = config.readTimeout
|
||||
}
|
||||
xhr.open(config.method, config.url, false)
|
||||
for (const header in config.headers) {
|
||||
xhr.setRequestHeader(header, config.headers[header])
|
||||
|
||||
@@ -48,13 +48,12 @@ class Reflect {
|
||||
try {
|
||||
// Try getting a public field
|
||||
field = this.class.getField(nameOrIndex)
|
||||
} catch (ex: any) {
|
||||
} catch (ex) {
|
||||
// Try again, getting a non-public field
|
||||
field = declaredField(this.class, nameOrIndex)
|
||||
}
|
||||
}
|
||||
if (!field) throw new Error(`can't reflect field ${typeof nameOrIndex == "number" ? 'index' : 'name'} ${nameOrIndex} from ${this.class.getName()}!`)
|
||||
fieldCache.set(key, field)
|
||||
return accessible(field)
|
||||
}
|
||||
|
||||
@@ -114,10 +113,10 @@ function declaredConstructor(clazz, param) {
|
||||
let constructor
|
||||
try {
|
||||
constructor = clazz.getDeclaredConstructor(types(param))
|
||||
} catch (ex: any) {
|
||||
} catch (ex) {
|
||||
try {
|
||||
constructor = clazz.getDeclaredConstructor(types(param, true))
|
||||
} catch (ex: any) {
|
||||
} catch (ex) {
|
||||
constructor = clazz.getDeclaredConstructors()[0]
|
||||
}
|
||||
}
|
||||
@@ -130,14 +129,12 @@ function declaredField(clazz: java.lang.Class<any>, name: string | java.lang.Str
|
||||
let field = null
|
||||
// noinspection JSUnresolvedVariable
|
||||
while (target !== JavaObject.class) {
|
||||
console.debug(`reflect field ${name} from ${target.getName()}`)
|
||||
try {
|
||||
field = target.getDeclaredField(name)
|
||||
if (field !== null) { break }
|
||||
} catch (error: any) {
|
||||
} catch (e) {
|
||||
if (target === undefined) { break }
|
||||
target = target.getSuperclass()
|
||||
console.debug(`切换到超类: ${target.getName()}`)
|
||||
}
|
||||
}
|
||||
if (field === null) {
|
||||
@@ -149,32 +146,21 @@ function declaredField(clazz: java.lang.Class<any>, name: string | java.lang.Str
|
||||
function declaredMethod(clazz: java.lang.Class<any>, nameOrIndex: string | number, ...clazzs: java.lang.Class<any>[]): java.lang.reflect.Method {
|
||||
let key = clazz.getName() + '.' + nameOrIndex + ':' + (clazzs || []).map(c => c.getName()).join(':')
|
||||
if (methodCache.has(key)) { return methodCache.get(key) }
|
||||
let target = clazz
|
||||
if (typeof nameOrIndex === "number") {
|
||||
methodCache.set(key, declaredMethods(clazz)[nameOrIndex])
|
||||
} else {
|
||||
while (target !== JavaObject.class && !methodCache.has(key)) {
|
||||
try {
|
||||
methodCache.set(key, clazz.getMethod(nameOrIndex, clazzs as any))
|
||||
} 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.set(key, clazz.getDeclaredMethod(nameOrIndex, clazzs as any))
|
||||
} catch (ex) {
|
||||
for (const m of Java.from(declaredMethods(clazz))) {
|
||||
if (m.getName() == nameOrIndex) {
|
||||
methodCache.set(key, m)
|
||||
break
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (target === undefined) { break }
|
||||
target = target.getSuperclass()
|
||||
console.debug(`切换到超类: ${target.getName()}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/compile",
|
||||
"version": "0.27.5",
|
||||
"version": "0.16.0",
|
||||
"description": "MiaoScript compile package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -20,7 +20,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^4.1.2",
|
||||
"typescript": "^4.9.5"
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.3.5"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/container",
|
||||
"version": "0.27.5",
|
||||
"version": "0.16.0",
|
||||
"description": "MiaoScript container package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,13 +19,13 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.27.5",
|
||||
"@ccms/nashorn": "^0.16.0",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^4.1.2",
|
||||
"typescript": "^4.9.5"
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.3.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"inversify": "^6.0.1",
|
||||
"inversify": "^5.1.1",
|
||||
"inversify-binding-decorators": "^4.0.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,38 @@
|
||||
import { interfaces, Container } from "inversify"
|
||||
import { _proxyGetter } from "./utils"
|
||||
|
||||
let _container: Container
|
||||
|
||||
const ContainerInstance = Symbol.for("@ccms/ioc:Container")
|
||||
const INJECTION = Symbol.for("INJECTION")
|
||||
|
||||
function _proxyGetter(
|
||||
proto: any,
|
||||
key: string,
|
||||
resolve: () => any,
|
||||
doCache: boolean
|
||||
) {
|
||||
function getter(this: object) {
|
||||
if (doCache && !Reflect.hasMetadata(INJECTION, this, key)) {
|
||||
Reflect.defineMetadata(INJECTION, resolve(), this, key)
|
||||
}
|
||||
if (Reflect.hasMetadata(INJECTION, this, key)) {
|
||||
return Reflect.getMetadata(INJECTION, this, key)
|
||||
} else {
|
||||
return resolve()
|
||||
}
|
||||
}
|
||||
|
||||
function setter(this: object, newVal: any) {
|
||||
Reflect.defineMetadata(INJECTION, newVal, this, key)
|
||||
}
|
||||
|
||||
Object.defineProperty(proto, key, {
|
||||
configurable: true,
|
||||
enumerable: true,
|
||||
get: getter,
|
||||
set: setter
|
||||
})
|
||||
}
|
||||
|
||||
function initContainer(container: Container) {
|
||||
Reflect.defineMetadata(ContainerInstance, container, Reflect)
|
||||
|
||||
@@ -5,7 +5,6 @@ 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"
|
||||
|
||||
/**
|
||||
* 注册一个命名对象
|
||||
@@ -38,8 +37,8 @@ export const provideSingletonNamed = (identifier: interfaces.ServiceIdentifier<a
|
||||
*/
|
||||
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) { }
|
||||
try { target[propertyKey] = Java.type(className).class; return } catch (error) { }
|
||||
try { target[propertyKey] = base.getClass(className); return } catch (error) { }
|
||||
console.warn('JavaClass', className, 'Inject target', target.constructor.name, 'propertyKey', propertyKey, 'failed!')
|
||||
}
|
||||
}
|
||||
@@ -50,11 +49,9 @@ export const JavaClass = (className: string) => {
|
||||
*/
|
||||
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)
|
||||
try { target[propertyKey] = Java.type(className); return } catch (error) { }
|
||||
try { target[propertyKey] = base.getClass(className).static; return } catch (error) { }
|
||||
console.warn('JSClass', className, 'Inject target', target.constructor.name, 'propertyKey', propertyKey, 'failed!')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -91,59 +88,6 @@ export const Resource = (resourceName?: string | any) => {
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
@@ -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
|
||||
})
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@ccms/core",
|
||||
"version": "0.27.5",
|
||||
"description": "MiaoScript core package",
|
||||
"version": "0.16.2",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
"minecraft",
|
||||
@@ -20,12 +20,12 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^4.1.2",
|
||||
"typescript": "^4.9.5"
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.3.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.27.5",
|
||||
"@ccms/container": "^0.27.5"
|
||||
"@ccms/api": "^0.16.2",
|
||||
"@ccms/container": "^0.16.0"
|
||||
},
|
||||
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
||||
}
|
||||
|
||||
1
packages/core/src/.gitignore
vendored
1
packages/core/src/.gitignore
vendored
@@ -1 +0,0 @@
|
||||
script
|
||||
@@ -1,15 +1,9 @@
|
||||
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 { plugin, server, task, constants } 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')
|
||||
const MiaoScriptAPI = Java.type('pw.yumc.MiaoScript.api.MiaoScriptAPI')
|
||||
|
||||
@provideSingleton(MiaoScriptCore)
|
||||
class MiaoScriptCore {
|
||||
@@ -23,31 +17,17 @@ class MiaoScriptCore {
|
||||
private pluginManager: plugin.PluginManager
|
||||
|
||||
enable() {
|
||||
process.emit('core.before.enable')
|
||||
this.loadServerConsole()
|
||||
try {
|
||||
MiaoScriptAPI.setPluginManager(this.pluginManager)
|
||||
} catch (error) {
|
||||
}
|
||||
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()
|
||||
}
|
||||
|
||||
loadServerConsole() {
|
||||
process.emit('core.before.load.console')
|
||||
//@ts-ignore
|
||||
global.setGlobal('console', new this.Console(), { writable: false, configurable: false })
|
||||
process.emit('core.after.load.console')
|
||||
}
|
||||
|
||||
loadPlugins() {
|
||||
process.emit('core.before.load.plugins')
|
||||
let loadPluginStartTime = new Date().getTime()
|
||||
console.i18n("ms.core.plugin.initialize")
|
||||
this.pluginManager.scan(this.pluginFolder)
|
||||
@@ -55,25 +35,15 @@ class MiaoScriptCore {
|
||||
this.pluginManager.load(this.pluginManager.getPlugins())
|
||||
this.pluginManager.enable(this.pluginManager.getPlugins())
|
||||
console.i18n("ms.core.plugin.completed", { time: (new Date().getTime() - loadPluginStartTime) / 1000 })
|
||||
process.emit('core.after.load.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')
|
||||
console.i18n("ms.core.engine.disable.finish", { version: 'v' + global.ScriptEngineVersion, time: (new Date().getTime() - disableStartTime) / 1000 })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,101 +51,56 @@ function detectServer(): constants.ServerType {
|
||||
try {
|
||||
Java.type("org.bukkit.Bukkit")
|
||||
return constants.ServerType.Bukkit
|
||||
} catch (ex: any) {
|
||||
} catch (ex) {
|
||||
}
|
||||
try {
|
||||
Java.type("org.spongepowered.api.Sponge")
|
||||
return constants.ServerType.Sponge
|
||||
} catch (ex: any) {
|
||||
} catch (ex) {
|
||||
}
|
||||
try {
|
||||
Java.type("cn.nukkit.Nukkit")
|
||||
return constants.ServerType.Nukkit
|
||||
} catch (ex: any) {
|
||||
} catch (ex) {
|
||||
}
|
||||
try {
|
||||
Java.type("net.md_5.bungee.api.ProxyServer")
|
||||
return constants.ServerType.Bungee
|
||||
} catch (ex: any) {
|
||||
} catch (ex) {
|
||||
}
|
||||
try {
|
||||
Java.type("org.springframework.boot.SpringApplication")
|
||||
return constants.ServerType.Spring
|
||||
} catch (ex: any) {
|
||||
} catch (ex) {
|
||||
}
|
||||
throw Error('Unknow Server Type...')
|
||||
}
|
||||
|
||||
function loadCoreScript(name) {
|
||||
try {
|
||||
let scriptname = name + (global.debug ? '-debug' : '')
|
||||
engineLoad({
|
||||
script: http.get(`https://mscript.yumc.pw/api/plugin/download/name/${scriptname}`),
|
||||
name: `core/${scriptname}.js`
|
||||
})
|
||||
} catch (error: any) {
|
||||
if (global.debug) {
|
||||
console.debug(error)
|
||||
console.ex(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function loadMiaoScriptConfig() {
|
||||
let configFile = fs.concat(root, 'config.yml')
|
||||
if (!fs.exists(configFile)) {
|
||||
global.ScriptEngineConfig = base.save(configFile, yaml.dump({
|
||||
uuid: UUID.randomUUID().toString(),
|
||||
slow_execute: 50
|
||||
}))
|
||||
} else {
|
||||
global.ScriptEngineConfig = yaml.load(base.read(configFile))
|
||||
}
|
||||
global.ScriptSlowExecuteTime = global.ScriptEngineConfig.slow_execute || 50
|
||||
}
|
||||
|
||||
function createCore() {
|
||||
let corePackageStartTime = new Date().getTime()
|
||||
container.bind(ContainerInstance).toConstantValue(container)
|
||||
container.bind(plugin.PluginInstance).toConstantValue(base.getInstance())
|
||||
container.bind(plugin.PluginFolder).toConstantValue('plugins')
|
||||
let type = detectServer()
|
||||
|
||||
process.emit('core.before.initialize.detect')
|
||||
console.i18n("ms.core.initialize.detect", { scope: global.scope, type })
|
||||
container.bind(server.ServerType).toConstantValue(type)
|
||||
container.bind(server.ServerChecker).toSelf().inSingletonScope()
|
||||
container.bind(server.NativePluginManager).toSelf().inSingletonScope()
|
||||
container.bind(server.NativePluginChecker).toSelf().inSingletonScope()
|
||||
process.emit('core.after.initialize.detect')
|
||||
|
||||
process.emit('core.before.package.initialize')
|
||||
console.i18n("ms.core.package.initialize", { scope: global.scope, type })
|
||||
require(`${global.scope}/${type}`).default(container)
|
||||
require(`${global.scope}/plugin`)
|
||||
container.load(buildProviderModule())
|
||||
console.i18n("ms.core.package.completed", { scope: global.scope, type, time: (Date.now() - corePackageStartTime) / 1000 })
|
||||
process.emit('core.after.package.initialize')
|
||||
return container.get<MiaoScriptCore>(MiaoScriptCore)
|
||||
}
|
||||
|
||||
function initialize() {
|
||||
process.emit('core.before.initialize')
|
||||
loadMiaoScriptConfig()
|
||||
global.ScriptEngineVersion = require('../package.json').version
|
||||
global.setGlobal('loadCoreScript', loadCoreScript)
|
||||
loadCoreScript('initialize')
|
||||
try { engineLoad({ script: http.get("http://ms.yumc.pw/api/plugin/download/name/initialize"), name: 'core/initialize.js' }) } catch (error) { console.debug(error) }
|
||||
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", { scope: global.scope, type })
|
||||
container.bind(server.ServerType).toConstantValue(type)
|
||||
container.bind(server.ServerChecker).toSelf().inSingletonScope()
|
||||
container.bind(server.NativePluginManager).toSelf().inSingletonScope()
|
||||
console.i18n("ms.core.package.initialize", { scope: global.scope, type })
|
||||
require(`${global.scope}/${type}`).default(container)
|
||||
require(`${global.scope}/plugin`)
|
||||
container.load(buildProviderModule())
|
||||
console.i18n("ms.core.package.completed", { scope: global.scope, type, time: (Date.now() - corePackageStartTime) / 1000 })
|
||||
let disable = container.get<MiaoScriptCore>(MiaoScriptCore).enable()
|
||||
console.i18n("ms.core.engine.completed", { version: 'v' + global.ScriptEngineVersion, time: (Date.now() - global.ScriptEngineStartTime) / 1000 })
|
||||
return disable
|
||||
} catch (error) {
|
||||
console.i18n("ms.core.initialize.error", { error })
|
||||
console.ex(error)
|
||||
return () => console.i18n('ms.core.engine.disable.abnormal')
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/database",
|
||||
"version": "0.27.5",
|
||||
"version": "0.16.2",
|
||||
"description": "MiaoScript database package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -21,11 +21,11 @@
|
||||
"devDependencies": {
|
||||
"@javatypes/spring-jdbc": "^0.0.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^4.1.2",
|
||||
"typescript": "^4.9.5"
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.3.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.27.5",
|
||||
"@ccms/container": "^0.27.5"
|
||||
"@ccms/api": "^0.16.2",
|
||||
"@ccms/container": "^0.16.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,109 +1,88 @@
|
||||
import { database } from '@ccms/api'
|
||||
import { JSClass } from '@ccms/container'
|
||||
import { Model } from './model'
|
||||
|
||||
const Thread = Java.type('java.lang.Thread')
|
||||
const JavaString = Java.type('java.lang.String')
|
||||
const Properties = Java.type('java.util.Properties')
|
||||
const HikariDataSource = Java.type('com.zaxxer.hikari.HikariDataSource')
|
||||
const HikariConfig = Java.type('com.zaxxer.hikari.HikariConfig')
|
||||
const JdbcTemplate = Java.type('org.springframework.jdbc.core.JdbcTemplate')
|
||||
|
||||
/**
|
||||
* 数据库配置
|
||||
*/
|
||||
export interface DataBaseConfig {
|
||||
/**
|
||||
* 数据库连接串
|
||||
*/
|
||||
url: string | javax.sql.DataSource
|
||||
/**
|
||||
* 数据库驱动
|
||||
*/
|
||||
driverClassName?: string
|
||||
/**
|
||||
* 用户名
|
||||
*/
|
||||
username?: string
|
||||
/**
|
||||
* 密码
|
||||
*/
|
||||
password?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 数据库封装类
|
||||
*/
|
||||
export class DataBase extends database.DataBase {
|
||||
export class DataBase {
|
||||
private dataSource: javax.sql.DataSource
|
||||
private jdbcTemplate: org.springframework.jdbc.core.JdbcTemplate
|
||||
|
||||
@JSClass('com.zaxxer.hikari.HikariDataSource')
|
||||
private HikariDataSource: any
|
||||
@JSClass('com.zaxxer.hikari.HikariConfig')
|
||||
private HikariConfig: any
|
||||
@JSClass('org.springframework.jdbc.core.JdbcTemplate')
|
||||
private JdbcTemplate: typeof org.springframework.jdbc.core.JdbcTemplate
|
||||
|
||||
constructor(dbConfig: database.DataBaseConfig) {
|
||||
super()
|
||||
constructor(dbConfig: DataBaseConfig) {
|
||||
if (!dbConfig.url) { throw new Error('DataBase url can\'t be null!') }
|
||||
this.createDataSource(dbConfig)
|
||||
this.initialize()
|
||||
}
|
||||
|
||||
private createDataSource(dbConfig: database.DataBaseConfig) {
|
||||
private createDataSource(dbConfig: DataBaseConfig) {
|
||||
if (typeof dbConfig.url === "string") {
|
||||
let originClassLoader = Thread.currentThread().getContextClassLoader()
|
||||
Thread.currentThread().setContextClassLoader(base.getInstance().class.classLoader)
|
||||
let config = new this.HikariConfig()
|
||||
if (!dbConfig.username || !dbConfig.password) {
|
||||
throw new Error('DataBase username or password can\'t be null!')
|
||||
}
|
||||
let config = new HikariConfig()
|
||||
if (dbConfig.driverClassName) {
|
||||
config.setDriverClassName(dbConfig.driverClassName)
|
||||
} else {
|
||||
switch (dbConfig.type) {
|
||||
case "h2":
|
||||
config.setDriverClassName("org.h2.Driver")
|
||||
break
|
||||
case "sqlite":
|
||||
config.setDriverClassName("org.sqlite.JDBC")
|
||||
break
|
||||
default:
|
||||
}
|
||||
}
|
||||
if (dbConfig.username) {
|
||||
config.setUsername(dbConfig.username)
|
||||
}
|
||||
if (dbConfig.password) {
|
||||
config.setPassword(dbConfig.password)
|
||||
}
|
||||
config.setUsername(dbConfig.username)
|
||||
config.setPassword(dbConfig.password)
|
||||
config.setJdbcUrl(dbConfig.url)
|
||||
if (dbConfig.properties) {
|
||||
let properties = new Properties()
|
||||
for (const key in dbConfig.properties) {
|
||||
properties.setProperty(key, dbConfig.properties[key])
|
||||
}
|
||||
config.setDataSourceProperties(properties)
|
||||
}
|
||||
console.debug('createDataSource from config ' + JSON.stringify(dbConfig))
|
||||
this.dataSource = new this.HikariDataSource(config)
|
||||
Thread.currentThread().setContextClassLoader(originClassLoader)
|
||||
this.dataSource = new HikariDataSource(config)
|
||||
} else {
|
||||
this.dataSource = dbConfig.url
|
||||
}
|
||||
this.jdbcTemplate = new this.JdbcTemplate(this.dataSource)
|
||||
}
|
||||
|
||||
getDataSource() {
|
||||
return this.dataSource
|
||||
private initialize() {
|
||||
this.jdbcTemplate = new JdbcTemplate(this.dataSource)
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行SQL查询
|
||||
* @param sql SQL语句
|
||||
* @param args 参数
|
||||
*/
|
||||
query<T>(sql: string, ...args: any[]): Array<T> {
|
||||
let startTime = Date.now()
|
||||
let result = Java.from<any>(this.jdbcTemplate.queryForList(sql, args))
|
||||
console.debug(JavaString.format(`\n[DB] query \nSQL : ${sql.replace(/\?/ig, '%s')} \nCOST : ${Date.now() - startTime}ms`, args))
|
||||
console.debug(java.lang.String.format(`\n[DB] query \nSQL : ${sql.replace(/\?/ig, '%s')} \nCOST : ${Date.now() - startTime}ms`, args))
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行SQL更新
|
||||
* @param sql SQL语句
|
||||
* @param args 参数
|
||||
*/
|
||||
update(sql: string, ...args: any[]): number {
|
||||
let startTime = Date.now()
|
||||
let result = this.jdbcTemplate.update(sql, args)
|
||||
console.debug(JavaString.format(`\n[DB] update \nSQL : ${sql.replace(/\?/ig, '%s')} \nCOST : ${Date.now() - startTime}ms`, args))
|
||||
console.debug(java.lang.String.format(`\n[DB] update \nSQL : ${sql.replace(/\?/ig, '%s')} \nCOST : ${Date.now() - startTime}ms`, args))
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行SQL语句
|
||||
* @param sql SQL语句
|
||||
*/
|
||||
execute(sql: string): void {
|
||||
let startTime = Date.now()
|
||||
this.jdbcTemplate.execute(sql)
|
||||
console.debug(`\n[DB] execute \nSQL : ${sql} \nCOST : ${Date.now() - startTime}ms`)
|
||||
}
|
||||
|
||||
close() {
|
||||
//@ts-ignore
|
||||
this.dataSource.close()
|
||||
|
||||
7
packages/database/src/decorators.ts
Normal file
7
packages/database/src/decorators.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import 'reflect-metadata'
|
||||
|
||||
export function id() {
|
||||
return (target: Object, propertyKey: string | symbol) => void {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,5 @@
|
||||
/// <reference types="@javatypes/jdk" />
|
||||
/// <reference types="@javatypes/spring-jdbc" />
|
||||
|
||||
import { loadMavenDepend } from '@ccms/container'
|
||||
|
||||
loadMavenDepend('com.h2database', 'h2', '2.1.212')
|
||||
loadMavenDepend("com.zaxxer", "HikariCP", "4.0.3")
|
||||
loadMavenDepend("org.springframework", "spring-jdbc", "5.3.19", true)
|
||||
|
||||
export * from './database'
|
||||
export * from './manager'
|
||||
export * from './manager'
|
||||
@@ -1,46 +1,27 @@
|
||||
import { database } from '@ccms/api'
|
||||
import { JSClass, provideSingleton } from '@ccms/container'
|
||||
import { DataBase } from './database'
|
||||
import { plugin, database } from '@ccms/api'
|
||||
import { provideSingleton, inject, postConstruct } from '@ccms/container'
|
||||
import { DataBase, DataBaseConfig } from './database'
|
||||
|
||||
@provideSingleton(database.DataBaseManager)
|
||||
export class DataBaseManager extends database.DataBaseManager {
|
||||
export class DataBaseManager {
|
||||
@inject(plugin.PluginInstance)
|
||||
private instance: any
|
||||
|
||||
private beanFactory: any
|
||||
private mainDatabase: DataBase
|
||||
private databases = new Map<string, DataBase>()
|
||||
private databases: { [key: string]: DataBase } = {}
|
||||
|
||||
@JSClass('org.h2.tools.Server')
|
||||
private Server: any
|
||||
|
||||
private webManager: any
|
||||
|
||||
constructor() {
|
||||
super()
|
||||
process.on('exit', () => this.shutdown())
|
||||
}
|
||||
|
||||
startWebManager(...args: string[]) {
|
||||
this.webManager = this.Server.createWebServer(args)
|
||||
this.webManager.start()
|
||||
}
|
||||
|
||||
stopWebManager() {
|
||||
if (this.webManager) {
|
||||
this.webManager.stop()
|
||||
this.webManager.shutdown()
|
||||
@postConstruct()
|
||||
initialize() {
|
||||
try {
|
||||
this.beanFactory = this.instance.getAutowireCapableBeanFactory()
|
||||
let mainDatasource = this.beanFactory.getBean(Packages.javax.sql.DataSource.class)
|
||||
this.mainDatabase = new DataBase({ url: mainDatasource })
|
||||
} catch (error) {
|
||||
console.ex(error)
|
||||
}
|
||||
}
|
||||
|
||||
shutdown() {
|
||||
this.stopWebManager()
|
||||
this.disable()
|
||||
}
|
||||
/**
|
||||
* 设置主数据库
|
||||
* @param mainDatabase 主数据库
|
||||
*/
|
||||
setMainDatabase(mainDatabase: DataBase) {
|
||||
this.mainDatabase = mainDatabase
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得主数据库
|
||||
* Get MainDatabase
|
||||
@@ -55,28 +36,18 @@ export class DataBaseManager extends database.DataBaseManager {
|
||||
* @param name 数据库名称 用于代码 database Name use at code
|
||||
* @param config 数据库配置
|
||||
*/
|
||||
createDatabase(name: string, config: database.DataBaseConfig) {
|
||||
return Java.synchronized(() => {
|
||||
if (!this.databases.has(name)) {
|
||||
this.databases.set(name, new DataBase(config))
|
||||
}
|
||||
return this.databases.get(name)
|
||||
createDatabase(name: string, config: DataBaseConfig) {
|
||||
Java.synchronized(() => {
|
||||
if (this.databases[name]) return this.databases[name]
|
||||
return this.databases[name] = new DataBase(config)
|
||||
}, this.databases)()
|
||||
}
|
||||
|
||||
removeDatabase(name: string) {
|
||||
if (this.databases.has(name)) {
|
||||
this.databases.get(name).close()
|
||||
}
|
||||
return this.databases.delete(name)
|
||||
}
|
||||
|
||||
getDatabase(name: string) {
|
||||
return this.databases.get(name)
|
||||
return this.databases[name]
|
||||
}
|
||||
|
||||
disable() {
|
||||
this.databases.forEach((db) => db.close())
|
||||
this.databases.clear()
|
||||
Object.values(this.databases).forEach((ds) => ds?.close())
|
||||
}
|
||||
}
|
||||
|
||||
11
packages/database/src/model.ts
Normal file
11
packages/database/src/model.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { DataBase } from "./database"
|
||||
|
||||
export class Model<T> {
|
||||
constructor(private database: DataBase) {
|
||||
|
||||
}
|
||||
queryForList(): Array<T> {
|
||||
|
||||
return []
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,6 @@ ms.core.plugin.initialize: "Initialization MiaoScript Plugin System. Please wait
|
||||
ms.core.plugin.completed: "MiaoScript Plugin System loading completed({time}s)!"
|
||||
ms.core.engine.completed: "MiaoScript ScriptEngine loading completed... Done({time}s)!"
|
||||
ms.core.engine.disable: "Disable MiaoScript Engine..."
|
||||
ms.core.engine.disable.finish: "MiaoScript framework {loader} engine {version} 关闭完成... 耗时({time}s)!"
|
||||
ms.core.engine.disable.abnormal: "abnormal Initialization MiaoScript Engine. Skip disable step..."
|
||||
|
||||
ms.api.event.resource.not.found: "Can't Mapping Event Because not found Resources {resource}!"
|
||||
@@ -22,20 +21,16 @@ ms.api.event.not.found: "§6Plugin §b{name} §6register {event} error. event no
|
||||
ms.api.event.execute.slow: "§cWARN! §6Plugin §b{name} §6execute §d{event} §6evnet §ccost §4{cost}ms !"
|
||||
ms.api.event.execute.error: "§6Plugin §b{name} §6execute §d{event} §6event error §4{ex}"
|
||||
ms.api.event.listen.plugin.name.empty: "Plugin name can't be empty!"
|
||||
ms.api.event.register: "[{name}] register event {event} priority {priority} ignoreCancelled {ignore}"
|
||||
ms.api.event.register: "[{name}] register event {event}"
|
||||
ms.api.event.unregister: "[{name}] unregister event {event}"
|
||||
|
||||
ms.api.command.register.input.error: "CommandExec Must be a function... Input: {exec}"
|
||||
ms.api.command.register: "[{plugin}] register command {name}({cmd})..."
|
||||
ms.api.command.unregister: "[{plugin}] unregister command {name}..."
|
||||
ms.api.command.execute.slow: "§cWarn. §6Player §a{player} §6exec §b{plugin} §6Plugin §d{command} {args} §6Command §cCost §4{cost}ms !"
|
||||
ms.api.command.execute.error: "§6Player {player} §6exec §b{plugin} §6Plugin Command §d{command} {args} §6error §4{ex}"
|
||||
ms.api.command.tab.completer.slow: "§cWarn. §6Player §a{player} §6exec §b{plugin} §6Plugin §d{command} {args} §6TabComplete §cCost §4{cost}ms !"
|
||||
ms.api.command.tab.completer.error: "§6Player {player} §6exec §b{plugin} §6Plugin TabComplete §d{command} {args} §6error §4{ex}"
|
||||
|
||||
ms.plugin.initialize: "Initialization MiaoScript Plugin System: Plugin: {plugin} Loader: {loader}..."
|
||||
ms.plugin.event.map: "Total {count} {type} Event Mapping Complate..."
|
||||
ms.plugin.event.map.error: "Mapping {type} Event Failed. Error: {error}"
|
||||
ms.plugin.manager.scan: "Scanner {scanner} Scanning Plugins in {folder} ..."
|
||||
ms.plugin.manager.scan.finish: "Scanner {scanner} Found {size} Plugins in {folder} Start Build..."
|
||||
ms.plugin.manager.initialize.error: "§6Plugin §b{name} §6initialize error §4{ex}"
|
||||
|
||||
@@ -10,9 +10,9 @@ ms.core.package.initialize: "初始化 MiaoScript 扩展 {scope}/core {scope}/{t
|
||||
ms.core.package.completed: "MiaoScript 扩展 {scope}/core {scope}/{type} {scope}/plugin 加载完成 耗时({time}s)"
|
||||
ms.core.plugin.initialize: "MiaoScript 开始引导插件系统. 请稍候..."
|
||||
ms.core.plugin.completed: "MiaoScript 插件加载完毕 耗时({time}s)!"
|
||||
ms.core.engine.completed: "MiaoScript 框架 {loader} 引擎 {version} 加载完毕... 耗时({time}s)!"
|
||||
ms.core.engine.completed: "MiaoScript 脚本引擎 {version} 加载完毕... 耗时({time}s)!"
|
||||
ms.core.engine.disable: "MiaoScript 关闭脚本引擎 请稍候..."
|
||||
ms.core.engine.disable.finish: "MiaoScript 框架 {loader} 引擎 {version} 关闭完成... 耗时({time}s)!"
|
||||
ms.core.engine.disable.finish: "MiaoScript 脚本引擎 {version} 关闭完成... 耗时({time}s)!"
|
||||
ms.core.engine.disable.abnormal: "引擎异常启动或初始化未完成 跳过关闭流程..."
|
||||
|
||||
ms.api.event.resource.not.found: "无法映射事件 未找到资源文件 {resource}!"
|
||||
@@ -22,22 +22,18 @@ ms.api.event.not.found: "§6插件 §b{name} §6注册事件 §c{event} §6失
|
||||
ms.api.event.execute.slow: "§c注意! §6插件 §b{name} §6处理 §d{event} §6事件 §c耗时 §4{cost}ms !"
|
||||
ms.api.event.execute.error: "§6插件 §b{name} §6处理 §d{event} §6事件时发生异常 §4{ex}"
|
||||
ms.api.event.listen.plugin.name.empty: "插件名称为空 请检查传入参数!"
|
||||
ms.api.event.register: "[{name}] 注册事件 {event} => 执行器 {exec} 优先级 {priority} 忽略取消 {ignore}"
|
||||
ms.api.event.register: "[{name}] 注册事件 {event} => 执行器 {exec}"
|
||||
ms.api.event.unregister: "[{name}] 注销事件 {event} => 执行器 {exec}"
|
||||
|
||||
ms.api.command.register.input.error: "CommandExec 必须为一个函数... 输入: {exec}"
|
||||
ms.api.command.register: "[{plugin}] 注册命令 {name}({cmd})..."
|
||||
ms.api.command.unregister: "[{plugin}] 注销命令 {name}..."
|
||||
ms.api.command.execute.slow: "§c注意! §6玩家 §a{player} §6执行 §b{plugin} §6插件 §d{command} {args} §6命令 §c耗时 §4{cost}ms !"
|
||||
ms.api.command.execute.error: "§6玩家 §a{player} §6执行 §b{plugin} §6插件 §d{command} {args} §6命令时发生异常 §4{ex}"
|
||||
ms.api.command.tab.completer.slow: "§c注意! §6玩家 §a{player} §6执行 §b{plugin} §6插件 §d{command} {args} §6补全 §c耗时 §4{cost}ms !"
|
||||
ms.api.command.tab.completer.error: "§6玩家 §a{player} §6执行 §b{plugin} §6插件 §d{command} {args} §6补全时发生异常 §4{ex}"
|
||||
|
||||
ms.plugin.initialize: "初始化 MiaoScript 插件系统: 实例: {plugin} 加载器: {loader}..."
|
||||
ms.plugin.event.map: "映射 {type} 事件 成功 总计 {count} 个 {type} 事件..."
|
||||
ms.plugin.event.map.error: "映射 {type} 事件 异常 将无法使用事件简称. Error: {error}"
|
||||
ms.plugin.event.map: "总计 {count} 个 {type} 事件 映射完成..."
|
||||
ms.plugin.manager.scan: "扫描器 {scanner} 扫描 {folder} 中的插件..."
|
||||
ms.plugin.manager.scan.finish: "扫描器 {scanner} 在 {folder} 中 发现 {size} 个插件 开始编译..."
|
||||
ms.plugin.manager.scan.finish: "扫描器 {scanner} 在 {folder} 中 发现 {size} 个插件 开始构建..."
|
||||
ms.plugin.manager.initialize.error: "§6插件 §b{name} §6初始化错误 §4{ex}"
|
||||
ms.plugin.manager.stage: "{stage} {plugin} 版本 {version} 作者 {author}"
|
||||
ms.plugin.manager.stage.exec: "[{plugin}] 执行 {stage} 阶段函数 {name} 匹配类型 {servers}..."
|
||||
@@ -45,7 +41,7 @@ ms.plugin.manager.stage.exec.error: "§6插件 §b{plugin} §6执行 §d{executo
|
||||
ms.plugin.manager.stage.load: "加载"
|
||||
ms.plugin.manager.stage.enable: "启用"
|
||||
ms.plugin.manager.stage.disable: "关闭"
|
||||
ms.plugin.manager.build: "插件 {name}({version}) 编译完成 来源: {file}({scanner}) 引导: {loader} 编译耗时: {cost}s."
|
||||
ms.plugin.manager.build: "插件 {name}({version}) 构建完成 来源: {file}({scanner}) 引导: {loader} 构建耗时: {cost}s."
|
||||
ms.plugin.manager.build.error: "§6从文件 §b{file} §6加载插件失败 §4错误: §c{error}"
|
||||
ms.plugin.manager.build.update: "自动更新插件 {name} ..."
|
||||
ms.plugin.manager.build.not.extends: "§4发现错误的插件 §b{source} §4未继承接口 interfaces.Plugin, 将不会被载入到服务器!"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/i18n",
|
||||
"version": "0.27.5",
|
||||
"version": "0.16.0",
|
||||
"description": "MiaoScript i18n package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,11 +19,11 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.27.5",
|
||||
"@types/js-yaml": "^4.0.5",
|
||||
"@ccms/nashorn": "^0.16.0",
|
||||
"@types/js-yaml": "^4.0.2",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^4.1.2",
|
||||
"typescript": "^4.9.5"
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.3.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"js-yaml": "^4.1.0"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/keyvalue",
|
||||
"version": "0.27.5",
|
||||
"version": "0.16.2",
|
||||
"description": "MiaoScript keyvalue package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,18 +19,18 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.27.5",
|
||||
"@ccms/common": "^0.27.5",
|
||||
"@ccms/container": "^0.27.5"
|
||||
"@ccms/api": "^0.16.2",
|
||||
"@ccms/common": "^0.16.0",
|
||||
"@ccms/container": "^0.16.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.27.5",
|
||||
"@ccms/nashorn": "^0.16.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": "^4.1.2",
|
||||
"typescript": "^4.9.5"
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.3.5"
|
||||
},
|
||||
"gitHead": "2589633069d24f646ac09261b1b2304c21d4ea75"
|
||||
}
|
||||
|
||||
6
packages/molang/.gitignore
vendored
6
packages/molang/.gitignore
vendored
@@ -1,6 +0,0 @@
|
||||
node_modules
|
||||
perf/*
|
||||
|
||||
|
||||
tsconfig.tsbuildinfo
|
||||
.DS_STORE
|
||||
@@ -1,29 +0,0 @@
|
||||
{
|
||||
"name": "@ccms/molang",
|
||||
"version": "0.27.5",
|
||||
"description": "A fast parser for Minecraft's MoLang",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/solvedDev/MoLang.git"
|
||||
},
|
||||
"author": "solvedDev",
|
||||
"license": "MIT",
|
||||
"bugs": {
|
||||
"url": "https://github.com/solvedDev/MoLang/issues"
|
||||
},
|
||||
"homepage": "https://github.com/solvedDev/MoLang#readme",
|
||||
"devDependencies": {
|
||||
"@types/node": "^18.13.0",
|
||||
"rimraf": "^4.1.2",
|
||||
"tslib": "^2.5.0",
|
||||
"typescript": "^4.9.5"
|
||||
}
|
||||
}
|
||||
@@ -1,129 +0,0 @@
|
||||
import { ExecutionEnvironment } from './env/env'
|
||||
import { IExpression, IParserConfig } from './main'
|
||||
import { StaticExpression } from './parser/expressions/static'
|
||||
import { StringExpression } from './parser/expressions/string'
|
||||
import { MoLangParser } from './parser/molang'
|
||||
|
||||
export class MoLang {
|
||||
protected expressionCache: Record<string, IExpression> = {}
|
||||
protected totalCacheEntries = 0
|
||||
protected executionEnvironment!: ExecutionEnvironment
|
||||
|
||||
protected parser: MoLangParser
|
||||
|
||||
constructor(
|
||||
env: Record<string, unknown> = {},
|
||||
protected config: Partial<IParserConfig> = {}
|
||||
) {
|
||||
if (config.useOptimizer === undefined) this.config.useOptimizer = true
|
||||
if (config.useCache === undefined) this.config.useCache = true
|
||||
if (config.earlyReturnsSkipParsing === undefined)
|
||||
this.config.earlyReturnsSkipParsing = true
|
||||
if (config.earlyReturnsSkipTokenization === undefined)
|
||||
this.config.earlyReturnsSkipTokenization = true
|
||||
if (config.convertUndefined === undefined)
|
||||
this.config.convertUndefined = false
|
||||
|
||||
this.parser = new MoLangParser({
|
||||
...this.config,
|
||||
tokenizer: undefined,
|
||||
})
|
||||
|
||||
this.updateExecutionEnv(env)
|
||||
}
|
||||
|
||||
updateConfig(newConfig: Partial<IParserConfig>) {
|
||||
newConfig = Object.assign(this.config, newConfig)
|
||||
|
||||
if (newConfig.tokenizer) this.parser.setTokenizer(newConfig.tokenizer)
|
||||
this.parser.updateConfig({ ...this.config, tokenizer: undefined })
|
||||
this.executionEnvironment.updateConfig(newConfig)
|
||||
}
|
||||
updateExecutionEnv(env: Record<string, unknown>, isFlat = false) {
|
||||
this.executionEnvironment = new ExecutionEnvironment(env, {
|
||||
useRadians: this.config.useRadians,
|
||||
convertUndefined: this.config.convertUndefined,
|
||||
isFlat,
|
||||
variableHandler: this.config.variableHandler,
|
||||
})
|
||||
this.parser.setExecutionEnvironment(this.executionEnvironment)
|
||||
}
|
||||
/**
|
||||
* Clears the MoLang expression cache
|
||||
*/
|
||||
clearCache() {
|
||||
this.expressionCache = {}
|
||||
this.totalCacheEntries = 0
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the given MoLang string `expression`
|
||||
* @param expression The MoLang string to execute
|
||||
*
|
||||
* @returns The value the MoLang expression corresponds to
|
||||
*/
|
||||
execute(expression: string) {
|
||||
this.parser.setExecutionEnvironment(this.executionEnvironment)
|
||||
const abstractSyntaxTree = this.parse(expression)
|
||||
|
||||
const result = abstractSyntaxTree.eval()
|
||||
if (result === undefined) return 0
|
||||
if (typeof result === 'boolean') return Number(result)
|
||||
return result
|
||||
}
|
||||
/**
|
||||
* Execute the given MoLang string `expression`
|
||||
* In case of errors, return 0
|
||||
* @param expression The MoLang string to execute
|
||||
*
|
||||
* @returns The value the MoLang expression corresponds to and 0 if the statement is invalid
|
||||
*/
|
||||
executeAndCatch(expression: string) {
|
||||
try {
|
||||
return this.execute(expression)
|
||||
} catch {
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the given MoLang string `expression`
|
||||
* @param expression The MoLang string to parse
|
||||
*
|
||||
* @returns An AST that corresponds to the MoLang expression
|
||||
*/
|
||||
parse(expression: string): IExpression {
|
||||
if (this.config.useCache ?? true) {
|
||||
const abstractSyntaxTree = this.expressionCache[expression]
|
||||
if (abstractSyntaxTree) return abstractSyntaxTree
|
||||
}
|
||||
|
||||
this.parser.init(expression)
|
||||
let abstractSyntaxTree = this.parser.parseExpression()
|
||||
if ((this.config.useOptimizer ?? true) && abstractSyntaxTree.isStatic())
|
||||
abstractSyntaxTree = new StaticExpression(abstractSyntaxTree.eval())
|
||||
// console.log(JSON.stringify(abstractSyntaxTree, null, ' '))
|
||||
|
||||
if (this.config.useCache ?? true) {
|
||||
if (this.totalCacheEntries > (this.config.maxCacheSize || 256))
|
||||
this.clearCache()
|
||||
|
||||
this.expressionCache[expression] = abstractSyntaxTree
|
||||
this.totalCacheEntries++
|
||||
}
|
||||
|
||||
return abstractSyntaxTree
|
||||
}
|
||||
|
||||
resolveStatic(ast: IExpression) {
|
||||
ast.walk((expr) => {
|
||||
if (expr instanceof StringExpression) return
|
||||
|
||||
if (expr.isStatic()) return new StaticExpression(expr.eval())
|
||||
})
|
||||
}
|
||||
|
||||
getParser() {
|
||||
return this.parser
|
||||
}
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
import { Parser } from '../parser/parse'
|
||||
import { Token } from '../parser/../tokenizer/token'
|
||||
import { IPrefixParselet } from '../parser/parselets/prefix'
|
||||
import { Expression, IExpression } from '../parser/expression'
|
||||
import { StringExpression } from '../parser/expressions/string'
|
||||
import { StatementExpression } from '../parser/expressions/statement'
|
||||
import { CustomMoLangParser } from './main'
|
||||
import { GroupExpression } from '../parser/expressions/group'
|
||||
|
||||
export class CustomFunctionParselet implements IPrefixParselet {
|
||||
constructor(public precedence = 0) {}
|
||||
|
||||
parse(parser: Parser, token: Token) {
|
||||
parser.consume('LEFT_PARENT')
|
||||
if (parser.match('RIGHT_PARENT'))
|
||||
throw new Error(`function() called without arguments`)
|
||||
|
||||
let args: string[] = []
|
||||
let functionBody: IExpression | undefined
|
||||
let functionName: string | undefined
|
||||
do {
|
||||
const expr = parser.parseExpression()
|
||||
if (expr instanceof StringExpression) {
|
||||
if (!functionName) functionName = <string>expr.eval()
|
||||
else args.push(<string>expr.eval())
|
||||
} else if (
|
||||
expr instanceof StatementExpression ||
|
||||
expr instanceof GroupExpression
|
||||
) {
|
||||
functionBody = expr
|
||||
} else {
|
||||
throw new Error(
|
||||
`Unexpected expresion: found "${expr.constructor.name}"`
|
||||
)
|
||||
}
|
||||
} while (parser.match('COMMA'))
|
||||
parser.consume('RIGHT_PARENT')
|
||||
|
||||
if (!functionName)
|
||||
throw new Error(
|
||||
`Missing function() name (argument 1); found "${functionName}"`
|
||||
)
|
||||
if (!functionBody)
|
||||
throw new Error(
|
||||
`Missing function() body (argument ${args.length + 2})`
|
||||
)
|
||||
|
||||
return new CustomFunctionExpression(
|
||||
(<CustomMoLangParser>parser).functions,
|
||||
functionName,
|
||||
args,
|
||||
functionBody
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
class CustomFunctionExpression extends Expression {
|
||||
type = 'CustomFunctionExpression'
|
||||
constructor(
|
||||
functions: Map<string, [string[], string]>,
|
||||
functionName: string,
|
||||
args: string[],
|
||||
protected functionBody: IExpression
|
||||
) {
|
||||
super()
|
||||
functions.set(functionName, [
|
||||
args,
|
||||
functionBody instanceof GroupExpression
|
||||
? functionBody.allExpressions[0].toString()
|
||||
: functionBody.toString(),
|
||||
])
|
||||
}
|
||||
|
||||
get allExpressions() {
|
||||
return [this.functionBody]
|
||||
}
|
||||
setExpressionAt(_: number, expr: IExpression) {
|
||||
this.functionBody = expr
|
||||
}
|
||||
|
||||
get isReturn() {
|
||||
// Scopes inside of functions may use return statements
|
||||
return false
|
||||
}
|
||||
|
||||
isStatic() {
|
||||
return true
|
||||
}
|
||||
|
||||
eval() {
|
||||
return 0
|
||||
}
|
||||
}
|
||||
@@ -1,229 +0,0 @@
|
||||
import { ExecutionEnvironment } from '../env/env'
|
||||
import { IParserConfig } from '../main'
|
||||
import { MoLangParser } from '../parser/molang'
|
||||
import { Tokenizer } from '../tokenizer/Tokenizer'
|
||||
import { CustomFunctionParselet } from './function'
|
||||
import { MoLang } from '../MoLang'
|
||||
import { StatementExpression } from '../parser/expressions/statement'
|
||||
import { transformStatement } from './transformStatement'
|
||||
import { NameExpression } from '../parser/expressions/name'
|
||||
import { ReturnExpression } from '../parser/expressions/return'
|
||||
import { GenericOperatorExpression } from '../parser/expressions/genericOperator'
|
||||
import { TernaryExpression } from '../parser/expressions/ternary'
|
||||
import { IExpression } from '../parser/expression'
|
||||
import { VoidExpression } from '../parser/expressions/void'
|
||||
import { GroupExpression } from '../parser/expressions/group'
|
||||
|
||||
export class CustomMoLangParser extends MoLangParser {
|
||||
public readonly functions = new Map<string, [string[], string]>()
|
||||
|
||||
constructor(config: Partial<IParserConfig>) {
|
||||
super(config)
|
||||
this.registerPrefix('FUNCTION', new CustomFunctionParselet())
|
||||
}
|
||||
|
||||
reset() {
|
||||
this.functions.clear()
|
||||
}
|
||||
}
|
||||
|
||||
export class CustomMoLang {
|
||||
protected parser: CustomMoLangParser
|
||||
|
||||
constructor(env: any) {
|
||||
this.parser = new CustomMoLangParser({
|
||||
useCache: false,
|
||||
useOptimizer: true,
|
||||
useAgressiveStaticOptimizer: true,
|
||||
keepGroups: true,
|
||||
earlyReturnsSkipParsing: false,
|
||||
earlyReturnsSkipTokenization: false,
|
||||
})
|
||||
this.parser.setExecutionEnvironment(
|
||||
new ExecutionEnvironment(this.parser, env)
|
||||
)
|
||||
this.parser.setTokenizer(new Tokenizer(new Set(['function'])))
|
||||
}
|
||||
|
||||
get functions() {
|
||||
return this.parser.functions
|
||||
}
|
||||
|
||||
parse(expression: string) {
|
||||
this.parser.init(expression)
|
||||
const abstractSyntaxTree = this.parser.parseExpression()
|
||||
|
||||
return abstractSyntaxTree
|
||||
}
|
||||
|
||||
transform(source: string) {
|
||||
const molang = new MoLang(
|
||||
{},
|
||||
{
|
||||
useCache: false,
|
||||
keepGroups: true,
|
||||
useOptimizer: true,
|
||||
useAgressiveStaticOptimizer: true,
|
||||
earlyReturnsSkipParsing: true,
|
||||
earlyReturnsSkipTokenization: false,
|
||||
}
|
||||
)
|
||||
|
||||
let totalScoped = 0
|
||||
let ast = molang.parse(source)
|
||||
|
||||
let isComplexExpression = false
|
||||
if (ast instanceof StatementExpression) {
|
||||
isComplexExpression = true
|
||||
}
|
||||
|
||||
let containsComplexExpressions = false
|
||||
ast = ast.walk((expr: any) => {
|
||||
// Only run code on function expressions which start with "f." or "function."
|
||||
if (
|
||||
expr.type !== 'FunctionExpression' ||
|
||||
(!expr.name.name.startsWith?.('f.') &&
|
||||
!expr.name.name.startsWith?.('function.'))
|
||||
)
|
||||
return
|
||||
|
||||
const nameExpr = expr.name
|
||||
const functionName = nameExpr.name.replace(/(f|function)\./g, '')
|
||||
const argValues = expr.args
|
||||
|
||||
let [args, functionBody] = this.functions.get(functionName) ?? []
|
||||
if (!functionBody || !args) return
|
||||
|
||||
// Insert argument values
|
||||
functionBody = functionBody.replace(
|
||||
/(a|arg)\.(\w+)/g,
|
||||
(match, prefix, argName) => {
|
||||
const val =
|
||||
argValues[args!.indexOf(argName)]?.toString() ?? '0'
|
||||
|
||||
return val.replace(/(t|temp)\./, 'outer_temp.')
|
||||
}
|
||||
)
|
||||
|
||||
let funcAst = transformStatement(molang.parse(functionBody))
|
||||
if (funcAst instanceof StatementExpression) {
|
||||
funcAst = molang.parse(`({${functionBody}}+t.return_value)`)
|
||||
|
||||
containsComplexExpressions = true
|
||||
}
|
||||
|
||||
const varNameMap = new Map<string, string>()
|
||||
funcAst = funcAst.walk((expr) => {
|
||||
if (expr instanceof NameExpression) {
|
||||
const fullName = expr.toString()
|
||||
// Remove "a."/"t."/etc. from var name
|
||||
let tmp = fullName.split('.')
|
||||
const varType = tmp.shift()
|
||||
const varName = tmp.join('.')
|
||||
|
||||
if (varType === 't' || varType === 'temp') {
|
||||
// Scope temp./t. variables to functions
|
||||
let newName = varNameMap.get(fullName)
|
||||
if (!newName) {
|
||||
newName = `t.__scvar${totalScoped++}`
|
||||
varNameMap.set(fullName, newName)
|
||||
}
|
||||
|
||||
expr.setName(newName)
|
||||
} else if (varType === 'outer_temp') {
|
||||
expr.setName(`t.${varName}`)
|
||||
}
|
||||
|
||||
return undefined
|
||||
} else if (expr instanceof ReturnExpression) {
|
||||
const nameExpr = new NameExpression(
|
||||
molang.getParser().executionEnv,
|
||||
't.return_value'
|
||||
)
|
||||
const returnValExpr = expr.allExpressions[0]
|
||||
|
||||
return new GenericOperatorExpression(
|
||||
nameExpr,
|
||||
returnValExpr,
|
||||
'=',
|
||||
() => {
|
||||
nameExpr.setPointer(returnValExpr.eval())
|
||||
}
|
||||
)
|
||||
} else if (expr instanceof StatementExpression) {
|
||||
// Make early returns work correctly by adjusting ternary statements which contain return statements
|
||||
const expressions: IExpression[] = []
|
||||
|
||||
for (let i = 0; i < expr.allExpressions.length; i++) {
|
||||
const currExpr = expr.allExpressions[i]
|
||||
|
||||
if (
|
||||
currExpr instanceof TernaryExpression &&
|
||||
currExpr.hasReturn
|
||||
) {
|
||||
handleTernary(
|
||||
currExpr,
|
||||
expr.allExpressions.slice(i + 1)
|
||||
)
|
||||
|
||||
expressions.push(currExpr)
|
||||
break
|
||||
} else if (currExpr.isReturn) {
|
||||
expressions.push(currExpr)
|
||||
break
|
||||
}
|
||||
|
||||
expressions.push(currExpr)
|
||||
}
|
||||
|
||||
return new StatementExpression(expressions)
|
||||
}
|
||||
})
|
||||
|
||||
return funcAst
|
||||
})
|
||||
|
||||
const finalAst = molang.parse(ast.toString())
|
||||
molang.resolveStatic(finalAst)
|
||||
return !isComplexExpression && containsComplexExpressions
|
||||
? `return ${finalAst.toString()};`
|
||||
: finalAst.toString()
|
||||
}
|
||||
|
||||
reset() {
|
||||
this.functions.clear()
|
||||
}
|
||||
}
|
||||
|
||||
function handleTernary(
|
||||
returnTernary: TernaryExpression,
|
||||
currentExpressions: IExpression[]
|
||||
) {
|
||||
// If & else branch end with return statements -> we can omit everything after the ternary
|
||||
if (returnTernary.isReturn) return
|
||||
|
||||
const notReturningBranchIndex = returnTernary.allExpressions[2].isReturn
|
||||
? 1
|
||||
: 2
|
||||
const notReturningBranch =
|
||||
returnTernary.allExpressions[notReturningBranchIndex]
|
||||
|
||||
if (!(notReturningBranch instanceof VoidExpression)) {
|
||||
if (
|
||||
notReturningBranch instanceof GroupExpression &&
|
||||
notReturningBranch.allExpressions[0] instanceof StatementExpression
|
||||
) {
|
||||
currentExpressions.unshift(...notReturningBranch.allExpressions)
|
||||
} else {
|
||||
currentExpressions.unshift(notReturningBranch)
|
||||
}
|
||||
}
|
||||
if (currentExpressions.length > 0)
|
||||
returnTernary.setExpressionAt(
|
||||
notReturningBranchIndex,
|
||||
new GroupExpression(
|
||||
new StatementExpression(currentExpressions),
|
||||
'{}'
|
||||
)
|
||||
)
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
import { IExpression } from '../parser/expression'
|
||||
import { GroupExpression } from '../parser/expressions/group'
|
||||
import { ReturnExpression } from '../parser/expressions/return'
|
||||
import { StatementExpression } from '../parser/expressions/statement'
|
||||
|
||||
export function transformStatement(expression: IExpression) {
|
||||
if (expression instanceof ReturnExpression)
|
||||
return new GroupExpression(expression.allExpressions[0], '()')
|
||||
if (!(expression instanceof StatementExpression)) return expression
|
||||
if (expression.allExpressions.length > 1) return expression
|
||||
|
||||
// Only one statement, test whether it is a return statement
|
||||
const expr = expression.allExpressions[0]
|
||||
if (expr instanceof ReturnExpression) {
|
||||
return new GroupExpression(expr.allExpressions[0], '()')
|
||||
} else {
|
||||
return expression
|
||||
}
|
||||
}
|
||||
143
packages/molang/src/env/env.ts
vendored
143
packages/molang/src/env/env.ts
vendored
@@ -1,143 +0,0 @@
|
||||
import { standardEnv } from './standardEnv'
|
||||
|
||||
export type TVariableHandler = (
|
||||
variableName: string,
|
||||
variables: Record<string, unknown>
|
||||
) => unknown
|
||||
|
||||
export interface IEnvConfig {
|
||||
useRadians?: boolean
|
||||
convertUndefined?: boolean
|
||||
variableHandler?: TVariableHandler
|
||||
isFlat?: boolean
|
||||
}
|
||||
|
||||
export class ExecutionEnvironment {
|
||||
protected env: Record<string, any>
|
||||
|
||||
constructor(env: Record<string, any>, public readonly config: IEnvConfig) {
|
||||
if (!env) throw new Error(`Provided environment must be an object`)
|
||||
|
||||
if (config.isFlat)
|
||||
this.env = Object.assign(
|
||||
env,
|
||||
standardEnv(config.useRadians ?? false)
|
||||
)
|
||||
else
|
||||
this.env = {
|
||||
...standardEnv(config.useRadians ?? false),
|
||||
...this.flattenEnv(env),
|
||||
}
|
||||
}
|
||||
|
||||
updateConfig({
|
||||
variableHandler,
|
||||
convertUndefined,
|
||||
useRadians,
|
||||
}: IEnvConfig) {
|
||||
if (convertUndefined !== undefined)
|
||||
this.config.convertUndefined = convertUndefined
|
||||
if (typeof variableHandler === 'function')
|
||||
this.config.variableHandler = variableHandler
|
||||
|
||||
if (!!this.config.useRadians !== !!useRadians) {
|
||||
this.env = Object.assign(this.env, standardEnv(!!useRadians))
|
||||
}
|
||||
}
|
||||
|
||||
protected flattenEnv(
|
||||
newEnv: Record<string, any>,
|
||||
addKey = '',
|
||||
current: any = {}
|
||||
) {
|
||||
for (let key in newEnv) {
|
||||
if (key[1] === '.') {
|
||||
switch (key[0]) {
|
||||
case 'q':
|
||||
key = 'query' + key.substring(1, key.length)
|
||||
break
|
||||
case 't':
|
||||
key = 'temp' + key.substring(1, key.length)
|
||||
break
|
||||
case 'v':
|
||||
key = 'variable' + key.substring(1, key.length)
|
||||
break
|
||||
case 'c':
|
||||
key = 'context' + key.substring(1, key.length)
|
||||
break
|
||||
case 'f':
|
||||
key = 'function' + key.substring(1, key.length)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if (newEnv[key].__isContext) {
|
||||
current[`${addKey}${key}`] = newEnv[key].env
|
||||
} else if (
|
||||
typeof newEnv[key] === 'object' &&
|
||||
!Array.isArray(newEnv[key])
|
||||
) {
|
||||
this.flattenEnv(newEnv[key], `${addKey}${key}.`, current)
|
||||
} else {
|
||||
current[`${addKey}${key}`] = newEnv[key]
|
||||
}
|
||||
}
|
||||
|
||||
return current
|
||||
}
|
||||
|
||||
setAt(lookup: string, value: unknown) {
|
||||
if (lookup[1] === '.') {
|
||||
switch (lookup[0]) {
|
||||
case 'q':
|
||||
lookup = 'query' + lookup.substring(1, lookup.length)
|
||||
break
|
||||
case 't':
|
||||
lookup = 'temp' + lookup.substring(1, lookup.length)
|
||||
break
|
||||
case 'v':
|
||||
lookup = 'variable' + lookup.substring(1, lookup.length)
|
||||
break
|
||||
case 'c':
|
||||
lookup = 'context' + lookup.substring(1, lookup.length)
|
||||
break
|
||||
case 'f':
|
||||
lookup = 'function' + lookup.substring(1, lookup.length)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return (this.env[lookup] = value)
|
||||
}
|
||||
|
||||
getFrom(lookup: string) {
|
||||
if (lookup[1] === '.') {
|
||||
switch (lookup[0]) {
|
||||
case 'q':
|
||||
lookup = 'query' + lookup.substring(1, lookup.length)
|
||||
break
|
||||
case 't':
|
||||
lookup = 'temp' + lookup.substring(1, lookup.length)
|
||||
break
|
||||
case 'v':
|
||||
lookup = 'variable' + lookup.substring(1, lookup.length)
|
||||
break
|
||||
case 'c':
|
||||
lookup = 'context' + lookup.substring(1, lookup.length)
|
||||
break
|
||||
case 'f':
|
||||
lookup = 'function' + lookup.substring(1, lookup.length)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
const res =
|
||||
this.env[lookup] ?? this.config.variableHandler?.(lookup, this.env)
|
||||
return res === undefined && this.config.convertUndefined ? 0 : res
|
||||
}
|
||||
}
|
||||
|
||||
export class Context {
|
||||
public readonly __isContext = true
|
||||
constructor(public readonly env: any) {}
|
||||
}
|
||||
86
packages/molang/src/env/math.ts
vendored
86
packages/molang/src/env/math.ts
vendored
@@ -1,86 +0,0 @@
|
||||
const clamp = (value: number, min: number, max: number) => {
|
||||
if (typeof value !== 'number' || Number.isNaN(value)) return min
|
||||
else if (value > max) return max
|
||||
else if (value < min) return min
|
||||
return value
|
||||
}
|
||||
const dieRoll = (sum: number, low: number, high: number) => {
|
||||
let i = 0
|
||||
let total = 0
|
||||
while (i < sum) total += random(low, high)
|
||||
return total
|
||||
}
|
||||
const dieRollInt = (sum: number, low: number, high: number) => {
|
||||
let i = 0
|
||||
let total = 0
|
||||
while (i < sum) total += randomInt(low, high)
|
||||
return total
|
||||
}
|
||||
const hermiteBlend = (value: number) => 3 * value ** 2 - 2 * value ** 3
|
||||
const lerp = (start: number, end: number, amount: number) => {
|
||||
if (amount < 0) amount = 0
|
||||
else if (amount > 1) amount = 1
|
||||
|
||||
return start + (end - start) * amount
|
||||
}
|
||||
// Written by @JannisX11 (https://github.com/JannisX11/MolangJS/blob/master/molang.js#L383); modified for usage inside of this MoLang parser
|
||||
const lerprotate = (start: number, end: number, amount: number) => {
|
||||
const radify = (n: number) => (((n + 180) % 360) + 180) % 360
|
||||
start = radify(start)
|
||||
end = radify(end)
|
||||
if (start > end) {
|
||||
let tmp = start
|
||||
start = end
|
||||
end = tmp
|
||||
}
|
||||
|
||||
if (end - start > 180) return radify(end + amount * (360 - (end - start)))
|
||||
else return start + amount * (end - start)
|
||||
}
|
||||
const mod = (value: number, denominator: number) => value % denominator
|
||||
const random = (low: number, high: number) => low + Math.random() * (high - low)
|
||||
const randomInt = (low: number, high: number) =>
|
||||
Math.round(low + Math.random() * (high - low))
|
||||
|
||||
const minAngle = (value: number) => {
|
||||
value = value % 360
|
||||
value = (value + 360) % 360
|
||||
|
||||
if (value > 179) value -= 360
|
||||
return value
|
||||
}
|
||||
|
||||
export const MoLangMathLib = (useRadians: boolean) => {
|
||||
const degRadFactor = useRadians ? 1 : Math.PI / 180
|
||||
|
||||
return {
|
||||
'math.abs': Math.abs,
|
||||
'math.acos': (x: number) => Math.acos(x) / degRadFactor,
|
||||
'math.asin': (x: number) => Math.asin(x) / degRadFactor,
|
||||
'math.atan': (x: number) => Math.atan(x) / degRadFactor,
|
||||
'math.atan2': (y: number, x: number) => Math.atan2(y, x) / degRadFactor,
|
||||
'math.ceil': Math.ceil,
|
||||
'math.clamp': clamp,
|
||||
'math.cos': (x: number) => Math.cos(x * degRadFactor),
|
||||
'math.die_roll': dieRoll,
|
||||
'math.die_roll_integer': dieRollInt,
|
||||
'math.exp': Math.exp,
|
||||
'math.floor': Math.floor,
|
||||
'math.hermite_blend': hermiteBlend,
|
||||
'math.lerp': lerp,
|
||||
'math.lerp_rotate': lerprotate,
|
||||
'math.ln': Math.log,
|
||||
'math.max': Math.max,
|
||||
'math.min': Math.min,
|
||||
'math.min_angle': minAngle,
|
||||
'math.mod': mod,
|
||||
'math.pi': Math.PI,
|
||||
'math.pow': Math.pow,
|
||||
'math.random': random,
|
||||
'math.random_integer': randomInt,
|
||||
'math.round': Math.round,
|
||||
'math.sin': (x: number) => Math.sin(x * degRadFactor),
|
||||
'math.sqrt': Math.sqrt,
|
||||
'math.trunc': Math.trunc,
|
||||
}
|
||||
}
|
||||
25
packages/molang/src/env/queries.ts
vendored
25
packages/molang/src/env/queries.ts
vendored
@@ -1,25 +0,0 @@
|
||||
const inRange = (value: number, min: number, max: number) => {
|
||||
// Check that value, min and max are numbers
|
||||
if (
|
||||
typeof value !== 'number' ||
|
||||
typeof min !== 'number' ||
|
||||
typeof max !== 'number'
|
||||
) {
|
||||
console.error('"query.in_range": value, min and max must be numbers')
|
||||
return false
|
||||
}
|
||||
|
||||
return value >= min && value <= max
|
||||
}
|
||||
|
||||
const all = (mustMatch: unknown, ...values: unknown[]) =>
|
||||
values.every((v) => v === mustMatch)
|
||||
|
||||
const any = (mustMatch: unknown, ...values: unknown[]) =>
|
||||
values.some((v) => v === mustMatch)
|
||||
|
||||
export const standardQueries = {
|
||||
'query.in_range': inRange,
|
||||
'query.all': all,
|
||||
'query.any': any,
|
||||
}
|
||||
7
packages/molang/src/env/standardEnv.ts
vendored
7
packages/molang/src/env/standardEnv.ts
vendored
@@ -1,7 +0,0 @@
|
||||
import { MoLangMathLib } from './math'
|
||||
import { standardQueries } from './queries'
|
||||
|
||||
export const standardEnv = (useRadians: boolean) => ({
|
||||
...MoLangMathLib(useRadians),
|
||||
...standardQueries,
|
||||
})
|
||||
@@ -1 +0,0 @@
|
||||
export * from './main'
|
||||
@@ -1,91 +0,0 @@
|
||||
import { TVariableHandler } from './env/env'
|
||||
import { Tokenizer } from './tokenizer/Tokenizer'
|
||||
|
||||
/**
|
||||
* How the parser and interpreter should handle your MoLang expression
|
||||
*/
|
||||
|
||||
export interface IParserConfig {
|
||||
/**
|
||||
* Whether a cache should be used to speed up executing MoLang.
|
||||
* The cache saves an AST for every parsed expression.
|
||||
* This allows us to skip the tokenization & parsing step before executing known MoLang expressions
|
||||
*
|
||||
* Default: true
|
||||
*/
|
||||
useCache: boolean
|
||||
/**
|
||||
* How many expressions can be cached. After reaching `maxCacheSize`, the whole cache is cleared automatically.
|
||||
* Can be set to `Infinity` to remove the limit completely
|
||||
*
|
||||
* Default: 256
|
||||
*/
|
||||
maxCacheSize: number
|
||||
/**
|
||||
* The optimizer can drastically speed up parsing & executing MoLang.
|
||||
* It enables skipping of unreachable statements, pre-evaluating static expressions and skipping of statements with no effect
|
||||
* when used together with the `useAgressiveStaticOptimizer` option
|
||||
*
|
||||
* Default: true
|
||||
*/
|
||||
useOptimizer: boolean
|
||||
/**
|
||||
* Skip execution of statements with no effect
|
||||
* when used together with the `useOptimizer` option
|
||||
*
|
||||
* Default: true
|
||||
*/
|
||||
useAgressiveStaticOptimizer: boolean
|
||||
|
||||
/**
|
||||
* This options makes early return statements skip all parsing work completely
|
||||
*
|
||||
* Default: true
|
||||
*/
|
||||
earlyReturnsSkipParsing: boolean
|
||||
/**
|
||||
* This options makes early return statements skip all tokenization work completely if earlyReturnsSkipParsing is set to true
|
||||
*
|
||||
* Default: true
|
||||
*/
|
||||
earlyReturnsSkipTokenization: boolean
|
||||
/**
|
||||
* Tokenizer to use for tokenizing the expression
|
||||
*/
|
||||
tokenizer: Tokenizer
|
||||
/**
|
||||
* Create expression instances for brackets ("()", "{}")
|
||||
*
|
||||
* This should only be set to true if you want to use the .toString() method of an expression
|
||||
* or you want to iterate over the whole AST
|
||||
*
|
||||
* Default: false
|
||||
*/
|
||||
keepGroups: boolean
|
||||
|
||||
/**
|
||||
* Whether to convert undefined variables to "0"
|
||||
*
|
||||
* Default: false
|
||||
*/
|
||||
convertUndefined: boolean
|
||||
|
||||
/**
|
||||
* Use radians instead of degrees for trigonometric functions
|
||||
*
|
||||
* Default: false
|
||||
*/
|
||||
useRadians: boolean
|
||||
|
||||
/**
|
||||
* Resolve undefined variables
|
||||
*/
|
||||
variableHandler: TVariableHandler
|
||||
}
|
||||
|
||||
export { Tokenizer } from './tokenizer/Tokenizer'
|
||||
export { IExpression } from './parser/expression'
|
||||
export { CustomMoLang } from './custom/main'
|
||||
export { MoLang } from './MoLang'
|
||||
export * as expressions from './parser/expressions/index'
|
||||
export { Context } from './env/env'
|
||||
@@ -1,57 +0,0 @@
|
||||
/**
|
||||
* Interface that describes an AST Expression
|
||||
*/
|
||||
export interface IExpression {
|
||||
readonly type: string
|
||||
readonly isReturn?: boolean
|
||||
readonly isBreak?: boolean
|
||||
readonly isContinue?: boolean
|
||||
readonly allExpressions: IExpression[]
|
||||
|
||||
setFunctionCall?: (value: boolean) => void
|
||||
setPointer?: (value: unknown) => void
|
||||
setExpressionAt(index: number, expr: IExpression): void
|
||||
eval(): unknown
|
||||
isStatic(): boolean
|
||||
walk(cb: TIterateCallback): IExpression
|
||||
iterate(cb: TIterateCallback, visited: Set<IExpression>): void
|
||||
}
|
||||
|
||||
export abstract class Expression implements IExpression {
|
||||
public abstract readonly type: string
|
||||
|
||||
abstract eval(): unknown
|
||||
abstract isStatic(): boolean
|
||||
|
||||
toString() {
|
||||
return `${this.eval()}`
|
||||
}
|
||||
|
||||
abstract allExpressions: IExpression[]
|
||||
abstract setExpressionAt(index: number, expr: IExpression): void
|
||||
|
||||
walk(cb: TIterateCallback, visited = new Set<IExpression>()): IExpression {
|
||||
let expr = cb(this) ?? this
|
||||
|
||||
expr.iterate(cb, visited)
|
||||
|
||||
return expr
|
||||
}
|
||||
iterate(cb: TIterateCallback, visited: Set<IExpression>) {
|
||||
for (let i = 0; i < this.allExpressions.length; i++) {
|
||||
const originalExpr = this.allExpressions[i]
|
||||
if (visited.has(originalExpr)) continue
|
||||
else visited.add(originalExpr)
|
||||
|
||||
const expr = cb(originalExpr) ?? originalExpr
|
||||
|
||||
if (expr !== originalExpr && visited.has(expr)) continue
|
||||
else visited.add(expr)
|
||||
|
||||
this.setExpressionAt(i, expr)
|
||||
expr.iterate(cb, visited)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export type TIterateCallback = (expr: IExpression) => IExpression | undefined
|
||||
@@ -1,32 +0,0 @@
|
||||
import { Expression, IExpression } from '../expression'
|
||||
|
||||
export class ArrayAccessExpression extends Expression {
|
||||
type = 'ArrayAccessExpression'
|
||||
constructor(protected name: IExpression, protected lookup: IExpression) {
|
||||
super()
|
||||
}
|
||||
|
||||
get allExpressions() {
|
||||
return [this.name, this.lookup]
|
||||
}
|
||||
setExpressionAt(index: number, expr: IExpression) {
|
||||
if (index === 0) this.name = expr
|
||||
else if (index === 1) this.lookup = expr
|
||||
}
|
||||
|
||||
isStatic() {
|
||||
return false
|
||||
}
|
||||
|
||||
setPointer(value: unknown) {
|
||||
;(<any>this.name.eval())[<number>this.lookup.eval()] = value
|
||||
}
|
||||
|
||||
eval() {
|
||||
return (<any>this.name.eval())[<number>this.lookup.eval()]
|
||||
}
|
||||
|
||||
toString() {
|
||||
return `${this.name.toString()}[${this.lookup.toString()}]`
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
import { Expression } from '../expression'
|
||||
|
||||
export class BooleanExpression extends Expression {
|
||||
type = 'BooleanExpression'
|
||||
constructor(protected value: boolean) {
|
||||
super()
|
||||
}
|
||||
|
||||
get allExpressions() {
|
||||
return []
|
||||
}
|
||||
setExpressionAt() {}
|
||||
|
||||
isStatic() {
|
||||
return true
|
||||
}
|
||||
|
||||
eval() {
|
||||
return this.value
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
import { Expression } from '../expression'
|
||||
|
||||
export class BreakExpression extends Expression {
|
||||
type = 'BreakExpression'
|
||||
isBreak = true
|
||||
|
||||
constructor() {
|
||||
super()
|
||||
}
|
||||
|
||||
get allExpressions() {
|
||||
return []
|
||||
}
|
||||
setExpressionAt() {}
|
||||
|
||||
isStatic() {
|
||||
return false
|
||||
}
|
||||
|
||||
eval() {
|
||||
return 0
|
||||
}
|
||||
isString() {
|
||||
return 'break'
|
||||
}
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
import { ExecutionEnvironment } from '../../env/env'
|
||||
import { Expression, IExpression } from '../expression'
|
||||
import { NameExpression } from './name'
|
||||
|
||||
export class ContextSwitchExpression extends Expression {
|
||||
type = 'NameExpression'
|
||||
|
||||
constructor(
|
||||
protected leftExpr: NameExpression,
|
||||
protected rightExpr: NameExpression
|
||||
) {
|
||||
super()
|
||||
}
|
||||
|
||||
get allExpressions() {
|
||||
return [this.leftExpr, this.rightExpr]
|
||||
}
|
||||
setExpressionAt(index: number, expr: IExpression) {
|
||||
if (!(expr instanceof NameExpression))
|
||||
throw new Error(
|
||||
`Cannot use context switch operator "->" on ${expr.type}`
|
||||
)
|
||||
|
||||
if (index === 0) this.leftExpr = expr
|
||||
else if (index === 1) this.rightExpr = expr
|
||||
}
|
||||
|
||||
isStatic() {
|
||||
return false
|
||||
}
|
||||
|
||||
eval() {
|
||||
const context = this.leftExpr.eval()
|
||||
if (typeof context !== 'object') return 0
|
||||
|
||||
this.rightExpr.setExecutionEnv(
|
||||
new ExecutionEnvironment(
|
||||
context,
|
||||
this.rightExpr.executionEnv.config
|
||||
)
|
||||
)
|
||||
return this.rightExpr.eval()
|
||||
}
|
||||
|
||||
toString() {
|
||||
return `${this.leftExpr.toString()}->${this.rightExpr.toString()}`
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
import { Expression } from '../expression'
|
||||
|
||||
export class ContinueExpression extends Expression {
|
||||
type = 'ContinueExpression'
|
||||
isContinue = true
|
||||
|
||||
constructor() {
|
||||
super()
|
||||
}
|
||||
|
||||
get allExpressions() {
|
||||
return []
|
||||
}
|
||||
setExpressionAt() {}
|
||||
|
||||
isStatic() {
|
||||
return false
|
||||
}
|
||||
|
||||
eval() {
|
||||
return 0
|
||||
}
|
||||
toString() {
|
||||
return 'continue'
|
||||
}
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
import { Expression, IExpression } from '../expression'
|
||||
|
||||
export class ForEachExpression extends Expression {
|
||||
type = 'ForEachExpression'
|
||||
|
||||
constructor(
|
||||
protected variable: IExpression,
|
||||
protected arrayExpression: IExpression,
|
||||
protected expression: IExpression
|
||||
) {
|
||||
super()
|
||||
if (!this.variable.setPointer)
|
||||
throw new Error(
|
||||
`First for_each() argument must be a variable, received "${typeof this.variable.eval()}"`
|
||||
)
|
||||
}
|
||||
|
||||
get isReturn() {
|
||||
return this.expression.isReturn
|
||||
}
|
||||
get allExpressions() {
|
||||
return [this.variable, this.arrayExpression, this.expression]
|
||||
}
|
||||
setExpressionAt(index: number, expr: IExpression) {
|
||||
if (index === 0) this.variable = expr
|
||||
else if (index === 1) this.arrayExpression = expr
|
||||
else if (index === 2) this.expression = expr
|
||||
}
|
||||
|
||||
isStatic() {
|
||||
return (
|
||||
this.variable.isStatic() &&
|
||||
this.arrayExpression.isStatic() &&
|
||||
this.expression.isStatic()
|
||||
)
|
||||
}
|
||||
|
||||
eval() {
|
||||
const array = this.arrayExpression.eval()
|
||||
if (!Array.isArray(array))
|
||||
throw new Error(
|
||||
`Second for_each() argument must be an array, received "${typeof array}"`
|
||||
)
|
||||
|
||||
let i = 0
|
||||
while (i < array.length) {
|
||||
// Error detection for this.variable is part of the constructor
|
||||
this.variable.setPointer?.(array[i++])
|
||||
|
||||
const res = this.expression.eval()
|
||||
|
||||
if (this.expression.isBreak) break
|
||||
else if (this.expression.isContinue) continue
|
||||
else if (this.expression.isReturn) return res
|
||||
}
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
toString() {
|
||||
return `loop(${this.variable.toString()},${this.arrayExpression.toString()},${this.expression.toString()})`
|
||||
}
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
import { NameExpression } from './name'
|
||||
import { Expression, IExpression } from '../expression'
|
||||
|
||||
export class FunctionExpression extends Expression {
|
||||
type = 'FunctionExpression'
|
||||
|
||||
constructor(protected name: IExpression, protected args: IExpression[]) {
|
||||
super()
|
||||
}
|
||||
|
||||
get allExpressions() {
|
||||
return [this.name, ...this.args]
|
||||
}
|
||||
setExpressionAt(index: number, expr: Expression) {
|
||||
if (index === 0) this.name = expr
|
||||
else if (index > 0) this.args[index - 1] = expr
|
||||
}
|
||||
|
||||
isStatic() {
|
||||
return false
|
||||
}
|
||||
|
||||
eval() {
|
||||
const args: unknown[] = []
|
||||
let i = 0
|
||||
while (i < this.args.length) args.push(this.args[i++].eval())
|
||||
|
||||
const func = <(...args: unknown[]) => unknown>this.name.eval()
|
||||
if (typeof func !== 'function')
|
||||
throw new Error(
|
||||
`${(<NameExpression>this.name).toString()} is not callable!`
|
||||
)
|
||||
return func(...args)
|
||||
}
|
||||
|
||||
toString() {
|
||||
let str = `${this.name.toString()}(`
|
||||
for (let i = 0; i < this.args.length; i++) {
|
||||
str += `${this.args[i].toString()}${
|
||||
i + 1 < this.args.length ? ',' : ''
|
||||
}`
|
||||
}
|
||||
|
||||
return `${str})`
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
import { Expression, IExpression } from '../expression'
|
||||
|
||||
export class GenericOperatorExpression extends Expression {
|
||||
type = 'GenericOperatorExpression'
|
||||
|
||||
constructor(
|
||||
protected left: IExpression,
|
||||
protected right: IExpression,
|
||||
protected operator: string,
|
||||
protected evalHelper: (
|
||||
leftExpression: IExpression,
|
||||
rightExpression: IExpression
|
||||
) => unknown
|
||||
) {
|
||||
super()
|
||||
}
|
||||
|
||||
get allExpressions() {
|
||||
return [this.left, this.right]
|
||||
}
|
||||
setExpressionAt(index: number, expr: IExpression) {
|
||||
if (index === 0) this.left = expr
|
||||
else if (index === 1) this.right = expr
|
||||
}
|
||||
|
||||
isStatic() {
|
||||
return this.left.isStatic() && this.right.isStatic()
|
||||
}
|
||||
|
||||
eval() {
|
||||
return this.evalHelper(this.left, this.right)
|
||||
}
|
||||
|
||||
toString() {
|
||||
return `${this.left.toString()}${this.operator}${this.right.toString()}`
|
||||
}
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
import { Expression, IExpression } from '../expression'
|
||||
|
||||
export class GroupExpression extends Expression {
|
||||
type = 'GroupExpression'
|
||||
|
||||
constructor(protected expression: IExpression, protected brackets: string) {
|
||||
super()
|
||||
}
|
||||
|
||||
get allExpressions() {
|
||||
return [this.expression]
|
||||
}
|
||||
setExpressionAt(_: number, expr: IExpression) {
|
||||
this.expression = expr
|
||||
}
|
||||
|
||||
isStatic() {
|
||||
return this.expression.isStatic()
|
||||
}
|
||||
get isReturn() {
|
||||
return this.expression.isReturn
|
||||
}
|
||||
get isBreak() {
|
||||
return this.expression.isBreak
|
||||
}
|
||||
get isContinue() {
|
||||
return this.expression.isContinue
|
||||
}
|
||||
|
||||
eval() {
|
||||
return this.expression.eval()
|
||||
}
|
||||
toString() {
|
||||
return `${this.brackets[0]}${this.expression.toString()}${
|
||||
this.brackets[1]
|
||||
}`
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
export { ArrayAccessExpression } from './arrayAccess'
|
||||
export { BooleanExpression } from './boolean'
|
||||
export { BreakExpression } from './break'
|
||||
export { ContinueExpression } from './continue'
|
||||
export { ForEachExpression } from './forEach'
|
||||
export { FunctionExpression } from './function'
|
||||
export { GenericOperatorExpression } from './genericOperator'
|
||||
export { GroupExpression } from './group'
|
||||
export { LoopExpression } from './loop'
|
||||
export { NameExpression } from './name'
|
||||
export { NumberExpression } from './number'
|
||||
export { PostfixExpression } from './postfix'
|
||||
export { PrefixExpression } from './prefix'
|
||||
export { ReturnExpression } from './return'
|
||||
export { StatementExpression } from './statement'
|
||||
export { StaticExpression } from './static'
|
||||
export { StringExpression } from './string'
|
||||
export { TernaryExpression } from './ternary'
|
||||
export { VoidExpression } from './void'
|
||||
@@ -1,56 +0,0 @@
|
||||
import { Expression, IExpression } from '../expression'
|
||||
|
||||
export class LoopExpression extends Expression {
|
||||
type = 'LoopExpression'
|
||||
|
||||
constructor(
|
||||
protected count: IExpression,
|
||||
protected expression: IExpression
|
||||
) {
|
||||
super()
|
||||
}
|
||||
|
||||
get allExpressions() {
|
||||
return [this.count, this.expression]
|
||||
}
|
||||
setExpressionAt(index: number, expr: IExpression) {
|
||||
if (index === 0) this.count = expr
|
||||
else if (index === 1) this.expression = expr
|
||||
}
|
||||
|
||||
get isReturn() {
|
||||
return this.expression.isReturn
|
||||
}
|
||||
|
||||
isStatic() {
|
||||
return this.count.isStatic() && this.expression.isStatic()
|
||||
}
|
||||
|
||||
eval() {
|
||||
const repeatCount = Number(this.count.eval())
|
||||
if (Number.isNaN(repeatCount))
|
||||
throw new Error(
|
||||
`First loop() argument must be of type number, received "${typeof this.count.eval()}"`
|
||||
)
|
||||
if (repeatCount > 1024)
|
||||
throw new Error(
|
||||
`Cannot loop more than 1024x times, received "${repeatCount}"`
|
||||
)
|
||||
|
||||
let i = 0
|
||||
while (i < repeatCount) {
|
||||
i++
|
||||
const res = this.expression.eval()
|
||||
|
||||
if (this.expression.isBreak) break
|
||||
else if (this.expression.isContinue) continue
|
||||
else if (this.expression.isReturn) return res
|
||||
}
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
toString() {
|
||||
return `loop(${this.count.toString()},${this.expression.toString()})`
|
||||
}
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
import { ExecutionEnvironment } from '../../env/env'
|
||||
import { Expression } from '../expression'
|
||||
|
||||
export class NameExpression extends Expression {
|
||||
type = 'NameExpression'
|
||||
|
||||
constructor(
|
||||
public executionEnv: ExecutionEnvironment,
|
||||
protected name: string,
|
||||
protected isFunctionCall = false
|
||||
) {
|
||||
super()
|
||||
}
|
||||
|
||||
get allExpressions() {
|
||||
return []
|
||||
}
|
||||
setExpressionAt() {}
|
||||
|
||||
isStatic() {
|
||||
return false
|
||||
}
|
||||
|
||||
setPointer(value: unknown) {
|
||||
this.executionEnv.setAt(this.name, value)
|
||||
}
|
||||
|
||||
setFunctionCall(value = true) {
|
||||
this.isFunctionCall = value
|
||||
}
|
||||
setName(name: string) {
|
||||
this.name = name
|
||||
}
|
||||
setExecutionEnv(executionEnv: ExecutionEnvironment) {
|
||||
this.executionEnv = executionEnv
|
||||
}
|
||||
|
||||
eval() {
|
||||
const value = this.executionEnv.getFrom(this.name)
|
||||
if (!this.isFunctionCall && typeof value === 'function') return value()
|
||||
return value
|
||||
}
|
||||
|
||||
toString() {
|
||||
return this.name
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
import { Expression } from '../expression'
|
||||
|
||||
export class NumberExpression extends Expression {
|
||||
type = 'NumberExpression'
|
||||
|
||||
constructor(protected value: number) {
|
||||
super()
|
||||
}
|
||||
|
||||
get allExpressions() {
|
||||
return []
|
||||
}
|
||||
setExpressionAt() {}
|
||||
|
||||
isStatic() {
|
||||
return true
|
||||
}
|
||||
|
||||
eval() {
|
||||
return this.value
|
||||
}
|
||||
toString() {
|
||||
return '' + this.value
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
import { TTokenType } from '../../tokenizer/token'
|
||||
import { Expression, IExpression } from '../expression'
|
||||
|
||||
export class PostfixExpression extends Expression {
|
||||
type = 'PostfixExpression'
|
||||
|
||||
constructor(
|
||||
protected expression: IExpression,
|
||||
protected tokenType: TTokenType
|
||||
) {
|
||||
super()
|
||||
}
|
||||
|
||||
get allExpressions() {
|
||||
return [this.expression]
|
||||
}
|
||||
setExpressionAt(_: number, expr: IExpression) {
|
||||
this.expression = expr
|
||||
}
|
||||
|
||||
isStatic() {
|
||||
return this.expression.isStatic()
|
||||
}
|
||||
|
||||
eval() {
|
||||
switch (this.tokenType) {
|
||||
case 'X': {
|
||||
// DO SOMETHING
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
import { TTokenType } from '../../tokenizer/token'
|
||||
import { Expression, IExpression } from '../expression'
|
||||
|
||||
export class PrefixExpression extends Expression {
|
||||
type = 'PrefixExpression'
|
||||
|
||||
constructor(
|
||||
protected tokenType: TTokenType,
|
||||
protected expression: IExpression
|
||||
) {
|
||||
super()
|
||||
}
|
||||
|
||||
get allExpressions() {
|
||||
return [this.expression]
|
||||
}
|
||||
setExpressionAt(_: number, expr: IExpression) {
|
||||
this.expression = expr
|
||||
}
|
||||
|
||||
isStatic() {
|
||||
return this.expression.isStatic()
|
||||
}
|
||||
|
||||
eval() {
|
||||
const value = this.expression.eval()
|
||||
|
||||
if (typeof value !== 'number')
|
||||
throw new Error(
|
||||
`Cannot use "${
|
||||
this.tokenType
|
||||
}" operator in front of ${typeof value} "${value}"`
|
||||
)
|
||||
|
||||
switch (this.tokenType) {
|
||||
case 'MINUS': {
|
||||
return -value
|
||||
}
|
||||
case 'BANG': {
|
||||
return !value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
toString() {
|
||||
switch (this.tokenType) {
|
||||
case 'MINUS': {
|
||||
return `-${this.expression.toString()}`
|
||||
}
|
||||
case 'BANG': {
|
||||
return `!${this.expression.toString()}`
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(`Unknown prefix operator: "${this.tokenType}"`)
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
import { Expression, IExpression } from '../expression'
|
||||
|
||||
export class ReturnExpression extends Expression {
|
||||
type = 'ReturnExpression'
|
||||
isReturn = true
|
||||
|
||||
constructor(protected expression: IExpression) {
|
||||
super()
|
||||
}
|
||||
|
||||
get allExpressions() {
|
||||
return [this.expression]
|
||||
}
|
||||
setExpressionAt(_: number, expr: IExpression) {
|
||||
this.expression = expr
|
||||
}
|
||||
|
||||
isStatic() {
|
||||
return false
|
||||
}
|
||||
|
||||
eval() {
|
||||
return this.expression.eval()
|
||||
}
|
||||
|
||||
toString() {
|
||||
return `return ${this.expression.toString()}`
|
||||
}
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
import { Expression, IExpression } from '../expression'
|
||||
import { StaticExpression } from './static'
|
||||
import { VoidExpression } from './void'
|
||||
|
||||
export class StatementExpression extends Expression {
|
||||
type = 'StatementExpression'
|
||||
protected didReturn?: boolean = undefined
|
||||
protected wasLoopBroken = false
|
||||
protected wasLoopContinued = false
|
||||
|
||||
constructor(protected expressions: IExpression[]) {
|
||||
super()
|
||||
}
|
||||
|
||||
get allExpressions() {
|
||||
return this.expressions
|
||||
}
|
||||
setExpressionAt(index: number, expr: IExpression) {
|
||||
this.expressions[index] = expr
|
||||
}
|
||||
|
||||
get isReturn() {
|
||||
if (this.didReturn !== undefined) return this.didReturn
|
||||
|
||||
// This breaks scope vs. statement parsing for some reason
|
||||
let i = 0
|
||||
while (i < this.expressions.length) {
|
||||
const expr = this.expressions[i]
|
||||
|
||||
if (expr.isBreak) return false
|
||||
if (expr.isContinue) return false
|
||||
if (expr.isReturn) {
|
||||
this.didReturn = true
|
||||
return true
|
||||
}
|
||||
i++
|
||||
}
|
||||
this.didReturn = false
|
||||
return false
|
||||
}
|
||||
|
||||
get isBreak() {
|
||||
if (this.wasLoopBroken) {
|
||||
this.wasLoopBroken = false
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
get isContinue() {
|
||||
if (this.wasLoopContinued) {
|
||||
this.wasLoopContinued = false
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
isStatic() {
|
||||
let i = 0
|
||||
while (i < this.expressions.length) {
|
||||
if (!this.expressions[i].isStatic()) return false
|
||||
i++
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
eval() {
|
||||
this.didReturn = false
|
||||
this.wasLoopBroken = false
|
||||
this.wasLoopContinued = false
|
||||
let i = 0
|
||||
while (i < this.expressions.length) {
|
||||
let res = this.expressions[i].eval()
|
||||
|
||||
if (this.expressions[i].isReturn) {
|
||||
this.didReturn = true
|
||||
return res
|
||||
} else if (this.expressions[i].isContinue) {
|
||||
this.wasLoopContinued = true
|
||||
return
|
||||
} else if (this.expressions[i].isBreak) {
|
||||
this.wasLoopBroken = true
|
||||
return
|
||||
}
|
||||
i++
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
toString() {
|
||||
let str = ''
|
||||
for (const expr of this.expressions) {
|
||||
if (
|
||||
expr instanceof VoidExpression ||
|
||||
(expr instanceof StaticExpression && !expr.isReturn)
|
||||
)
|
||||
continue
|
||||
str += `${expr.toString()};`
|
||||
}
|
||||
|
||||
return str
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
import { Expression } from '../expression'
|
||||
|
||||
export class StaticExpression extends Expression {
|
||||
type = 'StaticExpression'
|
||||
constructor(protected value: unknown, public readonly isReturn = false) {
|
||||
super()
|
||||
}
|
||||
|
||||
get allExpressions() {
|
||||
return []
|
||||
}
|
||||
setExpressionAt() {}
|
||||
|
||||
isStatic() {
|
||||
return true
|
||||
}
|
||||
|
||||
eval() {
|
||||
return this.value
|
||||
}
|
||||
toString() {
|
||||
let val = this.value
|
||||
if (typeof val === 'string') val = `'${val}'`
|
||||
|
||||
if (this.isReturn) return `return ${val}`
|
||||
return '' + val
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
import { Expression } from '../expression'
|
||||
|
||||
export class StringExpression extends Expression {
|
||||
type = 'StringExpression'
|
||||
|
||||
constructor(protected name: string) {
|
||||
super()
|
||||
}
|
||||
|
||||
get allExpressions() {
|
||||
return []
|
||||
}
|
||||
setExpressionAt() {}
|
||||
|
||||
isStatic() {
|
||||
return true
|
||||
}
|
||||
|
||||
eval() {
|
||||
return this.name.substring(1, this.name.length - 1)
|
||||
}
|
||||
|
||||
toString() {
|
||||
return this.name
|
||||
}
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
import { Expression, IExpression } from '../expression'
|
||||
import { VoidExpression } from './void'
|
||||
|
||||
export class TernaryExpression extends Expression {
|
||||
type = 'TernaryExpression'
|
||||
protected leftResult: unknown
|
||||
|
||||
constructor(
|
||||
protected leftExpression: IExpression,
|
||||
protected thenExpression: IExpression,
|
||||
protected elseExpression: IExpression
|
||||
) {
|
||||
super()
|
||||
}
|
||||
|
||||
get allExpressions() {
|
||||
if (this.leftExpression.isStatic())
|
||||
return [
|
||||
this.leftExpression,
|
||||
this.leftExpression.eval()
|
||||
? this.thenExpression
|
||||
: this.elseExpression,
|
||||
]
|
||||
return [this.leftExpression, this.thenExpression, this.elseExpression]
|
||||
}
|
||||
setExpressionAt(index: number, expr: IExpression) {
|
||||
if (index === 0) this.leftExpression = expr
|
||||
else if (index === 1) this.thenExpression = expr
|
||||
else if (index === 2) this.elseExpression = expr
|
||||
}
|
||||
|
||||
get isReturn() {
|
||||
if (this.leftResult === undefined)
|
||||
return this.thenExpression.isReturn && this.elseExpression.isReturn
|
||||
return this.leftResult
|
||||
? this.thenExpression.isReturn
|
||||
: this.elseExpression.isReturn
|
||||
}
|
||||
get hasReturn() {
|
||||
return this.thenExpression.isReturn || this.elseExpression.isReturn
|
||||
}
|
||||
get isContinue() {
|
||||
if (this.leftResult === undefined)
|
||||
return (
|
||||
this.thenExpression.isContinue && this.elseExpression.isContinue
|
||||
)
|
||||
return this.leftResult
|
||||
? this.thenExpression.isContinue
|
||||
: this.elseExpression.isContinue
|
||||
}
|
||||
get isBreak() {
|
||||
if (this.leftResult === undefined)
|
||||
return this.thenExpression.isBreak && this.elseExpression.isBreak
|
||||
return this.leftResult
|
||||
? this.thenExpression.isBreak
|
||||
: this.elseExpression.isBreak
|
||||
}
|
||||
|
||||
isStatic() {
|
||||
return (
|
||||
this.leftExpression.isStatic() &&
|
||||
this.thenExpression.isStatic() &&
|
||||
this.elseExpression.isStatic()
|
||||
)
|
||||
}
|
||||
|
||||
eval() {
|
||||
this.leftResult = this.leftExpression.eval()
|
||||
return this.leftResult
|
||||
? this.thenExpression.eval()
|
||||
: this.elseExpression.eval()
|
||||
}
|
||||
|
||||
toString() {
|
||||
if (this.elseExpression instanceof VoidExpression)
|
||||
return `${this.leftExpression.toString()}?${this.thenExpression.toString()}`
|
||||
return `${this.leftExpression.toString()}?${this.thenExpression.toString()}:${this.elseExpression.toString()}`
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
import { Expression } from '../expression'
|
||||
|
||||
export class VoidExpression extends Expression {
|
||||
type = 'VoidExpression'
|
||||
|
||||
get allExpressions() {
|
||||
return []
|
||||
}
|
||||
setExpressionAt() {}
|
||||
|
||||
isStatic() {
|
||||
return true
|
||||
}
|
||||
|
||||
eval() {
|
||||
return 0
|
||||
}
|
||||
toString() {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user