Compare commits
242 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 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 |
@@ -20,3 +20,4 @@ wallaby.js
|
||||
.vscode
|
||||
.theia
|
||||
type_definitions
|
||||
tsconfig.tsbuildinfo
|
||||
|
||||
@@ -4,3 +4,8 @@
|
||||
- 更新日志 [](https://docs.yumc.pw/MiaoScript/CHANGELOG.html)
|
||||
- 安装文档 [](https://docs.yumc.pw/MiaoScript/1-user/1.1-check-env.html)
|
||||
- 开发文档 [](https://docs.yumc.pw/MiaoScript/2-develop/1.1-check-env.html)
|
||||
- 兼容服务端 Spigot CatServer Sponge BungeeCord Nukkit(没错 他还兼容Nukkit)
|
||||
|
||||
### 腐竹版本(开发中)
|
||||
|
||||
- 先上几张图
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"version": "0.6.5",
|
||||
"version": "0.8.1",
|
||||
"useWorkspaces": true,
|
||||
"npmClient": "yarn",
|
||||
"packages": [
|
||||
@@ -10,6 +10,7 @@
|
||||
"stream": true
|
||||
},
|
||||
"publish": {
|
||||
"access": "public",
|
||||
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,12 +12,14 @@
|
||||
"build": "lerna run build --scope=\"@ccms/!(plugins)\"",
|
||||
"build:plugins": "lerna run build --scope=\"@ccms/plugins\"",
|
||||
"ug": "yarn upgrade-interactive --latest",
|
||||
"lp": "lerna publish"
|
||||
"np": "lerna exec \"npm publish --access=public --registry https://registry.npmjs.org\" --scope=\"@ccms/!(client|plugins)\"",
|
||||
"lsp": "npm login --registry=https://registry.npmjs.org --scope=@ccms",
|
||||
"lp": "lerna publish --registry https://registry.npmjs.org"
|
||||
},
|
||||
"workspaces": [
|
||||
"packages/*"
|
||||
],
|
||||
"devDependencies": {
|
||||
"lerna": "^3.20.2"
|
||||
"lerna": "^3.21.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
1
packages/amqp/.npmignore
Symbolic link
1
packages/amqp/.npmignore
Symbolic link
@@ -0,0 +1 @@
|
||||
../../.npmignore
|
||||
32
packages/amqp/package.json
Normal file
32
packages/amqp/package.json
Normal file
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"name": "@ccms/amqp",
|
||||
"version": "0.8.1",
|
||||
"description": "MiaoScript amqp package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
"minecraft",
|
||||
"bukkit",
|
||||
"sponge"
|
||||
],
|
||||
"author": "MiaoWoo <admin@yumc.pw>",
|
||||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.8.1",
|
||||
"@ccms/common": "^0.8.0",
|
||||
"@ccms/container": "^0.8.0",
|
||||
"@ccms/nashorn": "^0.8.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.2"
|
||||
}
|
||||
}
|
||||
17
packages/amqp/src/adapter/admin.ts
Normal file
17
packages/amqp/src/adapter/admin.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import { ConnectionFactoryAdapter } from "./connection"
|
||||
import { RabbitTemplateAdapter } from "./template"
|
||||
import { JSClass } from "@ccms/container"
|
||||
|
||||
export const RabbitAdmin = Java.type('org.springframework.amqp.rabbit.core.RabbitAdmin')
|
||||
|
||||
export class RabbitAdminAdapter {
|
||||
@JSClass('org.springframework.amqp.rabbit.core.RabbitAdmin')
|
||||
private RabbitAdmin: org.springframework.amqp.rabbit.core.RabbitAdmin
|
||||
private _Handler: org.springframework.amqp.rabbit.core.RabbitAdmin
|
||||
constructor(config: RabbitTemplateAdapter | org.springframework.amqp.rabbit.core.RabbitTemplate | ConnectionFactoryAdapter | org.springframework.amqp.rabbit.connection.ConnectionFactory) {
|
||||
this._Handler = new RabbitAdmin((config instanceof RabbitTemplateAdapter || config instanceof ConnectionFactoryAdapter) ? config.getHandler() : config)
|
||||
}
|
||||
getHandler(): org.springframework.amqp.rabbit.core.RabbitAdmin {
|
||||
return this._Handler
|
||||
}
|
||||
}
|
||||
30
packages/amqp/src/adapter/callback.ts
Normal file
30
packages/amqp/src/adapter/callback.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
export const ConfirmCallback = Java.type('org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback')
|
||||
export const ReturnCallback = Java.type('org.springframework.amqp.rabbit.core.RabbitTemplate.ReturnCallback')
|
||||
|
||||
export abstract class ConfirmCallbackAdapter {
|
||||
private _Handler: org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback
|
||||
constructor() {
|
||||
let ConfirmCallbackImpl = Java.extend(ReturnCallback, {
|
||||
confirm: (correlationData: org.springframework.amqp.rabbit.connection.CorrelationData, ack: boolean, cause: string) => this.confirm(correlationData, ack, cause)
|
||||
})
|
||||
this._Handler = new ConfirmCallbackImpl()
|
||||
}
|
||||
abstract confirm(correlationData: org.springframework.amqp.rabbit.connection.CorrelationData, ack: boolean, cause: string)
|
||||
getHandler() {
|
||||
return this._Handler
|
||||
}
|
||||
}
|
||||
|
||||
export abstract class ReturnCallbackAdapter {
|
||||
private _Handler: org.springframework.amqp.rabbit.core.RabbitTemplate.ReturnCallback
|
||||
constructor() {
|
||||
let ReturnCallbackImpl = Java.extend(ReturnCallback, {
|
||||
returnedMessage: (message: org.springframework.amqp.core.Message, replyCode: number, replyText: string, exchange: string, routingKey: string) => this.returnedMessage(message, replyCode, replyText, exchange, routingKey)
|
||||
})
|
||||
this._Handler = new ReturnCallbackImpl()
|
||||
}
|
||||
abstract returnedMessage(message: org.springframework.amqp.core.Message, replyCode: number, replyText: string, exchange: string, routingKey: string)
|
||||
getHandler() {
|
||||
return this._Handler
|
||||
}
|
||||
}
|
||||
31
packages/amqp/src/adapter/connection.ts
Normal file
31
packages/amqp/src/adapter/connection.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import threadPool from '@ccms/common/dist/thread-pool'
|
||||
|
||||
export const ConnectionFactory = Java.type('org.springframework.amqp.rabbit.connection.ConnectionFactory')
|
||||
const CachingConnectionFactory = Java.type('org.springframework.amqp.rabbit.connection.CachingConnectionFactory')
|
||||
interface ConnectionConfig {
|
||||
url: string,
|
||||
username?: string,
|
||||
password?: string,
|
||||
publisherConfirms?: boolean
|
||||
cacheSize?: number
|
||||
}
|
||||
|
||||
export class ConnectionFactoryAdapter {
|
||||
private _Handler: org.springframework.amqp.rabbit.connection.CachingConnectionFactory
|
||||
|
||||
constructor(config: ConnectionConfig) {
|
||||
if (!config.url) { throw new Error('Connection UrI Can\'t be undefiend!') }
|
||||
config = { publisherConfirms: true, cacheSize: 50, ...config }
|
||||
this._Handler = new CachingConnectionFactory(new java.net.URI(config.url))
|
||||
config.username && this._Handler.setUsername(config.username)
|
||||
config.password && this._Handler.setPassword(config.password)
|
||||
this._Handler.setPublisherConfirms(config.publisherConfirms)
|
||||
this._Handler.setExecutor(threadPool.create({
|
||||
groupName: '@ccms/amqp-rabbit'
|
||||
}))
|
||||
this._Handler.setChannelCacheSize(config.cacheSize)
|
||||
}
|
||||
getHandler() {
|
||||
return this._Handler
|
||||
}
|
||||
}
|
||||
30
packages/amqp/src/adapter/container.ts
Normal file
30
packages/amqp/src/adapter/container.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { ConnectionFactoryAdapter, ConnectionFactory } from "./connection"
|
||||
import { ChannelAwareMessageListenerAdapter, ChannelAwareMessageListener } from "./listener"
|
||||
|
||||
export const SimpleMessageListenerContainer = org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer
|
||||
export const AcknowledgeMode: org.springframework.amqp.core.AcknowledgeMode = Java.type('org.springframework.amqp.core.AcknowledgeMode')
|
||||
interface ContainerConfig {
|
||||
connectionFactory: ConnectionFactoryAdapter | typeof ConnectionFactory
|
||||
queueNames: string[]
|
||||
messageListener: ChannelAwareMessageListenerAdapter | typeof ChannelAwareMessageListener
|
||||
maxConcurrentConsumers?: number
|
||||
concurrentConsumers?: number
|
||||
acknowledgeMode?: org.springframework.amqp.core.AcknowledgeMode
|
||||
}
|
||||
|
||||
export class MessageListenerContainerAdapter {
|
||||
private _Handler: org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer
|
||||
constructor(config: ContainerConfig) {
|
||||
config = { concurrentConsumers: 5, maxConcurrentConsumers: 10, acknowledgeMode: AcknowledgeMode.AUTO, ...config }
|
||||
this._Handler = new SimpleMessageListenerContainer(config.connectionFactory instanceof ConnectionFactoryAdapter ? config.connectionFactory.getHandler() : config.connectionFactory)
|
||||
//@ts-ignore
|
||||
this._Handler.setQueueNames(config.queueNames)
|
||||
this._Handler.setMaxConcurrentConsumers(config.maxConcurrentConsumers)
|
||||
this._Handler.setConcurrentConsumers(config.concurrentConsumers)
|
||||
this._Handler.setAcknowledgeMode(config.acknowledgeMode)
|
||||
this._Handler.setMessageListener(config.messageListener instanceof ChannelAwareMessageListenerAdapter ? config.messageListener.getHandler() : config.messageListener)
|
||||
}
|
||||
getHandler() {
|
||||
return this._Handler
|
||||
}
|
||||
}
|
||||
37
packages/amqp/src/adapter/converter.ts
Normal file
37
packages/amqp/src/adapter/converter.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
const JavaString = Java.type('java.lang.String')
|
||||
const MessageProperties = org.springframework.amqp.core.MessageProperties
|
||||
const Message = org.springframework.amqp.core.Message
|
||||
|
||||
export const MessageConverter = Java.type('org.springframework.amqp.support.converter.MessageConverter')
|
||||
|
||||
export class MessageConverterAdapter {
|
||||
private _Handler: org.springframework.amqp.support.converter.MessageConverter
|
||||
constructor() {
|
||||
var MessageConverterImpl = Java.extend(MessageConverter, {
|
||||
toMessage: (object: any, messageProperties: org.springframework.amqp.core.MessageProperties) => this.toMessage(object, messageProperties),
|
||||
fromMessage: (message: org.springframework.amqp.core.Message) => this.fromMessage(message)
|
||||
})
|
||||
this._Handler = new MessageConverterImpl()
|
||||
}
|
||||
toMessage(object: any, messageProperties: org.springframework.amqp.core.MessageProperties) {
|
||||
if (typeof object == "string") {
|
||||
messageProperties.setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN)
|
||||
return new Message(new JavaString(object).getBytes(), messageProperties)
|
||||
} else {
|
||||
messageProperties.setContentType(MessageProperties.CONTENT_TYPE_JSON)
|
||||
return new Message(new JavaString(JSON.stringify(object)).getBytes(), messageProperties)
|
||||
}
|
||||
}
|
||||
fromMessage(message: org.springframework.amqp.core.Message) {
|
||||
if (message.getMessageProperties().getContentType() == MessageProperties.CONTENT_TYPE_TEXT_PLAIN) {
|
||||
return new JavaString(message.getBody(), message.getMessageProperties().getContentEncoding())
|
||||
}
|
||||
if (message.getMessageProperties().getContentType() == MessageProperties.CONTENT_TYPE_JSON) {
|
||||
return JSON.parse(new JavaString(message.getBody(), message.getMessageProperties().getContentEncoding()))
|
||||
}
|
||||
return message
|
||||
}
|
||||
getHandler() {
|
||||
return this._Handler
|
||||
}
|
||||
}
|
||||
7
packages/amqp/src/adapter/index.ts
Normal file
7
packages/amqp/src/adapter/index.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
export * from './admin'
|
||||
export * from './callback'
|
||||
export * from './connection'
|
||||
export * from './container'
|
||||
export * from './converter'
|
||||
export * from './listener'
|
||||
export * from './template'
|
||||
49
packages/amqp/src/adapter/listener.ts
Normal file
49
packages/amqp/src/adapter/listener.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
const JavaString = Java.type('java.lang.String')
|
||||
export const MessageProperties = org.springframework.amqp.core.MessageProperties
|
||||
export const ChannelAwareMessageListener = Java.type('org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener')
|
||||
export const AmqpRejectAndDontRequeueException = org.springframework.amqp.AmqpRejectAndDontRequeueException
|
||||
export const Channel: com.rabbitmq.client.Channel = Java.type('com.rabbitmq.client.Channel')
|
||||
export const Message = org.springframework.amqp.core.Message
|
||||
export type MessageHandler<T> = (content: T, message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel) => any
|
||||
export abstract class ChannelAwareMessageListenerAdapter<T = any> {
|
||||
private _Handler: org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener
|
||||
constructor(manual: boolean = false) {
|
||||
let ChannelAwareMessageListenerImpl = Java.extend(ChannelAwareMessageListener, {
|
||||
onMessage: (message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel) => {
|
||||
let content = new JavaString(message.getBody(), message.getMessageProperties().getContentEncoding() || "UTF-8")
|
||||
try {
|
||||
if (message.getMessageProperties().getContentType() == MessageProperties.CONTENT_TYPE_JSON) {
|
||||
content = JSON.parse(content)
|
||||
}
|
||||
} catch (error) {
|
||||
if (manual) {
|
||||
channel.basicReject(message.getMessageProperties().getDeliveryTag(), true)
|
||||
} else {
|
||||
throw new AmqpRejectAndDontRequeueException(`${error}`, error)
|
||||
}
|
||||
}
|
||||
manual ? this.manualOnMessage(content, message, channel) : this.onMessage(content, message, channel)
|
||||
}
|
||||
})
|
||||
this._Handler = new ChannelAwareMessageListenerImpl()
|
||||
}
|
||||
abstract onMessage(content: T, message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel): any
|
||||
onError(error: Error, message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel): any { }
|
||||
getHandler() {
|
||||
return this._Handler
|
||||
}
|
||||
private manualOnMessage(content: T, message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel) {
|
||||
let deliveryTag = message.getMessageProperties().getDeliveryTag()
|
||||
try {
|
||||
if (this.onMessage(content, message, channel)) {
|
||||
channel.basicAck(deliveryTag, false)
|
||||
} else if (message.getMessageProperties().getRedelivered()) {
|
||||
channel.basicReject(deliveryTag, true)
|
||||
} else {
|
||||
channel.basicNack(deliveryTag, false, true)
|
||||
}
|
||||
} catch (error) {
|
||||
channel.basicReject(deliveryTag, this.onError(error, message, channel))
|
||||
}
|
||||
}
|
||||
}
|
||||
27
packages/amqp/src/adapter/template.ts
Normal file
27
packages/amqp/src/adapter/template.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { MessageConverterAdapter } from "./converter"
|
||||
import { ConnectionFactoryAdapter } from "./connection"
|
||||
import { ConfirmCallbackAdapter, ReturnCallbackAdapter } from "./callback"
|
||||
|
||||
export const RabbitTemplate = Java.type('org.springframework.amqp.rabbit.core.RabbitTemplate')
|
||||
|
||||
interface TemplateConfig {
|
||||
connectionFactory: ConnectionFactoryAdapter | org.springframework.amqp.rabbit.connection.ConnectionFactory
|
||||
confirmCallback?: ConfirmCallbackAdapter
|
||||
returnCallback?: ReturnCallbackAdapter
|
||||
messageConverter?: MessageConverterAdapter
|
||||
}
|
||||
export class RabbitTemplateAdapter {
|
||||
private _Handler: org.springframework.amqp.rabbit.core.RabbitTemplate
|
||||
constructor(config: TemplateConfig) {
|
||||
config = { messageConverter: new MessageConverterAdapter(), ...config }
|
||||
console.debug(JSON.stringify(config))
|
||||
this._Handler = new RabbitTemplate(config.connectionFactory instanceof ConnectionFactoryAdapter ? config.connectionFactory.getHandler() : config.connectionFactory)
|
||||
config.returnCallback && this._Handler.setReturnCallback(config.returnCallback.getHandler())
|
||||
config.confirmCallback && this._Handler.setConfirmCallback(config.confirmCallback.getHandler())
|
||||
config.messageConverter && this._Handler.setMessageConverter(config.messageConverter.getHandler())
|
||||
}
|
||||
|
||||
getHandler() {
|
||||
return this._Handler
|
||||
}
|
||||
}
|
||||
89
packages/amqp/src/admin.ts
Normal file
89
packages/amqp/src/admin.ts
Normal file
@@ -0,0 +1,89 @@
|
||||
import { JSClass } from "@ccms/container"
|
||||
import { RabbitAdminAdapter, MessageListenerContainerAdapter, AcknowledgeMode, MessageHandler, ChannelAwareMessageListenerAdapter } from "./adapter"
|
||||
|
||||
export class AmqpAdmin {
|
||||
@JSClass('org.springframework.amqp.core.TopicExchange')
|
||||
private TopicExchange: typeof org.springframework.amqp.core.TopicExchange
|
||||
@JSClass('org.springframework.amqp.core.Queue')
|
||||
private Queue: typeof org.springframework.amqp.core.Queue
|
||||
@JSClass('org.springframework.amqp.core.Binding')
|
||||
private Binding: typeof org.springframework.amqp.core.Binding
|
||||
@JSClass('org.springframework.amqp.rabbit.core.RabbitAdmin')
|
||||
private RabbitAdmin: typeof org.springframework.amqp.rabbit.core.RabbitAdmin
|
||||
@JSClass('org.springframework.amqp.core.Binding.DestinationType')
|
||||
private DestinationType: org.springframework.amqp.core.Binding.DestinationType
|
||||
|
||||
private amqpAdmin: org.springframework.amqp.rabbit.core.RabbitAdmin
|
||||
|
||||
constructor(amqpAdmin: org.springframework.amqp.rabbit.core.RabbitAdmin | any) {
|
||||
if (amqpAdmin instanceof this.RabbitAdmin) {
|
||||
this.amqpAdmin = amqpAdmin
|
||||
} else if (amqpAdmin instanceof RabbitAdminAdapter) {
|
||||
this.amqpAdmin = amqpAdmin.getHandler()
|
||||
} else {
|
||||
this.amqpAdmin = new RabbitAdminAdapter(amqpAdmin).getHandler()
|
||||
}
|
||||
}
|
||||
|
||||
getHandler() {
|
||||
return this.amqpAdmin
|
||||
}
|
||||
|
||||
getQueueProperties(name: string) {
|
||||
return this.amqpAdmin.getQueueProperties(name)
|
||||
}
|
||||
|
||||
declareExchange(name: string) {
|
||||
let exchange = new this.TopicExchange(name, true, false)
|
||||
this.amqpAdmin.declareExchange(exchange)
|
||||
return this
|
||||
}
|
||||
|
||||
declareQueue(name: string) {
|
||||
let queue = new this.Queue(name, true)
|
||||
this.amqpAdmin.declareQueue(queue)
|
||||
return this
|
||||
}
|
||||
|
||||
declareBinding(queue: string, exchange: string, routerKey: string, argument: any = null) {
|
||||
let binding = new this.Binding(queue, this.DestinationType.QUEUE, exchange, routerKey, argument)
|
||||
this.amqpAdmin.declareBinding(binding)
|
||||
return this
|
||||
}
|
||||
|
||||
declareQueueAndBindExchange(queue: string, exchange: string, routerKey: string) {
|
||||
return this.declareQueue(queue).declareExchange(exchange).declareBinding(queue, exchange, routerKey)
|
||||
}
|
||||
|
||||
createContainer<T>(queue: string, listener: MessageHandler<T>, acknowledgeMode = AcknowledgeMode.AUTO) {
|
||||
let connection = this.amqpAdmin.getRabbitTemplate().getConnectionFactory()
|
||||
return new MessageListenerContainerAdapter({
|
||||
connectionFactory: connection,
|
||||
queueNames: [queue],
|
||||
messageListener: new SimpleMessageHandler(listener),
|
||||
acknowledgeMode: acknowledgeMode
|
||||
}).getHandler()
|
||||
}
|
||||
|
||||
send()
|
||||
send() {
|
||||
|
||||
}
|
||||
|
||||
getTemplate() {
|
||||
return this.amqpAdmin.getRabbitTemplate()
|
||||
}
|
||||
|
||||
close() {
|
||||
this.getTemplate().stop()
|
||||
}
|
||||
}
|
||||
|
||||
export class SimpleMessageHandler extends ChannelAwareMessageListenerAdapter {
|
||||
constructor(private handler: MessageHandler<any>) {
|
||||
super()
|
||||
}
|
||||
onMessage(content: any, message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel) {
|
||||
return this.handler(content, message, channel)
|
||||
}
|
||||
}
|
||||
3
packages/amqp/src/constants.ts
Normal file
3
packages/amqp/src/constants.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export const METADATA_KEY = {
|
||||
|
||||
}
|
||||
34
packages/amqp/src/index.ts
Normal file
34
packages/amqp/src/index.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
/// <reference types="@ccms/nashorn" />
|
||||
/// <reference types="@javatypes/jdk" />
|
||||
/// <reference types="@javatypes/spring-amqp" />
|
||||
/// <reference types="@javatypes/spring-rabbit" />
|
||||
/// <reference types="@javatypes/amqp-client" />
|
||||
|
||||
import { amqp } from '@ccms/api'
|
||||
import { getContainer, reduceMetadata } from '@ccms/container'
|
||||
|
||||
function init() {
|
||||
const beanFactory = base.getInstance().getAutowireCapableBeanFactory()
|
||||
getContainer().bind(amqp.rabbit.Template).toDynamicValue((ctx) => {
|
||||
let metadata = reduceMetadata(ctx)
|
||||
if (!metadata.named) {
|
||||
return beanFactory.getBean('rabbitTemplate')
|
||||
} else {
|
||||
return beanFactory.getBean(`${metadata.named}-rabbitTemplate`)
|
||||
}
|
||||
})
|
||||
getContainer().bind(amqp.rabbit.Admin).toDynamicValue((ctx) => {
|
||||
let metadata = reduceMetadata(ctx)
|
||||
if (!metadata.named) {
|
||||
return beanFactory.getBean('rabbitAdmin')
|
||||
} else {
|
||||
return beanFactory.getBean(`${metadata.named}-rabbitAdmin`)
|
||||
}
|
||||
})
|
||||
}
|
||||
init()
|
||||
|
||||
export * from './admin'
|
||||
export * from './adapter'
|
||||
export * from './manager'
|
||||
export * from './constants'
|
||||
5
packages/amqp/src/listener.ts
Normal file
5
packages/amqp/src/listener.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
export class AmqpListener {
|
||||
constructor() {
|
||||
|
||||
}
|
||||
}
|
||||
18
packages/amqp/src/manager.ts
Normal file
18
packages/amqp/src/manager.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { amqp } from "@ccms/api"
|
||||
import { provideSingleton } from "@ccms/container"
|
||||
|
||||
import { ConnectionFactoryAdapter, RabbitTemplateAdapter, RabbitAdminAdapter } from "./adapter"
|
||||
import { AmqpAdmin } from "./admin"
|
||||
|
||||
@provideSingleton(amqp.Manager)
|
||||
export class AmqpManager {
|
||||
createConnection(url: string, username: string, password: string) {
|
||||
return new ConnectionFactoryAdapter({ url, username, password })
|
||||
}
|
||||
createTemplate(adapter: ConnectionFactoryAdapter) {
|
||||
return new RabbitTemplateAdapter({ connectionFactory: adapter })
|
||||
}
|
||||
createAdmin(adapter: RabbitTemplateAdapter | ConnectionFactoryAdapter) {
|
||||
return new AmqpAdmin(new RabbitAdminAdapter(adapter))
|
||||
}
|
||||
}
|
||||
7
packages/amqp/tsconfig.json
Normal file
7
packages/amqp/tsconfig.json
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"baseUrl": "src",
|
||||
"outDir": "dist"
|
||||
}
|
||||
}
|
||||
1
packages/api/.npmignore
Symbolic link
1
packages/api/.npmignore
Symbolic link
@@ -0,0 +1 @@
|
||||
../../.npmignore
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/api",
|
||||
"version": "0.6.5",
|
||||
"version": "0.8.1",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,8 +19,9 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/container": "^0.6.0",
|
||||
"@ccms/ployfill": "^0.6.5",
|
||||
"@ccms/common": "^0.8.0",
|
||||
"@ccms/container": "^0.8.0",
|
||||
"@ccms/ployfill": "^0.8.1",
|
||||
"base64-js": "^1.3.1",
|
||||
"source-map-builder": "^0.0.7"
|
||||
},
|
||||
@@ -28,6 +29,6 @@
|
||||
"@types/base64-js": "^1.2.5",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.8.3"
|
||||
"typescript": "^3.9.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import i18n from '@ccms/i18n'
|
||||
import { injectable } from "@ccms/container";
|
||||
import { injectable } from "@ccms/container"
|
||||
import { plugin } from './interfaces'
|
||||
|
||||
export namespace command {
|
||||
@injectable()
|
||||
@@ -10,16 +11,17 @@ export namespace command {
|
||||
* @param name 命令
|
||||
* @param exec 执行器
|
||||
*/
|
||||
on(plugin: any, name: string, exec: { cmd: Function, tab?: Function }) {
|
||||
var cmd = this.create(plugin, name);
|
||||
on(plugin: plugin.Plugin, name: string, exec: { cmd: Function, tab?: Function }) {
|
||||
var cmd = this.create(plugin, name)
|
||||
if (!cmd) { throw Error("") }
|
||||
console.debug(i18n.translate("ms.api.command.register", { plugin: plugin.description.name, name, cmd }))
|
||||
if (exec.cmd && typeof exec.cmd === "function") {
|
||||
this.onCommand(plugin, cmd, exec.cmd);
|
||||
this.onCommand(plugin, cmd, exec.cmd)
|
||||
} else {
|
||||
throw Error(i18n.translate("ms.api.command.register.input.error", { exec: exec.cmd }))
|
||||
}
|
||||
if (exec.tab && typeof exec.tab === "function") {
|
||||
this.onTabComplete(plugin, cmd, exec.tab);
|
||||
this.onTabComplete(plugin, cmd, exec.tab)
|
||||
}
|
||||
}
|
||||
/**
|
||||
@@ -27,40 +29,40 @@ export namespace command {
|
||||
* @param plugin 插件
|
||||
* @param name 命令
|
||||
*/
|
||||
off(plugin: any, name: string) {
|
||||
off(plugin: plugin.Plugin, name: string) {
|
||||
console.debug(i18n.translate("ms.api.command.unregister", { plugin: plugin.description.name, name }))
|
||||
this.remove(plugin, name);
|
||||
this.remove(plugin, name)
|
||||
}
|
||||
|
||||
protected abstract create(plugin: any, command: string);
|
||||
protected abstract remove(plugin: any, command: string);
|
||||
protected abstract onCommand(plugin: any, command: any, executor: Function);
|
||||
protected abstract onTabComplete(plugin: any, command: any, tabCompleter: Function);
|
||||
protected setExecutor(plugin: any, command: any, executor: Function) {
|
||||
protected abstract create(plugin: plugin.Plugin, command: string): any
|
||||
protected abstract remove(plugin: plugin.Plugin, command: string): void
|
||||
protected abstract onCommand(plugin: plugin.Plugin, command: any, executor: Function)
|
||||
protected abstract onTabComplete(plugin: plugin.Plugin, command: any, tabCompleter: Function)
|
||||
protected setExecutor(plugin: plugin.Plugin, command: any, executor: Function) {
|
||||
return (sender: any, _: any, command: string, args: string[]) => {
|
||||
try {
|
||||
return executor(sender, command, Java.from(args));
|
||||
return executor(sender, command, Java.from(args))
|
||||
} catch (ex) {
|
||||
console.i18n("ms.api.command.execute.error", { player: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex })
|
||||
console.ex(ex);
|
||||
console.ex(ex)
|
||||
if (sender.name != 'CONSOLE') {
|
||||
console.sender(sender, [i18n.translate("ms.api.command.execute.error", { player: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex }), ...console.stack(ex)])
|
||||
}
|
||||
return true;
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
protected setTabCompleter(plugin: any, command: any, tabCompleter: Function) {
|
||||
protected setTabCompleter(plugin: plugin.Plugin, command: any, tabCompleter: Function) {
|
||||
return (sender: any, _: any, command: string, args: string[]) => {
|
||||
try {
|
||||
var token = args[args.length - 1];
|
||||
var complete = tabCompleter(sender, command, Java.from(args)) || [];
|
||||
return this.copyPartialMatches(complete, token);
|
||||
var token = args[args.length - 1]
|
||||
var complete = tabCompleter(sender, command, Java.from(args)) || []
|
||||
return this.copyPartialMatches(complete, token)
|
||||
} catch (ex) {
|
||||
console.i18n("ms.api.command.tab.completer.error", { sender: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex })
|
||||
console.ex(ex);
|
||||
console.sender(sender, [i18n.translate("ms.api.command.tab.completer.error", { sender: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex }), ...console.stack(ex)]);
|
||||
return [];
|
||||
console.ex(ex)
|
||||
console.sender(sender, [i18n.translate("ms.api.command.tab.completer.error", { sender: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex }), ...console.stack(ex)])
|
||||
return []
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -70,7 +72,7 @@ export namespace command {
|
||||
if (typeof e === "string" && e.toLowerCase().startsWith(token.toLowerCase())) {
|
||||
array.push(e)
|
||||
}
|
||||
});
|
||||
})
|
||||
return array
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,10 +2,10 @@ import i18m from '@ccms/i18n'
|
||||
import { SourceMapBuilder } from 'source-map-builder'
|
||||
import * as base64 from 'base64-js'
|
||||
|
||||
const Arrays = Java.type('java.util.Arrays');
|
||||
const Level = Java.type('java.util.logging.Level');
|
||||
const Paths = Java.type('java.nio.file.Paths');
|
||||
const ignoreLogPrefix = ['java.', 'net.minecraft.', 'org.bukkit.', 'jdk.nashorn.', 'io.netty.', 'org.spongepowered.'];
|
||||
const Arrays = Java.type('java.util.Arrays')
|
||||
const Level = Java.type('java.util.logging.Level')
|
||||
const Paths = Java.type('java.nio.file.Paths')
|
||||
const ignoreLogPrefix = ['java.', 'javax.', 'sun.', 'net.minecraft.', 'org.bukkit.', 'jdk.nashorn.', 'io.netty.', 'org.spongepowered.', 'org.apache', 'org.springframework']
|
||||
|
||||
enum LogLevel {
|
||||
ALL,
|
||||
@@ -19,19 +19,19 @@ enum LogLevel {
|
||||
}
|
||||
|
||||
export class MiaoScriptConsole implements Console {
|
||||
Console: NodeJS.ConsoleConstructor;
|
||||
Console: NodeJS.ConsoleConstructor
|
||||
|
||||
private sourceMaps: { [key: string]: SourceMapBuilder } = {};
|
||||
private sourceFileMaps: { [key: string]: string } = {};
|
||||
private _name: string = '';
|
||||
private _level: LogLevel = LogLevel.INFO;
|
||||
private static sourceMaps: { [key: string]: SourceMapBuilder } = {}
|
||||
private static sourceFileMaps: { [key: string]: string } = {}
|
||||
private _name: string = ''
|
||||
private _level: LogLevel = LogLevel.INFO
|
||||
|
||||
protected logger: any;
|
||||
protected prefix: string = '§6[§bMiaoScript§6]§r ';
|
||||
protected logger: any
|
||||
protected prefix: string = '§6[§bMiaoScript§6]§r '
|
||||
|
||||
constructor(name?: string) {
|
||||
this.name = name;
|
||||
this.logger = global.logger;
|
||||
this.name = name
|
||||
this.logger = global.logger
|
||||
if (global.debug) {
|
||||
this._level = LogLevel.DEBUG
|
||||
}
|
||||
@@ -41,36 +41,36 @@ export class MiaoScriptConsole implements Console {
|
||||
}
|
||||
|
||||
get name() {
|
||||
return this._name;
|
||||
return this._name
|
||||
}
|
||||
|
||||
set name(name: string) {
|
||||
if (name) {
|
||||
this._name = `[${name}] `;
|
||||
this._name = `[${name}] `
|
||||
// noinspection JSUnusedGlobalSymbols
|
||||
this.prefix = `§6[§cMS§6][§b${name}§6]§r `;
|
||||
this.prefix = `§6[§cMS§6][§b${name}§6]§r `
|
||||
}
|
||||
}
|
||||
log(...args: any[]): void {
|
||||
this.logger.info(this.name + args.join(' '));
|
||||
this.logger.info(this.name + args.join(' '))
|
||||
}
|
||||
info(...args: any[]) {
|
||||
this.logger.info(this.name + args.join(' '));
|
||||
this.logger.info(this.name + args.join(' '))
|
||||
}
|
||||
warn(...args: any[]) {
|
||||
this.logger.warning(this.name + args.join(' '));
|
||||
this.logger.warning(this.name + args.join(' '))
|
||||
}
|
||||
error(...args: any[]) {
|
||||
this.logger.log(Level.SEVERE, this.name + args.join(' '));
|
||||
this.logger.log(Level.SEVERE, this.name + args.join(' '))
|
||||
}
|
||||
debug(...args: any[]) {
|
||||
if (global.debug) {
|
||||
this.logger.info(this.name + '[DEBUG] ' + args.join(' '));
|
||||
this.logger.info(this.name + '[DEBUG] ' + args.join(' '))
|
||||
}
|
||||
}
|
||||
trace(...args: any[]): void {
|
||||
if (this._level <= LogLevel.TRACE) {
|
||||
this.logger.info(this.name + '[TRACE] ' + args.join(' '));
|
||||
this.logger.info(this.name + '[TRACE] ' + args.join(' '))
|
||||
}
|
||||
}
|
||||
sender(...args) {
|
||||
@@ -93,31 +93,31 @@ export class MiaoScriptConsole implements Console {
|
||||
readSourceMap(fileName: string, lineNumber: number) {
|
||||
try {
|
||||
if (fileName.endsWith('js')) {
|
||||
if (this.sourceMaps[fileName] === undefined) {
|
||||
this.sourceMaps[fileName] = null
|
||||
let sourceLine = base.read(fileName).split('\n');
|
||||
if (MiaoScriptConsole.sourceMaps[fileName] === undefined) {
|
||||
MiaoScriptConsole.sourceMaps[fileName] = null
|
||||
let sourceLine = base.read(fileName).split('\n')
|
||||
let lastLine = sourceLine[sourceLine.length - 1]
|
||||
if (lastLine.startsWith('//# sourceMappingURL=')) {
|
||||
let sourceContent = null;
|
||||
let sourceMappingURL = lastLine.split('sourceMappingURL=', 2)[1];
|
||||
if (sourceMappingURL.startsWith('data:application/json;base64,')) {
|
||||
let sourceContent = null
|
||||
let sourceMappingURL = lastLine.split('sourceMappingURL=', 2)[1]
|
||||
if (sourceMappingURL.startsWith('data:application/jsonbase64,')) {
|
||||
sourceContent = String.fromCharCode(...Array.from(base64.toByteArray(sourceMappingURL.split(',', 2)[1])))
|
||||
} else if (sourceMappingURL.startsWith('http')) {
|
||||
// TODO
|
||||
} else {
|
||||
let file = Paths.get(Paths.get(fileName, '..', sourceMappingURL).toFile().getCanonicalPath()).toFile();
|
||||
let file = Paths.get(Paths.get(fileName, '..', sourceMappingURL).toFile().getCanonicalPath()).toFile()
|
||||
if (file.exists()) { sourceContent = base.read(file) }
|
||||
}
|
||||
if (sourceContent) {
|
||||
this.sourceMaps[fileName] = new SourceMapBuilder(JSON.parse(sourceContent))
|
||||
this.sourceFileMaps[fileName] = Paths.get(fileName, '..', this.sourceMaps[fileName].sources[0]).toFile().getCanonicalPath();
|
||||
MiaoScriptConsole.sourceMaps[fileName] = new SourceMapBuilder(JSON.parse(sourceContent))
|
||||
MiaoScriptConsole.sourceFileMaps[fileName] = Paths.get(fileName, '..', MiaoScriptConsole.sourceMaps[fileName].sources[0]).toFile().getCanonicalPath()
|
||||
}
|
||||
}
|
||||
}
|
||||
if (this.sourceMaps[fileName]) {
|
||||
let sourceMapping = this.sourceMaps[fileName].getSource(lineNumber, 25, true, true);
|
||||
fileName = this.sourceFileMaps[fileName]
|
||||
if (sourceMapping && lineNumber != sourceMapping.mapping.sourceLine) { lineNumber = sourceMapping.mapping.sourceLine; }
|
||||
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) {
|
||||
@@ -128,22 +128,26 @@ export class MiaoScriptConsole implements Console {
|
||||
lineNumber
|
||||
}
|
||||
}
|
||||
stack(ex: Error): string[] {
|
||||
let stack = ex.getStackTrace();
|
||||
let cache = ['§c' + ex];
|
||||
stack(ex: Error, color: boolean = true): string[] {
|
||||
let stack = ex.getStackTrace()
|
||||
let cache = [(color ? '§c' : '') + ex]
|
||||
//@ts-ignore
|
||||
if (stack.class) {
|
||||
stack = Arrays.asList(stack)
|
||||
}
|
||||
stack.forEach(trace => {
|
||||
if (!trace.fileName || trace.fileName.startsWith('jar:file:')) { return }
|
||||
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] }
|
||||
cache.push(` §e->§c ${fileName} => §4${trace.methodName}:${lineNumber}`)
|
||||
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;
|
||||
let className = trace.className
|
||||
var fileName = trace.fileName as string
|
||||
if (className.startsWith('jdk.nashorn.internal.scripts')) {
|
||||
className = className.substr(className.lastIndexOf('$') + 1)
|
||||
var { fileName, lineNumber } = this.readSourceMap(trace.fileName, trace.lineNumber)
|
||||
@@ -151,70 +155,74 @@ export class MiaoScriptConsole implements Console {
|
||||
} else {
|
||||
for (let prefix in ignoreLogPrefix) {
|
||||
if (className.startsWith(ignoreLogPrefix[prefix])) {
|
||||
return;
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
cache.push(` §e->§c ${className}.${trace.methodName}(§4${fileName}:${lineNumber}§c)`);
|
||||
if (color) {
|
||||
cache.push(` §e->§c ${className}.${trace.methodName}(§4${fileName}:${lineNumber}§c)`)
|
||||
} else {
|
||||
cache.push(` -> ${className}.${trace.methodName}(${fileName}:${lineNumber})`)
|
||||
}
|
||||
}
|
||||
});
|
||||
return cache;
|
||||
})
|
||||
return cache
|
||||
}
|
||||
assert(value: any, message?: string, ...optionalParams: any[]): void {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
clear(): void {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
count(label?: string): void {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
countReset(label?: string): void {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
dir(obj: any, options?: NodeJS.InspectOptions): void {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
dirxml(...data: any[]): void {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
group(...label: any[]): void {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
groupCollapsed(...label: any[]): void {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
groupEnd(): void {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
table(tabularData: any, properties?: string[]): void {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
time(label?: string): void {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
timeEnd(label?: string): void {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
timeLog(label?: string, ...data: any[]): void {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
markTimeline(label?: string): void {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
profile(label?: string): void {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
profileEnd(label?: string): void {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
timeStamp(label?: string): void {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
timeline(label?: string): void {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
timelineEnd(label?: string): void {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ export namespace constants {
|
||||
Bukkit = 'bukkit',
|
||||
Sponge = 'sponge',
|
||||
Nukkit = 'nukkit',
|
||||
Bungee = 'bungee'
|
||||
Bungee = 'bungee',
|
||||
Spring = 'spring'
|
||||
}
|
||||
}
|
||||
|
||||
7
packages/api/src/interfaces/amqp.ts
Normal file
7
packages/api/src/interfaces/amqp.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
export namespace amqp {
|
||||
export const Manager = Symbol('AmqpManager')
|
||||
export namespace rabbit {
|
||||
export const Admin = Symbol('RabbitAdmin')
|
||||
export const Template = Symbol('RabbitTemplate')
|
||||
}
|
||||
}
|
||||
5
packages/api/src/interfaces/database.ts
Normal file
5
packages/api/src/interfaces/database.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
export namespace database {
|
||||
export const DataBaseManager = Symbol("DataBaseManager");
|
||||
export const DataSource = Symbol("DataSource");
|
||||
export const DataBase = Symbol("DataBase");
|
||||
}
|
||||
@@ -1,2 +1,5 @@
|
||||
export * from './web'
|
||||
export * from './amqp'
|
||||
export * from './plugin'
|
||||
export * from './server'
|
||||
export * from './database'
|
||||
|
||||
@@ -2,73 +2,186 @@ export namespace plugin {
|
||||
/**
|
||||
* MiaoScript Plugin
|
||||
*/
|
||||
export const Plugin = Symbol("Plugin");
|
||||
export const Plugin = Symbol("Plugin")
|
||||
/**
|
||||
* MiaoScript Plugin Folder
|
||||
*/
|
||||
export const PluginFolder = Symbol("PluginFolder");
|
||||
export const PluginFolder = Symbol("PluginFolder")
|
||||
/**
|
||||
* Runtime Plugin Instance
|
||||
*/
|
||||
export const PluginInstance = Symbol("PluginInstance");
|
||||
export const PluginInstance = Symbol("PluginInstance")
|
||||
/**
|
||||
* MiaoScript Plugin Manager Symbol
|
||||
*/
|
||||
export const PluginManager = Symbol("PluginManager");
|
||||
export const PluginManager = Symbol("PluginManager")
|
||||
/**
|
||||
* MiaoScript Plugin Manager Interface
|
||||
*/
|
||||
export interface PluginManager {
|
||||
scan(folder: string): void;
|
||||
build(): void;
|
||||
loadFromFile(file: string): Plugin;
|
||||
load(...args: any[]): void;
|
||||
enable(...args: any[]): void;
|
||||
disable(...args: any[]): void;
|
||||
reload(...args: any[]): void;
|
||||
getPlugins(): Map<string, any>;
|
||||
scan(folder: string): void
|
||||
build(): void
|
||||
loadFromFile(file: string, scanner?: plugin.PluginScanner): Plugin
|
||||
load(...args: any[]): void
|
||||
enable(...args: any[]): void
|
||||
disable(...args: any[]): void
|
||||
reload(...args: any[]): void
|
||||
getPlugin(name: string): plugin.Plugin
|
||||
getPlugins(): Map<string, plugin.Plugin>
|
||||
}
|
||||
export const PluginScanner = Symbol("PluginScanner")
|
||||
/**
|
||||
* 插件加载元信息
|
||||
*/
|
||||
export interface PluginLoadMetadata {
|
||||
/**
|
||||
* 插件加载类型
|
||||
*/
|
||||
type: string
|
||||
/**
|
||||
* 插件名称
|
||||
*/
|
||||
name?: string
|
||||
/**
|
||||
* 插件文件
|
||||
*/
|
||||
file?: string
|
||||
/**
|
||||
* 插件实例
|
||||
*/
|
||||
instance?: any
|
||||
/**
|
||||
* 插件元信息
|
||||
*/
|
||||
metadata?: PluginMetadata
|
||||
/**
|
||||
* 插件扫描器
|
||||
*/
|
||||
scanner: PluginScanner
|
||||
/**
|
||||
* 插件加载器
|
||||
*/
|
||||
loader?: PluginLoader
|
||||
/**
|
||||
* 是否已加载
|
||||
*/
|
||||
loaded?: boolean
|
||||
[key: string]: any
|
||||
}
|
||||
/**
|
||||
* 插件扫描器
|
||||
*/
|
||||
export interface PluginScanner {
|
||||
/**
|
||||
* 扫描器类型
|
||||
*/
|
||||
type: string
|
||||
/**
|
||||
* 扫描插件目录 返回插件加载元信息列表
|
||||
* @param target 扫描目标
|
||||
*/
|
||||
scan(target: any): PluginLoadMetadata[]
|
||||
/**
|
||||
* 读取插件 返回插件加载元信息
|
||||
* @param target
|
||||
*/
|
||||
read(target: any): PluginLoadMetadata
|
||||
/**
|
||||
* 加载扫描到的目标
|
||||
* @param target 加载目标
|
||||
*/
|
||||
load(target: PluginLoadMetadata): PluginLoadMetadata
|
||||
}
|
||||
export const PluginLoader = Symbol("PluginLoader")
|
||||
/**
|
||||
* 插件加载器
|
||||
*/
|
||||
export interface PluginLoader {
|
||||
/**
|
||||
* 加载器类型
|
||||
*/
|
||||
type: string
|
||||
/**
|
||||
* 加载插件 获取元数据
|
||||
* @param target 加载目标
|
||||
* @param result 扫描器加载的结果
|
||||
*/
|
||||
require(loadMetadata: PluginLoadMetadata): PluginLoadMetadata
|
||||
/**
|
||||
* 构建插件
|
||||
* @param metadata 插件元信息
|
||||
*/
|
||||
build(metadata: PluginMetadata): Plugin
|
||||
/**
|
||||
* Load 阶段
|
||||
* @param plugin 插件
|
||||
*/
|
||||
load(plugin: Plugin): void
|
||||
/**
|
||||
* Enable 阶段
|
||||
* @param plugin 插件
|
||||
*/
|
||||
enable(plugin: Plugin): void
|
||||
/**
|
||||
* Disable 阶段
|
||||
* @param plugin 插件
|
||||
*/
|
||||
disable(plugin: Plugin): void
|
||||
/**
|
||||
* Reload 阶段
|
||||
* @param plugin 插件
|
||||
*/
|
||||
reload(plugin: Plugin): void
|
||||
}
|
||||
export interface Plugin {
|
||||
description: PluginMetadata;
|
||||
logger: Console;
|
||||
load(): void;
|
||||
enable(): void;
|
||||
disable(): void;
|
||||
description: PluginMetadata
|
||||
logger: Console
|
||||
load(): void
|
||||
enable(): void
|
||||
disable(): void
|
||||
}
|
||||
interface BaseMetadata {
|
||||
export interface BaseMetadata {
|
||||
/**
|
||||
* 名称 为空则为对象名称
|
||||
*/
|
||||
name?: string;
|
||||
name?: string
|
||||
/**
|
||||
* 支持的服务器列表 为空则代表所有
|
||||
*/
|
||||
servers?: string[];
|
||||
servers?: string[]
|
||||
}
|
||||
export interface PluginMetadata extends BaseMetadata {
|
||||
/**
|
||||
* 插件名称
|
||||
*/
|
||||
name: string;
|
||||
name: string
|
||||
/**
|
||||
* 前缀
|
||||
*/
|
||||
prefix?: string;
|
||||
prefix?: string
|
||||
/**
|
||||
* 插件版本
|
||||
*/
|
||||
version: string;
|
||||
version: string
|
||||
/**
|
||||
* 插件版本
|
||||
*/
|
||||
author: string | string[];
|
||||
author: string | string[]
|
||||
/**
|
||||
* 插件源文件 必须指定为 __filename
|
||||
*/
|
||||
source: string;
|
||||
source: string
|
||||
/**
|
||||
* 插件类型 默认为 ioc 执行 MiaoScript 加载逻辑
|
||||
*/
|
||||
type?: string
|
||||
/**
|
||||
* 插件加载信息
|
||||
*/
|
||||
loadMetadata?: PluginLoadMetadata
|
||||
/**
|
||||
* 插件本体
|
||||
*/
|
||||
target?: any;
|
||||
target?: any
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,36 +1,143 @@
|
||||
import * as reflect from '@ccms/common/dist/reflect'
|
||||
import { injectable } from '@ccms/container'
|
||||
|
||||
import { NativePluginManager } from './native_plugin'
|
||||
import { constants } from '../../constants'
|
||||
|
||||
export namespace server {
|
||||
/**
|
||||
* Runtime ServerType
|
||||
*/
|
||||
export const ServerType = Symbol("ServerType");
|
||||
export const ServerType = Symbol("ServerType")
|
||||
/**
|
||||
* Runtime Console
|
||||
*/
|
||||
export const Console = Symbol("Console");
|
||||
export const Console = Symbol("Console")
|
||||
/**
|
||||
* MiaoScript Server
|
||||
*/
|
||||
export const Server = Symbol("Server");
|
||||
export const Server = Symbol("Server")
|
||||
/**
|
||||
* Runtime Server Instance
|
||||
*/
|
||||
export const ServerInstance = Symbol("ServerInstance");
|
||||
export const ServerInstance = Symbol("ServerInstance")
|
||||
/**
|
||||
* MiaoScript Server
|
||||
*/
|
||||
export interface Server {
|
||||
getVersion(): string;
|
||||
getPlayer(name: string): any;
|
||||
getOnlinePlayers(): any[];
|
||||
getConsoleSender(): any;
|
||||
getService(service: string): any;
|
||||
dispatchCommand(sender: string | any, command: string): boolean;
|
||||
dispatchConsoleCommand(command: string): boolean;
|
||||
getPluginsFolder(): string;
|
||||
getNativePluginManager(): NativePluginManager;
|
||||
getNettyPipeline(): any;
|
||||
sendJson(sender: string | any, json: object | string): void;
|
||||
getVersion(): string
|
||||
getPlayer(name: string): any
|
||||
getOnlinePlayers(): any[]
|
||||
getConsoleSender(): any
|
||||
getService(service: string): any
|
||||
dispatchCommand(sender: string | any, command: string): boolean
|
||||
dispatchConsoleCommand(command: string): boolean
|
||||
getPluginsFolder(): string
|
||||
getNativePluginManager(): NativePluginManager
|
||||
getDedicatedServer?(): any
|
||||
getNettyPipeline(): any
|
||||
getRootLogger(): any
|
||||
sendJson(sender: string | any, json: object | string): void
|
||||
tabComplete?(sender: string | any, input: string, index?: number): string[]
|
||||
}
|
||||
@injectable()
|
||||
export abstract class ReflectServer implements server.Server {
|
||||
protected pipeline: any
|
||||
protected rootLogger: any
|
||||
|
||||
constructor() {
|
||||
this.reflect()
|
||||
}
|
||||
|
||||
getVersion(): string {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
getPlayer(name: string) {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
getOnlinePlayers(): any[] {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
getConsoleSender() {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
getService(service: string) {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
dispatchCommand(sender: any, command: string): boolean {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
dispatchConsoleCommand(command: string): boolean {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
getPluginsFolder(): string {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
getNativePluginManager(): NativePluginManager {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
getDedicatedServer() {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
getNettyPipeline() {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
getRootLogger() {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
sendJson(sender: any, json: string | object): void {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
tabComplete?(sender: any, input: string, index?: number): string[] {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
protected reflect() {
|
||||
try {
|
||||
let consoleServer = this.getDedicatedServer()
|
||||
this.reflectPipeline(consoleServer)
|
||||
this.reflectRootLogger(consoleServer)
|
||||
} catch (error) {
|
||||
console.error('Error When Reflect MinecraftServer!', error)
|
||||
console.ex(error)
|
||||
}
|
||||
}
|
||||
protected reflectPipeline(consoleServer: any) {
|
||||
let connection: any
|
||||
let promise: any
|
||||
for (const method of constants.Reflect.Method.getServerConnection) {
|
||||
try {
|
||||
connection = reflect.on(consoleServer).call(method).get()
|
||||
if (connection.class.name.indexOf('ServerConnection') !== -1
|
||||
|| connection.class.name.indexOf('NetworkSystem') !== -1) { break }
|
||||
connection = undefined
|
||||
} catch (error) { }
|
||||
}
|
||||
if (!connection) { console.error("Can't found ServerConnection!"); return }
|
||||
for (const field of constants.Reflect.Field.listeningChannels) {
|
||||
try {
|
||||
promise = reflect.on(connection).get(field).get().get(0)
|
||||
if (promise.class.name.indexOf('Promise') !== -1) { break }
|
||||
promise = undefined
|
||||
} catch (error) { }
|
||||
}
|
||||
if (!promise) { console.error("Can't found listeningChannels!"); return }
|
||||
this.pipeline = reflect.on(promise).get('channel').get().pipeline()
|
||||
}
|
||||
protected reflectRootLogger(consoleServer: any) {
|
||||
try {
|
||||
this.rootLogger = reflect.on(consoleServer).get('LOGGER').get().parent
|
||||
} catch (error) {
|
||||
try { this.rootLogger = reflect.on(consoleServer).get(0).get().parent } catch (error) { }
|
||||
}
|
||||
if (this.rootLogger && this.rootLogger.class.name.indexOf('Logger') === -1) {
|
||||
console.error('Error Logger Class: ' + this.rootLogger.class.name)
|
||||
this.rootLogger = undefined
|
||||
}
|
||||
// get root logger
|
||||
for (let index = 0; index < 5 && this.rootLogger.parent; index++) {
|
||||
this.rootLogger = this.rootLogger.parent
|
||||
}
|
||||
if (!this.rootLogger) { console.error("Can't found rootLogger!") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
3
packages/api/src/interfaces/web.ts
Normal file
3
packages/api/src/interfaces/web.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export namespace web {
|
||||
export const Server = Symbol('Server')
|
||||
}
|
||||
@@ -58,9 +58,9 @@ export namespace task {
|
||||
return this;
|
||||
}
|
||||
|
||||
protected run(): void {
|
||||
protected run(...args: any[]): void {
|
||||
try {
|
||||
this.func();
|
||||
this.func(...args);
|
||||
} catch (ex) {
|
||||
console.console('§4插件执行任务时发生错误', ex)
|
||||
console.ex(ex);
|
||||
@@ -69,8 +69,9 @@ export namespace task {
|
||||
|
||||
/**
|
||||
* 提交任务
|
||||
* @param args 任务参数
|
||||
*/
|
||||
abstract submit(): Cancelable;
|
||||
abstract submit(...args: any[]): Cancelable;
|
||||
}
|
||||
/**
|
||||
* 返可取消的对象
|
||||
|
||||
1
packages/bukkit/.npmignore
Symbolic link
1
packages/bukkit/.npmignore
Symbolic link
@@ -0,0 +1 @@
|
||||
../../.npmignore
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/bukkit",
|
||||
"version": "0.6.5",
|
||||
"version": "0.8.1",
|
||||
"description": "MiaoScript bukkit package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -21,11 +21,11 @@
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.8.3"
|
||||
"typescript": "^3.9.2"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.6.5",
|
||||
"@ccms/common": "^0.6.4",
|
||||
"@ccms/container": "^0.6.0"
|
||||
"@ccms/api": "^0.8.1",
|
||||
"@ccms/common": "^0.8.0",
|
||||
"@ccms/container": "^0.8.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/// <reference types="@ccms/types/dist/typings/bukkit" />
|
||||
/// <reference types="@javatypes/spigot-api" />
|
||||
|
||||
import { server } from '@ccms/api'
|
||||
import { Container } from '@ccms/container'
|
||||
|
||||
@@ -7,13 +7,12 @@ import chat from './enhance/chat'
|
||||
let Bukkit = org.bukkit.Bukkit;
|
||||
|
||||
@provideSingleton(server.Server)
|
||||
export class BukkitServer implements server.Server {
|
||||
export class BukkitServer extends server.ReflectServer {
|
||||
private pluginsFolder: string;
|
||||
private pipeline: any;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this.pluginsFolder = Bukkit.getUpdateFolderFile().getParentFile().getCanonicalPath();
|
||||
this.reflectPipeline()
|
||||
}
|
||||
|
||||
getPlayer(name: string) {
|
||||
@@ -46,9 +45,15 @@ export class BukkitServer implements server.Server {
|
||||
getNativePluginManager() {
|
||||
return Bukkit.getPluginManager() as any;
|
||||
}
|
||||
getDedicatedServer() {
|
||||
return reflect.on(Bukkit.getServer()).get('console').get()
|
||||
}
|
||||
getNettyPipeline() {
|
||||
return this.pipeline;
|
||||
}
|
||||
getRootLogger() {
|
||||
return this.rootLogger;
|
||||
}
|
||||
sendJson(sender: string | any, json: object | string): void {
|
||||
if (typeof sender === "string") {
|
||||
sender = this.getPlayer(sender)
|
||||
@@ -58,27 +63,4 @@ export class BukkitServer implements server.Server {
|
||||
this.dispatchConsoleCommand(result)
|
||||
}
|
||||
}
|
||||
|
||||
private reflectPipeline() {
|
||||
let consoleServer = reflect.on(Bukkit.getServer()).get('console').get()
|
||||
let connection: any;
|
||||
let promise: any;
|
||||
for (const method of constants.Reflect.Method.getServerConnection) {
|
||||
try {
|
||||
connection = reflect.on(consoleServer).call(method).get()
|
||||
if (connection.class.name.indexOf('ServerConnection') !== -1) { break; }
|
||||
connection = undefined;
|
||||
} catch (error) { }
|
||||
}
|
||||
if (!connection) { console.error("Can't found ServerConnection!"); return }
|
||||
for (const field of constants.Reflect.Field.listeningChannels) {
|
||||
try {
|
||||
promise = reflect.on(connection).get(field).get().get(0);
|
||||
if (promise.class.name.indexOf('Promise') !== -1) { break; }
|
||||
promise = undefined;
|
||||
} catch (error) { }
|
||||
}
|
||||
if (!promise) { console.error("Can't found listeningChannels!"); return }
|
||||
this.pipeline = reflect.on(promise).get('channel').get().pipeline()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,10 +23,8 @@ export class BukkitTaskManager implements task.TaskManager {
|
||||
}
|
||||
|
||||
export class BukkitTask extends task.Task {
|
||||
submit(): task.Cancelable {
|
||||
let run = new BukkitRunnable({
|
||||
run: () => this.run()
|
||||
})
|
||||
submit(...args: any[]): task.Cancelable {
|
||||
let run = new BukkitRunnable({ run: () => this.run(...args) })
|
||||
let funcName = `runTask${this.interval ? 'Timer' : 'Later'}${this.isAsync ? 'Asynchronously' : ''}`
|
||||
if (this.interval) {
|
||||
return run[funcName](this.plugin, this.laterTime, this.interval)
|
||||
|
||||
1
packages/bungee/.npmignore
Symbolic link
1
packages/bungee/.npmignore
Symbolic link
@@ -0,0 +1 @@
|
||||
../../.npmignore
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/bungee",
|
||||
"version": "0.6.5",
|
||||
"version": "0.8.1",
|
||||
"description": "MiaoScript bungee package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -21,11 +21,11 @@
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.8.3"
|
||||
"typescript": "^3.9.2"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.6.5",
|
||||
"@ccms/common": "^0.6.4",
|
||||
"@ccms/container": "^0.6.0"
|
||||
"@ccms/api": "^0.8.1",
|
||||
"@ccms/common": "^0.8.0",
|
||||
"@ccms/container": "^0.8.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/// <reference types="@ccms/types/dist/typings/bungee" />
|
||||
/// <reference types="@javatypes/bungee-api" />
|
||||
|
||||
import { server } from '@ccms/api'
|
||||
import { Container } from '@ccms/container'
|
||||
|
||||
@@ -9,6 +9,7 @@ let Bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy();
|
||||
export class BungeeServer implements server.Server {
|
||||
private pluginsFolder: string;
|
||||
private pipeline: any;
|
||||
private rootLogger: any;
|
||||
|
||||
@inject(task.TaskManager)
|
||||
private task: task.TaskManager
|
||||
@@ -35,6 +36,11 @@ export class BungeeServer implements server.Server {
|
||||
}
|
||||
}
|
||||
}).later(10).timer(20).submit()
|
||||
try {
|
||||
this.rootLogger = Bungee.getLogger()
|
||||
} catch (error) {
|
||||
console.error("Can't found rootLogger!")
|
||||
}
|
||||
}
|
||||
|
||||
getPlayer(name: string) {
|
||||
@@ -70,6 +76,9 @@ export class BungeeServer implements server.Server {
|
||||
getNettyPipeline() {
|
||||
return this.pipeline;
|
||||
}
|
||||
getRootLogger() {
|
||||
return this.rootLogger;
|
||||
}
|
||||
sendJson(sender: string | any, json: string): void {
|
||||
throw new Error("Method not implemented.");
|
||||
}
|
||||
|
||||
@@ -22,8 +22,8 @@ export class BungeeTaskManager implements task.TaskManager {
|
||||
}
|
||||
|
||||
export class BungeeTask extends task.Task {
|
||||
submit(): task.Cancelable {
|
||||
let run = new Runnable({ run: () => this.run() })
|
||||
submit(...args: any[]): task.Cancelable {
|
||||
let run = new Runnable({ run: () => this.run(...args) })
|
||||
if (this.isAsync) {
|
||||
return this.plugin.getProxy().getScheduler().runAsync(this.plugin, run)
|
||||
}
|
||||
|
||||
1
packages/client/.npmignore
Symbolic link
1
packages/client/.npmignore
Symbolic link
@@ -0,0 +1 @@
|
||||
../../.npmignore
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"private": true,
|
||||
"name": "@ccms/client",
|
||||
"version": "0.6.3",
|
||||
"version": "0.8.0",
|
||||
"description": "MiaoScript client package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -26,6 +26,6 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.8.3"
|
||||
"typescript": "^3.9.2"
|
||||
}
|
||||
}
|
||||
|
||||
1
packages/common/.npmignore
Symbolic link
1
packages/common/.npmignore
Symbolic link
@@ -0,0 +1 @@
|
||||
../../.npmignore
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/common",
|
||||
"version": "0.6.4",
|
||||
"version": "0.8.0",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -21,10 +21,11 @@
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.8.3"
|
||||
"typescript": "^3.9.2"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/nashorn": "^0.6.4"
|
||||
"@ccms/nashorn": "^0.8.0",
|
||||
"@javatypes/jdk": "^1.14.0"
|
||||
},
|
||||
"gitHead": "562e2d00175c9d3a99c8b672aa07e6d92706a027"
|
||||
}
|
||||
|
||||
@@ -1,196 +1,204 @@
|
||||
/// <reference types="@javatypes/jdk" />
|
||||
|
||||
/**
|
||||
* 反射工具类
|
||||
* Created by MiaoWoo on 2017/2/9 0009.
|
||||
*/
|
||||
const JavaClass = Java.type('java.lang.Class');
|
||||
const JavaClass = Java.type('java.lang.Class')
|
||||
const JavaObject = Java.type('java.lang.Object')
|
||||
const NoSuchFieldException = Java.type('java.lang.NoSuchFieldException');
|
||||
const methodCache = [];
|
||||
const NoSuchFieldException = Java.type('java.lang.NoSuchFieldException')
|
||||
const methodCache = []
|
||||
|
||||
class Reflect {
|
||||
private obj: any;
|
||||
private class: any
|
||||
private obj: java.lang.Object
|
||||
private class: java.lang.Class<any>
|
||||
|
||||
constructor(obj: any) {
|
||||
// if (obj === undefined || obj === null) { throw Error(`reflect object can't be ${obj}!`) }
|
||||
if (obj instanceof JavaClass) {
|
||||
this.obj = null;
|
||||
this.class = obj;
|
||||
this.obj = null
|
||||
this.class = obj
|
||||
} else {
|
||||
this.obj = obj;
|
||||
this.obj = obj
|
||||
if (obj !== null && obj !== undefined && obj.class) {
|
||||
this.class = obj.class;
|
||||
this.class = obj.class
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
method(...args: any[]) {
|
||||
return declaredMethod(this.class, args[0], types(args.slice(1)));
|
||||
method(name: string, ...args: java.lang.Class<any>[]) {
|
||||
return declaredMethod(this.class, name, ...args)
|
||||
}
|
||||
|
||||
methods() {
|
||||
return Java.from(declaredMethods(this.class));
|
||||
return Java.from(declaredMethods(this.class))
|
||||
}
|
||||
|
||||
field(name): Reflect {
|
||||
field(name: string | java.lang.String): Reflect {
|
||||
try {
|
||||
// Try getting a public field
|
||||
let field = this.class.field(name);
|
||||
return on(field.get(this.obj));
|
||||
let field = this.class.getField(name)
|
||||
return on(field.get(this.obj))
|
||||
} catch (ex) {
|
||||
// Try again, getting a non-public field
|
||||
return on(accessible(declaredField(this.class, name)).get(this.obj));
|
||||
return on(accessible(declaredField(this.class, name)).get(this.obj))
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
fields(declared = false) {
|
||||
return Java.from(declared ? this.class.declaredFields : this.class.fields);
|
||||
fields(declared = false): java.lang.reflect.Field[] {
|
||||
return Java.from(declared ? this.class.getDeclaredFields() : this.class.getFields())
|
||||
}
|
||||
|
||||
values(declared = false) {
|
||||
let cache = {};
|
||||
this.fields(declared).forEach(fed => cache[fed.name] = this.field(fed.name).get())
|
||||
return cache;
|
||||
return this.fields(declared).reduce((cache, field) => { return cache[field.getName()] = this.field(field.getName()).get() }, {}) as any
|
||||
}
|
||||
|
||||
call(...args): Reflect {
|
||||
let params = args.slice(1);
|
||||
let method = accessible(declaredMethod(this.class, args[0], types(params)));
|
||||
let result = method.invoke(this.get(), params);
|
||||
return result && on(result);
|
||||
};
|
||||
call(...args: any[]): Reflect {
|
||||
let params = args.slice(1)
|
||||
let method = accessible(declaredMethod(this.class, args[0], ...types(params)))
|
||||
let result = method.invoke(this.get(), params)
|
||||
return result && on(result)
|
||||
}
|
||||
|
||||
get(...args): Reflect | any {
|
||||
return args.length === 1 ? this.field(args[0]) : this.obj;
|
||||
};
|
||||
get(): any
|
||||
get(index: number, declared?: boolean): Reflect
|
||||
get(prop: string): Reflect
|
||||
get(param?: string | number, declared: boolean = true): Reflect | any {
|
||||
if (param == undefined || param == null) return this.obj
|
||||
if (typeof param == "number") {
|
||||
return on(accessible(this.fields(declared)[param]).get(this.obj))
|
||||
}
|
||||
if (typeof param == "string") {
|
||||
return this.field(param)
|
||||
}
|
||||
}
|
||||
|
||||
// noinspection JSUnusedGlobalSymbols
|
||||
set(name, value): Reflect {
|
||||
accessible(declaredField(this.class, name)).set(this.obj, value);
|
||||
return this;
|
||||
};
|
||||
set(name: any, value: any): Reflect {
|
||||
accessible(declaredField(this.class, name)).set(this.obj, value)
|
||||
return this
|
||||
}
|
||||
|
||||
create(...args): Reflect {
|
||||
return on(declaredConstructor(this.class, args).newInstance(args));
|
||||
};
|
||||
return on(declaredConstructor(this.class, args).newInstance(args))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an array of types for an array of objects
|
||||
*/
|
||||
function types(values, def?) {
|
||||
function types(values: any[], def?: any) {
|
||||
if (values === null) {
|
||||
return [];
|
||||
return []
|
||||
}
|
||||
let result: any[] = [];
|
||||
values.forEach(t => result.push((t || def) ? JavaObject.class : t instanceof JavaClass ? t : t.class));
|
||||
return result;
|
||||
let result: java.lang.Class<any>[] = []
|
||||
values.forEach(t => result.push((t || def) ? JavaObject.class : t instanceof JavaClass ? t : t.class))
|
||||
return result
|
||||
}
|
||||
|
||||
function accessible(accessible) {
|
||||
function accessible<T extends java.lang.reflect.AccessibleObject>(accessible: T): T {
|
||||
if (accessible === null) {
|
||||
return null;
|
||||
return null
|
||||
}
|
||||
if (!accessible.isAccessible()) {
|
||||
accessible.setAccessible(true);
|
||||
accessible.setAccessible(true)
|
||||
}
|
||||
return accessible;
|
||||
return accessible
|
||||
}
|
||||
|
||||
function declaredConstructor(clazz, param) {
|
||||
let constructor;
|
||||
let constructor
|
||||
try {
|
||||
constructor = clazz.getDeclaredConstructor(types(param));
|
||||
constructor = clazz.getDeclaredConstructor(types(param))
|
||||
} catch (ex) {
|
||||
try {
|
||||
constructor = clazz.getDeclaredConstructor(types(param, true));
|
||||
constructor = clazz.getDeclaredConstructor(types(param, true))
|
||||
} catch (ex) {
|
||||
constructor = clazz.getDeclaredConstructors()[0];
|
||||
constructor = clazz.getDeclaredConstructors()[0]
|
||||
}
|
||||
}
|
||||
return accessible(constructor);
|
||||
return accessible(constructor)
|
||||
}
|
||||
|
||||
function declaredField(clazz, name) {
|
||||
function declaredField(clazz: java.lang.Class<any>, name: string | java.lang.String) {
|
||||
if (!clazz) { throw Error(`target class can't be ${clazz}!`) }
|
||||
let target = clazz;
|
||||
let field = null;
|
||||
let target = clazz
|
||||
let field = null
|
||||
// noinspection JSUnresolvedVariable
|
||||
while (target !== JavaObject.class) {
|
||||
try {
|
||||
field = target.getDeclaredField(name);
|
||||
if (field !== null) { break; }
|
||||
field = target.getDeclaredField(name)
|
||||
if (field !== null) { break }
|
||||
} catch (e) {
|
||||
if (target === undefined) { break; }
|
||||
target = target.getSuperclass();
|
||||
if (target === undefined) { break }
|
||||
target = target.getSuperclass()
|
||||
}
|
||||
}
|
||||
if (field === null) {
|
||||
throw new NoSuchFieldException(name + " is not found in " + clazz.name);
|
||||
throw new NoSuchFieldException(name + " is not found in " + clazz.getName())
|
||||
}
|
||||
return field;
|
||||
return field
|
||||
}
|
||||
|
||||
function declaredMethod(clazz, name, clazzs) {
|
||||
let key = clazz.name + '.' + name + ':' + (clazzs || []).join(':');
|
||||
function declaredMethod(clazz: java.lang.Class<any>, name: string, ...clazzs: java.lang.Class<any>[]): java.lang.reflect.Method {
|
||||
let key = clazz.getName() + '.' + name + ':' + (clazzs || []).join(':')
|
||||
if (!methodCache[key]) {
|
||||
try {
|
||||
methodCache[key] = clazz.getMethod(name, clazzs);
|
||||
methodCache[key] = clazz.getMethod(name, ...clazzs)
|
||||
} catch (ex) {
|
||||
try {
|
||||
methodCache[key] = clazz.getDeclaredMethod(name, clazzs);
|
||||
methodCache[key] = clazz.getDeclaredMethod(name, clazzs as any)
|
||||
} catch (ex) {
|
||||
for (const m of Java.from(declaredMethods(clazz))) {
|
||||
if (m.name == name) {
|
||||
methodCache[key] = m;
|
||||
break;
|
||||
if (m.getName() == name) {
|
||||
methodCache[key] = m
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return methodCache[key];
|
||||
return methodCache[key]
|
||||
}
|
||||
|
||||
function declaredMethods(clazz) {
|
||||
return clazz.declaredMethods;
|
||||
function declaredMethods(clazz: java.lang.Class<any>) {
|
||||
return clazz.getDeclaredMethods()
|
||||
}
|
||||
|
||||
let classMethodsCache: any[] = [];
|
||||
let classMethodsCache: any[] = []
|
||||
|
||||
function mapToObject(javaObj) {
|
||||
if (!javaObj || !javaObj.class) { throw new TypeError(`参数 ${javaObj} 不是一个Java对象!`) }
|
||||
let target = {};
|
||||
getJavaObjectMethods(javaObj).forEach(t => mapMethod(target, javaObj, t));
|
||||
return target;
|
||||
let target = {}
|
||||
getJavaObjectMethods(javaObj).forEach(t => mapMethod(target, javaObj, t))
|
||||
return target
|
||||
}
|
||||
|
||||
function getJavaObjectMethods(javaObj) {
|
||||
let className = javaObj.class.name;
|
||||
let className = javaObj.class.name
|
||||
if (!classMethodsCache[className]) {
|
||||
let names: any[] = [];
|
||||
let methods = javaObj.class.methods;
|
||||
let names: any[] = []
|
||||
let methods = javaObj.class.methods
|
||||
for (let i in methods) {
|
||||
names.push(methods[i].name);
|
||||
names.push(methods[i].name)
|
||||
}
|
||||
classMethodsCache[className] = names;
|
||||
classMethodsCache[className] = names
|
||||
}
|
||||
return classMethodsCache[className];
|
||||
return classMethodsCache[className]
|
||||
}
|
||||
|
||||
function mapMethod(target, source, name) {
|
||||
target[name] = function __SimpleDynamicMethod__(...args) {
|
||||
if (args.length > 0) {
|
||||
return source[name](args);
|
||||
return source[name](args)
|
||||
} else {
|
||||
return source[name]();
|
||||
return source[name]()
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function on(obj) {
|
||||
// if (!obj || !obj.class) { throw new TypeError(`参数 ${obj} 不是一个Java对象!`) }
|
||||
return new Reflect(obj);
|
||||
return new Reflect(obj)
|
||||
}
|
||||
|
||||
export = {
|
||||
|
||||
32
packages/common/src/thread-pool.ts
Normal file
32
packages/common/src/thread-pool.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
const Thread = Java.type('java.lang.Thread')
|
||||
const ThreadGroup = Java.type("java.lang.ThreadGroup")
|
||||
const AtomicInteger = Java.type("java.util.concurrent.atomic.AtomicInteger")
|
||||
const ThreadPoolExecutor = Java.type('java.util.concurrent.ThreadPoolExecutor')
|
||||
const LinkedBlockingQueue = Java.type("java.util.concurrent.LinkedBlockingQueue")
|
||||
|
||||
interface ThreadPoolConfig {
|
||||
corePoolSize?: number
|
||||
maximumPoolSize?: number
|
||||
keepAliveTime?: number
|
||||
workQueueSize?: number
|
||||
groupName: string
|
||||
}
|
||||
|
||||
export default {
|
||||
create(config: ThreadPoolConfig): java.util.concurrent.ThreadPoolExecutor {
|
||||
let threadCount = new AtomicInteger(0)
|
||||
config = {
|
||||
corePoolSize: 10,
|
||||
maximumPoolSize: 100,
|
||||
keepAliveTime: 60,
|
||||
workQueueSize: 500,
|
||||
...config
|
||||
}
|
||||
return new ThreadPoolExecutor(
|
||||
config.corePoolSize, config.maximumPoolSize, config.keepAliveTime, Packages.java.util.concurrent.TimeUnit.SECONDS,
|
||||
new LinkedBlockingQueue(config.workQueueSize),
|
||||
(run: any) => new Thread(new ThreadGroup(config.groupName), run, config.groupName + "-" + threadCount.incrementAndGet()),
|
||||
new ThreadPoolExecutor.CallerRunsPolicy()
|
||||
)
|
||||
}
|
||||
}
|
||||
1
packages/compile/.npmignore
Symbolic link
1
packages/compile/.npmignore
Symbolic link
@@ -0,0 +1 @@
|
||||
../../.npmignore
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/compile",
|
||||
"version": "0.6.0",
|
||||
"version": "0.8.0",
|
||||
"description": "MiaoScript compile package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -21,6 +21,6 @@
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.8.3"
|
||||
"typescript": "^3.9.2"
|
||||
}
|
||||
}
|
||||
|
||||
1
packages/container/.npmignore
Symbolic link
1
packages/container/.npmignore
Symbolic link
@@ -0,0 +1 @@
|
||||
../../.npmignore
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/container",
|
||||
"version": "0.6.0",
|
||||
"version": "0.8.0",
|
||||
"description": "MiaoScript container package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -21,9 +21,10 @@
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.8.3"
|
||||
"typescript": "^3.9.2"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/nashorn": "^0.8.0",
|
||||
"inversify": "^5.0.1",
|
||||
"inversify-binding-decorators": "^4.0.0"
|
||||
}
|
||||
|
||||
7
packages/container/src/constants.ts
Normal file
7
packages/container/src/constants.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
export namespace ioc {
|
||||
export const Autowired = Symbol('Autowired')
|
||||
export const Resource = Symbol('Resource')
|
||||
export const JavaClass = Symbol('JavaClass')
|
||||
export const JavaInstance = Symbol('JavaInstance')
|
||||
export const JavaStaticClass = Symbol('JavaStaticClass')
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
import { interfaces, Container } from "inversify";
|
||||
import { interfaces, Container } from "inversify"
|
||||
|
||||
let _container: Container;
|
||||
let _container: Container
|
||||
|
||||
const ContainerInstance = Symbol.for("@ccms/ioc:Container");
|
||||
const INJECTION = Symbol.for("INJECTION");
|
||||
const ContainerInstance = Symbol.for("@ccms/ioc:Container")
|
||||
const INJECTION = Symbol.for("INJECTION")
|
||||
|
||||
function _proxyGetter(
|
||||
proto: any,
|
||||
@@ -13,17 +13,17 @@ function _proxyGetter(
|
||||
) {
|
||||
function getter(this: object) {
|
||||
if (doCache && !Reflect.hasMetadata(INJECTION, this, key)) {
|
||||
Reflect.defineMetadata(INJECTION, resolve(), this, key);
|
||||
Reflect.defineMetadata(INJECTION, resolve(), this, key)
|
||||
}
|
||||
if (Reflect.hasMetadata(INJECTION, this, key)) {
|
||||
return Reflect.getMetadata(INJECTION, this, key);
|
||||
return Reflect.getMetadata(INJECTION, this, key)
|
||||
} else {
|
||||
return resolve();
|
||||
return resolve()
|
||||
}
|
||||
}
|
||||
|
||||
function setter(this: object, newVal: any) {
|
||||
Reflect.defineMetadata(INJECTION, newVal, this, key);
|
||||
Reflect.defineMetadata(INJECTION, newVal, this, key)
|
||||
}
|
||||
|
||||
Object.defineProperty(proto, key, {
|
||||
@@ -31,63 +31,63 @@ function _proxyGetter(
|
||||
enumerable: true,
|
||||
get: getter,
|
||||
set: setter
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
function initContainer(container: Container) {
|
||||
Reflect.defineMetadata(ContainerInstance, container, Reflect);
|
||||
_container = container;
|
||||
Reflect.defineMetadata(ContainerInstance, container, Reflect)
|
||||
return _container = container
|
||||
}
|
||||
|
||||
function getContainer(): Container {
|
||||
return _container || Reflect.getMetadata(ContainerInstance, Reflect)
|
||||
return _container || initContainer(new Container())
|
||||
}
|
||||
|
||||
function makePropertyInjectDecorator(doCache: boolean) {
|
||||
return function(serviceIdentifier: interfaces.ServiceIdentifier<any>) {
|
||||
return function(proto: any, key: string): void {
|
||||
return function (serviceIdentifier: interfaces.ServiceIdentifier<any>) {
|
||||
return function (proto: any, key: string): void {
|
||||
let resolve = () => {
|
||||
return getContainer().get(serviceIdentifier);
|
||||
};
|
||||
_proxyGetter(proto, key, resolve, doCache);
|
||||
};
|
||||
};
|
||||
return getContainer().get(serviceIdentifier)
|
||||
}
|
||||
_proxyGetter(proto, key, resolve, doCache)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function makePropertyInjectNamedDecorator(doCache: boolean) {
|
||||
return function(serviceIdentifier: interfaces.ServiceIdentifier<any>, named: string) {
|
||||
return function(proto: any, key: string): void {
|
||||
return function (serviceIdentifier: interfaces.ServiceIdentifier<any>, named: string) {
|
||||
return function (proto: any, key: string): void {
|
||||
let resolve = () => {
|
||||
return getContainer().getNamed(serviceIdentifier, named);
|
||||
};
|
||||
_proxyGetter(proto, key, resolve, doCache);
|
||||
};
|
||||
};
|
||||
return getContainer().getNamed(serviceIdentifier, named)
|
||||
}
|
||||
_proxyGetter(proto, key, resolve, doCache)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function makePropertyInjectTaggedDecorator(doCache: boolean) {
|
||||
return function(serviceIdentifier: interfaces.ServiceIdentifier<any>, key: string, value: any) {
|
||||
return function(proto: any, propertyName: string): void {
|
||||
return function (serviceIdentifier: interfaces.ServiceIdentifier<any>, key: string, value: any) {
|
||||
return function (proto: any, propertyName: string): void {
|
||||
let resolve = () => {
|
||||
return getContainer().getTagged(serviceIdentifier, key, value);
|
||||
};
|
||||
_proxyGetter(proto, propertyName, resolve, doCache);
|
||||
};
|
||||
};
|
||||
return getContainer().getTagged(serviceIdentifier, key, value)
|
||||
}
|
||||
_proxyGetter(proto, propertyName, resolve, doCache)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function makePropertyMultiInjectDecorator(doCache: boolean) {
|
||||
return function(serviceIdentifier: interfaces.ServiceIdentifier<any>) {
|
||||
return function(proto: any, key: string): void {
|
||||
return function (serviceIdentifier: interfaces.ServiceIdentifier<any>) {
|
||||
return function (proto: any, key: string): void {
|
||||
let resolve = () => {
|
||||
return getContainer().getAll(serviceIdentifier);
|
||||
};
|
||||
_proxyGetter(proto, key, resolve, doCache);
|
||||
};
|
||||
};
|
||||
return getContainer().getAll(serviceIdentifier)
|
||||
}
|
||||
_proxyGetter(proto, key, resolve, doCache)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let doCache = true;
|
||||
let doCache = true
|
||||
|
||||
let lazyInject = makePropertyInjectDecorator(doCache)
|
||||
let lazyInjectNamed = makePropertyInjectNamedDecorator(doCache)
|
||||
@@ -102,4 +102,4 @@ export {
|
||||
lazyInjectNamed,
|
||||
lazyInjectTagged,
|
||||
lazyMultiInject
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,25 +1,91 @@
|
||||
import "reflect-metadata";
|
||||
import { initContainer } from './decorators'
|
||||
import { interfaces, Container } from 'inversify';
|
||||
import { fluentProvide } from 'inversify-binding-decorators';
|
||||
/// <reference types="@ccms/nashorn" />
|
||||
|
||||
const provideNamed = (identifier: interfaces.ServiceIdentifier<any>, name: string) => {
|
||||
return fluentProvide(identifier).whenTargetNamed(name).done();
|
||||
};
|
||||
import "reflect-metadata"
|
||||
import { initContainer, getContainer } from './decorators'
|
||||
import { interfaces, Container } from 'inversify'
|
||||
import { fluentProvide } from 'inversify-binding-decorators'
|
||||
import { ioc } from "./constants"
|
||||
|
||||
const provideSingleton = (identifier: interfaces.ServiceIdentifier<any>) => {
|
||||
return fluentProvide(identifier).inSingletonScope().done();
|
||||
};
|
||||
/**
|
||||
* 注册一个命名对象
|
||||
* @param identifier 标识符
|
||||
* @param name 名称
|
||||
*/
|
||||
export const provideNamed = (identifier: interfaces.ServiceIdentifier<any>, name: string) => {
|
||||
return fluentProvide(identifier).whenTargetNamed(name).done()
|
||||
}
|
||||
|
||||
const DefaultContainer = new Container();
|
||||
initContainer(DefaultContainer);
|
||||
/**
|
||||
* 注册一个单例对象
|
||||
* @param identifier 标识符
|
||||
*/
|
||||
export const provideSingleton = (identifier: interfaces.ServiceIdentifier<any>) => {
|
||||
return fluentProvide(identifier).inSingletonScope().done()
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册一个单例对象
|
||||
* @param identifier 标识符
|
||||
*/
|
||||
export const provideSingletonNamed = (identifier: interfaces.ServiceIdentifier<any>, name: string) => {
|
||||
return fluentProvide(identifier).inSingletonScope().whenTargetNamed(name).done()
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得一个 java.lang.Class
|
||||
* @param className Java全类名
|
||||
*/
|
||||
export const JavaClass = (className: string) => {
|
||||
return function (target: any, propertyKey: string, index?: number) {
|
||||
try { target[propertyKey] = Java.type(className).class; return } catch (error) { }
|
||||
try { target[propertyKey] = base.getClass(className); return } catch (error) { }
|
||||
console.warn('JavaClass Inject target', target, 'propertyKey', propertyKey, 'failed!')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得一个JS的Java类
|
||||
* @param className Java 全类名
|
||||
*/
|
||||
export const JSClass = (className: string) => {
|
||||
return function (target: any, propertyKey: string, index?: number) {
|
||||
try { target[propertyKey] = Java.type(className); return } catch (error) { }
|
||||
try { target[propertyKey] = base.getClass(className).static; return } catch (error) { }
|
||||
console.warn('JSClass Inject target', target, 'propertyKey', propertyKey, 'failed!')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 自动注入实例由平台实现
|
||||
* @param className 类名
|
||||
*/
|
||||
export const Autowired = (className?: string | any) => {
|
||||
return function (target: any, propertyKey: string) {
|
||||
target[propertyKey] = getContainer().getNamed(ioc.Autowired, className || propertyKey)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 自动注入资源由平台实现
|
||||
* @param className 类名
|
||||
*/
|
||||
export const Resource = (resourceName?: string | any) => {
|
||||
return function (target: any, propertyKey: string) {
|
||||
target[propertyKey] = getContainer().getNamed(ioc.Resource, resourceName || propertyKey)
|
||||
}
|
||||
}
|
||||
|
||||
export const reduceMetadata = (ctx: interfaces.Context): any => {
|
||||
return ctx.currentRequest.target.metadata.reduce((result, entry, index) => {
|
||||
result[entry.key] = entry.value
|
||||
return result
|
||||
}, {})
|
||||
}
|
||||
|
||||
export const DefaultContainer = new Container()
|
||||
initContainer(DefaultContainer)
|
||||
|
||||
export * from 'inversify'
|
||||
export * from './constants'
|
||||
export * from './decorators'
|
||||
export * from 'inversify-binding-decorators'
|
||||
export {
|
||||
fluentProvide,
|
||||
provideNamed,
|
||||
provideSingleton,
|
||||
DefaultContainer
|
||||
};
|
||||
|
||||
1
packages/core/.npmignore
Symbolic link
1
packages/core/.npmignore
Symbolic link
@@ -0,0 +1 @@
|
||||
../../.npmignore
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/core",
|
||||
"version": "0.6.5",
|
||||
"version": "0.8.1",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -21,11 +21,11 @@
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.8.3"
|
||||
"typescript": "^3.9.2"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.6.5",
|
||||
"@ccms/container": "^0.6.0"
|
||||
"@ccms/api": "^0.8.1",
|
||||
"@ccms/container": "^0.8.0"
|
||||
},
|
||||
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { plugin, server, task, constants } from '@ccms/api'
|
||||
import { DefaultContainer as container, inject, provideSingleton, ContainerInstance, buildProviderModule } from '@ccms/container'
|
||||
console.i18n("ms.core.ioc.completed", { scope: global.scope, time: (Date.now() - containerStartTime) / 1000 })
|
||||
import http from '@ccms/common/dist/http'
|
||||
import { EventEmitter } from 'events'
|
||||
|
||||
@provideSingleton(MiaoScriptCore)
|
||||
class MiaoScriptCore {
|
||||
@@ -30,11 +31,11 @@ class MiaoScriptCore {
|
||||
}
|
||||
|
||||
loadTaskFunction() {
|
||||
global.setGlobal('setTimeout', (func: Function, tick: number, async: boolean = false) => {
|
||||
this.taskManager.create(func).later(tick).async(async).submit()
|
||||
global.setGlobal('setTimeout', (func: Function, tick: number, ...args: any[]) => {
|
||||
return this.taskManager.create(func).later(tick).submit(...args)
|
||||
}, { writable: false, configurable: false })
|
||||
global.setGlobal('setInterval', (func: Function, tick: number, async: boolean = false) => {
|
||||
this.taskManager.create(func).timer(tick).async(async).submit()
|
||||
global.setGlobal('setInterval', (func: Function, tick: number, ...args: any[]) => {
|
||||
return this.taskManager.create(func).timer(tick).submit(...args)
|
||||
}, { writable: false, configurable: false })
|
||||
}
|
||||
|
||||
@@ -52,8 +53,8 @@ class MiaoScriptCore {
|
||||
console.i18n("ms.core.engine.disable")
|
||||
this.pluginManager.disable(this.pluginManager.getPlugins())
|
||||
this.taskManager.disable()
|
||||
//@ts-ignore
|
||||
require.disable()
|
||||
process.emit('exit', 0)
|
||||
process.exit(0)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,6 +79,11 @@ function detectServer(): constants.ServerType {
|
||||
return constants.ServerType.Bungee
|
||||
} catch (ex) {
|
||||
}
|
||||
try {
|
||||
Java.type("org.springframework.boot.SpringApplication")
|
||||
return constants.ServerType.Spring
|
||||
} catch (ex) {
|
||||
}
|
||||
throw Error('Unknow Server Type...')
|
||||
}
|
||||
|
||||
|
||||
1
packages/database/.npmignore
Symbolic link
1
packages/database/.npmignore
Symbolic link
@@ -0,0 +1 @@
|
||||
../../.npmignore
|
||||
30
packages/database/package.json
Normal file
30
packages/database/package.json
Normal file
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"name": "@ccms/database",
|
||||
"version": "0.8.1",
|
||||
"description": "MiaoScript database package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
"minecraft",
|
||||
"bukkit",
|
||||
"sponge"
|
||||
],
|
||||
"author": "MiaoWoo <admin@yumc.pw>",
|
||||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.2"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.8.1",
|
||||
"@ccms/container": "^0.8.0"
|
||||
}
|
||||
}
|
||||
3
packages/database/src/constants.ts
Normal file
3
packages/database/src/constants.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export const METADATA_KEY = {
|
||||
|
||||
}
|
||||
90
packages/database/src/database.ts
Normal file
90
packages/database/src/database.ts
Normal file
@@ -0,0 +1,90 @@
|
||||
import { Model } from './model'
|
||||
|
||||
const HikariDataSource = Java.type('com.zaxxer.hikari.HikariDataSource')
|
||||
const HikariConfig = Java.type('com.zaxxer.hikari.HikariConfig')
|
||||
const JdbcTemplate = Java.type('org.springframework.jdbc.core.JdbcTemplate')
|
||||
|
||||
/**
|
||||
* 数据库配置
|
||||
*/
|
||||
export interface DataBaseConfig {
|
||||
/**
|
||||
* 数据库连接串
|
||||
*/
|
||||
url: string | javax.sql.DataSource
|
||||
/**
|
||||
* 数据库驱动
|
||||
*/
|
||||
driverClassName?: string
|
||||
/**
|
||||
* 用户名
|
||||
*/
|
||||
username?: string
|
||||
/**
|
||||
* 密码
|
||||
*/
|
||||
password?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 数据库封装类
|
||||
*/
|
||||
export class DataBase {
|
||||
private dataSource: javax.sql.DataSource
|
||||
private jdbcTemplate: org.springframework.jdbc.core.JdbcTemplate
|
||||
|
||||
constructor(dbConfig: DataBaseConfig) {
|
||||
if (!dbConfig.url) { throw new Error('DataBase url can\'t be null!') }
|
||||
this.createDataSource(dbConfig)
|
||||
this.initialize()
|
||||
}
|
||||
|
||||
private createDataSource(dbConfig: DataBaseConfig) {
|
||||
if (typeof dbConfig.url === "string") {
|
||||
if (!dbConfig.username || !dbConfig.password) {
|
||||
throw new Error('DataBase username or password can\'t be null!')
|
||||
}
|
||||
let config = new HikariConfig()
|
||||
if (dbConfig.driverClassName) {
|
||||
config.setDriverClassName(dbConfig.driverClassName)
|
||||
}
|
||||
config.setUsername(dbConfig.username)
|
||||
config.setPassword(dbConfig.password)
|
||||
config.setJdbcUrl(dbConfig.url)
|
||||
this.dataSource = new HikariDataSource(config)
|
||||
} else {
|
||||
this.dataSource = dbConfig.url
|
||||
}
|
||||
}
|
||||
|
||||
private initialize() {
|
||||
this.jdbcTemplate = new JdbcTemplate(this.dataSource)
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行SQL查询
|
||||
* @param sql SQL语句
|
||||
*/
|
||||
query<T>(sql: string, ...args: any[]): Array<T> {
|
||||
let startTime = Date.now()
|
||||
let result = Java.from<any>(this.jdbcTemplate.queryForList(sql, args))
|
||||
console.debug(java.lang.String.format(`\n[DB] query \nSQL : ${sql.replace(/\?/ig, '%s')} \nCOST : ${Date.now() - startTime}ms`, args))
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行SQL更新
|
||||
* @param sql SQL语句
|
||||
*/
|
||||
update(sql: string, ...args: any[]): number {
|
||||
let startTime = Date.now()
|
||||
let result = this.jdbcTemplate.update(sql, args)
|
||||
console.debug(java.lang.String.format(`\n[DB] update \nSQL : ${sql.replace(/\?/ig, '%s')} \nCOST : ${Date.now() - startTime}ms`, args))
|
||||
return result
|
||||
}
|
||||
|
||||
close() {
|
||||
//@ts-ignore
|
||||
this.dataSource.close()
|
||||
}
|
||||
}
|
||||
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 {
|
||||
|
||||
}
|
||||
}
|
||||
6
packages/database/src/index.ts
Normal file
6
packages/database/src/index.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
/// <reference types="@ccms/nashorn" />
|
||||
/// <reference types="@javatypes/jdk" />
|
||||
/// <reference types="@javatypes/spring-jdbc" />
|
||||
|
||||
export * from './database'
|
||||
export * from './manager'
|
||||
53
packages/database/src/manager.ts
Normal file
53
packages/database/src/manager.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import { plugin, database } from '@ccms/api'
|
||||
import { provideSingleton, inject, postConstruct } from '@ccms/container'
|
||||
import { DataBase, DataBaseConfig } from './database'
|
||||
|
||||
@provideSingleton(database.DataBaseManager)
|
||||
export class DataBaseManager {
|
||||
@inject(plugin.PluginInstance)
|
||||
private instance: any
|
||||
|
||||
private beanFactory: any
|
||||
private mainDatabase: DataBase
|
||||
private databases: { [key: string]: DataBase } = {}
|
||||
|
||||
@postConstruct()
|
||||
initialize() {
|
||||
try {
|
||||
this.beanFactory = this.instance.getAutowireCapableBeanFactory()
|
||||
let mainDatasource = this.beanFactory.getBean(Packages.javax.sql.DataSource.class)
|
||||
this.mainDatabase = new DataBase({ url: mainDatasource })
|
||||
} catch (error) {
|
||||
console.ex(error)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得主数据库
|
||||
* Get MainDatabase
|
||||
*/
|
||||
getMainDatabase() {
|
||||
return this.mainDatabase
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建数据库
|
||||
* Create A Database Instance
|
||||
* @param name 数据库名称 用于代码 database Name use at code
|
||||
* @param config 数据库配置
|
||||
*/
|
||||
createDatabase(name: string, config: DataBaseConfig) {
|
||||
Java.synchronized(() => {
|
||||
if (this.databases[name]) return this.databases[name]
|
||||
return this.databases[name] = new DataBase(config)
|
||||
}, this.databases)()
|
||||
}
|
||||
|
||||
getDatabase(name: string) {
|
||||
return this.databases[name]
|
||||
}
|
||||
|
||||
disable() {
|
||||
Object.values(this.databases).forEach((ds) => ds?.close())
|
||||
}
|
||||
}
|
||||
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 []
|
||||
}
|
||||
}
|
||||
7
packages/database/tsconfig.json
Normal file
7
packages/database/tsconfig.json
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"baseUrl": "src",
|
||||
"outDir": "dist"
|
||||
}
|
||||
}
|
||||
1
packages/i18n/.npmignore
Symbolic link
1
packages/i18n/.npmignore
Symbolic link
@@ -0,0 +1 @@
|
||||
../../.npmignore
|
||||
@@ -43,4 +43,6 @@ ms.plugin.manager.build.error: "§6Load Plugin From §b{file} §6failed. §4Erro
|
||||
ms.plugin.manager.build.update: "Auto Update Plugin {name} ..."
|
||||
ms.plugin.manager.build.not.extends: "§4Found error plugin §b{source} §4it's not extends interfaces.Plugin, the plugin will be ignore!"
|
||||
ms.plugin.manager.build.exists: "§4Found duplicate plugin §b{exists} §4and §b{source}§4. the first plugin will be ignore!"
|
||||
ms.plugin.manager.config.load.error: "[{plugin}] config {name}.{format} load failed. Error: {error}"
|
||||
ms.plugin.manager.config.save.error: "[{plugin}] config {name}.{format} save failed. Error: {error}"
|
||||
ms.plugin.manager.config.save.default: "[{plugin}] config {name}.{format} not exists. auto create from default variable..."
|
||||
|
||||
@@ -43,4 +43,6 @@ ms.plugin.manager.build.error: "§6从文件 §b{file} §6加载插件失败 §4
|
||||
ms.plugin.manager.build.update: "自动更新插件 {name} ..."
|
||||
ms.plugin.manager.build.not.extends: "§4发现错误的插件 §b{source} §4未继承接口 interfaces.Plugin, 将不会被载入到服务器!"
|
||||
ms.plugin.manager.build.duplicate: "§4发现已存在插件 §b{exists} §4和 §b{source}§4 存在冲突. 已存在插件将会被替换!"
|
||||
ms.plugin.manager.config.load.error: "[{plugin}] 配置 {name}.{format} 加载失败. 错误: {error}"
|
||||
ms.plugin.manager.config.save.error: "[{plugin}] 配置 {name}.{format} 保存失败. 错误: {error}"
|
||||
ms.plugin.manager.config.save.default: "[{plugin}] 配置 {name}.{format} 不存在. 从默认值自动创建保存..."
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/i18n",
|
||||
"version": "0.6.4",
|
||||
"version": "0.8.0",
|
||||
"description": "MiaoScript i18n package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -22,10 +22,10 @@
|
||||
"@types/js-yaml": "^3.12.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.8.3"
|
||||
"typescript": "^3.9.2"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/nashorn": "^0.6.4",
|
||||
"@ccms/nashorn": "^0.8.0",
|
||||
"js-yaml": "^3.13.1"
|
||||
},
|
||||
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
test
|
||||
typings
|
||||
bundled
|
||||
build
|
||||
coverage
|
||||
docs
|
||||
wiki
|
||||
gulpfile.js
|
||||
bower.json
|
||||
karma.conf.js
|
||||
tsconfig.json
|
||||
typings.json
|
||||
CONTRIBUTING.md
|
||||
ISSUE_TEMPLATE.md
|
||||
PULL_REQUEST_TEMPLATE.md
|
||||
tslint.json
|
||||
wallaby.js
|
||||
.travis.yml
|
||||
.gitignore
|
||||
.vscode
|
||||
.theia
|
||||
type_definitions
|
||||
1
packages/nashorn/.npmignore
Symbolic link
1
packages/nashorn/.npmignore
Symbolic link
@@ -0,0 +1 @@
|
||||
../../.npmignore
|
||||
@@ -1,12 +0,0 @@
|
||||
# sponge bukkit jdk bungee nukkit
|
||||
TYPE=nukkit
|
||||
TARGET=../types/dist/typings
|
||||
npx tsc src/build.ts --outDir dist
|
||||
cd dist
|
||||
rm -rf temp
|
||||
mkdir -p temp
|
||||
node build.js ${TYPE}
|
||||
cd ../
|
||||
rm -rf ${TARGET}/${TYPE}
|
||||
mkdir -p ${TARGET}/${TYPE}
|
||||
cp dist/temp/* ${TARGET}/${TYPE}/ -R
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/nashorn",
|
||||
"version": "0.6.4",
|
||||
"version": "0.8.0",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -22,6 +22,6 @@
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.8.3"
|
||||
"typescript": "^3.9.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,200 +0,0 @@
|
||||
import * as fs from "fs";
|
||||
|
||||
function convertJson2TypeDefiend(infile: string, outDir: string) {
|
||||
const file = infile.split(".json")[0];
|
||||
const json = fs.readFileSync(`${inDir}/${file}.json`).toString();
|
||||
const obj = JSON.parse(json);
|
||||
const qnas: string[] = obj.qualifiedName.split(".");
|
||||
let closeBuk = 0;
|
||||
let temp = `declare namespace ${qnas[0]} {\n`;
|
||||
closeBuk++;
|
||||
const nms = qnas.slice(1, qnas.length - 1);
|
||||
for (const nm of nms) {
|
||||
temp += `${' '.repeat(closeBuk)}namespace ${nm.replace('function', 'function$')} {\n`;
|
||||
closeBuk++;
|
||||
}
|
||||
let classModifier = formatClassModifier(obj.modifiers)
|
||||
temp += `${' '.repeat(closeBuk)}// @ts-ignore\n`
|
||||
temp += `${' '.repeat(closeBuk)}${classModifier}${qnas[qnas.length - 1]}`
|
||||
let isInterface = classModifier.includes('interface')
|
||||
let safeInterface = [];
|
||||
for (const ifs of obj.interfaces) {
|
||||
if (!ifs.qualifiedName.startsWith('java')) {
|
||||
safeInterface.push(ifs)
|
||||
}
|
||||
}
|
||||
if (isInterface) {
|
||||
if (safeInterface.length > 0) {
|
||||
temp += ' extends '
|
||||
for (const ifs of safeInterface) {
|
||||
temp += ifs.qualifiedName;
|
||||
temp += ', '
|
||||
}
|
||||
temp = temp.substr(0, temp.length - 2);
|
||||
}
|
||||
} else {
|
||||
temp += `${(obj.superclass) ? (' extends ' + (obj.superclass.qualifiedName == "<any>" ? "object" : obj.superclass.qualifiedName)) : ''}`;
|
||||
if (safeInterface.length > 0) {
|
||||
temp += ' implements '
|
||||
for (const ifs of safeInterface) {
|
||||
temp += ifs.qualifiedName;
|
||||
temp += ', '
|
||||
}
|
||||
temp = temp.substr(0, temp.length - 2);
|
||||
}
|
||||
}
|
||||
temp += ' {\n'
|
||||
closeBuk++;
|
||||
for (const constructor of obj.constructors) {
|
||||
temp += `${formatDoc(constructor.docString, closeBuk)}${' '.repeat(closeBuk)}// @ts-ignore\n${' '.repeat(closeBuk)}constructor(${formatParameters(constructor.parameters)})\n`;
|
||||
}
|
||||
|
||||
let members = [];
|
||||
|
||||
let methods = '';
|
||||
for (const method of obj.methods) {
|
||||
let methodModifier = isInterface ? '' : replaceModifiers(method.modifiers, classModifier.includes('abstract'))
|
||||
if (!whiteKey.includes(method.name)) {
|
||||
if (members[method.name] && methodModifier.includes('abstract')) {
|
||||
continue;
|
||||
}
|
||||
members[method.name] = methodModifier;
|
||||
}
|
||||
methods += `${formatDoc(method.docString, closeBuk)}${' '.repeat(closeBuk)}// @ts-ignore\n${' '.repeat(closeBuk)}${methodModifier} ${method.name}(${formatParameters(method.parameters)}): ${mappingType(method.returnType.type)};\n`;
|
||||
}
|
||||
|
||||
let fields = '';
|
||||
for (const field of obj.fields) {
|
||||
if (members[field.name]) {
|
||||
continue;
|
||||
}
|
||||
fields += `${' '.repeat(closeBuk)}// @ts-ignore\n${' '.repeat(closeBuk)}${isInterface ? '' : replaceModifiers(field.modifiers)} ${field.name}: ${mappingType(field.type ? field.type.type : "any")};\n`;
|
||||
}
|
||||
|
||||
temp += fields + methods;
|
||||
|
||||
for (let index = 0; index < closeBuk; index++) {
|
||||
temp += `${' '.repeat(closeBuk - index - 1)}}\n`;
|
||||
}
|
||||
|
||||
fs.writeFileSync(`${outDir}/${file}.${suffix}`, temp);
|
||||
return `${file}.${suffix}`;
|
||||
}
|
||||
|
||||
function formatClassModifier(modifiers: string) {
|
||||
let tempm = modifiers.replace('public', '').replace('static', '').replace('final', '').trim();
|
||||
if (!modifiers.includes('interface')) { tempm += ' class' }
|
||||
return tempm.length > 0 ? (tempm + ' ') : '';
|
||||
}
|
||||
|
||||
function formatDoc(doc: string, closeBuk: number) {
|
||||
let middleDoc = '';
|
||||
for (const line of doc.split('\n')) {
|
||||
if (line.trim().length != 0) {
|
||||
middleDoc += `${' '.repeat(closeBuk)} * ${line.trim()}\n`
|
||||
}
|
||||
}
|
||||
return middleDoc.length > 0 ? `${' '.repeat(closeBuk)}/**\n${middleDoc}${' '.repeat(closeBuk)} */\n` : '';
|
||||
}
|
||||
|
||||
function replaceModifiers(modifiers: string, absClass = false): string {
|
||||
// modifiers = modifiers.replace(' final', ' readonly');
|
||||
modifiers = modifiers.split(" final")[0];
|
||||
modifiers = modifiers.split(" native")[0];
|
||||
modifiers = modifiers.split(" volatile")[0];
|
||||
modifiers = modifiers.split(" transient")[0];
|
||||
modifiers = modifiers.split(" synchronized")[0];
|
||||
if (!absClass) {
|
||||
modifiers = modifiers.split(" abstract")[0];
|
||||
}
|
||||
return modifiers;
|
||||
}
|
||||
|
||||
function formatParameters(params: any[]) {
|
||||
let tempParam = '';
|
||||
for (const p of params) {
|
||||
tempParam += `${mappingName(p.name)}: ${mappingType(p.type ? p.type.qualifiedName : 'any')}, `
|
||||
}
|
||||
return tempParam.substr(0, tempParam.length - 2);
|
||||
}
|
||||
|
||||
const nameMap = [];
|
||||
nameMap['function'] = 'func'
|
||||
nameMap['in'] = 'input'
|
||||
nameMap['var'] = 'variable'
|
||||
|
||||
function mappingName(name: string) {
|
||||
if (whiteKey.includes(name)) { return name }
|
||||
let outName = nameMap[name] || name || '';
|
||||
return outName;
|
||||
}
|
||||
|
||||
let whiteKey = ['shift', "map", 'filter', 'values', 'valueOf', 'toString', 'length', 'includes', 'entries', 'keys', 'join', 'fill']
|
||||
|
||||
const typeMap = [];
|
||||
typeMap['int'] = 'number';
|
||||
typeMap['int[]'] = 'number[]';
|
||||
typeMap['int[][]'] = 'number[][]';
|
||||
typeMap['byte'] = 'number';
|
||||
typeMap['byte[]'] = 'number[]';
|
||||
typeMap['double'] = 'number';
|
||||
typeMap['double[]'] = 'number[]';
|
||||
typeMap['short'] = 'number';
|
||||
typeMap['short[]'] = 'number[]';
|
||||
typeMap['float'] = 'number';
|
||||
typeMap['float[]'] = 'number[]';
|
||||
typeMap['long'] = 'number';
|
||||
typeMap['long[]'] = 'number[]';
|
||||
typeMap['<any>'] = 'any';
|
||||
typeMap['char'] = 'string';
|
||||
typeMap['char[]'] = 'string[]';
|
||||
typeMap['java.lang.String'] = "string";
|
||||
// typeMap['java.util.Date'] = 'any /*java.util.Date*/'
|
||||
// typeMap['java.util.List'] = 'any[] /*java.util.List*/'
|
||||
// typeMap['java.util.Set'] = 'any[] /*java.util.Set*/'
|
||||
// typeMap['java.util.Collection'] = 'any[] /*java.util.Collection*/'
|
||||
// typeMap['java.util.Map'] = 'Map<any, any> /*java.util.Map*/'
|
||||
// Sponge
|
||||
typeMap['Vectori'] = 'any /*Vector3i*/'
|
||||
typeMap['Vectord'] = 'any /*Vector3d*/'
|
||||
typeMap['Vectorf'] = 'any /*Vector3f*/'
|
||||
typeMap['Vector2i'] = 'any /*Vector2i*/'
|
||||
typeMap['Vector2d'] = 'any /*Vector2d*/'
|
||||
typeMap['Vector2f'] = 'any /*Vector2f*/'
|
||||
typeMap['Vector3i'] = 'any /*Vector3i*/'
|
||||
typeMap['Vector3d'] = 'any /*Vector3d*/'
|
||||
typeMap['Vector3f'] = 'any /*Vector3f*/'
|
||||
typeMap['Type'] = 'any /*Type*/'
|
||||
typeMap['Gson'] = 'any /*Gson*/'
|
||||
typeMap['Logger'] = 'any /*Logger*/'
|
||||
typeMap['MethodVisitor'] = 'any /*MethodVisitor*/'
|
||||
typeMap['ConfigurationNode'] = 'any /*ConfigurationNode*/'
|
||||
typeMap['TypeSerializerCollection'] = 'any /*TypeSerializerCollection*/'
|
||||
typeMap['Quaterniond'] = 'any /*Quaterniond*/'
|
||||
typeMap['Matrix2d'] = 'any /*Matrix2d*/'
|
||||
typeMap['Matrix3d'] = 'any /*Matrix3d*/'
|
||||
typeMap['Matrix4d'] = 'any /*Matrix4d*/'
|
||||
|
||||
function mappingType(type: string): string {
|
||||
let outType = typeMap[type] || type || 'any';
|
||||
if (outType.indexOf('.') != -1) {
|
||||
if (outType.startsWith('java.') || outType.startsWith('org.') || outType.startsWith('net.') || outType.startsWith('cn.')) {
|
||||
|
||||
} else {
|
||||
outType = `any /*${outType}*/`
|
||||
}
|
||||
}
|
||||
return outType.replace('function', 'function$');
|
||||
}
|
||||
|
||||
var args = process.argv.splice(2)
|
||||
|
||||
const suffix = 'd.ts'
|
||||
const inDir = `../docs/${args[0]}`
|
||||
const outDir = "./temp";
|
||||
const files = fs.readdirSync(inDir);
|
||||
let index = '';
|
||||
for (const file of files) {
|
||||
index += `/// <reference path="./${convertJson2TypeDefiend(file, outDir)}" />\n`;
|
||||
}
|
||||
fs.writeFileSync(`${outDir}/index.${suffix}`, index);
|
||||
@@ -1,75 +1,85 @@
|
||||
declare global {
|
||||
const __FILE__: string;
|
||||
const __LINE__: number;
|
||||
const __DIR__: string;
|
||||
let Packages: any;
|
||||
const __FILE__: string
|
||||
const __LINE__: number
|
||||
const __DIR__: string
|
||||
const Packages: any
|
||||
|
||||
function print(...message: any[]): void;
|
||||
function load(script: string | object);
|
||||
function loadWithNewGlobal(script: string | object);
|
||||
function exit(code?: number);
|
||||
function quit(code?: number);
|
||||
function JavaImporter(...className: string[]);
|
||||
function print(...message: any[]): void
|
||||
function load(script: string | object)
|
||||
function loadWithNewGlobal(script: string | object)
|
||||
function exit(code?: number)
|
||||
function quit(code?: number)
|
||||
function JavaImporter(...className: string[])
|
||||
|
||||
namespace Java {
|
||||
function type(clazz: string): any;
|
||||
function from(javaObj: any): any[];
|
||||
function to(array: any[]): any;
|
||||
function extend(...parentTypes: any[]);
|
||||
function type<T = any>(clazz: string): T
|
||||
function from<T = any>(javaObj: T[]): T[]
|
||||
function to<T = any>(array: T[], type?: T): T[]
|
||||
function extend(...parentTypes: any[]): any
|
||||
function synchronized(func: () => void, lock: any): Function
|
||||
function asJSONCompatible<T = any>(obj: T): T
|
||||
//@ts-ignore
|
||||
// function super(type: any);
|
||||
}
|
||||
|
||||
interface Error {
|
||||
readonly lineNumber?: number;
|
||||
readonly columnNumber?: number;
|
||||
readonly fileName?: string;
|
||||
dumpStack?: Function;
|
||||
printStackTrace?: Function;
|
||||
getStackTrace?: () => any[];
|
||||
readonly class?: any
|
||||
readonly lineNumber?: number
|
||||
readonly columnNumber?: number
|
||||
readonly fileName?: string
|
||||
dumpStack?: Function
|
||||
printStackTrace?: Function
|
||||
getStackTrace?: () => any[]
|
||||
}
|
||||
|
||||
interface String {
|
||||
trimLeft(): string;
|
||||
trimRight(): string;
|
||||
trimLeft(): string
|
||||
trimRight(): string
|
||||
}
|
||||
|
||||
interface Object {
|
||||
setPrototypeOf(obj: object, prototype: object): void;
|
||||
bindProperties(to: object, from: object): void;
|
||||
setPrototypeOf(obj: object, prototype: object): void
|
||||
bindProperties(to: object, from: object): void
|
||||
}
|
||||
|
||||
namespace NodeJS {
|
||||
interface Global {
|
||||
scope: string;
|
||||
logger: any;
|
||||
debug: boolean;
|
||||
level: string;
|
||||
NashornEngineStartTime: number;
|
||||
setGlobal: (key: string, value: any, config?: PropertyDescriptor & ThisType<any>) => void;
|
||||
noop: () => void;
|
||||
console: Console;
|
||||
scope: string
|
||||
logger: any
|
||||
debug: boolean
|
||||
level: string
|
||||
NashornEngineStartTime: number
|
||||
setGlobal: (key: string, value: any, config?: PropertyDescriptor & ThisType<any>) => void
|
||||
noop: () => void
|
||||
console: Console
|
||||
}
|
||||
interface Process {
|
||||
on(event: string, listener: any): this
|
||||
emit(event: string, ...message: any): this
|
||||
}
|
||||
}
|
||||
var root: string;
|
||||
var base: Core;
|
||||
var ScriptEngineContextHolder: any;
|
||||
function engineLoad(str: string): any;
|
||||
const root: string
|
||||
const base: Core
|
||||
const ScriptEngineContextHolder: any
|
||||
function engineLoad(str: string | { script: string, name: string }): any
|
||||
interface Core {
|
||||
getClass(name: String): any;
|
||||
getProxyClass(): any;
|
||||
getInstance(): any;
|
||||
read(path: string): string;
|
||||
save(path: string, content: string): void;
|
||||
delete(path: string): void;
|
||||
getClass(name: String): any
|
||||
getProxyClass(): any
|
||||
getInstance(): any
|
||||
read(path: string): string
|
||||
save(path: string, content: string): void
|
||||
delete(path: string): void
|
||||
}
|
||||
interface Console {
|
||||
ex(err: Error): void;
|
||||
stack(err: Error): string[];
|
||||
sender(...args: any): void;
|
||||
console(...args: any): void;
|
||||
i18n(name: string, ...params: any[]): void;
|
||||
ex(err: Error): void
|
||||
stack(err: Error, color?: boolean): string[]
|
||||
sender(...args: any): void
|
||||
console(...args: any): void
|
||||
i18n(name: string, ...params: any[]): void
|
||||
}
|
||||
interface ProxyConstructor {
|
||||
newProxy<T extends object>(target: T, handler: ProxyHandler<T>): T
|
||||
}
|
||||
}
|
||||
|
||||
export { };
|
||||
export { }
|
||||
|
||||
1
packages/nodejs/.npmignore
Symbolic link
1
packages/nodejs/.npmignore
Symbolic link
@@ -0,0 +1 @@
|
||||
../../.npmignore
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/nodejs",
|
||||
"version": "0.6.4",
|
||||
"version": "0.8.0",
|
||||
"description": "MiaoScript nodejs package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -21,10 +21,10 @@
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.8.3"
|
||||
"typescript": "^3.9.2"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/nashorn": "^0.6.4"
|
||||
"@ccms/nashorn": "^0.8.0"
|
||||
},
|
||||
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
||||
}
|
||||
|
||||
1
packages/nukkit/.npmignore
Symbolic link
1
packages/nukkit/.npmignore
Symbolic link
@@ -0,0 +1 @@
|
||||
../../.npmignore
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/nukkit",
|
||||
"version": "0.6.5",
|
||||
"version": "0.8.1",
|
||||
"description": "MiaoScript nukkit package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -21,11 +21,11 @@
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.8.3"
|
||||
"typescript": "^3.9.2"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.6.5",
|
||||
"@ccms/common": "^0.6.4",
|
||||
"@ccms/container": "^0.6.0"
|
||||
"@ccms/api": "^0.8.1",
|
||||
"@ccms/common": "^0.8.0",
|
||||
"@ccms/container": "^0.8.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/// <reference types="@ccms/types/dist/typings/nukkit" />
|
||||
/// <reference types="@javatypes/nukkit-api" />
|
||||
|
||||
import { server } from '@ccms/api'
|
||||
import { Container } from '@ccms/container'
|
||||
|
||||
@@ -45,6 +45,9 @@ export class NukkitServer implements server.Server {
|
||||
getNettyPipeline() {
|
||||
throw new Error("Method not implemented.");
|
||||
}
|
||||
getRootLogger() {
|
||||
return Packages.org.apache.logging.log4j.LogManager.getRootLogger()
|
||||
}
|
||||
sendJson(sender: string | any, json: object | string): void {
|
||||
throw new Error("Method not implemented.");
|
||||
}
|
||||
|
||||
@@ -21,10 +21,8 @@ export class NukkitTaskManager implements task.TaskManager {
|
||||
}
|
||||
|
||||
export class NukkitTask extends task.Task {
|
||||
submit(): task.Cancelable {
|
||||
let run = new NukkitRunnable({
|
||||
run: () => this.run()
|
||||
})
|
||||
submit(...args: any[]): task.Cancelable {
|
||||
let run = new NukkitRunnable({ run: () => this.run(...args) })
|
||||
let funcName = `runTask${this.interval ? 'Timer' : 'Later'}${this.isAsync ? 'Asynchronously' : ''}`
|
||||
if (this.interval) {
|
||||
run[funcName](this.plugin, this.laterTime, this.interval);
|
||||
|
||||
1
packages/ployfill/.npmignore
Symbolic link
1
packages/ployfill/.npmignore
Symbolic link
@@ -0,0 +1 @@
|
||||
../../.npmignore
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/ployfill",
|
||||
"version": "0.6.5",
|
||||
"version": "0.8.1",
|
||||
"description": "MiaoScript ployfill package",
|
||||
"author": "MiaoWoo <admin@yumc.pw>",
|
||||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
@@ -14,13 +14,14 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/i18n": "^0.6.4",
|
||||
"@ccms/nashorn": "^0.6.4",
|
||||
"core-js": "^3.6.4"
|
||||
"@ccms/i18n": "^0.8.0",
|
||||
"@ccms/nashorn": "^0.8.0",
|
||||
"@ccms/nodejs": "^0.8.0",
|
||||
"core-js": "^3.6.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.8.3"
|
||||
"typescript": "^3.9.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
/// <reference types="@ccms/nashorn" />
|
||||
|
||||
import '@ccms/nodejs'
|
||||
import i18n from '@ccms/i18n'
|
||||
let ployfillStartTime = new Date().getTime();
|
||||
i18n.initialize();
|
||||
console.i18n("ms.ployfill.initialize");
|
||||
require('./es5-ext');
|
||||
require('core-js');
|
||||
require('./node-shim');
|
||||
let ployfillStartTime = new Date().getTime()
|
||||
i18n.initialize()
|
||||
console.i18n("ms.ployfill.initialize")
|
||||
require('./es5-ext')
|
||||
require('./node-shim')
|
||||
require('core-js')
|
||||
//@ts-ignore
|
||||
process.on('exit', () => require.disable())
|
||||
global.setGlobal('Proxy', require('./proxy').Proxy)
|
||||
global.setGlobal('XMLHttpRequest', require('./xml-http-request').XMLHttpRequest)
|
||||
global.setGlobal('Blob', require('blob-polyfill').Blob)
|
||||
console.i18n("ms.ployfill.completed", { time: (new Date().getTime() - ployfillStartTime) / 1000 });
|
||||
console.i18n("ms.ployfill.completed", { time: (new Date().getTime() - ployfillStartTime) / 1000 })
|
||||
|
||||
@@ -1,8 +1,36 @@
|
||||
global.setGlobal('process', {
|
||||
env: {
|
||||
import { EventEmitter } from 'events'
|
||||
|
||||
const Thread = Java.type('java.lang.Thread')
|
||||
const ThreadGroup = Java.type("java.lang.ThreadGroup")
|
||||
const AtomicInteger = Java.type("java.util.concurrent.atomic.AtomicInteger")
|
||||
const ThreadPoolExecutor = Java.type('java.util.concurrent.ThreadPoolExecutor')
|
||||
const LinkedBlockingQueue = Java.type("java.util.concurrent.LinkedBlockingQueue")
|
||||
|
||||
const threadCount = new AtomicInteger(0)
|
||||
const threadGroup = new ThreadGroup("@ccms/ployfill-micro-task")
|
||||
const microTaskPool = new ThreadPoolExecutor(
|
||||
10, 100, 60, Packages.java.util.concurrent.TimeUnit.SECONDS,
|
||||
new LinkedBlockingQueue(500),
|
||||
(run: any) => new Thread(threadGroup, run, "@ccms/micro-task-" + threadCount.incrementAndGet()),
|
||||
new ThreadPoolExecutor.CallerRunsPolicy()
|
||||
)
|
||||
|
||||
class Process extends EventEmitter {
|
||||
env = {
|
||||
__noSuchProperty__: (prop) => {
|
||||
return Packages.java.lang.System.getenv(prop)
|
||||
}
|
||||
},
|
||||
platform: Packages.java.lang.System.getProperty("os.name")
|
||||
}, {})
|
||||
}
|
||||
platform = Packages.java.lang.System.getProperty("os.name")
|
||||
nextTick(func: Function) {
|
||||
microTaskPool.execute(func)
|
||||
}
|
||||
queueMicrotask(func: Function) {
|
||||
microTaskPool.execute(func)
|
||||
}
|
||||
exit() {
|
||||
microTaskPool.shutdown();
|
||||
}
|
||||
}
|
||||
global.setGlobal('process', new Process(), {})
|
||||
global.setGlobal('queueMicrotask', (func: any) => microTaskPool.execute(func), {})
|
||||
|
||||
1
packages/plugin/.npmignore
Symbolic link
1
packages/plugin/.npmignore
Symbolic link
@@ -0,0 +1 @@
|
||||
../../.npmignore
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/plugin",
|
||||
"version": "0.6.5",
|
||||
"version": "0.8.1",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -22,13 +22,13 @@
|
||||
"@types/js-yaml": "^3.12.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.8.3"
|
||||
"typescript": "^3.9.2"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.6.5",
|
||||
"@ccms/common": "^0.6.4",
|
||||
"@ccms/container": "^0.6.0",
|
||||
"@ccms/i18n": "^0.6.4",
|
||||
"@ccms/api": "^0.8.1",
|
||||
"@ccms/common": "^0.8.0",
|
||||
"@ccms/container": "^0.8.0",
|
||||
"@ccms/i18n": "^0.8.0",
|
||||
"js-yaml": "^3.13.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ export class YamlPluginConfig implements PluginConfigLoader {
|
||||
return yaml.safeLoad(content);
|
||||
}
|
||||
dump(variable: any): string {
|
||||
return yaml.safeDump(variable);
|
||||
return yaml.safeDump(variable, { skipInvalid: true });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { injectable, decorate } from "@ccms/container";
|
||||
import { plugin as pluginApi } from "@ccms/api"
|
||||
import { injectable, decorate } from "@ccms/container"
|
||||
import { interfaces } from './interfaces'
|
||||
import { METADATA_KEY } from './constants'
|
||||
import { getPluginMetadatas, getPluginCommandMetadata, getPluginListenerMetadata, getPluginTabCompleterMetadata, getPluginConfigMetadata, getPluginStageMetadata, getPluginSources } from './utils'
|
||||
@@ -7,19 +8,19 @@ import { getPluginMetadatas, getPluginCommandMetadata, getPluginListenerMetadata
|
||||
* MiaoScript plugin
|
||||
* @param metadata PluginMetadata
|
||||
*/
|
||||
export function plugin(metadata: interfaces.PluginMetadata) {
|
||||
export function plugin(metadata: pluginApi.PluginMetadata) {
|
||||
return function (target: any) {
|
||||
metadata.target = target;
|
||||
metadata.type = "ioc";
|
||||
decorate(injectable(), target);
|
||||
Reflect.defineMetadata(METADATA_KEY.plugin, metadata, target);
|
||||
const previousMetadata: Map<string, interfaces.PluginMetadata> = getPluginMetadatas();
|
||||
previousMetadata.set(metadata.name, metadata);
|
||||
Reflect.defineMetadata(METADATA_KEY.plugin, previousMetadata, Reflect);
|
||||
const previousSources: Map<string, interfaces.PluginMetadata> = getPluginSources();
|
||||
previousSources.set(metadata.source.toString(), metadata);
|
||||
Reflect.defineMetadata(METADATA_KEY.souece, previousSources, Reflect);
|
||||
};
|
||||
metadata.target = target
|
||||
metadata.type = "ioc"
|
||||
decorate(injectable(), target)
|
||||
Reflect.defineMetadata(METADATA_KEY.plugin, metadata, target)
|
||||
const previousMetadata: Map<string, pluginApi.PluginMetadata> = getPluginMetadatas()
|
||||
previousMetadata.set(metadata.name, metadata)
|
||||
Reflect.defineMetadata(METADATA_KEY.plugin, previousMetadata, Reflect)
|
||||
const previousSources: Map<string, pluginApi.PluginMetadata> = getPluginSources()
|
||||
previousSources.set(metadata.source.toString(), metadata)
|
||||
Reflect.defineMetadata(METADATA_KEY.souece, previousSources, Reflect)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -28,13 +29,13 @@ export function plugin(metadata: interfaces.PluginMetadata) {
|
||||
*/
|
||||
export function cmd(metadata: interfaces.CommandMetadata = {}) {
|
||||
return function (target: any, key: string, value: any) {
|
||||
metadata.name = metadata.name || key;
|
||||
metadata.executor = key;
|
||||
metadata.name = metadata.name || key
|
||||
metadata.executor = key
|
||||
metadata.paramtypes = Reflect.getMetadata("design:paramtypes", target, key)
|
||||
const previousMetadata: Map<string, interfaces.CommandMetadata> = getPluginCommandMetadata(target)
|
||||
previousMetadata.set(metadata.name, metadata);
|
||||
Reflect.defineMetadata(METADATA_KEY.cmd, previousMetadata, target.constructor);
|
||||
};
|
||||
previousMetadata.set(metadata.name, metadata)
|
||||
Reflect.defineMetadata(METADATA_KEY.cmd, previousMetadata, target.constructor)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -43,14 +44,14 @@ export function cmd(metadata: interfaces.CommandMetadata = {}) {
|
||||
*/
|
||||
export function tab(metadata: interfaces.CommandMetadata = {}) {
|
||||
return function (target: any, key: string, value: any) {
|
||||
metadata.name = metadata.name || (key.startsWith('tab') ? key.split('tab', 2)[1] : key);
|
||||
if (!metadata.name) { return; }
|
||||
metadata.executor = key;
|
||||
metadata.name = metadata.name || (key.startsWith('tab') ? key.split('tab', 2)[1] : key)
|
||||
if (!metadata.name) { return }
|
||||
metadata.executor = key
|
||||
metadata.paramtypes = Reflect.getMetadata("design:paramtypes", target, key)
|
||||
const previousMetadata: Map<string, interfaces.CommandMetadata> = getPluginTabCompleterMetadata(target)
|
||||
previousMetadata.set(metadata.name, metadata)
|
||||
Reflect.defineMetadata(METADATA_KEY.tab, previousMetadata, target.constructor);
|
||||
};
|
||||
Reflect.defineMetadata(METADATA_KEY.tab, previousMetadata, target.constructor)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -59,30 +60,32 @@ export function tab(metadata: interfaces.CommandMetadata = {}) {
|
||||
*/
|
||||
export function listener(metadata: interfaces.ListenerMetadata = {}) {
|
||||
return function (target: any, key: string, value: any) {
|
||||
metadata.name = metadata.name || key;
|
||||
metadata.executor = key;
|
||||
metadata.name = metadata.name || key
|
||||
metadata.executor = key
|
||||
const previousMetadata: interfaces.ListenerMetadata[] = getPluginListenerMetadata(target)
|
||||
Reflect.defineMetadata(METADATA_KEY.listener, [metadata, ...previousMetadata], target.constructor);
|
||||
};
|
||||
Reflect.defineMetadata(METADATA_KEY.listener, [metadata, ...previousMetadata], target.constructor)
|
||||
}
|
||||
}
|
||||
|
||||
export function config(metadata: interfaces.ConfigMetadata = { version: 1, format: 'yml' }) {
|
||||
export function config(metadata: interfaces.ConfigMetadata = {}) {
|
||||
return function (target: any, key: string) {
|
||||
metadata.name = metadata.name || key;
|
||||
metadata.variable = key;
|
||||
metadata.name = metadata.name || key
|
||||
metadata.variable = key
|
||||
metadata.version = metadata.version ?? 1
|
||||
metadata.format = metadata.format ?? 'yml'
|
||||
const previousMetadata: Map<string, interfaces.ConfigMetadata> = getPluginConfigMetadata(target)
|
||||
previousMetadata.set(metadata.name, metadata);
|
||||
Reflect.defineMetadata(METADATA_KEY.config, previousMetadata, target.constructor);
|
||||
previousMetadata.set(metadata.name, metadata)
|
||||
Reflect.defineMetadata(METADATA_KEY.config, previousMetadata, target.constructor)
|
||||
}
|
||||
}
|
||||
|
||||
function stage(metadata: interfaces.ExecMetadata = {}, stage: string) {
|
||||
return function (target: any, key: string, value: any) {
|
||||
metadata.name = metadata.name || key;
|
||||
metadata.executor = key;
|
||||
metadata.name = metadata.name || key
|
||||
metadata.executor = key
|
||||
const previousMetadata: interfaces.ExecMetadata[] = getPluginStageMetadata(target, stage)
|
||||
Reflect.defineMetadata(METADATA_KEY.stage[stage], [metadata, ...previousMetadata], target.constructor);
|
||||
};
|
||||
Reflect.defineMetadata(METADATA_KEY.stage[stage], [metadata, ...previousMetadata], target.constructor)
|
||||
}
|
||||
}
|
||||
|
||||
export function load(metadata: interfaces.ExecMetadata = {}) {
|
||||
|
||||
@@ -1,3 +1,15 @@
|
||||
import './scanner/file-scanner'
|
||||
import './loader/ioc-loader'
|
||||
import './loader/basic-loader'
|
||||
|
||||
export * from './manager'
|
||||
export * from './decorators'
|
||||
export * from './interfaces'
|
||||
|
||||
export {
|
||||
plugin as JSPlugin,
|
||||
cmd as Cmd,
|
||||
tab as Tab,
|
||||
listener as Listener,
|
||||
config as Config
|
||||
} from './decorators'
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import { server, MiaoScriptConsole, event } from "@ccms/api";
|
||||
import { injectable, inject, postConstruct } from "@ccms/container";
|
||||
import { getPluginMetadata } from "./utils";
|
||||
import { server, MiaoScriptConsole, event, plugin } from "@ccms/api"
|
||||
import { injectable, inject, postConstruct } from "@ccms/container"
|
||||
import { getPluginMetadata } from "./utils"
|
||||
|
||||
export namespace interfaces {
|
||||
@injectable()
|
||||
export abstract class Plugin {
|
||||
public description: PluginMetadata;
|
||||
public logger: Console;
|
||||
export abstract class Plugin implements plugin.Plugin {
|
||||
public description: plugin.PluginMetadata
|
||||
public logger: Console
|
||||
@inject(server.Console)
|
||||
private Console: MiaoScriptConsole;
|
||||
private Console: MiaoScriptConsole
|
||||
|
||||
constructor() {
|
||||
this.description = getPluginMetadata(this)
|
||||
@@ -24,82 +24,49 @@ export namespace interfaces {
|
||||
public enable() { }
|
||||
public disable() { }
|
||||
}
|
||||
interface BaseMetadata {
|
||||
/**
|
||||
* 名称 为空则为对象名称
|
||||
*/
|
||||
name?: string;
|
||||
/**
|
||||
* 支持的服务器列表 为空则代表所有
|
||||
*/
|
||||
servers?: string[];
|
||||
}
|
||||
export interface PluginMetadata extends BaseMetadata {
|
||||
/**
|
||||
* 插件名称
|
||||
*/
|
||||
name: string;
|
||||
/**
|
||||
* 前缀
|
||||
*/
|
||||
prefix?: string;
|
||||
/**
|
||||
* 插件版本
|
||||
*/
|
||||
version: string;
|
||||
/**
|
||||
* 插件版本
|
||||
*/
|
||||
author: string | string[];
|
||||
/**
|
||||
* 插件源文件 必须指定为 __filename
|
||||
*/
|
||||
source: string;
|
||||
/**
|
||||
* 插件类型 默认为 ioc 执行 MiaoScript 加载逻辑
|
||||
*/
|
||||
type?: string;
|
||||
/**
|
||||
* 插件本体
|
||||
*/
|
||||
target?: any;
|
||||
}
|
||||
export interface ExecMetadata extends BaseMetadata {
|
||||
export interface ExecMetadata extends plugin.BaseMetadata {
|
||||
/**
|
||||
* 执行器
|
||||
*/
|
||||
executor?: string;
|
||||
executor?: string
|
||||
}
|
||||
export interface CommandMetadata extends ExecMetadata {
|
||||
/**
|
||||
* 命令描述
|
||||
*/
|
||||
description?: string
|
||||
/**
|
||||
* 参数列表
|
||||
*/
|
||||
paramtypes?: string[];
|
||||
paramtypes?: string[]
|
||||
}
|
||||
export interface ListenerMetadata extends ExecMetadata {
|
||||
/**
|
||||
* 监听优先级
|
||||
*/
|
||||
priority?: event.EventPriority;
|
||||
priority?: event.EventPriority
|
||||
/**
|
||||
* 是否忽略已取消的事件
|
||||
*/
|
||||
ignoreCancel?: boolean;
|
||||
|
||||
ignoreCancel?: boolean
|
||||
}
|
||||
export interface ConfigMetadata extends BaseMetadata {
|
||||
export interface ConfigMetadata extends plugin.BaseMetadata {
|
||||
/**
|
||||
* 配置文件版本号
|
||||
*/
|
||||
version?: number;
|
||||
version?: number
|
||||
/**
|
||||
* 实体变量名称
|
||||
*/
|
||||
variable?: string;
|
||||
variable?: string
|
||||
/**
|
||||
* 配置文件格式 默认 yml
|
||||
*/
|
||||
format?: string;
|
||||
format?: string
|
||||
/**
|
||||
* 是否为只读(关闭时将不会自动保存)
|
||||
*/
|
||||
readonly?: boolean
|
||||
}
|
||||
export type PluginLike = Plugin | string;
|
||||
export type PluginLike = Plugin | string
|
||||
}
|
||||
|
||||
29
packages/plugin/src/loader/basic-loader.ts
Normal file
29
packages/plugin/src/loader/basic-loader.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { plugin } from "@ccms/api"
|
||||
import { provideSingleton } from "@ccms/container"
|
||||
|
||||
@provideSingleton(plugin.PluginLoader)
|
||||
export class BasicLoader implements plugin.PluginLoader {
|
||||
type: string = 'basic'
|
||||
|
||||
private pluginRequireMap: Map<string, any>
|
||||
|
||||
constructor() {
|
||||
this.pluginRequireMap = new Map()
|
||||
}
|
||||
require(loadMetadata: plugin.PluginLoadMetadata) {
|
||||
let metadata = loadMetadata.instance.description
|
||||
if (metadata && metadata.type == this.type) {
|
||||
loadMetadata.metadata = metadata
|
||||
loadMetadata.loaded = true
|
||||
this.pluginRequireMap.set(metadata.source.toString(), loadMetadata.instance)
|
||||
}
|
||||
return loadMetadata
|
||||
}
|
||||
build(metadata: plugin.PluginMetadata) {
|
||||
return this.pluginRequireMap.get(metadata.source.toString())
|
||||
}
|
||||
load(plugin: plugin.Plugin): void { }
|
||||
enable(plugin: plugin.Plugin): void { }
|
||||
disable(plugin: plugin.Plugin): void { }
|
||||
reload(plugin: plugin.Plugin): void { }
|
||||
}
|
||||
102
packages/plugin/src/loader/ioc-loader.ts
Normal file
102
packages/plugin/src/loader/ioc-loader.ts
Normal file
@@ -0,0 +1,102 @@
|
||||
import { plugin, server } from "@ccms/api"
|
||||
import { inject, ContainerInstance, Container, provideSingleton } from "@ccms/container"
|
||||
|
||||
import { interfaces } from "../interfaces"
|
||||
import { getPluginStageMetadata, getPluginSources } from "../utils"
|
||||
|
||||
@provideSingleton(plugin.PluginLoader)
|
||||
export class IocLoader implements plugin.PluginLoader {
|
||||
type: string = 'ioc'
|
||||
@inject(ContainerInstance)
|
||||
private container: Container
|
||||
@inject(server.ServerType)
|
||||
private serverType: string
|
||||
|
||||
private pluginMetadataMap: Map<string, plugin.PluginMetadata>
|
||||
|
||||
constructor() {
|
||||
this.pluginMetadataMap = getPluginSources()
|
||||
}
|
||||
|
||||
require(loadMetadata: plugin.PluginLoadMetadata) {
|
||||
let metadata = this.pluginMetadataMap.get(loadMetadata.file.toString())
|
||||
if (metadata && metadata.type == this.type) {
|
||||
loadMetadata.metadata = metadata
|
||||
loadMetadata.loaded = true
|
||||
}
|
||||
return loadMetadata
|
||||
}
|
||||
|
||||
build(metadata: plugin.PluginMetadata) {
|
||||
if (!this.allowProcess(metadata.servers)) { return }
|
||||
let pluginInstance: plugin.Plugin
|
||||
try {
|
||||
this.bindPlugin(metadata)
|
||||
pluginInstance = this.container.getNamed<plugin.Plugin>(plugin.Plugin, metadata.name)
|
||||
if (!(pluginInstance instanceof interfaces.Plugin)) {
|
||||
console.i18n('ms.plugin.manager.build.not.extends', { source: metadata.source })
|
||||
return
|
||||
}
|
||||
} catch (ex) {
|
||||
console.i18n("ms.plugin.manager.initialize.error", { name: metadata.name, ex })
|
||||
console.ex(ex)
|
||||
}
|
||||
return pluginInstance
|
||||
}
|
||||
|
||||
load(plugin: plugin.Plugin): void {
|
||||
this.stage(plugin, 'load')
|
||||
}
|
||||
enable(plugin: plugin.Plugin): void {
|
||||
this.stage(plugin, 'enable')
|
||||
}
|
||||
disable(plugin: plugin.Plugin): void {
|
||||
this.stage(plugin, 'disable')
|
||||
}
|
||||
reload(plugin: plugin.Plugin): void {
|
||||
this.disable(plugin)
|
||||
//@ts-ignore
|
||||
require(plugin.description.source, { cache: false })
|
||||
this.load(plugin)
|
||||
this.enable(plugin)
|
||||
}
|
||||
|
||||
private bindPlugin(metadata: plugin.PluginMetadata) {
|
||||
try {
|
||||
let pluginInstance = this.container.getNamed<plugin.Plugin>(plugin.Plugin, metadata.name)
|
||||
if (pluginInstance.description.source + '' !== metadata.source + '') {
|
||||
console.i18n('ms.plugin.manager.build.duplicate', { exists: pluginInstance.description.source, source: metadata.source })
|
||||
}
|
||||
this.container.rebind(plugin.Plugin).to(metadata.target).inSingletonScope().whenTargetNamed(metadata.name)
|
||||
} catch{
|
||||
this.container.bind(plugin.Plugin).to(metadata.target).inSingletonScope().whenTargetNamed(metadata.name)
|
||||
}
|
||||
}
|
||||
|
||||
private allowProcess(servers: string[]) {
|
||||
// Not set servers -> allow
|
||||
if (!servers || !servers.length) return true
|
||||
// include !type -> deny
|
||||
let denyServers = servers.filter(svr => svr.startsWith("!"))
|
||||
if (denyServers.length !== 0) {
|
||||
return !denyServers.includes(`!${this.serverType}`)
|
||||
} else {
|
||||
// only include -> allow
|
||||
return servers.includes(this.serverType)
|
||||
}
|
||||
}
|
||||
|
||||
private stage(pluginInstance: plugin.Plugin, stageName: string) {
|
||||
let stages = getPluginStageMetadata(pluginInstance, stageName)
|
||||
for (const stage of stages) {
|
||||
if (!this.allowProcess(stage.servers)) { continue }
|
||||
console.i18n("ms.plugin.manager.stage.exec", { plugin: pluginInstance.description.name, name: stage.executor, stage: stageName, servers: stage.servers })
|
||||
try {
|
||||
pluginInstance[stage.executor].apply(pluginInstance)
|
||||
} catch (error) {
|
||||
console.i18n("ms.plugin.manager.stage.exec.error", { plugin: pluginInstance.description.name, executor: stage.executor, error })
|
||||
console.ex(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,9 @@ import { plugin, server, command, event } from '@ccms/api'
|
||||
import { inject, provideSingleton, Container, ContainerInstance } from '@ccms/container'
|
||||
import * as fs from '@ccms/common/dist/fs'
|
||||
|
||||
import { getPluginMetadatas, getPluginCommandMetadata, getPluginListenerMetadata, getPlugin, getPluginTabCompleterMetadata, getPluginConfigMetadata, getPluginStageMetadata, getPluginSources } from './utils'
|
||||
import { interfaces } from './interfaces'
|
||||
import { getConfigLoader } from './config'
|
||||
import { getPluginCommandMetadata, getPluginListenerMetadata, getPluginTabCompleterMetadata, getPluginConfigMetadata } from './utils'
|
||||
|
||||
const Thread = Java.type('java.lang.Thread')
|
||||
|
||||
@@ -16,7 +16,7 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
||||
@inject(plugin.PluginInstance)
|
||||
private pluginInstance: any
|
||||
@inject(plugin.PluginFolder)
|
||||
private pluginFolder: string;
|
||||
private pluginFolder: string
|
||||
@inject(server.ServerType)
|
||||
private serverType: string
|
||||
@inject(command.Command)
|
||||
@@ -25,59 +25,115 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
||||
private EventManager: event.Event
|
||||
|
||||
private initialized: boolean = false
|
||||
private pluginRequireMap: Map<string, any>
|
||||
private pluginInstanceMap: Map<string, interfaces.Plugin>
|
||||
private pluginMetadataMap: Map<string, interfaces.PluginMetadata>
|
||||
|
||||
private sacnnerMap: Map<string, plugin.PluginScanner>
|
||||
private loaderMap: Map<string, plugin.PluginLoader>
|
||||
|
||||
private instanceMap: Map<string, plugin.Plugin>
|
||||
private metadataMap: Map<string, plugin.PluginMetadata>
|
||||
|
||||
constructor() {
|
||||
this.sacnnerMap = new Map()
|
||||
this.loaderMap = new Map()
|
||||
|
||||
this.instanceMap = new Map()
|
||||
this.metadataMap = new Map()
|
||||
}
|
||||
|
||||
initialize() {
|
||||
if (this.pluginInstance !== null && this.initialized !== true) {
|
||||
// 如果plugin不等于null 则代表是正式环境
|
||||
if (this.pluginInstance === undefined) { throw new Error("Can't found Plugin Instance!") }
|
||||
if (this.initialized !== true) {
|
||||
console.i18n('ms.plugin.initialize', { plugin: this.pluginInstance, loader: Thread.currentThread().contextClassLoader })
|
||||
console.i18n('ms.plugin.event.map', { count: this.EventManager.mapEventName().toFixed(0), type: this.serverType });
|
||||
this.pluginRequireMap = new Map()
|
||||
this.pluginInstanceMap = new Map()
|
||||
this.pluginMetadataMap = getPluginSources();
|
||||
this.initialized = true;
|
||||
console.i18n('ms.plugin.event.map', { count: this.EventManager.mapEventName().toFixed(0), type: this.serverType })
|
||||
let pluginScanner = this.container.getAll<plugin.PluginScanner>(plugin.PluginScanner)
|
||||
pluginScanner.forEach((scanner) => {
|
||||
console.debug(`loading plugin sacnner ${scanner.type}...`)
|
||||
this.sacnnerMap.set(scanner.type, scanner)
|
||||
})
|
||||
let pluginLoaders = this.container.getAll<plugin.PluginLoader>(plugin.PluginLoader)
|
||||
pluginLoaders.forEach((loader) => {
|
||||
console.debug(`loading plugin loader ${loader.type}...`)
|
||||
this.loaderMap.set(loader.type, loader)
|
||||
})
|
||||
this.initialized = true
|
||||
}
|
||||
}
|
||||
|
||||
scan(folder: string): void {
|
||||
if (!folder) { throw new Error('plugin scan folder can\'t be empty!') }
|
||||
this.initialize()
|
||||
var plugin = fs.file(root, folder)
|
||||
var files = this.scanFolder(plugin)
|
||||
this.loadPlugins(files)
|
||||
for (const [, scanner] of this.sacnnerMap) {
|
||||
try {
|
||||
scanner.scan(folder).forEach(loadMetadata => {
|
||||
try {
|
||||
this.loadPlugin(scanner.load(loadMetadata))
|
||||
} catch (error) {
|
||||
console.error(`plugin scanner ${scanner.type} load ${loadMetadata.name} occurred error ${error}`)
|
||||
console.ex(error)
|
||||
}
|
||||
})
|
||||
} catch (error) {
|
||||
console.error(`plugin scanner ${scanner.type} occurred error ${error}`)
|
||||
console.ex(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
build(): void {
|
||||
this.buildPlugins()
|
||||
}
|
||||
|
||||
private logStage(plugin: interfaces.Plugin, stage: string) {
|
||||
private logStage(plugin: plugin.Plugin, stage: string) {
|
||||
console.i18n("ms.plugin.manager.stage", { stage, plugin: plugin.description.name, version: plugin.description.version, author: plugin.description.author })
|
||||
}
|
||||
|
||||
private runPluginStage(plugin: interfaces.Plugin, stage: string, ext: Function) {
|
||||
this.logStage(plugin, i18n.translate(`ms.plugin.manager.stage.${stage}`))
|
||||
ext()
|
||||
this.runCatch(plugin, stage)
|
||||
this.runCatch(plugin, `${this.serverType}${stage}`)
|
||||
this.execPluginStage(plugin, stage)
|
||||
private runPluginStage(plugin: plugin.Plugin, stage: string, ext: Function) {
|
||||
if (!plugin) { throw new Error(`can't run runPluginStage ${stage} because plugin is ${plugin}`) }
|
||||
try {
|
||||
this.logStage(plugin, i18n.translate(`ms.plugin.manager.stage.${stage}`))
|
||||
ext()
|
||||
this.runCatch(plugin, stage)
|
||||
this.runCatch(plugin, `${this.serverType}${stage}`)
|
||||
plugin.description.loadMetadata.loader[stage](plugin)
|
||||
} catch (ex) {
|
||||
console.i18n("ms.plugin.manager.stage.exec.error", { plugin: plugin.description.name, executor: stage, error: ex })
|
||||
}
|
||||
}
|
||||
|
||||
private loadPlugin(loadMetadata: plugin.PluginLoadMetadata) {
|
||||
try {
|
||||
for (const [, loader] of this.loaderMap) {
|
||||
if (loader.require(loadMetadata).loaded) {
|
||||
loadMetadata.loader = loader
|
||||
let metadata = loadMetadata.metadata
|
||||
this.metadataMap.set(metadata.name, metadata)
|
||||
metadata.loadMetadata = loadMetadata
|
||||
return metadata
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.i18n("ms.plugin.manager.initialize.error", { name: loadMetadata.file, ex: error })
|
||||
console.ex(error)
|
||||
}
|
||||
console.console(`§6scanner: §b${loadMetadata.scanner.type} §ccan\'t load §6file §b${loadMetadata.file}. §eskip!`)
|
||||
}
|
||||
|
||||
/**
|
||||
* 从文件加载插件
|
||||
* @param file java.io.File
|
||||
*/
|
||||
loadFromFile(file: string): interfaces.Plugin {
|
||||
let metadata = this.loadPlugin(file);
|
||||
let plugin = this.buildPlugin(metadata && metadata.description ? metadata.description : this.pluginMetadataMap.get(file.toString()))
|
||||
loadFromFile(file: string, scanner = this.sacnnerMap.get('file')): plugin.Plugin {
|
||||
if (!file) { throw new Error('plugin file can\'t be null!') }
|
||||
if (!scanner) { throw new Error('plugin scanner can\'t be null!') }
|
||||
let metadata = this.loadPlugin(scanner.read(file))
|
||||
let plugin = metadata.loadMetadata.loader.build(metadata)
|
||||
this.load(plugin)
|
||||
this.enable(plugin)
|
||||
return plugin;
|
||||
return plugin
|
||||
}
|
||||
|
||||
load(...args: any[]): void {
|
||||
this.checkAndGet(args[0]).forEach((plugin: interfaces.Plugin) => {
|
||||
this.checkAndGet(args[0]).forEach((plugin: plugin.Plugin) => {
|
||||
this.runPluginStage(plugin, 'load', () => {
|
||||
this.loadConfig(plugin)
|
||||
})
|
||||
@@ -85,7 +141,7 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
||||
}
|
||||
|
||||
enable(...args: any[]): void {
|
||||
this.checkAndGet(args[0]).forEach((plugin: interfaces.Plugin) => {
|
||||
this.checkAndGet(args[0]).forEach((plugin: plugin.Plugin) => {
|
||||
this.runPluginStage(plugin, 'enable', () => {
|
||||
this.registryCommand(plugin)
|
||||
this.registryListener(plugin)
|
||||
@@ -94,8 +150,9 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
||||
}
|
||||
|
||||
disable(...args: any[]): void {
|
||||
this.checkAndGet(args[0]).forEach((plugin: interfaces.Plugin) => {
|
||||
this.checkAndGet(args[0]).forEach((plugin: plugin.Plugin) => {
|
||||
this.runPluginStage(plugin, 'disable', () => {
|
||||
this.saveConfig(plugin)
|
||||
this.unregistryCommand(plugin)
|
||||
this.unregistryListener(plugin)
|
||||
})
|
||||
@@ -103,14 +160,18 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
||||
}
|
||||
|
||||
reload(...args: any[]): void {
|
||||
this.checkAndGet(args[0]).forEach((pl: interfaces.Plugin) => {
|
||||
this.checkAndGet(args[0]).forEach((pl: plugin.Plugin) => {
|
||||
this.disable(pl)
|
||||
this.loadFromFile(pl.description.source)
|
||||
this.loadFromFile(pl.description.source, pl.description.loadMetadata.scanner)
|
||||
})
|
||||
}
|
||||
|
||||
getPlugin(name: string) {
|
||||
return this.instanceMap.get(name)
|
||||
}
|
||||
|
||||
getPlugins() {
|
||||
return this.pluginInstanceMap
|
||||
return this.instanceMap
|
||||
}
|
||||
|
||||
private runCatch(pl: any, func: string) {
|
||||
@@ -122,65 +183,14 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
||||
}
|
||||
}
|
||||
|
||||
private checkAndGet(name: string | interfaces.Plugin | undefined | any): Map<string, interfaces.Plugin> | interfaces.Plugin[] {
|
||||
if (name == this.pluginInstanceMap) { return this.pluginInstanceMap }
|
||||
if (typeof name == 'string' && this.pluginInstanceMap.has(name)) { return [this.pluginInstanceMap.get(name)] }
|
||||
if (name instanceof interfaces.Plugin) { return [name as interfaces.Plugin] }
|
||||
if (name.description || name.description.name) { return [name as interfaces.Plugin] }
|
||||
private checkAndGet(name: string | plugin.Plugin | undefined | any): Map<string, plugin.Plugin> | plugin.Plugin[] {
|
||||
if (name == this.instanceMap) { return this.instanceMap }
|
||||
if (typeof name == 'string' && this.instanceMap.has(name)) { return [this.instanceMap.get(name)] }
|
||||
if (name instanceof interfaces.Plugin) { return [name as plugin.Plugin] }
|
||||
if (name.description || name.description.name) { return [name as plugin.Plugin] }
|
||||
throw new Error(`Plugin ${JSON.stringify(name)} not exist!`)
|
||||
}
|
||||
|
||||
private scanFolder(folder: any): string[] {
|
||||
var files = []
|
||||
console.i18n('ms.plugin.manager.scan', { folder })
|
||||
this.checkUpdateFolder(folder)
|
||||
// must check file is exist maybe is a illegal symbolic link file
|
||||
fs.list(folder).forEach((file: any) => file.toFile().exists() ? files.push(file.toFile()) : void 0)
|
||||
return files
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新插件
|
||||
* @param path
|
||||
*/
|
||||
private checkUpdateFolder(path: any) {
|
||||
var update = fs.file(path, "update")
|
||||
if (!update.exists()) {
|
||||
update.mkdirs()
|
||||
}
|
||||
}
|
||||
|
||||
private loadPlugins(files: any[]): void {
|
||||
this.loadJsPlugins(files)
|
||||
}
|
||||
|
||||
/**
|
||||
* JS类型插件预加载
|
||||
*/
|
||||
private loadJsPlugins(files: any[]) {
|
||||
files.filter(file => file.name.endsWith(".js")).forEach(file => {
|
||||
try {
|
||||
this.loadPlugin(file)
|
||||
} catch (ex) {
|
||||
console.i18n("ms.plugin.manager.initialize.error", { name: file.name, ex })
|
||||
console.ex(ex)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private loadPlugin(file: any) {
|
||||
this.updatePlugin(file)
|
||||
return this.createPlugin(file.toString())
|
||||
}
|
||||
|
||||
private updatePlugin(file: any) {
|
||||
var update = fs.file(fs.file(file.parentFile, 'update'), file.name)
|
||||
if (update.exists()) {
|
||||
console.i18n("ms.plugin.manager.build.update", { name: file.name })
|
||||
fs.move(update, file, true)
|
||||
}
|
||||
}
|
||||
|
||||
private allowProcess(servers: string[]) {
|
||||
// Not set servers -> allow
|
||||
if (!servers || !servers.length) return true
|
||||
@@ -194,77 +204,59 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
||||
}
|
||||
}
|
||||
|
||||
private createPlugin(file: string) {
|
||||
//@ts-ignore
|
||||
let instance = require(file, { cache: false })
|
||||
this.pluginRequireMap.set(file, instance);
|
||||
return instance;
|
||||
}
|
||||
|
||||
private buildPlugins() {
|
||||
let metadatas = [];
|
||||
let pluginMetadatas = getPluginMetadatas()
|
||||
for (const [_, metadata] of pluginMetadatas) { metadatas.push(metadata); }
|
||||
for (const [_, instance] of this.pluginRequireMap) { if (instance.description) { this.buildPlugin(instance.description) } }
|
||||
for (const metadata of metadatas) {
|
||||
if (!this.allowProcess(metadata.servers)) { continue }
|
||||
this.buildPlugin(metadata)
|
||||
}
|
||||
}
|
||||
|
||||
private buildPlugin(metadata: interfaces.PluginMetadata) {
|
||||
let pluginInstance: interfaces.Plugin;
|
||||
switch (metadata.type) {
|
||||
case "ioc":
|
||||
try {
|
||||
this.bindPlugin(metadata)
|
||||
pluginInstance = this.container.getNamed<interfaces.Plugin>(plugin.Plugin, metadata.name)
|
||||
if (!(pluginInstance instanceof interfaces.Plugin)) {
|
||||
console.i18n('ms.plugin.manager.build.not.extends', { source: metadata.source })
|
||||
return
|
||||
}
|
||||
} catch (ex) {
|
||||
console.i18n("ms.plugin.manager.initialize.error", { name: metadata.name, ex })
|
||||
console.ex(ex)
|
||||
}
|
||||
break;
|
||||
case "basic":
|
||||
pluginInstance = this.pluginRequireMap.get(metadata.source.toString())
|
||||
break;
|
||||
default:
|
||||
throw new Error('§4不支持的插件类型 请检查加载器是否正常启用!')
|
||||
}
|
||||
this.pluginInstanceMap.set(metadata.name, pluginInstance)
|
||||
return pluginInstance;
|
||||
}
|
||||
|
||||
private bindPlugin(metadata: interfaces.PluginMetadata) {
|
||||
try {
|
||||
let pluginInstance = this.container.getNamed<interfaces.Plugin>(plugin.Plugin, metadata.name)
|
||||
if (pluginInstance.description.source + '' !== metadata.source + '') {
|
||||
console.i18n('ms.plugin.manager.build.duplicate', { exists: pluginInstance.description.source, source: metadata.source })
|
||||
for (const [, metadata] of this.metadataMap) {
|
||||
let pluginInstance: plugin.Plugin
|
||||
if (!this.loaderMap.has(metadata.type)) {
|
||||
console.error(`§4无法加载插件 §c${metadata.name} §4请检查 §c${metadata.type} §4加载器是否正常启用!`)
|
||||
continue
|
||||
}
|
||||
this.container.rebind(plugin.Plugin).to(metadata.target).inSingletonScope().whenTargetNamed(metadata.name)
|
||||
} catch{
|
||||
this.container.bind(plugin.Plugin).to(metadata.target).inSingletonScope().whenTargetNamed(metadata.name)
|
||||
pluginInstance = this.loaderMap.get(metadata.type).build(metadata)
|
||||
if (!pluginInstance) { console.error(`§4加载器 §c${metadata.type} §4加载插件 §c${metadata.name} §4失败!`); continue }
|
||||
this.instanceMap.set(metadata.name, pluginInstance)
|
||||
}
|
||||
}
|
||||
|
||||
private loadConfig(plugin: interfaces.Plugin) {
|
||||
let configs = getPluginConfigMetadata(plugin);
|
||||
private loadConfig(plugin: plugin.Plugin) {
|
||||
let configs = getPluginConfigMetadata(plugin)
|
||||
for (let [_, config] of configs) {
|
||||
let configFile = fs.concat(root, this.pluginFolder, plugin.description.name, config.name + '.' + config.format)
|
||||
let configFactory = getConfigLoader(config.format);
|
||||
if (!fs.exists(configFile)) {
|
||||
base.save(configFile, configFactory.dump(plugin[config.variable]))
|
||||
console.i18n("ms.plugin.manager.config.save.default", { plugin: plugin.description.name, name: config.name, format: config.format })
|
||||
} else {
|
||||
plugin[config.variable] = configFactory.load(base.read(configFile));
|
||||
try {
|
||||
let configFile = fs.concat(root, this.pluginFolder, plugin.description.name, config.name + '.' + config.format)
|
||||
let configFactory = getConfigLoader(config.format)
|
||||
if (!fs.exists(configFile)) {
|
||||
base.save(configFile, configFactory.dump(plugin[config.variable]))
|
||||
console.i18n("ms.plugin.manager.config.save.default", { plugin: plugin.description.name, name: config.name, format: config.format })
|
||||
} else {
|
||||
plugin[config.variable] = configFactory.load(base.read(configFile))
|
||||
plugin[config.variable].save = () => {
|
||||
let result = configFactory.dump(plugin[config.variable])
|
||||
base.save(configFile, result)
|
||||
console.debug(`[${plugin.description.name}] Save Config ${config.variable} to file ${configFile} result ${result}`)
|
||||
}
|
||||
console.debug(`[${plugin.description.name}] Load Config ${config.variable} from file ${configFile} result ${JSON.stringify(plugin[config.variable])}`)
|
||||
}
|
||||
} catch (error) {
|
||||
console.i18n("ms.plugin.manager.config.load.error", { plugin: plugin.description.name, name: config.name, format: config.format, error })
|
||||
console.ex(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private registryCommand(pluginInstance: interfaces.Plugin) {
|
||||
private saveConfig(plugin: plugin.Plugin) {
|
||||
let configs = getPluginConfigMetadata(plugin)
|
||||
for (let [_, config] of configs) {
|
||||
try {
|
||||
let configFile = fs.concat(root, this.pluginFolder, plugin.description.name, config.name + '.' + config.format)
|
||||
let configFactory = getConfigLoader(config.format)
|
||||
if (!config.readonly) { base.save(configFile, configFactory.dump(plugin[config.variable])) }
|
||||
} catch (error) {
|
||||
console.i18n("ms.plugin.manager.config.save.error", { plugin: plugin.description.name, name: config.name, format: config.format, error })
|
||||
console.ex(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private registryCommand(pluginInstance: plugin.Plugin) {
|
||||
let cmds = getPluginCommandMetadata(pluginInstance)
|
||||
let tabs = getPluginTabCompleterMetadata(pluginInstance)
|
||||
for (const [_, cmd] of cmds) {
|
||||
@@ -277,7 +269,7 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
||||
}
|
||||
}
|
||||
|
||||
private registryListener(pluginInstance: interfaces.Plugin) {
|
||||
private registryListener(pluginInstance: plugin.Plugin) {
|
||||
let events = getPluginListenerMetadata(pluginInstance)
|
||||
for (const event of events) {
|
||||
// ignore space listener
|
||||
@@ -287,28 +279,14 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
||||
}
|
||||
}
|
||||
|
||||
private unregistryCommand(pluginInstance: interfaces.Plugin) {
|
||||
private unregistryCommand(pluginInstance: plugin.Plugin) {
|
||||
let cmds = getPluginCommandMetadata(pluginInstance)
|
||||
cmds.forEach(cmd => {
|
||||
this.CommandManager.off(pluginInstance, cmd.name)
|
||||
})
|
||||
}
|
||||
|
||||
private unregistryListener(pluginInstance: interfaces.Plugin) {
|
||||
private unregistryListener(pluginInstance: plugin.Plugin) {
|
||||
this.EventManager.disable(pluginInstance)
|
||||
}
|
||||
|
||||
private execPluginStage(pluginInstance: interfaces.Plugin, stageName: string) {
|
||||
let stages = getPluginStageMetadata(pluginInstance, stageName);
|
||||
for (const stage of stages) {
|
||||
if (!this.allowProcess(stage.servers)) { continue }
|
||||
console.i18n("ms.plugin.manager.stage.exec", { plugin: pluginInstance.description.name, name: stage.executor, stage: stageName, servers: stage.servers })
|
||||
try {
|
||||
pluginInstance[stage.executor].apply(pluginInstance)
|
||||
} catch (error) {
|
||||
console.i18n("ms.plugin.manager.stage.exec.error", { plugin: pluginInstance.description.name, executor: stage.executor, error })
|
||||
console.ex(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
54
packages/plugin/src/scanner/file-scanner.ts
Normal file
54
packages/plugin/src/scanner/file-scanner.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import { plugin } from "@ccms/api"
|
||||
import * as fs from '@ccms/common/dist/fs'
|
||||
import { provideSingletonNamed } from "@ccms/container"
|
||||
|
||||
@provideSingletonNamed(plugin.PluginScanner, 'file')
|
||||
export class JSFileScanner implements plugin.PluginScanner {
|
||||
type: string = 'file'
|
||||
|
||||
scan(target: any): plugin.PluginLoadMetadata[] {
|
||||
return this.scanFolder(fs.concat(root, target)).map((file) => this.read(file))
|
||||
}
|
||||
|
||||
read(file: any): plugin.PluginLoadMetadata {
|
||||
return { file, type: this.type, scanner: this, loaded: false }
|
||||
}
|
||||
|
||||
load(metadata: plugin.PluginLoadMetadata): plugin.PluginLoadMetadata {
|
||||
if (metadata.type !== this.type) { return }
|
||||
this.updatePlugin(metadata.file)
|
||||
//@ts-ignore
|
||||
metadata.instance = require(metadata.file.toString(), { cache: false })
|
||||
return metadata
|
||||
}
|
||||
|
||||
private scanFolder(folder: any): string[] {
|
||||
var files = []
|
||||
console.i18n('ms.plugin.manager.scan', { folder })
|
||||
this.checkUpdateFolder(folder)
|
||||
// must check file is exist maybe is a illegal symbolic link file
|
||||
fs.list(folder).forEach((path: any) => {
|
||||
let file = path.toFile()
|
||||
if (file.exists() && file.getName().endsWith(".js")) {
|
||||
files.push(file)
|
||||
}
|
||||
})
|
||||
return files
|
||||
}
|
||||
|
||||
private checkUpdateFolder(path: any) {
|
||||
var update = fs.file(path, "update")
|
||||
if (!update.exists()) {
|
||||
update.mkdirs()
|
||||
}
|
||||
}
|
||||
|
||||
private updatePlugin(file: any) {
|
||||
var update = fs.file(fs.file(file.parentFile, 'update'), file.name)
|
||||
if (update.exists()) {
|
||||
console.i18n("ms.plugin.manager.build.update", { name: file.name })
|
||||
fs.move(update, file, true)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,78 +1,79 @@
|
||||
import { plugin } from '@ccms/api'
|
||||
import { interfaces } from './interfaces'
|
||||
import { METADATA_KEY } from './constants'
|
||||
|
||||
const pluginSourceCache = new Map<string, interfaces.PluginMetadata>();
|
||||
const pluginSourceCache = new Map<string, plugin.PluginMetadata>()
|
||||
|
||||
function getPlugins() {
|
||||
return [...getPluginMetadatas().values()].map((target) => target.target);
|
||||
return [...getPluginMetadatas().values()].map((target) => target.target)
|
||||
}
|
||||
|
||||
function getPlugin(name: string) {
|
||||
return getPluginMetadatas().get(name);
|
||||
return getPluginMetadatas().get(name)
|
||||
}
|
||||
|
||||
function getPluginSources() {
|
||||
let pluginSources: Map<string, interfaces.PluginMetadata> = Reflect.getMetadata(
|
||||
let pluginSources: Map<string, plugin.PluginMetadata> = Reflect.getMetadata(
|
||||
METADATA_KEY.souece,
|
||||
Reflect
|
||||
) || pluginSourceCache;
|
||||
return pluginSources;
|
||||
) || pluginSourceCache
|
||||
return pluginSources
|
||||
}
|
||||
|
||||
function getPluginMetadatas() {
|
||||
let pluginMetadatas: Map<string, interfaces.PluginMetadata> = Reflect.getMetadata(
|
||||
let pluginMetadatas: Map<string, plugin.PluginMetadata> = Reflect.getMetadata(
|
||||
METADATA_KEY.plugin,
|
||||
Reflect
|
||||
) || new Map<string, interfaces.PluginMetadata>();
|
||||
return pluginMetadatas;
|
||||
) || new Map<string, plugin.PluginMetadata>()
|
||||
return pluginMetadatas
|
||||
}
|
||||
|
||||
function getPluginMetadata(target: any) {
|
||||
let pluginMetadata: interfaces.PluginMetadata = Reflect.getMetadata(
|
||||
let pluginMetadata: plugin.PluginMetadata = Reflect.getMetadata(
|
||||
METADATA_KEY.plugin,
|
||||
target.constructor
|
||||
) || {};
|
||||
return pluginMetadata;
|
||||
) || {}
|
||||
return pluginMetadata
|
||||
}
|
||||
|
||||
function getPluginCommandMetadata(target: any) {
|
||||
let commandMetadata: Map<string, interfaces.CommandMetadata> = Reflect.getMetadata(
|
||||
METADATA_KEY.cmd,
|
||||
target.constructor
|
||||
) || new Map<string, interfaces.CommandMetadata>();
|
||||
return commandMetadata;
|
||||
) || new Map<string, interfaces.CommandMetadata>()
|
||||
return commandMetadata
|
||||
}
|
||||
|
||||
function getPluginTabCompleterMetadata(target: any) {
|
||||
let tabcompleterMetadata: Map<string, interfaces.CommandMetadata> = Reflect.getMetadata(
|
||||
METADATA_KEY.tab,
|
||||
target.constructor
|
||||
) || new Map<string, interfaces.CommandMetadata>();
|
||||
return tabcompleterMetadata;
|
||||
) || new Map<string, interfaces.CommandMetadata>()
|
||||
return tabcompleterMetadata
|
||||
}
|
||||
|
||||
function getPluginListenerMetadata(target: any) {
|
||||
let listnerMetadata: interfaces.ListenerMetadata[] = Reflect.getMetadata(
|
||||
METADATA_KEY.listener,
|
||||
target.constructor
|
||||
) || [];
|
||||
return listnerMetadata;
|
||||
) || []
|
||||
return listnerMetadata
|
||||
}
|
||||
|
||||
function getPluginConfigMetadata(target: any) {
|
||||
let configMetadata: Map<string, interfaces.ConfigMetadata> = Reflect.getMetadata(
|
||||
METADATA_KEY.config,
|
||||
target.constructor
|
||||
) || new Map<string, interfaces.ConfigMetadata>();
|
||||
return configMetadata;
|
||||
) || new Map<string, interfaces.ConfigMetadata>()
|
||||
return configMetadata
|
||||
}
|
||||
|
||||
function getPluginStageMetadata(target: any, stage: string) {
|
||||
let stageMetadata: interfaces.ExecMetadata[] = Reflect.getMetadata(
|
||||
METADATA_KEY.stage[stage],
|
||||
target.constructor
|
||||
) || [];
|
||||
return stageMetadata;
|
||||
) || []
|
||||
return stageMetadata
|
||||
}
|
||||
|
||||
export {
|
||||
|
||||
1
packages/plugins/.npmignore
Symbolic link
1
packages/plugins/.npmignore
Symbolic link
@@ -0,0 +1 @@
|
||||
../../.npmignore
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user