Compare commits
16 Commits
backup
...
v0.28.0-be
| Author | SHA1 | Date | |
|---|---|---|---|
| 9a25362140 | |||
| 54eaae96bd | |||
| 5bf4b1c09e | |||
| 54bea62735 | |||
| 0e4ae5d74f | |||
| bdad4136ec | |||
| a0866c1085 | |||
| afd3f91a3f | |||
| e70c78a255 | |||
| 9cfac1672a | |||
| 9126ec8035 | |||
| 23bc6068b5 | |||
| 27b428fbe2 | |||
| c07f1131c4 | |||
| 002f2c47c6 | |||
| 8633d9ea95 |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -1,3 +1,4 @@
|
||||
.yarn*
|
||||
.vscode
|
||||
.theia
|
||||
node_modules
|
||||
|
||||
47
README.MD
47
README.MD
@@ -8,27 +8,28 @@
|
||||
|
||||
```txt
|
||||
└─packages
|
||||
├─api 全平台兼容的接口
|
||||
├─core 核心代码 用于引导加载
|
||||
├─common 公共类库代码 例如 http reflect 模块
|
||||
├─client NodeJS的Minecraft客户端 用于调试插件
|
||||
├─container IOC容器 用于注入具体实现
|
||||
├─ployfill Nashorn 的一些自定义增强
|
||||
├─nashorn Nashorn 的类型定义
|
||||
├─bungee BungeeCordAPI内部实现
|
||||
├─bukkit BukkitAPI内部实现
|
||||
├─sponge SpongeAPI内部实现
|
||||
├─nukkit NukkitAPI内部实现
|
||||
├─plugin 插件管理器
|
||||
├─websocket Netty的WebSocket注入
|
||||
├─type Java的类型定义
|
||||
| ├─bungee BungeeCord类型定义
|
||||
| ├─bukkit Bukkit类型定义
|
||||
| ├─sponge Sponge类型定义
|
||||
| └─nukkit Nukkit类型定义
|
||||
└─plugins 这里当然是插件啦
|
||||
├─bungee 只兼容BungeeCord的插件
|
||||
├─bukkit 只兼容Bukkit的插件
|
||||
├─sponge 只兼容Sponge的插件
|
||||
└─nukkit 只兼容Nukkit的插件
|
||||
├─api 全平台兼容的接口
|
||||
├─core 核心代码 用于引导加载
|
||||
├─common 公共类库代码 例如 http reflect 模块
|
||||
├─compile 编译器相关功能
|
||||
├─client NodeJS 的 Minecraft 客户端 已迁移至 ms-client
|
||||
├─container IOC容器 用于注入具体实现
|
||||
├─database 数据库相关功能
|
||||
├─protocol 协议处理相关功能
|
||||
├─service 服务相关功能
|
||||
├─i18n 多语言环境相关支持
|
||||
├─polyfill Nashorn 的一些自定义增强
|
||||
├─nashorn Nashorn 的类型定义
|
||||
├─nodejs NodeJS 的部分 Java 实现
|
||||
├─bungee BungeeCordAPI 内部实现
|
||||
├─bukkit BukkitAPI 内部实现
|
||||
├─sponge SpongeAPI 内部实现
|
||||
├─nukkit NukkitAPI 内部实现
|
||||
├─molang MoLang 解析库
|
||||
├─qrcode 二维码相关类库
|
||||
├─plugin 插件管理器
|
||||
├─websocket WebSocket 相关实现
|
||||
| ├─client 基于 Netty 的 WebSocket 客户端
|
||||
| └─server 基于 Netty 的 WebSocket 服务端
|
||||
└─type 类型定义 已迁移到 @javatypes
|
||||
```
|
||||
|
||||
25
lerna.json
25
lerna.json
@@ -1,16 +1,15 @@
|
||||
{
|
||||
"version": "0.26.0",
|
||||
"useWorkspaces": true,
|
||||
"npmClient": "yarn",
|
||||
"packages": [
|
||||
"packages/*"
|
||||
],
|
||||
"command": {
|
||||
"run": {
|
||||
"stream": true
|
||||
}
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
"version": "0.28.0-beta.4",
|
||||
"npmClient": "pnpm",
|
||||
"packages": [
|
||||
"packages/*"
|
||||
],
|
||||
"command": {
|
||||
"run": {
|
||||
"stream": true
|
||||
}
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
}
|
||||
}
|
||||
|
||||
20
package.json
20
package.json
@@ -10,18 +10,26 @@
|
||||
"clean": "lerna run clean",
|
||||
"watch": "lerna run watch --parallel",
|
||||
"build": "lerna run build",
|
||||
"ug": "yarn upgrade-interactive --latest",
|
||||
"ug": "pnpm up -r -i",
|
||||
"np": "./script/push.sh",
|
||||
"lsp": "npm login -scope=@ccms",
|
||||
"lp": "lerna publish --verify-access --force-publish",
|
||||
"lpb": "lerna publish --preid beta --dist-tag beta --verify-access --force-publish",
|
||||
"lpc": "lerna publish --canary --preid beta --pre-dist-tag beta --verify-access --force-publish",
|
||||
"lpf": "lerna publish from-package --yes"
|
||||
"lp": "lerna publish --force-publish",
|
||||
"lpb": "lerna publish --preid beta --dist-tag beta --force-publish",
|
||||
"lpc": "lerna publish --canary --preid beta --pre-dist-tag beta --force-publish",
|
||||
"lpf": "lerna publish from-package --yes",
|
||||
"sync": "./script/sync.sh"
|
||||
},
|
||||
"workspaces": [
|
||||
"packages/*"
|
||||
],
|
||||
"devDependencies": {
|
||||
"lerna": "^6.4.1"
|
||||
"lerna": "^7.2.0",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^5.0.5",
|
||||
"typescript": "^5.2.2",
|
||||
"tslib": "^2.6.2",
|
||||
"@types/node": "^20.8.8",
|
||||
"@ccms/nashorn": "^0.28.0-beta.3",
|
||||
"@javatypes/jdk": "^0.0.3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
../../.npmignore
|
||||
@@ -1,35 +0,0 @@
|
||||
{
|
||||
"name": "@ccms/amqp",
|
||||
"version": "0.26.0",
|
||||
"description": "MiaoScript amqp package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
"minecraft",
|
||||
"bukkit",
|
||||
"sponge"
|
||||
],
|
||||
"author": "MiaoWoo <admin@yumc.pw>",
|
||||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.26.0",
|
||||
"@ccms/common": "^0.26.0",
|
||||
"@ccms/container": "^0.26.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.26.0",
|
||||
"@javatypes/amqp-client": "^0.0.3",
|
||||
"@javatypes/spring-amqp": "^0.0.3",
|
||||
"@javatypes/spring-rabbit": "^0.0.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^4.1.2",
|
||||
"typescript": "^4.9.5"
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
import { ConnectionFactoryAdapter } from "./connection"
|
||||
import { RabbitTemplateAdapter } from "./template"
|
||||
import { JSClass } from "@ccms/container"
|
||||
|
||||
export const RabbitAdmin = Java.type('org.springframework.amqp.rabbit.core.RabbitAdmin')
|
||||
|
||||
export class RabbitAdminAdapter {
|
||||
@JSClass('org.springframework.amqp.rabbit.core.RabbitAdmin')
|
||||
private RabbitAdmin: org.springframework.amqp.rabbit.core.RabbitAdmin
|
||||
private _Handler: org.springframework.amqp.rabbit.core.RabbitAdmin
|
||||
constructor(config: RabbitTemplateAdapter | org.springframework.amqp.rabbit.core.RabbitTemplate | ConnectionFactoryAdapter | org.springframework.amqp.rabbit.connection.ConnectionFactory) {
|
||||
this._Handler = new RabbitAdmin((config instanceof RabbitTemplateAdapter || config instanceof ConnectionFactoryAdapter) ? config.getHandler() : config)
|
||||
}
|
||||
getHandler(): org.springframework.amqp.rabbit.core.RabbitAdmin {
|
||||
return this._Handler
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
export const ConfirmCallback = Java.type('org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback')
|
||||
export const ReturnCallback = Java.type('org.springframework.amqp.rabbit.core.RabbitTemplate.ReturnCallback')
|
||||
|
||||
export abstract class ConfirmCallbackAdapter {
|
||||
private _Handler: org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback
|
||||
constructor() {
|
||||
let ConfirmCallbackImpl = Java.extend(ReturnCallback, {
|
||||
confirm: (correlationData: org.springframework.amqp.rabbit.connection.CorrelationData, ack: boolean, cause: string) => this.confirm(correlationData, ack, cause)
|
||||
})
|
||||
this._Handler = new ConfirmCallbackImpl()
|
||||
}
|
||||
abstract confirm(correlationData: org.springframework.amqp.rabbit.connection.CorrelationData, ack: boolean, cause: string)
|
||||
getHandler() {
|
||||
return this._Handler
|
||||
}
|
||||
}
|
||||
|
||||
export abstract class ReturnCallbackAdapter {
|
||||
private _Handler: org.springframework.amqp.rabbit.core.RabbitTemplate.ReturnCallback
|
||||
constructor() {
|
||||
let ReturnCallbackImpl = Java.extend(ReturnCallback, {
|
||||
returnedMessage: (message: org.springframework.amqp.core.Message, replyCode: number, replyText: string, exchange: string, routingKey: string) => this.returnedMessage(message, replyCode, replyText, exchange, routingKey)
|
||||
})
|
||||
this._Handler = new ReturnCallbackImpl()
|
||||
}
|
||||
abstract returnedMessage(message: org.springframework.amqp.core.Message, replyCode: number, replyText: string, exchange: string, routingKey: string)
|
||||
getHandler() {
|
||||
return this._Handler
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
import threadPool from '@ccms/common/dist/thread-pool'
|
||||
|
||||
export const ConnectionFactory = Java.type('org.springframework.amqp.rabbit.connection.ConnectionFactory')
|
||||
const CachingConnectionFactory = Java.type('org.springframework.amqp.rabbit.connection.CachingConnectionFactory')
|
||||
interface ConnectionConfig {
|
||||
url: string,
|
||||
username?: string,
|
||||
password?: string,
|
||||
publisherConfirms?: boolean
|
||||
cacheSize?: number
|
||||
}
|
||||
|
||||
export class ConnectionFactoryAdapter {
|
||||
private _Handler: org.springframework.amqp.rabbit.connection.CachingConnectionFactory
|
||||
|
||||
constructor(config: ConnectionConfig) {
|
||||
if (!config.url) { throw new Error('Connection UrI Can\'t be undefiend!') }
|
||||
config = { publisherConfirms: true, cacheSize: 50, ...config }
|
||||
this._Handler = new CachingConnectionFactory(new java.net.URI(config.url))
|
||||
config.username && this._Handler.setUsername(config.username)
|
||||
config.password && this._Handler.setPassword(config.password)
|
||||
this._Handler.setPublisherConfirms(config.publisherConfirms)
|
||||
this._Handler.setExecutor(threadPool.create({
|
||||
groupName: '@ccms/amqp-rabbit'
|
||||
}))
|
||||
this._Handler.setChannelCacheSize(config.cacheSize)
|
||||
}
|
||||
getHandler() {
|
||||
return this._Handler
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
import { ConnectionFactoryAdapter, ConnectionFactory } from "./connection"
|
||||
import { ChannelAwareMessageListenerAdapter, ChannelAwareMessageListener } from "./listener"
|
||||
|
||||
export const SimpleMessageListenerContainer = org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer
|
||||
export const AcknowledgeMode = org.springframework.amqp.core.AcknowledgeMode
|
||||
interface ContainerConfig {
|
||||
connectionFactory: ConnectionFactoryAdapter | typeof ConnectionFactory
|
||||
queueNames: string[]
|
||||
messageListener: ChannelAwareMessageListenerAdapter | typeof ChannelAwareMessageListener
|
||||
maxConcurrentConsumers?: number
|
||||
concurrentConsumers?: number
|
||||
acknowledgeMode?: org.springframework.amqp.core.AcknowledgeMode
|
||||
}
|
||||
|
||||
export class MessageListenerContainerAdapter {
|
||||
private _Handler: org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer
|
||||
constructor(config: ContainerConfig) {
|
||||
config = { concurrentConsumers: 5, maxConcurrentConsumers: 10, acknowledgeMode: AcknowledgeMode.AUTO, ...config }
|
||||
this._Handler = new SimpleMessageListenerContainer(config.connectionFactory instanceof ConnectionFactoryAdapter ? config.connectionFactory.getHandler() : config.connectionFactory)
|
||||
//@ts-ignore
|
||||
this._Handler.setQueueNames(config.queueNames)
|
||||
this._Handler.setMaxConcurrentConsumers(config.maxConcurrentConsumers)
|
||||
this._Handler.setConcurrentConsumers(config.concurrentConsumers)
|
||||
this._Handler.setAcknowledgeMode(config.acknowledgeMode)
|
||||
this._Handler.setMessageListener(config.messageListener instanceof ChannelAwareMessageListenerAdapter ? config.messageListener.getHandler() : config.messageListener)
|
||||
}
|
||||
getHandler() {
|
||||
return this._Handler
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
const JavaString = Java.type('java.lang.String')
|
||||
const MessageProperties = org.springframework.amqp.core.MessageProperties
|
||||
const Message = org.springframework.amqp.core.Message
|
||||
|
||||
export const MessageConverter = Java.type('org.springframework.amqp.support.converter.MessageConverter')
|
||||
|
||||
export class MessageConverterAdapter {
|
||||
private _Handler: org.springframework.amqp.support.converter.MessageConverter
|
||||
constructor() {
|
||||
var MessageConverterImpl = Java.extend(MessageConverter, {
|
||||
toMessage: (object: any, messageProperties: org.springframework.amqp.core.MessageProperties) => this.toMessage(object, messageProperties),
|
||||
fromMessage: (message: org.springframework.amqp.core.Message) => this.fromMessage(message)
|
||||
})
|
||||
this._Handler = new MessageConverterImpl()
|
||||
}
|
||||
toMessage(object: any, messageProperties: org.springframework.amqp.core.MessageProperties) {
|
||||
if (typeof object == "string") {
|
||||
messageProperties.setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN)
|
||||
return new Message(new JavaString(object).getBytes(), messageProperties)
|
||||
} else {
|
||||
messageProperties.setContentType(MessageProperties.CONTENT_TYPE_JSON)
|
||||
return new Message(new JavaString(JSON.stringify(object)).getBytes(), messageProperties)
|
||||
}
|
||||
}
|
||||
fromMessage(message: org.springframework.amqp.core.Message) {
|
||||
if (message.getMessageProperties().getContentType() == MessageProperties.CONTENT_TYPE_TEXT_PLAIN) {
|
||||
return new JavaString(message.getBody(), message.getMessageProperties().getContentEncoding())
|
||||
}
|
||||
if (message.getMessageProperties().getContentType() == MessageProperties.CONTENT_TYPE_JSON) {
|
||||
return JSON.parse(new JavaString(message.getBody(), message.getMessageProperties().getContentEncoding()))
|
||||
}
|
||||
return message
|
||||
}
|
||||
getHandler() {
|
||||
return this._Handler
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
export * from './admin'
|
||||
export * from './callback'
|
||||
export * from './connection'
|
||||
export * from './container'
|
||||
export * from './converter'
|
||||
export * from './listener'
|
||||
export * from './template'
|
||||
@@ -1,49 +0,0 @@
|
||||
const JavaString = Java.type('java.lang.String')
|
||||
export const MessageProperties = org.springframework.amqp.core.MessageProperties
|
||||
export const ChannelAwareMessageListener = Java.type('org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener')
|
||||
export const AmqpRejectAndDontRequeueException = org.springframework.amqp.AmqpRejectAndDontRequeueException
|
||||
export const Channel: com.rabbitmq.client.Channel = Java.type('com.rabbitmq.client.Channel')
|
||||
export const Message = org.springframework.amqp.core.Message
|
||||
export type MessageHandler<T> = (content: T, message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel) => any
|
||||
export abstract class ChannelAwareMessageListenerAdapter<T = any> {
|
||||
private _Handler: org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener
|
||||
constructor(manual: boolean = false) {
|
||||
let ChannelAwareMessageListenerImpl = Java.extend(ChannelAwareMessageListener, {
|
||||
onMessage: (message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel) => {
|
||||
let content = new JavaString(message.getBody(), message.getMessageProperties().getContentEncoding() || "UTF-8")
|
||||
try {
|
||||
if (message.getMessageProperties().getContentType() == MessageProperties.CONTENT_TYPE_JSON) {
|
||||
content = JSON.parse(content)
|
||||
}
|
||||
} catch (error: any) {
|
||||
if (manual) {
|
||||
channel.basicReject(message.getMessageProperties().getDeliveryTag(), true)
|
||||
} else {
|
||||
throw new AmqpRejectAndDontRequeueException(`${error}`, error)
|
||||
}
|
||||
}
|
||||
manual ? this.manualOnMessage(content, message, channel) : this.onMessage(content, message, channel)
|
||||
}
|
||||
})
|
||||
this._Handler = new ChannelAwareMessageListenerImpl()
|
||||
}
|
||||
abstract onMessage(content: T, message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel): any
|
||||
onError(error: Error, message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel): any { }
|
||||
getHandler() {
|
||||
return this._Handler
|
||||
}
|
||||
private manualOnMessage(content: T, message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel) {
|
||||
let deliveryTag = message.getMessageProperties().getDeliveryTag()
|
||||
try {
|
||||
if (this.onMessage(content, message, channel)) {
|
||||
channel.basicAck(deliveryTag, false)
|
||||
} else if (message.getMessageProperties().getRedelivered()) {
|
||||
channel.basicReject(deliveryTag, true)
|
||||
} else {
|
||||
channel.basicNack(deliveryTag, false, true)
|
||||
}
|
||||
} catch (error: any) {
|
||||
channel.basicReject(deliveryTag, this.onError(error, message, channel))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
import { MessageConverterAdapter } from "./converter"
|
||||
import { ConnectionFactoryAdapter } from "./connection"
|
||||
import { ConfirmCallbackAdapter, ReturnCallbackAdapter } from "./callback"
|
||||
|
||||
export const RabbitTemplate = Java.type('org.springframework.amqp.rabbit.core.RabbitTemplate')
|
||||
|
||||
interface TemplateConfig {
|
||||
connectionFactory: ConnectionFactoryAdapter | org.springframework.amqp.rabbit.connection.ConnectionFactory
|
||||
confirmCallback?: ConfirmCallbackAdapter
|
||||
returnCallback?: ReturnCallbackAdapter
|
||||
messageConverter?: MessageConverterAdapter
|
||||
}
|
||||
export class RabbitTemplateAdapter {
|
||||
private _Handler: org.springframework.amqp.rabbit.core.RabbitTemplate
|
||||
constructor(config: TemplateConfig) {
|
||||
config = { messageConverter: new MessageConverterAdapter(), ...config }
|
||||
console.debug(JSON.stringify(config))
|
||||
this._Handler = new RabbitTemplate(config.connectionFactory instanceof ConnectionFactoryAdapter ? config.connectionFactory.getHandler() : config.connectionFactory)
|
||||
config.returnCallback && this._Handler.setReturnCallback(config.returnCallback.getHandler())
|
||||
config.confirmCallback && this._Handler.setConfirmCallback(config.confirmCallback.getHandler())
|
||||
config.messageConverter && this._Handler.setMessageConverter(config.messageConverter.getHandler())
|
||||
}
|
||||
|
||||
getHandler() {
|
||||
return this._Handler
|
||||
}
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
import { JSClass } from "@ccms/container"
|
||||
import { RabbitAdminAdapter, MessageListenerContainerAdapter, AcknowledgeMode, MessageHandler, ChannelAwareMessageListenerAdapter } from "./adapter"
|
||||
|
||||
export class AmqpAdmin {
|
||||
@JSClass('org.springframework.amqp.core.TopicExchange')
|
||||
private TopicExchange: typeof org.springframework.amqp.core.TopicExchange
|
||||
@JSClass('org.springframework.amqp.core.Queue')
|
||||
private Queue: typeof org.springframework.amqp.core.Queue
|
||||
@JSClass('org.springframework.amqp.core.Binding')
|
||||
private Binding: typeof org.springframework.amqp.core.Binding
|
||||
@JSClass('org.springframework.amqp.rabbit.core.RabbitAdmin')
|
||||
private RabbitAdmin: typeof org.springframework.amqp.rabbit.core.RabbitAdmin
|
||||
@JSClass('org.springframework.amqp.core.Binding.DestinationType')
|
||||
private DestinationType: org.springframework.amqp.core.Binding.DestinationType
|
||||
|
||||
private amqpAdmin: org.springframework.amqp.rabbit.core.RabbitAdmin
|
||||
|
||||
constructor(amqpAdmin: org.springframework.amqp.rabbit.core.RabbitAdmin | any) {
|
||||
if (amqpAdmin instanceof this.RabbitAdmin) {
|
||||
this.amqpAdmin = amqpAdmin
|
||||
} else if (amqpAdmin instanceof RabbitAdminAdapter) {
|
||||
this.amqpAdmin = amqpAdmin.getHandler()
|
||||
} else {
|
||||
this.amqpAdmin = new RabbitAdminAdapter(amqpAdmin).getHandler()
|
||||
}
|
||||
}
|
||||
|
||||
getHandler() {
|
||||
return this.amqpAdmin
|
||||
}
|
||||
|
||||
getQueueProperties(name: string) {
|
||||
return this.amqpAdmin.getQueueProperties(name)
|
||||
}
|
||||
|
||||
declareExchange(name: string) {
|
||||
let exchange = new this.TopicExchange(name, true, false)
|
||||
this.amqpAdmin.declareExchange(exchange)
|
||||
return this
|
||||
}
|
||||
|
||||
declareQueue(name: string) {
|
||||
let queue = new this.Queue(name, true)
|
||||
this.amqpAdmin.declareQueue(queue)
|
||||
return this
|
||||
}
|
||||
|
||||
declareBinding(queue: string, exchange: string, routerKey: string, argument: any = null) {
|
||||
let binding = new this.Binding(queue, org.springframework.amqp.core.Binding.DestinationType.QUEUE, exchange, routerKey, argument)
|
||||
this.amqpAdmin.declareBinding(binding)
|
||||
return this
|
||||
}
|
||||
|
||||
declareQueueAndBindExchange(queue: string, exchange: string, routerKey: string) {
|
||||
return this.declareQueue(queue).declareExchange(exchange).declareBinding(queue, exchange, routerKey)
|
||||
}
|
||||
|
||||
createContainer<T>(queue: string, listener: MessageHandler<T>, acknowledgeMode = AcknowledgeMode.AUTO) {
|
||||
let connection = this.amqpAdmin.getRabbitTemplate().getConnectionFactory()
|
||||
return new MessageListenerContainerAdapter({
|
||||
connectionFactory: connection,
|
||||
queueNames: [queue],
|
||||
messageListener: new SimpleMessageHandler(listener),
|
||||
acknowledgeMode: acknowledgeMode
|
||||
}).getHandler()
|
||||
}
|
||||
|
||||
send()
|
||||
send() {
|
||||
|
||||
}
|
||||
|
||||
getTemplate() {
|
||||
return this.amqpAdmin.getRabbitTemplate()
|
||||
}
|
||||
|
||||
close() {
|
||||
this.getTemplate().stop()
|
||||
}
|
||||
}
|
||||
|
||||
export class SimpleMessageHandler extends ChannelAwareMessageListenerAdapter {
|
||||
constructor(private handler: MessageHandler<any>) {
|
||||
super()
|
||||
}
|
||||
onMessage(content: any, message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel) {
|
||||
return this.handler(content, message, channel)
|
||||
}
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
export const METADATA_KEY = {
|
||||
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
/// <reference types="@ccms/nashorn" />
|
||||
/// <reference types="@javatypes/jdk" />
|
||||
/// <reference types="@javatypes/spring-amqp" />
|
||||
/// <reference types="@javatypes/spring-rabbit" />
|
||||
/// <reference types="@javatypes/amqp-client" />
|
||||
|
||||
import { amqp } from '@ccms/api'
|
||||
import { getContainer, reduceMetadata } from '@ccms/container'
|
||||
|
||||
function init() {
|
||||
const beanFactory = base.getInstance().getAutowireCapableBeanFactory()
|
||||
getContainer().bind(amqp.rabbit.Template).toDynamicValue((ctx) => {
|
||||
let metadata = reduceMetadata(ctx)
|
||||
if (!metadata.named) {
|
||||
return beanFactory.getBean('rabbitTemplate')
|
||||
} else {
|
||||
return beanFactory.getBean(`${metadata.named}-rabbitTemplate`)
|
||||
}
|
||||
})
|
||||
getContainer().bind(amqp.rabbit.Admin).toDynamicValue((ctx) => {
|
||||
let metadata = reduceMetadata(ctx)
|
||||
if (!metadata.named) {
|
||||
return beanFactory.getBean('rabbitAdmin')
|
||||
} else {
|
||||
return beanFactory.getBean(`${metadata.named}-rabbitAdmin`)
|
||||
}
|
||||
})
|
||||
}
|
||||
init()
|
||||
|
||||
export * from './admin'
|
||||
export * from './adapter'
|
||||
export * from './manager'
|
||||
export * from './constants'
|
||||
@@ -1,5 +0,0 @@
|
||||
export class AmqpListener {
|
||||
constructor() {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
import { amqp } from "@ccms/api"
|
||||
import { provideSingleton } from "@ccms/container"
|
||||
|
||||
import { ConnectionFactoryAdapter, RabbitTemplateAdapter, RabbitAdminAdapter } from "./adapter"
|
||||
import { AmqpAdmin } from "./admin"
|
||||
|
||||
@provideSingleton(amqp.Manager)
|
||||
export class AmqpManager {
|
||||
createConnection(url: string, username: string, password: string) {
|
||||
return new ConnectionFactoryAdapter({ url, username, password })
|
||||
}
|
||||
createTemplate(adapter: ConnectionFactoryAdapter) {
|
||||
return new RabbitTemplateAdapter({ connectionFactory: adapter })
|
||||
}
|
||||
createAdmin(adapter: RabbitTemplateAdapter | ConnectionFactoryAdapter) {
|
||||
return new AmqpAdmin(new RabbitAdminAdapter(adapter))
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"baseUrl": "src",
|
||||
"outDir": "dist"
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/api",
|
||||
"version": "0.26.0",
|
||||
"version": "0.28.0-beta.4",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -12,23 +12,24 @@
|
||||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"build": "pnpm clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/common": "^0.26.0",
|
||||
"@ccms/container": "^0.26.0",
|
||||
"@ccms/polyfill": "^0.26.0",
|
||||
"@ccms/common": "^0.28.0-beta.4",
|
||||
"@ccms/container": "^0.28.0-beta.4",
|
||||
"@ccms/i18n": "^0.28.0-beta.4",
|
||||
"@ccms/polyfill": "^0.28.0-beta.4",
|
||||
"base64-js": "^1.5.1",
|
||||
"source-map-builder": "^0.0.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/base64-js": "^1.3.0",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^4.1.2",
|
||||
"typescript": "^4.9.5"
|
||||
"@types/base64-js": "^1.3.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
export namespace amqp {
|
||||
export const Manager = Symbol('AmqpManager')
|
||||
export namespace rabbit {
|
||||
export const Admin = Symbol('RabbitAdmin')
|
||||
export const Template = Symbol('RabbitTemplate')
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,12 @@ import { plugin } from './plugin'
|
||||
export namespace command {
|
||||
@injectable()
|
||||
export abstract class Command {
|
||||
/**
|
||||
* first time script engine need optimize jit code
|
||||
* so ignore first slow exec notify
|
||||
*/
|
||||
private cacheSlowKeys = {};
|
||||
|
||||
/**
|
||||
* 注册插件命令
|
||||
* @param plugin 插件
|
||||
@@ -46,36 +52,13 @@ export namespace command {
|
||||
try {
|
||||
let time = Date.now()
|
||||
let result = executor(sender, command, Java.from(args))
|
||||
let cost = Date.now() - time
|
||||
if (cost > global.ScriptSlowExecuteTime) {
|
||||
console.i18n("ms.api.command.execute.slow", {
|
||||
player: sender.name,
|
||||
plugin: plugin.description.name,
|
||||
command,
|
||||
args: Java.from(args).join(' '),
|
||||
cost
|
||||
})
|
||||
}
|
||||
this.checkSlow(Date.now() - time,
|
||||
"ms.api.command.execute.slow",
|
||||
plugin, command, sender, args)
|
||||
return result
|
||||
} catch (ex: any) {
|
||||
console.i18n("ms.api.command.execute.error", {
|
||||
player: sender.name,
|
||||
plugin: plugin.description.name,
|
||||
command,
|
||||
args: Java.from(args).join(' '),
|
||||
ex
|
||||
})
|
||||
console.ex(ex)
|
||||
if (sender.name != 'CONSOLE') {
|
||||
console.sender(sender, [i18n.translate("ms.api.command.execute.error", {
|
||||
player: sender.name,
|
||||
plugin: plugin.description.name,
|
||||
command,
|
||||
args: Java.from(args).join(' '),
|
||||
ex
|
||||
}),
|
||||
...console.stack(ex)])
|
||||
}
|
||||
this.printError(ex, "ms.api.command.execute.error",
|
||||
plugin, command, sender, args)
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -87,42 +70,18 @@ export namespace command {
|
||||
var token = args[args.length - 1]
|
||||
var complete = tabCompleter(sender, command, Java.from(args)) || []
|
||||
let result = this.copyPartialMatches(complete, token)
|
||||
let cost = Date.now() - time
|
||||
if (cost > global.ScriptSlowExecuteTime) {
|
||||
console.i18n("ms.api.command.tab.completer.slow", {
|
||||
player: sender.name,
|
||||
plugin: plugin.description.name,
|
||||
command,
|
||||
args: Java.from(args).join(' '),
|
||||
cost
|
||||
})
|
||||
}
|
||||
this.checkSlow(Date.now() - time,
|
||||
"ms.api.command.tab.completer.slow",
|
||||
plugin, command, sender, args)
|
||||
return result
|
||||
} catch (ex: any) {
|
||||
console.i18n("ms.api.command.tab.completer.error", {
|
||||
player: sender.name,
|
||||
plugin: plugin.description.name,
|
||||
command,
|
||||
args: Java.from(args).join(' '),
|
||||
ex
|
||||
})
|
||||
console.ex(ex)
|
||||
if (sender.name != 'CONSOLE') {
|
||||
console.sender(sender, [
|
||||
i18n.translate("ms.api.command.tab.completer.error", {
|
||||
player: sender.name,
|
||||
plugin: plugin.description.name,
|
||||
command,
|
||||
args: Java.from(args).join(' '),
|
||||
ex
|
||||
}),
|
||||
...console.stack(ex)
|
||||
])
|
||||
}
|
||||
this.printError(ex, "ms.api.command.tab.completer.error",
|
||||
plugin, command, sender, args)
|
||||
return []
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected copyPartialMatches(complete: string[], token: string, array: string[] = []): string[] {
|
||||
if (!token) { return complete }
|
||||
complete.forEach(function (e) {
|
||||
@@ -132,5 +91,35 @@ export namespace command {
|
||||
})
|
||||
return array
|
||||
}
|
||||
|
||||
private checkSlow(cost: number, key: string, plugin: plugin.Plugin, command: string, sender: any, args: any[]) {
|
||||
if (cost > global.ScriptSlowExecuteTime) {
|
||||
let completerKey = `${plugin.description.name}-${key}-${command}-${sender.name}`
|
||||
if (!this.cacheSlowKeys[completerKey]) {
|
||||
return this.cacheSlowKeys[completerKey] = cost
|
||||
}
|
||||
console.i18n(key, {
|
||||
player: sender.name,
|
||||
plugin: plugin.description.name,
|
||||
command,
|
||||
args: Java.from(args).join(' '),
|
||||
cost
|
||||
})
|
||||
}
|
||||
}
|
||||
private printError(error: Error, key: string, plugin: plugin.Plugin, command: string, sender: any, args: any[]) {
|
||||
let message = i18n.translate(key, {
|
||||
player: sender.name,
|
||||
plugin: plugin.description.name,
|
||||
command,
|
||||
args: Java.from(args).join(' '),
|
||||
error
|
||||
})
|
||||
console.console(message)
|
||||
console.ex(error)
|
||||
if (sender.name != 'CONSOLE') {
|
||||
console.sender(sender, [message, ...console.stack(error)])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ export namespace event {
|
||||
public EventPriority = EventPriority;
|
||||
|
||||
private mapEvent = [];
|
||||
private listenerMap = [];
|
||||
private pluginEventMap = [];
|
||||
private cacheSlowEventKey = {};
|
||||
|
||||
protected baseEventDir = '';
|
||||
@@ -130,7 +130,7 @@ export namespace event {
|
||||
if (!plugin || !plugin.description || !plugin.description.name) throw new TypeError(i18n.translate("ms.api.event.listen.plugin.name.empty"))
|
||||
var name = plugin.description.name
|
||||
var eventCls = this.name2Class(name, event)
|
||||
if (!eventCls) { return }
|
||||
if (!eventCls) { return () => { console.warn('event ' + event + ' not found ignore off listener.') } }
|
||||
if (typeof priority === 'boolean') {
|
||||
ignoreCancel = priority
|
||||
priority = EventPriority.NORMAL
|
||||
@@ -140,16 +140,15 @@ export namespace event {
|
||||
// @ts-ignore
|
||||
let executor = exec.name || exec.executor || '[anonymous]'
|
||||
// noinspection JSUnusedGlobalSymbols
|
||||
var listener = this.register(
|
||||
let listener = this.register(
|
||||
eventCls,
|
||||
this.createExecute(name, exec, eventCls),
|
||||
priority,
|
||||
ignoreCancel
|
||||
)
|
||||
var listenerMap = this.listenerMap
|
||||
// add to cache Be used for close plugin to close event
|
||||
if (!listenerMap[name]) listenerMap[name] = []
|
||||
var off = () => {
|
||||
if (!this.pluginEventMap[name]) this.pluginEventMap[name] = []
|
||||
let off = () => {
|
||||
if (off['offed']) return
|
||||
off['offed'] = true
|
||||
this.unregister(eventCls, listener)
|
||||
@@ -159,7 +158,7 @@ export namespace event {
|
||||
exec: executor
|
||||
}))
|
||||
}
|
||||
listenerMap[name].push(off)
|
||||
this.pluginEventMap[name].push(off)
|
||||
// noinspection JSUnresolvedVariable
|
||||
console.debug(i18n.translate("ms.api.event.register", {
|
||||
name,
|
||||
@@ -176,10 +175,10 @@ export namespace event {
|
||||
* @param plugin 插件
|
||||
*/
|
||||
disable(plugin: any) {
|
||||
var eventCache = this.listenerMap[plugin.description.name]
|
||||
var eventCache = this.pluginEventMap[plugin.description.name]
|
||||
if (eventCache) {
|
||||
eventCache.forEach((off: () => any) => off())
|
||||
delete this.listenerMap[plugin.description.name]
|
||||
delete this.pluginEventMap[plugin.description.name]
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import "@ccms/nashorn"
|
||||
|
||||
export * from './web'
|
||||
export * from './amqp'
|
||||
export * from './chat'
|
||||
export * from './task'
|
||||
export * from './item'
|
||||
|
||||
@@ -6,6 +6,12 @@ const UUID = Java.type('java.util.UUID')
|
||||
const Math = Java.type('java.lang.Math')
|
||||
|
||||
export namespace particle {
|
||||
@injectable()
|
||||
export abstract class ParticleSpawner {
|
||||
abstract spawn(location: any, particle: Particle)
|
||||
abstract spawnToPlayer(player: any, location: any, particle: Particle)
|
||||
}
|
||||
|
||||
/**
|
||||
* 表示一个特效对象
|
||||
*
|
||||
@@ -498,10 +504,4 @@ export namespace particle {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@injectable()
|
||||
export abstract class ParticleSpawner {
|
||||
abstract spawn(location: any, particle: Particle)
|
||||
abstract spawnToPlayer(player: any, location: any, particle: Particle)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { plugin } from './index'
|
||||
import { EventEmitter } from 'events'
|
||||
import { injectable } from '@ccms/container'
|
||||
|
||||
import { plugin } from './index'
|
||||
|
||||
const AtomicInteger = Java.type("java.util.concurrent.atomic.AtomicInteger")
|
||||
|
||||
export namespace task {
|
||||
@@ -32,9 +34,7 @@ export namespace task {
|
||||
|
||||
protected pluginDisable(plugin: plugin.Plugin) {
|
||||
if (this.pluginCacheTasks.has(plugin.description.name)) {
|
||||
this.pluginCacheTasks.get(plugin.description.name).forEach((task) => {
|
||||
task.cancel()
|
||||
})
|
||||
this.pluginCacheTasks.get(plugin.description.name).forEach((task) => task.cancel())
|
||||
this.pluginCacheTasks.delete(plugin.description.name)
|
||||
}
|
||||
}
|
||||
@@ -79,7 +79,7 @@ export namespace task {
|
||||
/**
|
||||
* 任务抽象
|
||||
*/
|
||||
export abstract class Task implements Cancelable {
|
||||
export abstract class Task extends EventEmitter implements Cancelable {
|
||||
protected func: Function
|
||||
protected isAsync: boolean = false;
|
||||
protected laterTime: number = 0;
|
||||
@@ -88,7 +88,10 @@ export namespace task {
|
||||
protected taskId: number
|
||||
protected innerTask: any
|
||||
|
||||
private cancelled: boolean = false
|
||||
|
||||
constructor(owner: plugin.Plugin, func: Function, id: number) {
|
||||
super()
|
||||
this.owner = owner
|
||||
this.func = func
|
||||
this.taskId = id
|
||||
@@ -134,20 +137,36 @@ export namespace task {
|
||||
*/
|
||||
cancel(): boolean {
|
||||
let result = this.cancel0()
|
||||
process.emit('task.finish', this)
|
||||
this.finish()
|
||||
this.cancelled = true
|
||||
return result
|
||||
}
|
||||
|
||||
protected run(...args: any[]): void {
|
||||
try {
|
||||
this.emit('before', this)
|
||||
if (this.cancelled) { return }
|
||||
this.func(...args)
|
||||
!this.interval && process.emit('task.finish', this)
|
||||
} catch (ex: any) {
|
||||
console.console('§4插件执行任务时发生错误', ex)
|
||||
console.ex(ex)
|
||||
this.emit('after', this)
|
||||
} catch (error: any) {
|
||||
try {
|
||||
this.emit('error', error)
|
||||
} catch (ignore) {
|
||||
console.console('§4插件执行任务时发生错误', error)
|
||||
console.ex(error)
|
||||
this.cancel()
|
||||
}
|
||||
} finally {
|
||||
this.emit('finally', this)
|
||||
if (!this.interval && !this.cancelled) { this.finish() }
|
||||
}
|
||||
}
|
||||
|
||||
protected finish() {
|
||||
process.emit('task.finish', this)
|
||||
this.emit('finish', this)
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交任务
|
||||
* @param args 任务参数
|
||||
@@ -161,7 +180,7 @@ export namespace task {
|
||||
* 提交任务
|
||||
* @param args 任务参数
|
||||
*/
|
||||
protected abstract submit0(...args: any[]): any
|
||||
protected abstract submit0(...args: any[]): Cancelable
|
||||
/**
|
||||
* 取消任务
|
||||
*/
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
export namespace web {
|
||||
export const Server = Symbol('Server')
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/bukkit",
|
||||
"version": "0.26.0",
|
||||
"version": "0.28.0-beta.4",
|
||||
"description": "MiaoScript bukkit package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -12,21 +12,21 @@
|
||||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"build": "pnpm clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@javatypes/spigot-api": "^0.0.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^4.1.2",
|
||||
"typescript": "^4.9.5"
|
||||
"@javatypes/spigot-api": "^0.0.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.26.0",
|
||||
"@ccms/common": "^0.26.0",
|
||||
"@ccms/container": "^0.26.0"
|
||||
"@ccms/api": "^0.28.0-beta.4",
|
||||
"@ccms/common": "^0.28.0-beta.4",
|
||||
"@ccms/container": "^0.28.0-beta.4"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/bungee",
|
||||
"version": "0.26.0",
|
||||
"version": "0.28.0-beta.4",
|
||||
"description": "MiaoScript bungee package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -12,21 +12,21 @@
|
||||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"build": "pnpm clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@javatypes/bungee-api": "^0.0.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^4.1.2",
|
||||
"typescript": "^4.9.5"
|
||||
"@javatypes/bungee-api": "^0.0.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.26.0",
|
||||
"@ccms/common": "^0.26.0",
|
||||
"@ccms/container": "^0.26.0"
|
||||
"@ccms/api": "^0.28.0-beta.4",
|
||||
"@ccms/common": "^0.28.0-beta.4",
|
||||
"@ccms/container": "^0.28.0-beta.4"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/common",
|
||||
"version": "0.26.0",
|
||||
"version": "0.28.0-beta.4",
|
||||
"description": "MiaoScript common package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -12,18 +12,18 @@
|
||||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"build": "pnpm clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.26.0",
|
||||
"@javatypes/jdk": "^0.0.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^4.1.2",
|
||||
"typescript": "^4.9.5"
|
||||
"@ccms/nashorn": "^0.28.0-beta.4",
|
||||
"@javatypes/jdk": "^0.0.3"
|
||||
},
|
||||
"gitHead": "562e2d00175c9d3a99c8b672aa07e6d92706a027"
|
||||
}
|
||||
|
||||
@@ -137,7 +137,7 @@ function declaredField(clazz: java.lang.Class<any>, name: string | java.lang.Str
|
||||
} catch (error: any) {
|
||||
if (target === undefined) { break }
|
||||
target = target.getSuperclass()
|
||||
console.debug(`切换到超类: ${target.getName()}`)
|
||||
console.debug(`switch to super class: ${target.getName()}`)
|
||||
}
|
||||
}
|
||||
if (field === null) {
|
||||
@@ -174,7 +174,7 @@ function declaredMethod(clazz: java.lang.Class<any>, nameOrIndex: string | numbe
|
||||
} catch (error) {
|
||||
if (target === undefined) { break }
|
||||
target = target.getSuperclass()
|
||||
console.debug(`切换到超类: ${target.getName()}`)
|
||||
console.debug(`switch to super class: ${target.getName()}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -187,7 +187,7 @@ function declaredMethods(clazz: java.lang.Class<any>) {
|
||||
}
|
||||
|
||||
function mapToObject(javaObj) {
|
||||
if (!Java.isJavaObject(javaObj)) { throw new TypeError(`参数 ${javaObj} 不是一个Java对象!`) }
|
||||
if (!Java.isJavaObject(javaObj)) { throw new TypeError(`argument ${javaObj} is not a java object.`) }
|
||||
let target = Proxy.newProxy(javaObj, {
|
||||
apply: (target, name, args) => { return args ? javaObj[name](args) : javaObj[name]() }
|
||||
})
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/compile",
|
||||
"version": "0.26.0",
|
||||
"version": "0.28.0-beta.4",
|
||||
"description": "MiaoScript compile package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -12,15 +12,33 @@
|
||||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"build": "pnpm clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^4.1.2",
|
||||
"typescript": "^4.9.5"
|
||||
"@ccms/api": "^0.28.0-beta.4",
|
||||
"@ccms/bukkit": "^0.28.0-beta.4",
|
||||
"@ccms/bungee": "^0.28.0-beta.4",
|
||||
"@ccms/common": "^0.28.0-beta.4",
|
||||
"@ccms/container": "^0.28.0-beta.4",
|
||||
"@ccms/core": "^0.28.0-beta.4",
|
||||
"@ccms/database": "^0.28.0-beta.4",
|
||||
"@ccms/i18n": "^0.28.0-beta.4",
|
||||
"@ccms/molang": "^0.28.0-beta.4",
|
||||
"@ccms/nashorn": "^0.28.0-beta.4",
|
||||
"@ccms/nodejs": "^0.28.0-beta.4",
|
||||
"@ccms/nukkit": "^0.28.0-beta.4",
|
||||
"@ccms/plugin": "^0.28.0-beta.4",
|
||||
"@ccms/polyfill": "^0.28.0-beta.4",
|
||||
"@ccms/protocol": "^0.28.0-beta.4",
|
||||
"@ccms/qrcode": "^0.28.0-beta.4",
|
||||
"@ccms/sponge": "^0.28.0-beta.4",
|
||||
"@ccms/websocket": "^0.28.0-beta.4"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/container",
|
||||
"version": "0.26.0",
|
||||
"version": "0.28.0-beta.4",
|
||||
"description": "MiaoScript container package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -12,17 +12,17 @@
|
||||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"build": "pnpm clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.26.0",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^4.1.2",
|
||||
"typescript": "^4.9.5"
|
||||
"@ccms/nashorn": "^0.28.0-beta.4"
|
||||
},
|
||||
"dependencies": {
|
||||
"inversify": "^6.0.1",
|
||||
|
||||
@@ -32,18 +32,28 @@ export const provideSingletonNamed = (identifier: interfaces.ServiceIdentifier<a
|
||||
return fluentProvide(identifier).inSingletonScope().whenTargetNamed(name).done()
|
||||
}
|
||||
|
||||
export function getJavaClass(className: string) {
|
||||
try { return Java.type(className).class; return } catch (error: any) { }
|
||||
try { return base.getClass(className); return } catch (error: any) { }
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得一个 java.lang.Class
|
||||
* @param className Java全类名
|
||||
*/
|
||||
export const JavaClass = (className: string) => {
|
||||
return function (target: object, propertyKey: string, index?: number) {
|
||||
try { target[propertyKey] = Java.type(className).class; return } catch (error: any) { }
|
||||
try { target[propertyKey] = base.getClass(className); return } catch (error: any) { }
|
||||
console.warn('JavaClass', className, 'Inject target', target.constructor.name, 'propertyKey', propertyKey, 'failed!')
|
||||
_proxyGetter(target, propertyKey, () => {
|
||||
return getJavaClass(className) || console.warn('JavaClass', className, 'Inject target', target.constructor.name, 'propertyKey', propertyKey, 'failed!')
|
||||
}, true)
|
||||
}
|
||||
}
|
||||
|
||||
export function getJSClass(className: string) {
|
||||
try { return Java.type(className) } catch (error: any) { }
|
||||
try { return base.getClass(className).static } catch (error: any) { }
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得一个JS的Java类
|
||||
* @param className Java 全类名
|
||||
@@ -51,9 +61,7 @@ export const JavaClass = (className: string) => {
|
||||
export const JSClass = (className: string) => {
|
||||
return function (target: object, propertyKey: string, index?: number) {
|
||||
_proxyGetter(target, propertyKey, () => {
|
||||
try { return Java.type(className) } catch (error: any) { }
|
||||
try { return base.getClass(className).static } catch (error: any) { }
|
||||
console.warn('JSClass', className, 'Inject target', target.constructor.name, 'propertyKey', propertyKey, 'failed!')
|
||||
return getJSClass(className) || console.warn('JSClass', className, 'Inject target', target.constructor.name, 'propertyKey', propertyKey, 'failed!')
|
||||
}, true)
|
||||
}
|
||||
}
|
||||
@@ -154,8 +162,10 @@ export const reduceMetadata = (ctx: interfaces.Context): any => {
|
||||
function initAutowired(container: Container) {
|
||||
container.bind(ioc.Autowired).toDynamicValue((ctx) => {
|
||||
var metadata: any = reduceMetadata(ctx)
|
||||
let key = Object.toString.call(metadata.named)
|
||||
let key = Object.prototype.toString.call(metadata.named)
|
||||
if (key === "[object Function]" || key === "[object Symbol]") { return container.get(metadata.named) }
|
||||
console.warn('container Autowired', metadata.named, 'failed. Error: illegal serviceIdentifier type', key)
|
||||
console.debug(metadata.named, 'metadata', JSON.stringify(metadata))
|
||||
return undefined
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/core",
|
||||
"version": "0.26.0",
|
||||
"version": "0.28.0-beta.4",
|
||||
"description": "MiaoScript core package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -12,20 +12,26 @@
|
||||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"watch": "pnpm rollup -c rollup.config.js --watch",
|
||||
"build": "pnpm clean && pnpm rollup -c rollup.config.js",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^4.1.2",
|
||||
"typescript": "^4.9.5"
|
||||
"@rollup/plugin-typescript": "^11.1.5",
|
||||
"rollup": "^2.79.1",
|
||||
"rollup-obfuscator": "^3.0.2",
|
||||
"rollup-plugin-peer-deps-external": "^2.2.4"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.26.0",
|
||||
"@ccms/container": "^0.26.0"
|
||||
"@ccms/api": "^0.28.0-beta.4",
|
||||
"@ccms/common": "^0.28.0-beta.4",
|
||||
"@ccms/container": "^0.28.0-beta.4",
|
||||
"js-yaml": "^4.1.0"
|
||||
},
|
||||
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
||||
}
|
||||
|
||||
49
packages/core/rollup.config.js
Normal file
49
packages/core/rollup.config.js
Normal file
@@ -0,0 +1,49 @@
|
||||
import typescript from '@rollup/plugin-typescript'
|
||||
import peerDepsExternal from 'rollup-plugin-peer-deps-external'
|
||||
import { obfuscator } from 'rollup-obfuscator'
|
||||
|
||||
import pkg from './package.json'
|
||||
|
||||
const external = ['path', 'fs', 'typescript', 'tslib']
|
||||
/**
|
||||
* @type {import('rollup').RollupOptions}
|
||||
*/
|
||||
export default {
|
||||
input: 'src/index.ts',
|
||||
plugins: [
|
||||
peerDepsExternal(),
|
||||
typescript(),
|
||||
obfuscator({
|
||||
compact: true,
|
||||
deadCodeInjection: true,
|
||||
deadCodeInjectionThreshold: 1,
|
||||
identifierNamesGenerator: 'mangled-shuffled',
|
||||
numbersToExpressions: true,
|
||||
simplify: true,
|
||||
stringArray: true,
|
||||
stringArrayThreshold: 1,
|
||||
stringArrayEncoding: ['rc4'],
|
||||
stringArrayCallsTransform: true,
|
||||
stringArrayCallsTransformThreshold: 1,
|
||||
stringArrayWrappersChainedCalls: true,
|
||||
stringArrayWrappersParametersMaxCount: 3,
|
||||
sourceMap: true,
|
||||
sourceMapSourcesMode: 'sources',
|
||||
inputFileName: `${pkg.name}.ts`,
|
||||
transformObjectKeys: true,
|
||||
unicodeEscapeSequence: true,
|
||||
target: 'browser-no-eval'
|
||||
}),
|
||||
],
|
||||
external,
|
||||
treeshake: false,
|
||||
output: [
|
||||
{
|
||||
format: 'cjs',
|
||||
interop: "auto",
|
||||
exports: "named",
|
||||
sourcemap: true,
|
||||
file: pkg.main || `dist/${pkg.name}.js`
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/database",
|
||||
"version": "0.26.0",
|
||||
"version": "0.28.0-beta.4",
|
||||
"description": "MiaoScript database package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -12,20 +12,20 @@
|
||||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"build": "pnpm clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@javatypes/spring-jdbc": "^0.0.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^4.1.2",
|
||||
"typescript": "^4.9.5"
|
||||
"@javatypes/spring-jdbc": "^0.0.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.26.0",
|
||||
"@ccms/container": "^0.26.0"
|
||||
"@ccms/api": "^0.28.0-beta.4",
|
||||
"@ccms/container": "^0.28.0-beta.4"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/i18n",
|
||||
"version": "0.26.0",
|
||||
"version": "0.28.0-beta.4",
|
||||
"description": "MiaoScript i18n package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -12,18 +12,19 @@
|
||||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"files": [
|
||||
"dist",
|
||||
"languages"
|
||||
],
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"build": "pnpm clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.26.0",
|
||||
"@types/js-yaml": "^4.0.5",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^4.1.2",
|
||||
"typescript": "^4.9.5"
|
||||
"@ccms/nashorn": "^0.28.0-beta.4",
|
||||
"@types/js-yaml": "^4.0.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"js-yaml": "^4.1.0"
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
../../.npmignore
|
||||
@@ -1,36 +0,0 @@
|
||||
{
|
||||
"name": "@ccms/keyvalue",
|
||||
"version": "0.26.0",
|
||||
"description": "MiaoScript keyvalue 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.26.0",
|
||||
"@ccms/common": "^0.26.0",
|
||||
"@ccms/container": "^0.26.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.26.0",
|
||||
"@javatypes/amqp-client": "^0.0.3",
|
||||
"@javatypes/spring-amqp": "^0.0.3",
|
||||
"@javatypes/spring-rabbit": "^0.0.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^4.1.2",
|
||||
"typescript": "^4.9.5"
|
||||
},
|
||||
"gitHead": "2589633069d24f646ac09261b1b2304c21d4ea75"
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
/// <reference types="@ccms/nashorn" />
|
||||
/// <reference types="@javatypes/jdk" />
|
||||
export { }
|
||||
@@ -1,7 +0,0 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"baseUrl": "src",
|
||||
"outDir": "dist"
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,16 @@
|
||||
{
|
||||
"name": "@ccms/molang",
|
||||
"version": "0.26.0",
|
||||
"version": "0.28.0-beta.4",
|
||||
"description": "A fast parser for Minecraft's MoLang",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"build": "pnpm clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"repository": {
|
||||
@@ -21,9 +24,6 @@
|
||||
},
|
||||
"homepage": "https://github.com/solvedDev/MoLang#readme",
|
||||
"devDependencies": {
|
||||
"@types/node": "^18.13.0",
|
||||
"rimraf": "^4.1.2",
|
||||
"tslib": "^2.5.0",
|
||||
"typescript": "^4.9.5"
|
||||
"@types/node": "^18.17.15"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/nashorn",
|
||||
"version": "0.26.0",
|
||||
"version": "0.28.0-beta.4",
|
||||
"description": "MiaoScript nashorn package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -13,15 +13,13 @@
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"build": "pnpm clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^4.1.2",
|
||||
"typescript": "^4.9.5"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/nodejs",
|
||||
"version": "0.26.0",
|
||||
"version": "0.28.0-beta.4",
|
||||
"description": "MiaoScript nodejs package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -12,18 +12,17 @@
|
||||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"build": "pnpm clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.26.0",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^4.1.2",
|
||||
"tslib": "^2.5.0",
|
||||
"typescript": "^4.9.5"
|
||||
"@ccms/nashorn": "^0.28.0-beta.4"
|
||||
},
|
||||
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
// USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
'use strict';
|
||||
var Throwable = Java.type('java.lang.Throwable')
|
||||
var R = typeof Reflect === 'object' ? Reflect : null
|
||||
var ReflectApply = R && typeof R.apply === 'function'
|
||||
? R.apply
|
||||
@@ -136,13 +137,19 @@ EventEmitter.prototype.emit = function emit(type) {
|
||||
var er;
|
||||
if (args.length > 0)
|
||||
er = args[0];
|
||||
if (er instanceof Error) {
|
||||
if (er instanceof Error || er instanceof Throwable) {
|
||||
// Note: The comments on the `throw` lines are intentional, they show
|
||||
// up in Node's output if this results in an unhandled exception.
|
||||
throw er; // Unhandled 'error' event
|
||||
}
|
||||
if (er.error instanceof Error || er.error instanceof Throwable) {
|
||||
throw er.error; // Unhandled 'error' event
|
||||
}
|
||||
if (er.cause instanceof Error || er.cause instanceof Throwable) {
|
||||
throw er.cause; // Unhandled 'error' event
|
||||
}
|
||||
// At least give some kind of context to the user
|
||||
var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
|
||||
var err = new Error('Unhandled error.' + (er ? ' (' + (er.message || er.error || er.cause || er) + ')' : ''));
|
||||
// @ts-ignore
|
||||
err.context = er;
|
||||
throw err; // Unhandled 'error' event
|
||||
|
||||
@@ -5,6 +5,7 @@ const Path = Java.type("java.nio.file.Path");
|
||||
const JavaString = Java.type("java.lang.String");
|
||||
const File = Java.type("java.io.File");
|
||||
const Files = Java.type("java.nio.file.Files");
|
||||
const Paths = Java.type("java.nio.file.Paths");
|
||||
const Collector = Java.type("java.util.stream.Collector")
|
||||
const separatorChar = File.separatorChar;
|
||||
const StandardCopyOption = Java.type("java.nio.file.StandardCopyOption");
|
||||
@@ -37,7 +38,7 @@ function javaFile(...opts: any[]) {
|
||||
}
|
||||
|
||||
export function renameSync(oldPath: PathLike, newPath: PathLike): void {
|
||||
|
||||
Files.move(Paths.get(oldPath), Paths.get(oldPath), StandardCopyOption['ATOMIC_MOVE'])
|
||||
}
|
||||
export function truncateSync() {
|
||||
|
||||
|
||||
@@ -715,6 +715,7 @@ function callbackify(original) {
|
||||
// implications (stack, `uncaughtException`, `async_hooks`)
|
||||
// @ts-ignore
|
||||
original.apply(this, args)
|
||||
// @ts-ignore
|
||||
.then(function (ret) { process.nextTick(cb.bind(null, null, ret)) },
|
||||
function (rej) { process.nextTick(callbackifyOnRejected.bind(null, rej, cb)) });
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/nukkit",
|
||||
"version": "0.26.0",
|
||||
"version": "0.28.0-beta.4",
|
||||
"description": "MiaoScript nukkit package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -12,21 +12,21 @@
|
||||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"build": "pnpm clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@javatypes/nukkit-api": "^0.0.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^4.1.2",
|
||||
"typescript": "^4.9.5"
|
||||
"@javatypes/nukkit-api": "^0.0.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.26.0",
|
||||
"@ccms/common": "^0.26.0",
|
||||
"@ccms/container": "^0.26.0"
|
||||
"@ccms/api": "^0.28.0-beta.4",
|
||||
"@ccms/common": "^0.28.0-beta.4",
|
||||
"@ccms/container": "^0.28.0-beta.4"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/plugin",
|
||||
"version": "0.26.0",
|
||||
"version": "0.28.0-beta.4",
|
||||
"description": "MiaoScript plugin package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -12,25 +12,25 @@
|
||||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"build": "pnpm clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/crypto-js": "^4.1.1",
|
||||
"@types/js-yaml": "^4.0.5",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^4.1.2",
|
||||
"typescript": "^4.9.5"
|
||||
"@types/crypto-js": "^4.1.2",
|
||||
"@types/js-yaml": "^4.0.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.26.0",
|
||||
"@ccms/common": "^0.26.0",
|
||||
"@ccms/container": "^0.26.0",
|
||||
"@ccms/i18n": "^0.26.0",
|
||||
"@ccms/verify": "^0.25.1",
|
||||
"@ccms/api": "^0.28.0-beta.4",
|
||||
"@ccms/common": "^0.28.0-beta.4",
|
||||
"@ccms/container": "^0.28.0-beta.4",
|
||||
"@ccms/i18n": "^0.28.0-beta.4",
|
||||
"@ccms/verify": "^0.26.1",
|
||||
"crypto-js": "^4.1.1",
|
||||
"js-yaml": "^4.1.0"
|
||||
}
|
||||
|
||||
@@ -15,51 +15,51 @@ export class PluginCommandManager {
|
||||
process.on('plugin.after.disable', this.unregistryCommand.bind(this))
|
||||
}
|
||||
|
||||
private registryCommand(pluginInstance: plugin.Plugin) {
|
||||
let cmds = getPluginCommandMetadata(pluginInstance)
|
||||
let tabs = getPluginTabCompleterMetadata(pluginInstance)
|
||||
public registryCommand(pluginInstance: plugin.Plugin, executor: any = pluginInstance) {
|
||||
let cmds = getPluginCommandMetadata(executor)
|
||||
let tabs = getPluginTabCompleterMetadata(executor)
|
||||
for (const cmd of cmds) {
|
||||
if (!this.ServerChecker.check(cmd.servers)) {
|
||||
console.debug(`[${pluginInstance.description.name}] ${cmd.target.constructor.name} incompatible command ${cmd.name} server(${cmd.servers}) ignore.`)
|
||||
continue
|
||||
}
|
||||
for (let command of [cmd.name, ...cmd.alias]) {
|
||||
let [cmdExecutor, cmdCompleter] = this.generateAutoMainCommand(pluginInstance, cmd, tabs.get(command))
|
||||
let [cmdExecutor, cmdCompleter] = this.generateAutoMainCommand(pluginInstance, executor, cmd, tabs.get(command))
|
||||
this.CommandManager.on(pluginInstance, command, {
|
||||
cmd: cmdExecutor.bind(pluginInstance),
|
||||
tab: cmdCompleter?.bind(pluginInstance)
|
||||
cmd: cmdExecutor.bind(executor),
|
||||
tab: cmdCompleter?.bind(executor)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private unregistryCommand(pluginInstance: plugin.Plugin) {
|
||||
let cmds = getPluginCommandMetadata(pluginInstance)
|
||||
public unregistryCommand(pluginInstance: plugin.Plugin, executor: any = pluginInstance) {
|
||||
let cmds = getPluginCommandMetadata(executor)
|
||||
for (const cmd of cmds) {
|
||||
if (!this.ServerChecker.check(cmd.servers)) {
|
||||
console.debug(`[${pluginInstance.description.name}] ${cmd.target.constructor.name} incompatible command ${cmd.name} server(${cmd.servers}) ignore.`)
|
||||
continue
|
||||
}
|
||||
for (let command of [cmd.name, ...cmd.alias]) {
|
||||
this.CommandManager.off(pluginInstance, command)
|
||||
this.CommandManager.off(executor, command)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private generateAutoMainCommand(pluginInstance: plugin.Plugin, cmd: interfaces.CommandMetadata, tab: interfaces.CommandMetadata) {
|
||||
let cmdExecutor = pluginInstance[cmd.executor]
|
||||
let cmdCompleter = tab ? pluginInstance[tab.executor] : undefined
|
||||
let cmdSubCache = Object.keys(pluginInstance.constructor.prototype).filter(s => s.startsWith('cmd')).map(s => s.substring(3))
|
||||
private generateAutoMainCommand(pluginInstance: plugin.Plugin, executor: any, cmd: interfaces.CommandMetadata, tab: interfaces.CommandMetadata) {
|
||||
let cmdExecutor = executor[cmd.executor]
|
||||
let cmdCompleter = tab ? executor[tab.executor] : undefined
|
||||
let cmdSubCache = Object.keys(executor.constructor.prototype).filter(s => s.startsWith('cmd')).map(s => s.substring(3))
|
||||
if (cmd.autoMain) {
|
||||
cmdExecutor = (sender: any, command: string, args: string[]) => {
|
||||
let subcommand = args[0]
|
||||
let cmdKey = 'cmd' + subcommand
|
||||
if (!cmdSubCache.includes(subcommand)) {
|
||||
if (!pluginInstance[cmd.executor].apply(pluginInstance, [sender, command, args])) {
|
||||
if (!executor[cmd.executor].apply(executor, [sender, command, args])) {
|
||||
subcommand && pluginInstance.logger.sender(sender, `§4未知的命令: §b/${command} §c${subcommand}`)
|
||||
pluginInstance.logger.sender(
|
||||
sender,
|
||||
pluginInstance['cmdhelp'] ?
|
||||
executor['cmdhelp'] ?
|
||||
`§6请执行 §b/${command} §ahelp §6查看帮助!` :
|
||||
[
|
||||
`§6插件: §b${pluginInstance.description.name}`,
|
||||
@@ -69,7 +69,7 @@ export class PluginCommandManager {
|
||||
}
|
||||
return
|
||||
}
|
||||
let subcommandexec = pluginInstance[cmdKey]
|
||||
let subcommandexec = executor[cmdKey]
|
||||
let permission: string
|
||||
if (cmd.permission && sender.hasPermission) {
|
||||
if (typeof cmd.permission == "string") {
|
||||
@@ -82,7 +82,7 @@ export class PluginCommandManager {
|
||||
}
|
||||
}
|
||||
args.shift()
|
||||
return subcommandexec.apply(pluginInstance, [sender, ...args])
|
||||
return subcommandexec.apply(executor, [sender, ...args])
|
||||
}
|
||||
let originCompleter = cmdCompleter
|
||||
cmdCompleter = (sender: any, command: string, args: string[]) => {
|
||||
@@ -95,7 +95,7 @@ export class PluginCommandManager {
|
||||
}
|
||||
if (!sender.hasPermission(permission)) { return [] }
|
||||
}
|
||||
return (args.length == 1 ? cmdSubCache : []).concat(originCompleter?.apply(pluginInstance, [sender, command, args]) || [])
|
||||
return (args.length == 1 ? cmdSubCache : []).concat(originCompleter?.apply(executor, [sender, command, args]) || [])
|
||||
}
|
||||
}
|
||||
if (!cmdCompleter) { console.debug(`[${pluginInstance.description.name}] command ${cmd.name} is not registry tabCompleter`) }
|
||||
|
||||
@@ -11,6 +11,8 @@ export class PluginEventManager {
|
||||
@Autowired()
|
||||
private nativePluginChecker: server.NativePluginChecker
|
||||
|
||||
private listenerMap = [];
|
||||
|
||||
constructor() {
|
||||
process.on('plugin.before.enable', this.registryListener.bind(this))
|
||||
process.on('plugin.after.disable', this.unregistryListener.bind(this))
|
||||
@@ -20,8 +22,9 @@ export class PluginEventManager {
|
||||
return this.eventManager.mapEventName().toFixed(0)
|
||||
}
|
||||
|
||||
private registryListener(pluginInstance: plugin.Plugin) {
|
||||
let events = getPluginListenerMetadata(pluginInstance)
|
||||
public registryListener(pluginInstance: plugin.Plugin, listener: any = pluginInstance) {
|
||||
let events = getPluginListenerMetadata(listener)
|
||||
let execes = []
|
||||
for (const event of events) {
|
||||
// ignore space listener
|
||||
if (!this.serverChecker.check(event.servers)) {
|
||||
@@ -35,13 +38,25 @@ export class PluginEventManager {
|
||||
}
|
||||
// here must bind this to pluginInstance
|
||||
let exec = event.target[event.executor]
|
||||
let execBinded = exec.bind(pluginInstance)
|
||||
let execBinded = exec.bind(listener)
|
||||
execBinded.executor = event.executor
|
||||
exec.off = this.eventManager.listen(pluginInstance, event.name, execBinded, event.priority, event.ignoreCancel)
|
||||
execes.push(exec)
|
||||
}
|
||||
let off = () => {
|
||||
if (off['offed']) return
|
||||
off['offed'] = true
|
||||
execes.forEach((exec: { off: () => void }) => exec.off())
|
||||
}
|
||||
listener.off = off
|
||||
}
|
||||
|
||||
private unregistryListener(pluginInstance: plugin.Plugin) {
|
||||
this.eventManager.disable(pluginInstance)
|
||||
public unregistryListener(pluginInstance: plugin.Plugin, listener: any = pluginInstance) {
|
||||
if (listener && listener.off) {
|
||||
listener.off()
|
||||
}
|
||||
if (pluginInstance) {
|
||||
this.eventManager.disable(pluginInstance)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,9 @@ export * from './manager'
|
||||
export * from './decorators'
|
||||
export * from './interfaces'
|
||||
|
||||
export * from './event'
|
||||
export * from './command'
|
||||
|
||||
export {
|
||||
plugin as JSPlugin,
|
||||
cmd as Cmd,
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { server, MiaoScriptConsole, event, plugin } from "@ccms/api"
|
||||
import { injectable, inject, postConstruct } from "@ccms/container"
|
||||
import { server, MiaoScriptConsole, event, plugin, task, command } from "@ccms/api"
|
||||
import { injectable, inject, postConstruct, Autowired } from "@ccms/container"
|
||||
import { getPluginMetadata } from "./utils"
|
||||
import { PluginEventManager } from "./event"
|
||||
import { PluginCommandManager } from "./command"
|
||||
|
||||
const File = Java.type('java.io.File')
|
||||
|
||||
@@ -8,9 +10,15 @@ export namespace interfaces {
|
||||
@injectable()
|
||||
export abstract class Plugin implements plugin.Plugin {
|
||||
public description: plugin.PluginMetadata
|
||||
public logger: Console
|
||||
public logger: MiaoScriptConsole
|
||||
@inject(server.Console)
|
||||
private Console: MiaoScriptConsole
|
||||
@Autowired()
|
||||
private taskManager: task.TaskManager
|
||||
@Autowired()
|
||||
private eventManager: PluginEventManager
|
||||
@Autowired()
|
||||
private commandManager: PluginCommandManager
|
||||
|
||||
constructor() {
|
||||
this.description = getPluginMetadata(this)
|
||||
@@ -28,6 +36,43 @@ export namespace interfaces {
|
||||
return dataFolder.getAbsolutePath()
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册命令
|
||||
* @param executor 命令执行器
|
||||
*/
|
||||
public registryCommand(executor: any) {
|
||||
this.commandManager.registryCommand(this, executor)
|
||||
}
|
||||
/**
|
||||
* 注销命令
|
||||
* @param executor 命令执行器
|
||||
*/
|
||||
public unregistryCommand(executor: any) {
|
||||
this.commandManager.unregistryCommand(this, executor)
|
||||
}
|
||||
/**
|
||||
* 注册事件
|
||||
* @param listener 事件监听器
|
||||
*/
|
||||
public registryListener(listener: any) {
|
||||
this.eventManager.registryListener(this, listener)
|
||||
}
|
||||
/**
|
||||
* 注销事件
|
||||
* @param listener 事件监听器
|
||||
*/
|
||||
public unregistryListener(listener: any) {
|
||||
this.eventManager.unregistryListener(this, listener)
|
||||
}
|
||||
/**
|
||||
* 创建任务
|
||||
* @param func 任务内容
|
||||
* @returns 任务
|
||||
*/
|
||||
public createTask(func: Function) {
|
||||
return this.taskManager.create(func, this)
|
||||
}
|
||||
|
||||
public load() { }
|
||||
public enable() { }
|
||||
public disable() { }
|
||||
|
||||
@@ -1,27 +1,27 @@
|
||||
{
|
||||
"name": "@ccms/polyfill",
|
||||
"version": "0.26.0",
|
||||
"version": "0.28.0-beta.4",
|
||||
"description": "MiaoScript polyfill package",
|
||||
"author": "MiaoWoo <admin@yumc.pw>",
|
||||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"build": "pnpm clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/i18n": "^0.26.0",
|
||||
"@ccms/nodejs": "^0.26.0",
|
||||
"core-js": "^3.27.2"
|
||||
"@ccms/i18n": "^0.28.0-beta.4",
|
||||
"@ccms/nodejs": "^0.28.0-beta.4",
|
||||
"core-js": "^3.32.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.26.0",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^4.1.2",
|
||||
"typescript": "^4.9.5"
|
||||
"@ccms/nashorn": "^0.28.0-beta.4"
|
||||
}
|
||||
}
|
||||
|
||||
239
packages/polyfill/src/core-js.ts
Normal file
239
packages/polyfill/src/core-js.ts
Normal file
@@ -0,0 +1,239 @@
|
||||
'use strict';
|
||||
import 'core-js/modules/es.symbol';
|
||||
import 'core-js/modules/es.symbol.description';
|
||||
import 'core-js/modules/es.symbol.async-iterator';
|
||||
import 'core-js/modules/es.symbol.has-instance';
|
||||
import 'core-js/modules/es.symbol.is-concat-spreadable';
|
||||
import 'core-js/modules/es.symbol.iterator';
|
||||
import 'core-js/modules/es.symbol.match';
|
||||
import 'core-js/modules/es.symbol.match-all';
|
||||
import 'core-js/modules/es.symbol.replace';
|
||||
import 'core-js/modules/es.symbol.search';
|
||||
import 'core-js/modules/es.symbol.species';
|
||||
import 'core-js/modules/es.symbol.split';
|
||||
import 'core-js/modules/es.symbol.to-primitive';
|
||||
import 'core-js/modules/es.symbol.to-string-tag';
|
||||
import 'core-js/modules/es.symbol.unscopables';
|
||||
import 'core-js/modules/es.array.at';
|
||||
import 'core-js/modules/es.array.concat';
|
||||
import 'core-js/modules/es.array.copy-within';
|
||||
import 'core-js/modules/es.array.every';
|
||||
import 'core-js/modules/es.array.fill';
|
||||
import 'core-js/modules/es.array.filter';
|
||||
import 'core-js/modules/es.array.find';
|
||||
import 'core-js/modules/es.array.find-index';
|
||||
import 'core-js/modules/es.array.find-last';
|
||||
import 'core-js/modules/es.array.find-last-index';
|
||||
import 'core-js/modules/es.array.flat';
|
||||
import 'core-js/modules/es.array.flat-map';
|
||||
import 'core-js/modules/es.array.for-each';
|
||||
import 'core-js/modules/es.array.from';
|
||||
import 'core-js/modules/es.array.includes';
|
||||
import 'core-js/modules/es.array.index-of';
|
||||
import 'core-js/modules/es.array.is-array';
|
||||
import 'core-js/modules/es.array.iterator';
|
||||
import 'core-js/modules/es.array.join';
|
||||
import 'core-js/modules/es.array.last-index-of';
|
||||
import 'core-js/modules/es.array.map';
|
||||
import 'core-js/modules/es.array.of';
|
||||
import 'core-js/modules/es.array.push';
|
||||
import 'core-js/modules/es.array.reduce';
|
||||
import 'core-js/modules/es.array.reduce-right';
|
||||
import 'core-js/modules/es.array.reverse';
|
||||
import 'core-js/modules/es.array.slice';
|
||||
import 'core-js/modules/es.array.some';
|
||||
import 'core-js/modules/es.array.sort';
|
||||
import 'core-js/modules/es.array.species';
|
||||
import 'core-js/modules/es.array.splice';
|
||||
import 'core-js/modules/es.array.to-reversed';
|
||||
import 'core-js/modules/es.array.to-sorted';
|
||||
import 'core-js/modules/es.array.to-spliced';
|
||||
import 'core-js/modules/es.array.unscopables.flat';
|
||||
import 'core-js/modules/es.array.unscopables.flat-map';
|
||||
import 'core-js/modules/es.array.unshift';
|
||||
import 'core-js/modules/es.array.with';
|
||||
import 'core-js/modules/es.array-buffer.constructor';
|
||||
import 'core-js/modules/es.array-buffer.is-view';
|
||||
import 'core-js/modules/es.array-buffer.slice';
|
||||
import 'core-js/modules/es.data-view';
|
||||
import 'core-js/modules/es.date.get-year';
|
||||
import 'core-js/modules/es.date.now';
|
||||
import 'core-js/modules/es.date.set-year';
|
||||
import 'core-js/modules/es.date.to-gmt-string';
|
||||
import 'core-js/modules/es.date.to-iso-string';
|
||||
import 'core-js/modules/es.date.to-json';
|
||||
import 'core-js/modules/es.date.to-primitive';
|
||||
import 'core-js/modules/es.date.to-string';
|
||||
import 'core-js/modules/es.escape';
|
||||
import 'core-js/modules/es.function.bind';
|
||||
import 'core-js/modules/es.function.has-instance';
|
||||
import 'core-js/modules/es.function.name';
|
||||
import 'core-js/modules/es.global-this';
|
||||
import 'core-js/modules/es.json.stringify';
|
||||
import 'core-js/modules/es.json.to-string-tag';
|
||||
import 'core-js/modules/es.map';
|
||||
import 'core-js/modules/es.math.acosh';
|
||||
import 'core-js/modules/es.math.asinh';
|
||||
import 'core-js/modules/es.math.atanh';
|
||||
import 'core-js/modules/es.math.cbrt';
|
||||
import 'core-js/modules/es.math.clz32';
|
||||
import 'core-js/modules/es.math.cosh';
|
||||
import 'core-js/modules/es.math.expm1';
|
||||
import 'core-js/modules/es.math.fround';
|
||||
import 'core-js/modules/es.math.hypot';
|
||||
import 'core-js/modules/es.math.imul';
|
||||
import 'core-js/modules/es.math.log10';
|
||||
import 'core-js/modules/es.math.log1p';
|
||||
import 'core-js/modules/es.math.log2';
|
||||
import 'core-js/modules/es.math.sign';
|
||||
import 'core-js/modules/es.math.sinh';
|
||||
import 'core-js/modules/es.math.tanh';
|
||||
import 'core-js/modules/es.math.to-string-tag';
|
||||
import 'core-js/modules/es.math.trunc';
|
||||
import 'core-js/modules/es.number.constructor';
|
||||
import 'core-js/modules/es.number.epsilon';
|
||||
import 'core-js/modules/es.number.is-finite';
|
||||
import 'core-js/modules/es.number.is-integer';
|
||||
import 'core-js/modules/es.number.is-nan';
|
||||
import 'core-js/modules/es.number.is-safe-integer';
|
||||
import 'core-js/modules/es.number.max-safe-integer';
|
||||
import 'core-js/modules/es.number.min-safe-integer';
|
||||
import 'core-js/modules/es.number.parse-float';
|
||||
import 'core-js/modules/es.number.parse-int';
|
||||
import 'core-js/modules/es.number.to-exponential';
|
||||
import 'core-js/modules/es.number.to-fixed';
|
||||
import 'core-js/modules/es.number.to-precision';
|
||||
import 'core-js/modules/es.object.assign';
|
||||
import 'core-js/modules/es.object.create';
|
||||
import 'core-js/modules/es.object.define-getter';
|
||||
import 'core-js/modules/es.object.define-properties';
|
||||
import 'core-js/modules/es.object.define-property';
|
||||
import 'core-js/modules/es.object.define-setter';
|
||||
import 'core-js/modules/es.object.entries';
|
||||
import 'core-js/modules/es.object.freeze';
|
||||
import 'core-js/modules/es.object.from-entries';
|
||||
import 'core-js/modules/es.object.get-own-property-descriptor';
|
||||
import 'core-js/modules/es.object.get-own-property-descriptors';
|
||||
import 'core-js/modules/es.object.get-own-property-names';
|
||||
import 'core-js/modules/es.object.get-prototype-of';
|
||||
import 'core-js/modules/es.object.has-own';
|
||||
import 'core-js/modules/es.object.is';
|
||||
import 'core-js/modules/es.object.is-extensible';
|
||||
import 'core-js/modules/es.object.is-frozen';
|
||||
import 'core-js/modules/es.object.is-sealed';
|
||||
import 'core-js/modules/es.object.keys';
|
||||
import 'core-js/modules/es.object.lookup-getter';
|
||||
import 'core-js/modules/es.object.lookup-setter';
|
||||
import 'core-js/modules/es.object.prevent-extensions';
|
||||
import 'core-js/modules/es.object.proto';
|
||||
import 'core-js/modules/es.object.seal';
|
||||
import 'core-js/modules/es.object.values';
|
||||
import 'core-js/modules/es.parse-float';
|
||||
import 'core-js/modules/es.parse-int';
|
||||
import 'core-js/modules/es.promise';
|
||||
import 'core-js/modules/es.promise.all-settled';
|
||||
import 'core-js/modules/es.promise.any';
|
||||
import 'core-js/modules/es.promise.finally';
|
||||
import 'core-js/modules/es.reflect.apply';
|
||||
import 'core-js/modules/es.reflect.construct';
|
||||
import 'core-js/modules/es.reflect.define-property';
|
||||
import 'core-js/modules/es.reflect.delete-property';
|
||||
import 'core-js/modules/es.reflect.get';
|
||||
import 'core-js/modules/es.reflect.get-own-property-descriptor';
|
||||
import 'core-js/modules/es.reflect.get-prototype-of';
|
||||
import 'core-js/modules/es.reflect.has';
|
||||
import 'core-js/modules/es.reflect.is-extensible';
|
||||
import 'core-js/modules/es.reflect.own-keys';
|
||||
import 'core-js/modules/es.reflect.prevent-extensions';
|
||||
import 'core-js/modules/es.reflect.set';
|
||||
import 'core-js/modules/es.reflect.set-prototype-of';
|
||||
import 'core-js/modules/es.reflect.to-string-tag';
|
||||
import 'core-js/modules/es.regexp.constructor';
|
||||
import 'core-js/modules/es.regexp.dot-all';
|
||||
import 'core-js/modules/es.regexp.exec';
|
||||
import 'core-js/modules/es.regexp.flags';
|
||||
import 'core-js/modules/es.regexp.sticky';
|
||||
import 'core-js/modules/es.regexp.test';
|
||||
import 'core-js/modules/es.regexp.to-string';
|
||||
import 'core-js/modules/es.set';
|
||||
import 'core-js/modules/es.string.at-alternative';
|
||||
import 'core-js/modules/es.string.code-point-at';
|
||||
import 'core-js/modules/es.string.ends-with';
|
||||
import 'core-js/modules/es.string.from-code-point';
|
||||
import 'core-js/modules/es.string.includes';
|
||||
import 'core-js/modules/es.string.is-well-formed';
|
||||
import 'core-js/modules/es.string.iterator';
|
||||
import 'core-js/modules/es.string.match';
|
||||
import 'core-js/modules/es.string.match-all';
|
||||
import 'core-js/modules/es.string.pad-end';
|
||||
import 'core-js/modules/es.string.pad-start';
|
||||
import 'core-js/modules/es.string.raw';
|
||||
import 'core-js/modules/es.string.repeat';
|
||||
import 'core-js/modules/es.string.replace';
|
||||
import 'core-js/modules/es.string.replace-all';
|
||||
import 'core-js/modules/es.string.search';
|
||||
import 'core-js/modules/es.string.split';
|
||||
import 'core-js/modules/es.string.starts-with';
|
||||
import 'core-js/modules/es.string.substr';
|
||||
import 'core-js/modules/es.string.to-well-formed';
|
||||
import 'core-js/modules/es.string.trim';
|
||||
import 'core-js/modules/es.string.trim-end';
|
||||
import 'core-js/modules/es.string.trim-start';
|
||||
import 'core-js/modules/es.string.anchor';
|
||||
import 'core-js/modules/es.string.big';
|
||||
import 'core-js/modules/es.string.blink';
|
||||
import 'core-js/modules/es.string.bold';
|
||||
import 'core-js/modules/es.string.fixed';
|
||||
import 'core-js/modules/es.string.fontcolor';
|
||||
import 'core-js/modules/es.string.fontsize';
|
||||
import 'core-js/modules/es.string.italics';
|
||||
import 'core-js/modules/es.string.link';
|
||||
import 'core-js/modules/es.string.small';
|
||||
import 'core-js/modules/es.string.strike';
|
||||
import 'core-js/modules/es.string.sub';
|
||||
import 'core-js/modules/es.string.sup';
|
||||
import 'core-js/modules/es.typed-array.float32-array';
|
||||
import 'core-js/modules/es.typed-array.float64-array';
|
||||
import 'core-js/modules/es.typed-array.int8-array';
|
||||
import 'core-js/modules/es.typed-array.int16-array';
|
||||
import 'core-js/modules/es.typed-array.int32-array';
|
||||
import 'core-js/modules/es.typed-array.uint8-array';
|
||||
import 'core-js/modules/es.typed-array.uint8-clamped-array';
|
||||
import 'core-js/modules/es.typed-array.uint16-array';
|
||||
import 'core-js/modules/es.typed-array.uint32-array';
|
||||
import 'core-js/modules/es.typed-array.at';
|
||||
import 'core-js/modules/es.typed-array.copy-within';
|
||||
import 'core-js/modules/es.typed-array.every';
|
||||
import 'core-js/modules/es.typed-array.fill';
|
||||
import 'core-js/modules/es.typed-array.filter';
|
||||
import 'core-js/modules/es.typed-array.find';
|
||||
import 'core-js/modules/es.typed-array.find-index';
|
||||
import 'core-js/modules/es.typed-array.find-last';
|
||||
import 'core-js/modules/es.typed-array.find-last-index';
|
||||
import 'core-js/modules/es.typed-array.for-each';
|
||||
import 'core-js/modules/es.typed-array.from';
|
||||
import 'core-js/modules/es.typed-array.includes';
|
||||
import 'core-js/modules/es.typed-array.index-of';
|
||||
import 'core-js/modules/es.typed-array.iterator';
|
||||
import 'core-js/modules/es.typed-array.join';
|
||||
import 'core-js/modules/es.typed-array.last-index-of';
|
||||
import 'core-js/modules/es.typed-array.map';
|
||||
import 'core-js/modules/es.typed-array.of';
|
||||
import 'core-js/modules/es.typed-array.reduce';
|
||||
import 'core-js/modules/es.typed-array.reduce-right';
|
||||
import 'core-js/modules/es.typed-array.reverse';
|
||||
import 'core-js/modules/es.typed-array.set';
|
||||
import 'core-js/modules/es.typed-array.slice';
|
||||
import 'core-js/modules/es.typed-array.some';
|
||||
import 'core-js/modules/es.typed-array.sort';
|
||||
import 'core-js/modules/es.typed-array.subarray';
|
||||
import 'core-js/modules/es.typed-array.to-locale-string';
|
||||
import 'core-js/modules/es.typed-array.to-reversed';
|
||||
import 'core-js/modules/es.typed-array.to-sorted';
|
||||
import 'core-js/modules/es.typed-array.to-string';
|
||||
import 'core-js/modules/es.typed-array.with';
|
||||
import 'core-js/modules/es.unescape';
|
||||
import 'core-js/modules/es.weak-map';
|
||||
import 'core-js/modules/es.weak-set';
|
||||
|
||||
module.exports = require('core-js/internals/path');
|
||||
@@ -7,7 +7,7 @@ console.i18n("ms.polyfill.initialize")
|
||||
import './openjdk-nashorn-shim'
|
||||
import './es5-ext'
|
||||
import './node-shim'
|
||||
import 'core-js'
|
||||
import './core-js'
|
||||
//@ts-ignore
|
||||
process.on('exit', () => require.disable())
|
||||
global.setGlobal('Proxy', require('./proxy').Proxy)
|
||||
|
||||
@@ -45,11 +45,13 @@ class Process extends EventEmitter {
|
||||
execArgv = ''
|
||||
execPath = ''
|
||||
|
||||
private queueMicrotaskExecuteTimeout = 5000
|
||||
|
||||
constructor() {
|
||||
super()
|
||||
this.on('exit', () => {
|
||||
console.log(`await microTaskPool termination! queueTask: ${microTaskPool.shutdownNow().size()} remainTask: ${threadGroup.activeCount()}`)
|
||||
microTaskPool.awaitTermination(3000, TimeUnit.MILLISECONDS)
|
||||
microTaskPool.awaitTermination(this.queueMicrotaskExecuteTimeout, TimeUnit.MILLISECONDS)
|
||||
})
|
||||
}
|
||||
on(event: string | symbol, listener: (...args: any[]) => void) {
|
||||
@@ -67,18 +69,30 @@ class Process extends EventEmitter {
|
||||
})
|
||||
}
|
||||
nextTick(callback: Function, ...args: any[]): void {
|
||||
microTaskPool.execute(() => {
|
||||
try {
|
||||
callback(args)
|
||||
} catch (origin: any) {
|
||||
try {
|
||||
super.emit('error', origin)
|
||||
} catch (error: any) {
|
||||
console.ex(origin)
|
||||
console.ex(error)
|
||||
try {
|
||||
microTaskPool.submit(new Callable({
|
||||
call: () => {
|
||||
try {
|
||||
callback(args)
|
||||
} catch (origin: any) {
|
||||
try {
|
||||
super.emit('error', origin)
|
||||
} catch (error: any) {
|
||||
console.ex(origin)
|
||||
console.ex(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
})).get(this.queueMicrotaskExecuteTimeout, TimeUnit.MILLISECONDS)
|
||||
} catch (error: any) {
|
||||
if (error instanceof InterruptedException) {
|
||||
return console.warn(`FixedThreadPool isInterrupted exit! Task ${callback.name || '<anonymous>'} exec exit!`)
|
||||
}
|
||||
})
|
||||
if (error instanceof TimeoutException) {
|
||||
return console.warn(`Task ${callback.name || '<anonymous>'} => ${callback} exec time greater than ${this.queueMicrotaskExecuteTimeout}ms!`)
|
||||
}
|
||||
throw error.getCause && error.getCause() || error
|
||||
}
|
||||
}
|
||||
exit(code: number) {
|
||||
console.log(`process exit by code ${code}!`)
|
||||
@@ -120,12 +134,10 @@ class Process extends EventEmitter {
|
||||
throw new Error('MiaoScript unsupport kill.')
|
||||
return true
|
||||
}
|
||||
toString() {
|
||||
return "[object process]"
|
||||
}
|
||||
}
|
||||
|
||||
class EventLoop {
|
||||
private threadCount = new AtomicInteger(0)
|
||||
private eventLoopMainThread = undefined
|
||||
private eventLoopTaskQueue = new DelayQueue()
|
||||
private taskExecuteTimeout = 3000
|
||||
@@ -134,10 +146,10 @@ class EventLoop {
|
||||
constructor() {
|
||||
this.taskExecuteTimeout = parseInt(process.env.MS_TASK_EXECUTE_TIMEOUT) || 3000
|
||||
this.fixedThreadPool = new ThreadPoolExecutor(
|
||||
1, 1, 0, TimeUnit.SECONDS,
|
||||
8, 16, 0, TimeUnit.SECONDS,
|
||||
new LinkedBlockingQueue(1024),
|
||||
new ThreadFactory((run: any) => {
|
||||
let thread = new Thread(run, "@ccms/event-loop")
|
||||
let thread = new Thread(run, "@ccms/event-loop-" + this.threadCount.incrementAndGet())
|
||||
thread.setDaemon(true)
|
||||
return thread
|
||||
}))
|
||||
@@ -173,7 +185,7 @@ class EventLoop {
|
||||
this.eventLoopMainThread.interrupt()
|
||||
this.fixedThreadPool.shutdownNow()
|
||||
console.log(`await fixedThreadPool termination!`)
|
||||
this.fixedThreadPool.awaitTermination(3000, TimeUnit.MILLISECONDS)
|
||||
this.fixedThreadPool.awaitTermination(this.taskExecuteTimeout, TimeUnit.MILLISECONDS)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -198,7 +210,7 @@ class EventLoop {
|
||||
try {
|
||||
callback.apply(undefined, args)
|
||||
} catch (cause: any) {
|
||||
cause = cause.getCause && cause.getCause() || cause
|
||||
cause = cause.getCause ? cause.getCause() : cause
|
||||
try {
|
||||
process.emit('error', cause)
|
||||
} catch (error: any) {
|
||||
@@ -213,7 +225,7 @@ class EventLoop {
|
||||
return console.warn(`FixedThreadPool isInterrupted exit! Task ${name} exec exit!`)
|
||||
}
|
||||
if (error instanceof TimeoutException) {
|
||||
return console.warn(`Task ${name} => ${callback} exec time greater than ${this.taskExecuteTimeout}s!`)
|
||||
return console.warn(`Task ${name} => ${callback} exec time greater than ${this.taskExecuteTimeout}ms!`)
|
||||
}
|
||||
throw error.getCause && error.getCause() || error
|
||||
}
|
||||
@@ -260,7 +272,7 @@ class EventLoop {
|
||||
}
|
||||
}
|
||||
global.setGlobal('process', new Process(), {})
|
||||
Object.defineProperty(process, require('core-js/es/symbol/to-string-tag'), { value: '[object process]' })
|
||||
Object.defineProperty(process, require('core-js/es/symbol/to-string-tag'), { value: 'process' })
|
||||
const eventLoop = new EventLoop()
|
||||
Object.defineProperty(process, 'eventLoop', { value: eventLoop })
|
||||
eventLoop.startEventLoop()
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/protocol",
|
||||
"version": "0.26.0",
|
||||
"version": "0.28.0-beta.4",
|
||||
"description": "MiaoScript protocol package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -13,15 +13,13 @@
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"build": "pnpm clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^4.1.2",
|
||||
"typescript": "^4.9.5"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/qrcode",
|
||||
"version": "0.26.0",
|
||||
"version": "0.28.0-beta.4",
|
||||
"description": "MiaoScript qrcode package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -12,15 +12,13 @@
|
||||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"build": "pnpm clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^4.1.2",
|
||||
"typescript": "^4.9.5"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/sponge",
|
||||
"version": "0.26.0",
|
||||
"version": "0.28.0-beta.4",
|
||||
"description": "MiaoScript sponge package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -12,21 +12,21 @@
|
||||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"build": "pnpm clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@javatypes/sponge-api": "^0.0.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^4.1.2",
|
||||
"typescript": "^4.9.5"
|
||||
"@javatypes/sponge-api": "^0.0.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.26.0",
|
||||
"@ccms/common": "^0.26.0",
|
||||
"@ccms/container": "^0.26.0"
|
||||
"@ccms/api": "^0.28.0-beta.4",
|
||||
"@ccms/common": "^0.28.0-beta.4",
|
||||
"@ccms/container": "^0.28.0-beta.4"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
../../.npmignore
|
||||
@@ -1,32 +0,0 @@
|
||||
{
|
||||
"name": "@ccms/spring",
|
||||
"version": "0.26.0",
|
||||
"description": "MiaoScript spring 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": "^4.1.2",
|
||||
"typescript": "^4.9.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.26.0",
|
||||
"@ccms/common": "^0.26.0",
|
||||
"@ccms/container": "^0.26.0",
|
||||
"@ccms/database": "^0.26.0"
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
import '@ccms/nashorn'
|
||||
|
||||
import { command, plugin } from '@ccms/api'
|
||||
import { inject, provideSingleton, postConstruct } from '@ccms/container'
|
||||
|
||||
import { CommandMap } from './internal/command'
|
||||
|
||||
@provideSingleton(command.Command)
|
||||
export class SpringCommand extends command.Command {
|
||||
@inject(CommandMap)
|
||||
private commandMap: CommandMap
|
||||
|
||||
protected create(plugin: any, command: string) {
|
||||
return this.commandMap.register(plugin, command)
|
||||
}
|
||||
public tabComplete(sender: any, input: string, index?: number): string[] {
|
||||
return this.commandMap.tabComplate(sender, input, index)
|
||||
}
|
||||
protected remove(plugin: any, command: string) {
|
||||
this.commandMap.unregister(plugin, command)
|
||||
}
|
||||
protected onCommand(plugin: any, command: any, executor: Function) {
|
||||
command.setExecutor(super.setExecutor(plugin, command, executor))
|
||||
}
|
||||
protected onTabComplete(plugin: any, command: any, tabCompleter: Function) {
|
||||
command.setTabCompleter(super.setTabCompleter(plugin, command, tabCompleter))
|
||||
}
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
import { MiaoScriptConsole } from '@ccms/api'
|
||||
|
||||
var colorMap = []
|
||||
colorMap['0'] = '38;5;0'
|
||||
colorMap['1'] = '38;5;4'
|
||||
colorMap['2'] = '38;5;2'
|
||||
colorMap['3'] = '38;5;6'
|
||||
colorMap['4'] = '38;5;1'
|
||||
colorMap['5'] = '38;5;5'
|
||||
colorMap['6'] = '38;5;3'
|
||||
colorMap['7'] = '38;5;7'
|
||||
colorMap['8'] = '38;5;8'
|
||||
colorMap['9'] = '38;5;12'
|
||||
colorMap['a'] = '38;5;10'
|
||||
colorMap['b'] = '38;5;14'
|
||||
colorMap['c'] = '38;5;9'
|
||||
colorMap['d'] = '38;5;13'
|
||||
colorMap['e'] = '38;5;11'
|
||||
colorMap['f'] = '38;5;15'
|
||||
colorMap['r'] = '0'
|
||||
colorMap['l'] = '1'
|
||||
colorMap['n'] = '4'
|
||||
var regexMap = []
|
||||
for (const c in colorMap) {
|
||||
regexMap[colorMap[c]] = new RegExp(`§${c}`, "g")
|
||||
}
|
||||
function mcColor2ANSI(str: string) {
|
||||
for (const regex in regexMap) {
|
||||
str = str.replace(regexMap[regex], `\u001b[${regex}m`)
|
||||
}
|
||||
return str
|
||||
}
|
||||
|
||||
export class SpringConsole extends MiaoScriptConsole {
|
||||
error(...args: any[]) {
|
||||
this.logger.error(args.join(' '))
|
||||
}
|
||||
warn(...args: any[]) {
|
||||
this.logger.warn(args.join(' '))
|
||||
}
|
||||
sender(sender: any, ...args: any[]) {
|
||||
sender = sender || {
|
||||
sendMessage: (message: string) => console.console(message)
|
||||
}
|
||||
if (!sender.sendMessage) {
|
||||
this.error('第一个参数未实现 sendMessage 无法发送消息!')
|
||||
return
|
||||
}
|
||||
if (Object.prototype.toString.call(args[0]) === '[object Array]') {
|
||||
args[0].forEach(line => sender.sendMessage(this.prefix + line))
|
||||
} else {
|
||||
sender.sendMessage(this.prefix + args.join(' '))
|
||||
}
|
||||
}
|
||||
console(...args: string[]): void {
|
||||
this.logger.info(mcColor2ANSI(args.join(' ') + '§r'))
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
import { event, plugin } from '@ccms/api'
|
||||
import { inject, provideSingleton } from '@ccms/container'
|
||||
|
||||
@provideSingleton(event.Event)
|
||||
export class SpringEvent extends event.Event {
|
||||
@inject(plugin.PluginInstance)
|
||||
private pluginInstance: any
|
||||
|
||||
constructor() {
|
||||
super('');
|
||||
}
|
||||
mapEventName() {
|
||||
return 0;
|
||||
}
|
||||
isValidEvent(clazz: any): boolean {
|
||||
throw new Error("Method not implemented.");
|
||||
}
|
||||
register(eventCls: any, exec: Function, priority: any, ignoreCancel: boolean) {
|
||||
throw new Error("Method not implemented.");
|
||||
}
|
||||
unregister(event: any, listener: any): void {
|
||||
throw new Error("Method not implemented.");
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
import { server } from '@ccms/api'
|
||||
import { ioc, Container, reduceMetadata } from '@ccms/container'
|
||||
|
||||
import { SpringConsole } from './console'
|
||||
import './event'
|
||||
import './server'
|
||||
import './command'
|
||||
import './task'
|
||||
|
||||
const toString = {}.toString
|
||||
|
||||
export default function SpringImpl(container: Container) {
|
||||
try {
|
||||
require('@ccms/web')
|
||||
require('@ccms/amqp')
|
||||
require('@ccms/database')
|
||||
require('./internal/scanner/mysql-scanner')
|
||||
} catch (error: any) {
|
||||
console.ex(error)
|
||||
}
|
||||
const beanFactory = base.getInstance().getAutowireCapableBeanFactory()
|
||||
container.bind(server.Console).toConstantValue(SpringConsole)
|
||||
container.rebind(ioc.Autowired).toDynamicValue((ctx) => {
|
||||
var metadata: any = reduceMetadata(ctx)
|
||||
let key = toString.call(metadata.named)
|
||||
if (key === "[object Function]" || key === "[object Symbol]") { return container.get(metadata.named) }
|
||||
if (key === '[object jdk.internal.dynalink.beans.StaticClass]') { metadata.named = metadata.named.class }
|
||||
return beanFactory.getBean(metadata.named)
|
||||
})
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
import { provideSingleton } from "@ccms/container"
|
||||
import { plugin } from "@ccms/api"
|
||||
|
||||
type CommandExec = (sender: any, _: any, command: string, args: string[]) => boolean
|
||||
type TabCompleter = (sender: any, _: any, command: string, args: string[]) => string[]
|
||||
type CommandStore = { [key: string]: SpringCommand }
|
||||
|
||||
@provideSingleton(CommandMap)
|
||||
export class CommandMap {
|
||||
private commands: CommandStore = {}
|
||||
private pluginCommands: { [key: string]: CommandStore } = {}
|
||||
|
||||
register(plugin: plugin.Plugin, command: string) {
|
||||
let springCommand = new SpringCommand(plugin, command)
|
||||
this.commands[command] = springCommand
|
||||
if (!this.pluginCommands[plugin.description.name]) { this.pluginCommands[plugin.description.name] = {} }
|
||||
this.pluginCommands[plugin.description.name][command] = springCommand
|
||||
return springCommand
|
||||
}
|
||||
|
||||
unregister(plugin: plugin.Plugin, command: string) {
|
||||
delete this.commands[command]
|
||||
delete this.pluginCommands[plugin.description.name][command]
|
||||
}
|
||||
|
||||
dispatch(sender: any, command: string, args: string[]): boolean {
|
||||
if (command === "help") {
|
||||
sender.sendMessage('§e--------- §rHelp: Index §e---------------------------')
|
||||
sender.sendMessage('Use /help [n] to get page n of help.')
|
||||
for (const cmdName of Object.getOwnPropertyNames(this.commands)) {
|
||||
sender.sendMessage(`§6/${cmdName}: §rA command provided by plugin §b${this.commands[cmdName].plugin.description.name}§r.`)
|
||||
}
|
||||
return
|
||||
}
|
||||
let exists = this.commands[command]
|
||||
if (exists) {
|
||||
try {
|
||||
return exists.executor(sender, '', command, Java.to(args))
|
||||
} catch (error: any) {
|
||||
console.ex(error)
|
||||
}
|
||||
return true
|
||||
} else {
|
||||
sender.sendMessage && sender.sendMessage(`Unknown command. Type "/help" for help.`)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
tabComplate(sender: any, input: string, index?: number): string[] {
|
||||
if (index == 0) { return Object.keys(this.commands).concat('help') }
|
||||
let [command, ...args] = input.split(' ')
|
||||
let exists = this.commands[command]
|
||||
if (exists && exists.tabCompleter) {
|
||||
try {
|
||||
if (args.length !== index) { args.push('') }
|
||||
return exists.tabCompleter(sender, '', command, Java.to(args))
|
||||
} catch (error: any) {
|
||||
console.ex(error)
|
||||
}
|
||||
}
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
export class SpringCommand {
|
||||
public plugin: plugin.Plugin
|
||||
public name: string
|
||||
public executor: CommandExec
|
||||
public tabCompleter: TabCompleter
|
||||
|
||||
constructor(plugin: plugin.Plugin, command: string, description: string = '暂无描述!') {
|
||||
this.plugin = plugin
|
||||
this.name = command
|
||||
}
|
||||
|
||||
setExecutor = (executor: CommandExec) => this.executor = executor
|
||||
setTabCompleter = (tabCompleter: TabCompleter) => this.tabCompleter = tabCompleter
|
||||
toString = () => `SpringCommand(${this.name})`
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
import { plugin, database } from '@ccms/api'
|
||||
import { DataBaseManager } from '@ccms/database'
|
||||
import { provideSingleton, inject } from '@ccms/container'
|
||||
|
||||
import * as fs from '@ccms/common/dist/fs'
|
||||
|
||||
interface MySQLPlugin {
|
||||
name: string
|
||||
source: string
|
||||
}
|
||||
|
||||
@provideSingleton(plugin.PluginScanner)
|
||||
export class MySQLScanner implements plugin.PluginScanner {
|
||||
type: string = "mysql"
|
||||
|
||||
private cacheDir = 'mysql-plugin-cache'
|
||||
private cacheFileMap: Map<string, MySQLPlugin> = new Map()
|
||||
private target: string
|
||||
|
||||
@inject(database.DataBaseManager)
|
||||
private databaseManager: DataBaseManager
|
||||
|
||||
scan(target: any): plugin.PluginLoadMetadata[] {
|
||||
this.target = target
|
||||
let plugins = this.databaseManager.getMainDatabase().query<MySQLPlugin>(`SELECT name FROM ${this.target} WHERE LENGTH(source) != 0 AND deleted = 0`)
|
||||
return plugins.map(p => this.read(p))
|
||||
}
|
||||
read(mysqlPlugin: MySQLPlugin): plugin.PluginLoadMetadata {
|
||||
// if invoke this function from loadFromFile mysqlPlugin is a string need read from cache
|
||||
if (typeof mysqlPlugin == "string") {
|
||||
if (!this.cacheFileMap.has(mysqlPlugin)) { throw new Error(`this file ${mysqlPlugin} is not read from mysql-scanner. can't reload from this scanner!`) }
|
||||
mysqlPlugin = this.cacheFileMap.get(mysqlPlugin)
|
||||
}
|
||||
let cacheFile = fs.concat(root, this.cacheDir, `${mysqlPlugin.name}.js`)
|
||||
this.cacheFileMap.set(cacheFile, mysqlPlugin)
|
||||
return { name: mysqlPlugin.name, file: cacheFile, type: this.type, mysqlPlugin, scanner: this }
|
||||
}
|
||||
load(metadata: plugin.PluginLoadMetadata) {
|
||||
if (metadata.type !== this.type) { return }
|
||||
var plugin: any = this.databaseManager.getMainDatabase().query<MySQLPlugin>(`SELECT source FROM ${this.target} WHERE name = ? AND deleted = 0`, metadata.name)
|
||||
if (plugin.length == 0) { throw new Error(`[MySQLScanner] plugin ${metadata.name} not found at mysql database...`) }; plugin = plugin[0]
|
||||
if (!plugin.source) { throw new Error(`[MySQLScanner] plugin ${metadata.name} source can\'t be undefiend or empty...`) }
|
||||
base.save(metadata.file, plugin.source)
|
||||
//@ts-ignore
|
||||
metadata.instance = require(metadata.file, { cache: false })
|
||||
return metadata
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
import { constants, server } from '@ccms/api'
|
||||
import { provideSingleton, postConstruct, Autowired, Container, ContainerInstance } from '@ccms/container'
|
||||
import { CommandMap } from './internal/command'
|
||||
|
||||
@provideSingleton(server.Server)
|
||||
export class SpringServer extends server.Server {
|
||||
@Autowired(ContainerInstance)
|
||||
private container: Container
|
||||
@Autowired()
|
||||
private commandMap: CommandMap
|
||||
|
||||
private nettyPipeline = base.getInstance().getAutowireCapableBeanFactory()
|
||||
private rootLogger = Packages.org.slf4j.LoggerFactory.getLogger("root") || global.logger
|
||||
|
||||
@postConstruct()
|
||||
initialize() {
|
||||
this.container.bind(constants.ServiceIdentifier.NettyPipeline).toConstantValue(this.nettyPipeline)
|
||||
this.container.bind(constants.ServiceIdentifier.RootLogger).toConstantValue(this.rootLogger)
|
||||
}
|
||||
|
||||
getVersion(): string {
|
||||
return "SpringFramework"
|
||||
}
|
||||
getConsoleSender() {
|
||||
return {
|
||||
name: 'CONSOLE',
|
||||
sendMessage: (message: string) => console.console(message)
|
||||
}
|
||||
}
|
||||
dispatchCommand(sender: any, command: string): boolean {
|
||||
let cmd_args = command.split(" ")
|
||||
return this.commandMap.dispatch(sender, cmd_args.shift(), cmd_args || [])
|
||||
}
|
||||
dispatchConsoleCommand(command: string): boolean {
|
||||
return this.dispatchCommand(this.getConsoleSender(), command)
|
||||
}
|
||||
getNettyPipeline() {
|
||||
return this.nettyPipeline
|
||||
}
|
||||
getRootLogger() {
|
||||
return this.rootLogger
|
||||
}
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
import { task, plugin } from '@ccms/api'
|
||||
import { inject, provideSingleton } from '@ccms/container'
|
||||
import thread_pool from '@ccms/common/dist/thread-pool'
|
||||
|
||||
const AtomicBoolean = Java.type("java.util.concurrent.atomic.AtomicBoolean")
|
||||
const Thread = Java.type('java.lang.Thread')
|
||||
|
||||
@provideSingleton(task.TaskManager)
|
||||
export class SpringTaskManager extends task.TaskManager {
|
||||
@inject(plugin.PluginInstance)
|
||||
private pluginInstance: any
|
||||
|
||||
private tasks: { [s: string]: task.Cancelable }
|
||||
private executor: java.util.concurrent.ThreadPoolExecutor
|
||||
|
||||
constructor() {
|
||||
super()
|
||||
this.tasks = {}
|
||||
this.executor = thread_pool.create({
|
||||
groupName: '@ccms/spring'
|
||||
})
|
||||
}
|
||||
|
||||
create0(owner: plugin.Plugin, func: Function, id: number): task.Task {
|
||||
return new SpringTask(owner, func, id, this)
|
||||
}
|
||||
callSyncMethod(func: Function): any {
|
||||
return func()
|
||||
}
|
||||
disable0() {
|
||||
Object.values(this.tasks).forEach((task) => task?.cancel())
|
||||
this.executor.shutdown()
|
||||
}
|
||||
nextId() {
|
||||
return this.taskId.incrementAndGet()
|
||||
}
|
||||
submit(id: number, task: SpringTask, func: Function) {
|
||||
this.tasks[id] = task
|
||||
this.executor.execute(func as any)
|
||||
}
|
||||
cancel(id: number) {
|
||||
delete this.tasks[id]
|
||||
}
|
||||
}
|
||||
|
||||
export class SpringTask extends task.Task {
|
||||
private id: number
|
||||
private taskManager: SpringTaskManager
|
||||
private running = new AtomicBoolean(true)
|
||||
|
||||
constructor(owner: plugin.Plugin, func: Function, id: number, taskManager: SpringTaskManager) {
|
||||
super(owner, func, id)
|
||||
this.id = taskManager.nextId()
|
||||
this.taskManager = taskManager
|
||||
}
|
||||
|
||||
run(...args: any[]) {
|
||||
if (this.laterTime > 0) {
|
||||
try {
|
||||
Thread.sleep(this.laterTime)
|
||||
} catch (ex: any) {
|
||||
Thread.currentThread().interrupt()
|
||||
}
|
||||
}
|
||||
while (this.running.get()) {
|
||||
try {
|
||||
this.func(...args)
|
||||
} catch (ex: any) {
|
||||
console.error("Task exec error:", ex)
|
||||
console.ex(ex)
|
||||
}
|
||||
// If we have a interval of 0 or less, only run once
|
||||
if (this.interval <= 0) { break }
|
||||
try {
|
||||
Thread.sleep(this.interval)
|
||||
} catch (ex: any) {
|
||||
Thread.currentThread().interrupt()
|
||||
}
|
||||
}
|
||||
this.cancel()
|
||||
}
|
||||
|
||||
cancel0() {
|
||||
var wasRunning = this.running.getAndSet(false)
|
||||
if (wasRunning) {
|
||||
this.taskManager.cancel(this.id)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
submit0(...args: any[]) {
|
||||
this.taskManager.submit(this.id, this, () => this.run(...args))
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"baseUrl": "src",
|
||||
"outDir": "dist"
|
||||
}
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
../../.npmignore
|
||||
@@ -1,35 +0,0 @@
|
||||
{
|
||||
"name": "@ccms/web",
|
||||
"version": "0.26.0",
|
||||
"description": "MiaoScript web 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": {
|
||||
"@javatypes/jdk": "^0.0.3",
|
||||
"@javatypes/spring-beans": "^0.0.3",
|
||||
"@javatypes/spring-core": "^0.0.3",
|
||||
"@javatypes/spring-web": "^0.0.3",
|
||||
"@javatypes/tomcat": "^0.0.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^4.1.2",
|
||||
"typescript": "^4.9.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.26.0",
|
||||
"@ccms/container": "^0.26.0"
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
export const WebProxyBeanName = 'webServerProxy'
|
||||
export const FilterProxyBeanName = 'webFilterProxy'
|
||||
export const METADATA_KEY = {
|
||||
Controller: Symbol("@ccms/web:Controller"),
|
||||
Action: Symbol("@ccms/web:Action"),
|
||||
Param: Symbol("@ccms/web:Param"),
|
||||
Middleware: Symbol("@ccms/web:Middleware"),
|
||||
}
|
||||
export enum PARAM_TYPE {
|
||||
QUERY = 'QUERY',
|
||||
BODY = 'BODY',
|
||||
HEADER = 'HEADER',
|
||||
COOKIE = 'COOKIE',
|
||||
REQUEST = 'REQUEST',
|
||||
RESPONSE = 'RESPONSE',
|
||||
}
|
||||
@@ -1,86 +0,0 @@
|
||||
import { plugin } from '@ccms/api'
|
||||
import { decorate, injectable, getContainer } from "@ccms/container"
|
||||
|
||||
import { METADATA_KEY, PARAM_TYPE } from '../constants'
|
||||
import { interfaces } from "../interfaces"
|
||||
import { addControllerMetadata, addControllerAction, addActionParam, getControllerMetadata } from "./utils"
|
||||
|
||||
export const Controllers = (...controllers: any[]) => {
|
||||
return (target: any, propertyKey: string) => {
|
||||
for (const controller of controllers) {
|
||||
addControllerMetadata(getControllerMetadata(controller), target)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const Controller = (metadata?: string | interfaces.ControllerMetadata) => {
|
||||
return (target: any) => {
|
||||
if (!metadata) { metadata = target.name.toLowerCase().replace('controller', '') }
|
||||
if (typeof metadata === "string") { metadata = { path: metadata } }
|
||||
metadata.target = target
|
||||
metadata.name = metadata.name || target.name
|
||||
metadata.path = metadata.path ?? `/${metadata}`
|
||||
metadata.path = metadata.path.startsWith('/') ? metadata.path : `/${metadata.path}`
|
||||
decorate(injectable(), target)
|
||||
Reflect.defineMetadata(METADATA_KEY.Controller, metadata, target)
|
||||
addControllerMetadata(metadata)
|
||||
}
|
||||
}
|
||||
|
||||
function action(method: interfaces.Method) {
|
||||
return (metadata?: string | interfaces.ActionMetadata) => {
|
||||
return (target: any, propertyKey: string) => {
|
||||
if (!metadata) { metadata = propertyKey.toLowerCase() }
|
||||
if (typeof metadata === "string") { metadata = { path: metadata } }
|
||||
metadata.path = metadata.path ?? `/${propertyKey}`
|
||||
metadata.path = metadata.path.startsWith('/') ? metadata.path : `/${metadata.path}`
|
||||
metadata.method = method
|
||||
metadata.executor = propertyKey
|
||||
Reflect.defineMetadata(METADATA_KEY.Action, metadata, target[propertyKey])
|
||||
addControllerAction(target, propertyKey)
|
||||
}
|
||||
}
|
||||
}
|
||||
export const Action = action('ALL')
|
||||
export const Get = action('GET')
|
||||
export const Post = action('POST')
|
||||
export const Put = action('PUT')
|
||||
export const Patch = action('PATCH')
|
||||
export const Head = action('HEAD')
|
||||
export const Delete = action('DELETE')
|
||||
|
||||
function param(type: PARAM_TYPE) {
|
||||
return (metadata?: string | interfaces.ParamMetadata) => {
|
||||
return (target: any, propertyKey: string, index: number) => {
|
||||
if (!metadata) { metadata = `${propertyKey}-${index}` }
|
||||
if (typeof metadata === "string") { metadata = { name: metadata } }
|
||||
metadata.type = type
|
||||
metadata.index = index
|
||||
metadata.paramtype = Reflect.getMetadata("design:paramtypes", target, propertyKey)[index]
|
||||
addActionParam(target, propertyKey, metadata)
|
||||
}
|
||||
}
|
||||
}
|
||||
export const Request = param(PARAM_TYPE.REQUEST)
|
||||
export const Response = param(PARAM_TYPE.RESPONSE)
|
||||
export const Header = param(PARAM_TYPE.HEADER)
|
||||
export const Cookie = param(PARAM_TYPE.COOKIE)
|
||||
export const Query = param(PARAM_TYPE.QUERY)
|
||||
export const Param = param(PARAM_TYPE.QUERY)
|
||||
export const Body = param(PARAM_TYPE.BODY)
|
||||
|
||||
function Middleware() {
|
||||
return (metadata?: string | interfaces.ActionMetadata) => {
|
||||
return (target: any, propertyKey: string) => {
|
||||
if (!metadata) { metadata = propertyKey.toLowerCase() }
|
||||
if (typeof metadata === "string") { metadata = { path: metadata } }
|
||||
metadata.path = metadata.path ?? `/${propertyKey}`
|
||||
metadata.path = metadata.path.startsWith('/') ? metadata.path : `/${metadata.path}`
|
||||
metadata.executor = propertyKey
|
||||
Reflect.defineMetadata(METADATA_KEY.Action, metadata, target[propertyKey])
|
||||
addControllerAction(target, propertyKey)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export * from './utils'
|
||||
@@ -1,29 +0,0 @@
|
||||
import { interfaces } from '../interfaces'
|
||||
import { METADATA_KEY } from '../constants'
|
||||
|
||||
export function getControllerMetadatas(target: any = Reflect): Map<string, interfaces.ControllerMetadata> {
|
||||
return Reflect.getMetadata(METADATA_KEY.Controller, target) || new Map<string, interfaces.ControllerMetadata>()
|
||||
}
|
||||
export function addControllerMetadata(metadata: interfaces.ControllerMetadata, target: any = Reflect) {
|
||||
let metadatas = getControllerMetadatas(target)
|
||||
metadatas.set(metadata.name, metadata)
|
||||
Reflect.defineMetadata(METADATA_KEY.Controller, metadatas, target)
|
||||
}
|
||||
export function getControllerActions(target: any): string[] {
|
||||
return Reflect.getMetadata(METADATA_KEY.Action, target.constructor) || []
|
||||
}
|
||||
export function addControllerAction(target: any, propertyKey: string) {
|
||||
Reflect.defineMetadata(METADATA_KEY.Action, [propertyKey, ...getControllerActions(target)], target.constructor)
|
||||
}
|
||||
export function getControllerMetadata(target: any): interfaces.ControllerMetadata {
|
||||
return Reflect.getMetadata(METADATA_KEY.Controller, target)
|
||||
}
|
||||
export function getActionMetadata(target: any, propertyKey: string): interfaces.ActionMetadata {
|
||||
return Reflect.getMetadata(METADATA_KEY.Action, target[propertyKey])
|
||||
}
|
||||
export function getActionParams(target: any, propertyKey: string): interfaces.ParamMetadata[] {
|
||||
return Reflect.getMetadata(METADATA_KEY.Param, target[propertyKey]) || []
|
||||
}
|
||||
export function addActionParam(target: any, propertyKey: string, metadata: interfaces.ParamMetadata) {
|
||||
Reflect.defineMetadata(METADATA_KEY.Param, [metadata, ...getActionParams(target, propertyKey)], target[propertyKey])
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
/// <reference types="@ccms/nashorn" />
|
||||
/// <reference types="@javatypes/jdk" />
|
||||
/// <reference types="@javatypes/tomcat" />
|
||||
/// <reference types="@javatypes/spring-web" />
|
||||
/// <reference types="@javatypes/spring-core" />
|
||||
/// <reference types="@javatypes/spring-beans" />
|
||||
|
||||
export * from './server'
|
||||
export * from './constants'
|
||||
export * from './decorators'
|
||||
export * from './interfaces'
|
||||
@@ -1,25 +0,0 @@
|
||||
export type RequestHandler = (ctx: Context) => any
|
||||
export interface InterceptorAdapter {
|
||||
name: string
|
||||
preHandle?(ctx: Context): void
|
||||
postHandle?(ctx: Context): void
|
||||
}
|
||||
|
||||
type StringKeyAndStringValue = { [key: string]: string }
|
||||
type StringKeyAndStringOrArrayValue = { [key: string]: string | string[] }
|
||||
|
||||
export type RequestHeaders = StringKeyAndStringOrArrayValue
|
||||
export type RequestParams = StringKeyAndStringOrArrayValue
|
||||
export type RequestCookies = StringKeyAndStringValue
|
||||
|
||||
export interface Context {
|
||||
request?: javax.servlet.http.HttpServletRequest
|
||||
response?: javax.servlet.http.HttpServletResponse
|
||||
handler?: RequestHandler
|
||||
url?: string
|
||||
headers?: RequestHeaders
|
||||
cookies?: RequestCookies
|
||||
params?: RequestParams
|
||||
body?: any
|
||||
result?: any
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
export * from './context'
|
||||
export * from './metadata'
|
||||
@@ -1,77 +0,0 @@
|
||||
import { PARAM_TYPE } from "../constants"
|
||||
|
||||
export namespace interfaces {
|
||||
export interface BaseMetadata {
|
||||
/**
|
||||
* 名称 为空则为对象名称
|
||||
*/
|
||||
name?: string
|
||||
/**
|
||||
* 支持的服务器列表 为空则代表所有
|
||||
*/
|
||||
servers?: string[]
|
||||
}
|
||||
export interface WebMetadata extends BaseMetadata {
|
||||
/**
|
||||
* 路径
|
||||
*/
|
||||
path: string
|
||||
/**
|
||||
* 对象
|
||||
*/
|
||||
target?: any
|
||||
}
|
||||
export interface ControllerMetadata extends WebMetadata {
|
||||
|
||||
}
|
||||
interface Newable<T> {
|
||||
new(...args: any[]): T
|
||||
}
|
||||
interface Abstract<T> {
|
||||
prototype: T
|
||||
}
|
||||
export type ServiceIdentifier<T> = (string | symbol | Newable<T> | Abstract<T>)
|
||||
export interface MiddlewareMetadata extends BaseMetadata {
|
||||
/**
|
||||
* 中间件名称列表
|
||||
*/
|
||||
names: Array<ServiceIdentifier<any>>
|
||||
}
|
||||
export type Method = 'ALL' | 'GET' | 'HEAD' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | 'TRACE'
|
||||
export interface ActionMetadata extends WebMetadata {
|
||||
/**
|
||||
* 请求方法
|
||||
*/
|
||||
method?: Method
|
||||
/**
|
||||
* 执行器
|
||||
*/
|
||||
executor?: string
|
||||
}
|
||||
export interface ParamMetadata extends BaseMetadata {
|
||||
/**
|
||||
* 参数类型
|
||||
*/
|
||||
type?: PARAM_TYPE
|
||||
/**
|
||||
* 默认值
|
||||
*/
|
||||
default?: any
|
||||
/**
|
||||
* 参数位置
|
||||
*/
|
||||
index?: number
|
||||
/**
|
||||
* 参数对象类型
|
||||
*/
|
||||
paramtype?: NewableFunction
|
||||
/**
|
||||
* 是否必传
|
||||
*/
|
||||
require?: boolean
|
||||
/**
|
||||
* 异常消息
|
||||
*/
|
||||
message?: string
|
||||
}
|
||||
}
|
||||
@@ -1,323 +0,0 @@
|
||||
import * as querystring from 'querystring'
|
||||
|
||||
import { web, plugin } from '@ccms/api'
|
||||
import { provideSingleton, JSClass, postConstruct, Container, ContainerInstance, inject } from '@ccms/container'
|
||||
|
||||
import { WebProxyBeanName, FilterProxyBeanName, METADATA_KEY, PARAM_TYPE } from './constants'
|
||||
import { Context, InterceptorAdapter, RequestHandler, interfaces } from './interfaces'
|
||||
import { getControllerActions, getActionMetadata, getControllerMetadata, getActionParams, getControllerMetadatas } from './decorators'
|
||||
|
||||
const HttpServletRequestWrapper = Java.type('javax.servlet.http.HttpServletRequestWrapper')
|
||||
const HttpServletResponseWrapper = Java.type('javax.servlet.http.HttpServletResponseWrapper')
|
||||
const ServletInputStream = Java.type('javax.servlet.ServletInputStream')
|
||||
const ServletOutputStream = Java.type('javax.servlet.ServletOutputStream')
|
||||
|
||||
@provideSingleton(web.Server)
|
||||
export class Server {
|
||||
@JSClass('pw.yumc.MiaoScript.web.WebServerProxy')
|
||||
private WebServerProxy: any
|
||||
@JSClass('pw.yumc.MiaoScript.web.WebFilterProxy')
|
||||
private WebFilterProxy: any
|
||||
|
||||
@inject(ContainerInstance)
|
||||
private container: Container
|
||||
|
||||
private StreamUtils = org.springframework.util.StreamUtils
|
||||
private ResponseEntity = org.springframework.http.ResponseEntity
|
||||
|
||||
private controllerActions: Map<string, interfaces.ActionMetadata[]>
|
||||
private interceptors: Map<string, InterceptorAdapter>
|
||||
private methodMappings: Map<string, Map<string, RequestHandler>>
|
||||
|
||||
private beanFactory: org.springframework.beans.factory.support.DefaultListableBeanFactory
|
||||
|
||||
@postConstruct()
|
||||
initialization() {
|
||||
this.beanFactory = base.getInstance().getAutowireCapableBeanFactory()
|
||||
this.controllerActions = new Map()
|
||||
this.interceptors = new Map()
|
||||
this.methodMappings = new Map()
|
||||
this.start()
|
||||
process.on('plugin.after.enable', (plugin: plugin.Plugin) => this.registryPlugin(plugin))
|
||||
process.on('plugin.after.disable', (plugin: plugin.Plugin) => this.unregistryPlugin(plugin))
|
||||
}
|
||||
|
||||
start() {
|
||||
this.registryFilterProxy()
|
||||
this.registryWebProxy()
|
||||
}
|
||||
|
||||
stop() {
|
||||
try {
|
||||
this.beanFactory.destroySingleton(FilterProxyBeanName)
|
||||
this.beanFactory.destroySingleton(WebProxyBeanName)
|
||||
} catch (error: any) {
|
||||
console.ex(error)
|
||||
}
|
||||
}
|
||||
|
||||
registryPlugin(plugin: plugin.Plugin) {
|
||||
let controllers = getControllerMetadatas(plugin).values()
|
||||
for (const controller of controllers) {
|
||||
console.debug(`Plugin ${plugin.description.name} Registry Controller ${controller.name}.`)
|
||||
this.registryController(controller.target)
|
||||
}
|
||||
}
|
||||
|
||||
unregistryPlugin(plugin: plugin.Plugin) {
|
||||
let controllers = getControllerMetadatas(plugin).values()
|
||||
for (const controller of controllers) {
|
||||
console.debug(`Plugin ${plugin.description.name} Unregistry Controller ${controller.name}.`)
|
||||
this.unregistryController(controller.target)
|
||||
}
|
||||
}
|
||||
|
||||
registryController(target: any) {
|
||||
if (!target) { throw new Error('Controller can\'t be undefiend!') }
|
||||
let controllerMetadata = getControllerMetadata(target)
|
||||
if (!controllerMetadata) { throw new Error(`Controller ${target.name} must have @Controller decorator!`) }
|
||||
target = this.bindController(target)
|
||||
let actions = getControllerActions(target)
|
||||
this.controllerActions.set(controllerMetadata.name, [])
|
||||
for (const action of actions) {
|
||||
let actionMetadata = getActionMetadata(target, action)
|
||||
this.controllerActions.get(controllerMetadata.name).push(actionMetadata)
|
||||
let path = `${controllerMetadata.path || ''}${actionMetadata.path || ''}`
|
||||
if (!path) throw new Error(`Controller ${controllerMetadata.name} Action ${actionMetadata.name} path is empty!`)
|
||||
if (!this.methodMappings.has(path)) { this.methodMappings.set(path, new Map()) }
|
||||
console.debug(`Controller ${controllerMetadata.name} Registry ${path} Action to ${actionMetadata.executor || '<anonymous>'} function.`)
|
||||
this.methodMappings.get(path).set(actionMetadata.method || 'ALL', (ctx: Context) => {
|
||||
let args = []
|
||||
let params = getActionParams(target, action)
|
||||
for (const index in params) {
|
||||
let param = params[index]
|
||||
let paramValue = undefined
|
||||
switch (param.type) {
|
||||
case PARAM_TYPE.REQUEST: paramValue = ctx.request; break
|
||||
case PARAM_TYPE.RESPONSE: paramValue = ctx.response; break
|
||||
case PARAM_TYPE.QUERY: paramValue = ctx.params[param.name]; break
|
||||
case PARAM_TYPE.HEADER: paramValue = ctx.headers[param.name]; break
|
||||
case PARAM_TYPE.BODY: paramValue = ctx.body; break
|
||||
case PARAM_TYPE.COOKIE: paramValue = ctx.cookies[param.name]; break
|
||||
}
|
||||
if (param.require && !paramValue) {
|
||||
return {
|
||||
status: 400,
|
||||
msg: param.message ?? `Param Type ${param.type} require not empty!`,
|
||||
data: param
|
||||
}
|
||||
}
|
||||
args[param.index] = paramValue ?? param.default
|
||||
}
|
||||
return target[actionMetadata.executor].apply(target, args)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
private bindController(target: any) {
|
||||
try {
|
||||
this.container.rebind(METADATA_KEY.Controller).to(target).inSingletonScope().whenTargetNamed(target.name)
|
||||
} catch{
|
||||
this.container.bind(METADATA_KEY.Controller).to(target).inSingletonScope().whenTargetNamed(target.name)
|
||||
}
|
||||
return this.container.getNamed(METADATA_KEY.Controller, target.name)
|
||||
}
|
||||
|
||||
unregistryController(target: any) {
|
||||
if (!target) { throw new Error('Controller can\'t be undefiend!') }
|
||||
let controllerMetadata = getControllerMetadata(target)
|
||||
if (!controllerMetadata) { throw new Error(`Controller ${target.name} must have @Controller decorator!`) }
|
||||
if (!this.controllerActions.has(controllerMetadata.name)) { return console.warn(`Controller ${controllerMetadata.name} not registry!`) }
|
||||
let actions = this.controllerActions.get(controllerMetadata.name)
|
||||
for (const actionMetadata of actions) {
|
||||
let path = `${controllerMetadata.path || ''}${actionMetadata.path || ''}`
|
||||
if (!this.methodMappings.has(path)) { continue }
|
||||
this.methodMappings.get(path).delete(actionMetadata.method)
|
||||
console.debug(`Controller ${controllerMetadata.name} Unregistry ${path} Action.`)
|
||||
}
|
||||
this.controllerActions.delete(controllerMetadata.name)
|
||||
}
|
||||
|
||||
registryMapping(path: string, handler: RequestHandler) {
|
||||
console.debug(`Registry Mapping ${path} to handle ${handler.name || '<anonymous>'} function.`)
|
||||
if (!this.methodMappings.has(path)) { this.methodMappings.set(path, new Map()) }
|
||||
this.methodMappings.get(path).set("ALL", handler)
|
||||
}
|
||||
|
||||
unregistryMapping(path: string) {
|
||||
if (this.methodMappings.has(path)) { this.methodMappings.get(path).delete("ALL") }
|
||||
}
|
||||
|
||||
registryInterceptor(interceptor: InterceptorAdapter) {
|
||||
console.debug(`Registry ${interceptor.name} Interceptor.`)
|
||||
this.interceptors.set(interceptor.name, interceptor)
|
||||
}
|
||||
|
||||
unregistryInterceptor(interceptor: string | InterceptorAdapter) {
|
||||
if (typeof interceptor === "string") { interceptor = { name: interceptor } }
|
||||
console.debug(`Unregistry ${interceptor.name} Interceptor.`)
|
||||
this.interceptors.delete(interceptor.name)
|
||||
}
|
||||
|
||||
private registryFilterProxy() {
|
||||
try { this.beanFactory.destroySingleton(FilterProxyBeanName) } catch (ex: any) { }
|
||||
var WebFilterProxyNashorn = Java.extend(this.WebFilterProxy, {
|
||||
doFilter: (servletRequest: javax.servlet.http.HttpServletRequest, servletResponse: javax.servlet.http.HttpServletResponse, filterChain: javax.servlet.FilterChain) => {
|
||||
filterChain.doFilter(servletRequest, servletResponse)
|
||||
}
|
||||
})
|
||||
this.beanFactory.registerSingleton(FilterProxyBeanName, new WebFilterProxyNashorn())
|
||||
}
|
||||
|
||||
// private getRequestWrapper(servletRequest: javax.servlet.http.HttpServletRequest) {
|
||||
// var body = org.springframework.util.StreamUtils.copyToByteArray(servletRequest.getInputStream())
|
||||
// var HttpServletRequestWrapperAdapter = Java.extend(HttpServletRequestWrapper, {
|
||||
// getInputStream: () => {
|
||||
// var bais = new java.io.ByteArrayInputStream(body)
|
||||
// return new ServletInputStream({
|
||||
// read: () => bais.read(),
|
||||
// isFinished: () => bais.available() == 0
|
||||
// })
|
||||
// }
|
||||
// })
|
||||
// var wrapper = new HttpServletRequestWrapperAdapter(servletRequest)
|
||||
// return wrapper
|
||||
// }
|
||||
|
||||
// private getResponseWrapper(servletResponse: javax.servlet.http.HttpServletResponse) {
|
||||
// var HttpServletRequestWrapperAdapter = Java.extend(HttpServletRequestWrapper, {
|
||||
// getOutputStream: () => {
|
||||
// return new ServletOutputStream({
|
||||
// })
|
||||
// }
|
||||
// })
|
||||
// var wrapper = new HttpServletRequestWrapperAdapter(servletResponse)
|
||||
// return wrapper
|
||||
// }
|
||||
|
||||
private notFound(ctx: Context) {
|
||||
return {
|
||||
status: 404,
|
||||
msg: "handlerMapping Not Found!",
|
||||
method: ctx.request.getMethod(),
|
||||
path: ctx.request.getRequestURI(),
|
||||
timestamp: Date.now()
|
||||
}
|
||||
}
|
||||
|
||||
private registryWebProxy() {
|
||||
try { this.beanFactory.destroySingleton(WebProxyBeanName) } catch (ex: any) { }
|
||||
var WebServerProxyNashorn = Java.extend(this.WebServerProxy, {
|
||||
process: (req: javax.servlet.http.HttpServletRequest, resp: javax.servlet.http.HttpServletResponse) => {
|
||||
let ctx: Context = { request: req, response: resp, params: {}, body: {} }
|
||||
ctx.url = req.getRequestURI()
|
||||
// @ts-ignore
|
||||
ctx.headers = { __noSuchProperty__: (name: string) => req.getHeader(name) }
|
||||
ctx.cookies = {}
|
||||
for (const cookie of (req.getCookies() || [])) {
|
||||
ctx.cookies[cookie.getName()] = cookie.getValue()
|
||||
}
|
||||
if (req.getQueryString()) {
|
||||
ctx.url += `?${req.getQueryString()}`
|
||||
ctx.params = querystring.parse(req.getQueryString())
|
||||
}
|
||||
if (req.getMethod() == "POST") {
|
||||
ctx.body = this.StreamUtils.copyToString(req.getInputStream(), java.nio.charset.StandardCharsets.UTF_8)
|
||||
if ((ctx.headers['Content-Type'] || '').includes('application/json')) {
|
||||
try {
|
||||
ctx.body = JSON.parse(ctx.body)
|
||||
} catch (error: any) {
|
||||
return {
|
||||
status: 500,
|
||||
msg: `parse json body error: ${error}`,
|
||||
path: ctx.url,
|
||||
error: console.stack(error, false),
|
||||
timestamp: Date.now()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let result = this.process(ctx)
|
||||
result?.status && resp.setStatus(result.status)
|
||||
return result
|
||||
}
|
||||
})
|
||||
this.beanFactory.registerSingleton(WebProxyBeanName, new WebServerProxyNashorn())
|
||||
}
|
||||
|
||||
|
||||
private process(ctx: Context) {
|
||||
let startTime = Date.now()
|
||||
for (const [_, interceptor] of this.interceptors) {
|
||||
if (interceptor.preHandle) {
|
||||
try {
|
||||
let startTime = Date.now()
|
||||
ctx.result = interceptor.preHandle(ctx)
|
||||
let preHandleTime = Date.now() - startTime
|
||||
if (preHandleTime > 20) {
|
||||
console.debug(`[WARN] Interceptor ${interceptor.name} preHandle cost time ${preHandleTime}ms!`)
|
||||
}
|
||||
if (ctx.result) { return ctx.result }
|
||||
} catch (error: any) {
|
||||
console.ex(error)
|
||||
return {
|
||||
status: 500,
|
||||
msg: `Interceptor ${interceptor.name} preHandle error: ${error}`,
|
||||
path: ctx.url,
|
||||
error: console.stack(error, false),
|
||||
timestamp: Date.now()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let path = ctx.request.getRequestURI()
|
||||
if (!this.methodMappings.has(path)) return this.notFound(ctx)
|
||||
let mappings = this.methodMappings.get(ctx.request.getRequestURI())
|
||||
ctx.handler = mappings.get(ctx.request.getMethod()) || mappings.get("ALL")
|
||||
ctx.result = this.execRequestHandle(ctx)
|
||||
for (const [_, interceptor] of this.interceptors) {
|
||||
if (interceptor.postHandle) {
|
||||
try {
|
||||
let startTime = Date.now()
|
||||
ctx.result = interceptor.postHandle(ctx)
|
||||
let preHandleTime = Date.now() - startTime
|
||||
if (preHandleTime > 20) {
|
||||
console.debug(`[WARN] Interceptor ${interceptor.name} preHandle cost time ${preHandleTime}ms!`)
|
||||
}
|
||||
} catch (error: any) {
|
||||
return {
|
||||
status: 500,
|
||||
msg: `Interceptor ${interceptor.name} postHandle error: ${error}`,
|
||||
path: ctx.url,
|
||||
error: console.stack(error, false),
|
||||
timestamp: Date.now()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
console.debug(`
|
||||
===================== MiaoSpring =====================
|
||||
Request Method : ${ctx.request.getMethod()}
|
||||
Request URL : ${ctx.url}
|
||||
Request Body : ${JSON.stringify(ctx.body)}
|
||||
Response Body : ${JSON.stringify(Java.asJSONCompatible(ctx.result))}
|
||||
Handle Time : ${Date.now() - startTime}ms
|
||||
======================================================`)
|
||||
return ctx.result
|
||||
}
|
||||
|
||||
private execRequestHandle(ctx: Context) {
|
||||
if (!ctx.handler) return this.notFound(ctx)
|
||||
try {
|
||||
return ctx.handler(ctx)
|
||||
} catch (error: any) {
|
||||
return {
|
||||
status: 500,
|
||||
msg: '' + error,
|
||||
path: ctx.url,
|
||||
error: console.stack(error, false),
|
||||
timestamp: Date.now()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"baseUrl": "src",
|
||||
"outDir": "dist"
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/websocket",
|
||||
"version": "0.26.0",
|
||||
"version": "0.28.0-beta.4",
|
||||
"description": "MiaoScript websocket package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -12,10 +12,13 @@
|
||||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"build": "pnpm clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
@@ -24,10 +27,7 @@
|
||||
"parseuri": "^0.0.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.26.0",
|
||||
"@javatypes/tomcat-websocket-api": "^0.0.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^4.1.2",
|
||||
"typescript": "^4.9.5"
|
||||
"@ccms/nashorn": "^0.28.0-beta.4",
|
||||
"@javatypes/tomcat-websocket-api": "^0.0.3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
|
||||
import { EventEmitter } from 'events'
|
||||
import { Transport } from './transport'
|
||||
import { CloseEvent, ErrorEvent, Event, EventType, MessageEvent, WebSocketHeader } from './interface'
|
||||
import { ClientEvent, CloseEvent, ErrorEvent, Event, EventType, MessageEvent, WebSocketHeader } from './interface'
|
||||
|
||||
export class WebSocketManager {
|
||||
private clients = new Map<string, WebSocket>()
|
||||
@@ -9,7 +9,7 @@ export class WebSocketManager {
|
||||
constructor() {
|
||||
process.on('exit', () => {
|
||||
for (const client of this.clients.values()) {
|
||||
client.close(0, `client ${client.id} close connect`)
|
||||
client.close(1000, `client ${client.id} close connect due process exit.`)
|
||||
}
|
||||
this.clients.clear()
|
||||
})
|
||||
@@ -18,7 +18,9 @@ export class WebSocketManager {
|
||||
add(client: WebSocket) {
|
||||
this.clients.set(client.id, client)
|
||||
}
|
||||
|
||||
del(client: WebSocket) {
|
||||
client.removeAllListeners()
|
||||
this.clients.delete(client.id)
|
||||
}
|
||||
}
|
||||
@@ -26,12 +28,14 @@ export class WebSocketManager {
|
||||
export const manager = new WebSocketManager()
|
||||
|
||||
export class WebSocket extends EventEmitter {
|
||||
public static manager: WebSocketManager = manager
|
||||
|
||||
public static CONNECTING = 0
|
||||
public static OPEN = 1
|
||||
public static CLOSING = 2
|
||||
public static CLOSED = 3
|
||||
|
||||
public binaryType: 'blob' | 'arraybuffer'
|
||||
protected manager: WebSocketManager
|
||||
|
||||
protected _url: string
|
||||
protected _headers: WebSocketHeader = {}
|
||||
@@ -40,7 +44,6 @@ export class WebSocket extends EventEmitter {
|
||||
|
||||
constructor(url: string, subProtocol: string | string[] = '', headers: WebSocketHeader = {}) {
|
||||
super()
|
||||
this.manager = manager
|
||||
this._url = url
|
||||
this._headers = headers
|
||||
try {
|
||||
@@ -52,16 +55,14 @@ export class WebSocket extends EventEmitter {
|
||||
console.ex(error)
|
||||
return
|
||||
}
|
||||
this.client.on('open', (event) => {
|
||||
this.onopen?.(event)
|
||||
manager.add(this)
|
||||
})
|
||||
this.client.on('message', (event) => this.onmessage?.(event))
|
||||
this.client.on('close', (event) => {
|
||||
this.onclose?.(event)
|
||||
manager.del(this)
|
||||
})
|
||||
this.client.on('error', (event) => this.onerror?.(event))
|
||||
// mamanger connected client
|
||||
manager.add(this)
|
||||
this.client.on(ClientEvent.close, (_) => manager.del(this))
|
||||
// add event forward
|
||||
this.client.on(ClientEvent.open, (event) => this.onopen?.(event))
|
||||
this.client.on(ClientEvent.message, (event) => this.onmessage?.(event))
|
||||
this.client.on(ClientEvent.close, (event) => this.onclose?.(event))
|
||||
this.client.on(ClientEvent.error, (event) => this.onerror?.(event))
|
||||
setTimeout(() => this.client.connect(), 20)
|
||||
}
|
||||
get id() {
|
||||
@@ -77,26 +78,31 @@ export class WebSocket extends EventEmitter {
|
||||
return this.client.protocol
|
||||
}
|
||||
get readyState() {
|
||||
return this.client.readyStatus
|
||||
return this.client.readyState
|
||||
}
|
||||
get url() {
|
||||
return this._url
|
||||
}
|
||||
|
||||
public onopen: (event: Event) => void
|
||||
public onmessage: (event: MessageEvent) => void
|
||||
public onclose: (event: CloseEvent) => void
|
||||
public onerror: (event: ErrorEvent) => void
|
||||
|
||||
addEventListener(event: EventType, callback: () => void) {
|
||||
this[`on${event.toLowerCase()}`] = callback
|
||||
this.client.on(event, callback)
|
||||
public on(eventName: EventType, listener: (...args: any[]) => void): this {
|
||||
this.client.on(eventName, listener)
|
||||
return this
|
||||
}
|
||||
public emit(eventName: EventType, ...args: any[]): boolean {
|
||||
return this.client.emit(eventName, ...args)
|
||||
}
|
||||
|
||||
public send(data: any) {
|
||||
this.client.send(data)
|
||||
return this.client.send(data)
|
||||
}
|
||||
|
||||
public close(code?: number, reason?: string) {
|
||||
this.client.close(code, reason)
|
||||
this.removeAllListeners()
|
||||
return this.client.close(code, reason)
|
||||
}
|
||||
}
|
||||
global.setGlobal('WebSocket', WebSocket)
|
||||
|
||||
@@ -4,10 +4,18 @@ export interface WebSocketHeader {
|
||||
}
|
||||
|
||||
export type EventType =
|
||||
| 'close'
|
||||
| 'error'
|
||||
| 'message'
|
||||
| 'open'
|
||||
| ClientEvent.open
|
||||
| ClientEvent.message
|
||||
| ClientEvent.close
|
||||
| ClientEvent.error
|
||||
|
||||
export enum ClientEvent {
|
||||
open = 'open',
|
||||
message = 'message',
|
||||
close = 'close',
|
||||
error = 'error',
|
||||
}
|
||||
|
||||
export interface Event {
|
||||
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { NettyWebSocket } from '.'
|
||||
import { WebSocketClientHandlerAdapter } from './adapter/handler'
|
||||
|
||||
const Throwable = Java.type('java.lang.Throwable')
|
||||
const RuntimeException = Java.type('java.lang.RuntimeException')
|
||||
|
||||
const CharsetUtil = Java.type('io.netty.util.CharsetUtil')
|
||||
const TextWebSocketFrame = Java.type('io.netty.handler.codec.http.websocketx.TextWebSocketFrame')
|
||||
const CloseWebSocketFrame = Java.type('io.netty.handler.codec.http.websocketx.CloseWebSocketFrame')
|
||||
@@ -20,7 +23,7 @@ export class WebSocketClientHandler extends WebSocketClientHandlerAdapter {
|
||||
return true
|
||||
}
|
||||
handlerAdded(ctx: any) {
|
||||
console.debug(`${ctx} handlerAdded`)
|
||||
this.client.onconnection({})
|
||||
if (ctx.newPromise) {
|
||||
this.handshakeFuture = ctx.newPromise()
|
||||
} else {
|
||||
@@ -28,20 +31,22 @@ export class WebSocketClientHandler extends WebSocketClientHandlerAdapter {
|
||||
}
|
||||
}
|
||||
channelActive(ctx: any) {
|
||||
console.debug(`${ctx} channelActive`)
|
||||
this.handshaker.handshake(ctx.channel())
|
||||
setTimeout(() => {
|
||||
this.abortHandshake(new Error('handshake timed out.'))
|
||||
}, 10000)
|
||||
}
|
||||
channelInactive(ctx: any) {
|
||||
console.debug(`${ctx} channelInactive`)
|
||||
this.client.onclose({ code: 0, reason: 'client connection channel inactive!' })
|
||||
this.client.close(1006, 'connection was closed abnormally.', true)
|
||||
}
|
||||
channelRead0(ctx: any, msg: any) {
|
||||
console.trace(`${ctx} channelRead0 ${msg}`)
|
||||
let ch = ctx.channel()
|
||||
if (!this.handshaker.isHandshakeComplete()) {
|
||||
// web socket client connected
|
||||
console.debug(`Netty Handler channelRead0 websocket client connected`)
|
||||
// websocket client connected
|
||||
this.handshaker.finishHandshake(ch, msg)
|
||||
this.handshakeFuture.setSuccess()
|
||||
this.client.onconnect({})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -54,14 +59,19 @@ export class WebSocketClientHandler extends WebSocketClientHandlerAdapter {
|
||||
if (frame instanceof TextWebSocketFrame) {
|
||||
this.client.onmessage({ data: frame.text() })
|
||||
} else if (frame instanceof CloseWebSocketFrame) {
|
||||
this.client.onclose({ code: 0, reason: 'server close connection!' })
|
||||
this.client.receiverClose(frame.statusCode(), frame.reasonText())
|
||||
}
|
||||
}
|
||||
abortHandshake(reason: Error) {
|
||||
if (this.handshakeFuture.isDone()) { return }
|
||||
if (!(reason instanceof Throwable)) {
|
||||
reason = new RuntimeException(reason)
|
||||
}
|
||||
this.handshakeFuture.setFailure(reason)
|
||||
}
|
||||
exceptionCaught(ctx: any, cause: Error) {
|
||||
console.debug(`${ctx} exceptionCaught ${cause}`)
|
||||
this.client.abortHandshake(cause)
|
||||
this.client.onerror({ error: cause })
|
||||
if (!this.handshakeFuture.isDone()) {
|
||||
this.handshakeFuture.setFailure(cause)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,6 +60,8 @@ export class NettyWebSocket extends Transport {
|
||||
private channel: any
|
||||
private b: any
|
||||
|
||||
private handler: any
|
||||
|
||||
constructor(url: string, subProtocol: string = '', headers: WebSocketHeader = {}) {
|
||||
super(url, subProtocol, headers)
|
||||
if (!url) {
|
||||
@@ -85,13 +87,9 @@ export class NettyWebSocket extends Transport {
|
||||
console.debug(`constructor NettyWebSocket url: ${url} scheme: ${this._schema} host: ${this._host} port: ${this._port} header: ${JSON.stringify(headers)}`)
|
||||
}
|
||||
getId() {
|
||||
if (this.channel?.id) {
|
||||
return this.channel?.id() + ''
|
||||
}
|
||||
return 'NettyWebSocket#' + channelCount.incrementAndGet()
|
||||
return `${this.channel?.id()}` || `NettyWebSocket#${channelCount.incrementAndGet()}`
|
||||
}
|
||||
doConnect() {
|
||||
console.debug('client NettyWebSocket doConnect', this._url)
|
||||
let uri = URI.create(this._url)
|
||||
let headers = new DefaultHttpHeaders()
|
||||
for (const key of Object.getOwnPropertyNames(this._headers || {})) {
|
||||
@@ -100,7 +98,7 @@ export class NettyWebSocket extends Transport {
|
||||
// Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00.
|
||||
// If you change it to V00, ping is not supported and remember to change
|
||||
// HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline.
|
||||
let handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory
|
||||
this.handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory
|
||||
.newHandshaker(uri, WebSocketVersion.V13, null, false, headers), this)
|
||||
this.b = new Bootstrap()
|
||||
this.b.group(group)
|
||||
@@ -111,7 +109,7 @@ export class NettyWebSocket extends Transport {
|
||||
if (this._schema == "wss") {
|
||||
if (SslContextBuilder) {
|
||||
let sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build()
|
||||
pipeline.addLast(sslCtx.newHandler(ch.alloc(), this._host, this._port))
|
||||
pipeline.addLast('ssl', sslCtx.newHandler(ch.alloc(), this._host, this._port))
|
||||
} else {
|
||||
let sslEngine = SSLContext.getDefault().createSSLEngine()
|
||||
sslEngine.setUseClientMode(true)
|
||||
@@ -120,35 +118,36 @@ export class NettyWebSocket extends Transport {
|
||||
}
|
||||
pipeline.addLast("http-codec", new HttpClientCodec())
|
||||
pipeline.addLast("aggregator", new HttpObjectAggregator(65536))
|
||||
pipeline.addLast("websocket", handler.getHandler())
|
||||
pipeline.addLast("websocket", this.handler.getHandler())
|
||||
}
|
||||
}))
|
||||
this.b.connect(this._host, this._port).addListener(new ChannelFutureListener((future: any) => {
|
||||
try {
|
||||
this.channel = future.sync().channel()
|
||||
this.onconnection({})
|
||||
handler.handshakeFuture.addListener(new ChannelFutureListener((future: any) => {
|
||||
try {
|
||||
future.sync()
|
||||
// only trigger onconnect when not have error
|
||||
this.onconnect({})
|
||||
} catch (error: any) {
|
||||
// ignore error exceptionCaught from handler
|
||||
// this.onerror({ error })
|
||||
}
|
||||
}))
|
||||
} catch (error: any) {
|
||||
this.onerror({ error })
|
||||
}
|
||||
}))
|
||||
try {
|
||||
this.channel = this.b.connect(this._host, this._port).sync().channel()
|
||||
this.handler.handshakeFuture.sync()
|
||||
} catch (error) {
|
||||
// ignore connect error
|
||||
// tigger error at handshakeFuture
|
||||
}
|
||||
}
|
||||
doSend(text: string) {
|
||||
this.channel.writeAndFlush(new TextWebSocketFrame(text))
|
||||
}
|
||||
doClose(code: number, reason: string) {
|
||||
this.channel.writeAndFlush(new CloseWebSocketFrame())
|
||||
this.channel.close()
|
||||
this.channel.closeFuture().addListener(new ChannelFutureListener(() => console.debug(`NettyWebSocket close code: ${code} reason: ${reason}`)))
|
||||
doClose(code: number, reason: string, wasClean: boolean = false) {
|
||||
console.debug(`Netty Client doClose code: ${code} reason: ${reason}`)
|
||||
if (this.readyState == WebSocket.CLOSING) {
|
||||
if (!this._closeFrameSent) {
|
||||
console.debug(`Netty Client doClose send close frame code: ${code} reason: ${reason}`)
|
||||
this.channel?.writeAndFlush(new CloseWebSocketFrame(code, reason))
|
||||
this._closeFrameSent = true
|
||||
}
|
||||
if (!this._closeFrameReceived && !wasClean) { return console.debug(`Netty Client doClose wait server send close`) }
|
||||
}
|
||||
this.channel?.closeFuture().addListener(new ChannelFutureListener(() => {
|
||||
this.onclose({ code, reason })
|
||||
}))
|
||||
}
|
||||
abortHandshake(reason: Error): void {
|
||||
this.handler.abortHandshake(reason)
|
||||
}
|
||||
getChannel() {
|
||||
return this.channel
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { EventEmitter } from 'events'
|
||||
import { WebSocket } from './index'
|
||||
import { CloseEvent, ErrorEvent, Event, MessageEvent, WebSocketHeader } from './interface'
|
||||
import { ClientEvent, CloseEvent, ErrorEvent, Event, MessageEvent, WebSocketHeader } from './interface'
|
||||
|
||||
export abstract class Transport extends EventEmitter {
|
||||
protected _url: string
|
||||
@@ -8,6 +8,9 @@ export abstract class Transport extends EventEmitter {
|
||||
protected _protocol: string
|
||||
protected _headers: WebSocketHeader = {}
|
||||
|
||||
protected _closeFrameReceived = false;
|
||||
protected _closeFrameSent = false;
|
||||
|
||||
constructor(uri: string, subProtocol: string = '', headers: WebSocketHeader = {}) {
|
||||
super()
|
||||
this._url = uri
|
||||
@@ -23,25 +26,22 @@ export abstract class Transport extends EventEmitter {
|
||||
return this._protocol
|
||||
}
|
||||
|
||||
get readyStatus() {
|
||||
get readyState() {
|
||||
return this._state
|
||||
}
|
||||
|
||||
set readyStatus(state: number) {
|
||||
set readyState(state: number) {
|
||||
this._state = state
|
||||
}
|
||||
|
||||
connect() {
|
||||
console.debug(`client Transport connect`)
|
||||
try {
|
||||
this.doConnect()
|
||||
} catch (error: any) {
|
||||
console.ex(error)
|
||||
this.onerror({ error })
|
||||
}
|
||||
this.doConnect()
|
||||
}
|
||||
|
||||
send(text: string) {
|
||||
if (this.readyState === WebSocket.CONNECTING) {
|
||||
throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
|
||||
}
|
||||
try {
|
||||
this.doSend(text)
|
||||
} catch (error: any) {
|
||||
@@ -49,19 +49,21 @@ export abstract class Transport extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
close(code: number = 0, reason: string = '') {
|
||||
if (this.readyStatus != WebSocket.CLOSING && this.readyStatus != WebSocket.CLOSED) {
|
||||
this.readyStatus = WebSocket.CLOSING
|
||||
try {
|
||||
this.onclose({ code, reason })
|
||||
this.doClose(code, reason)
|
||||
} catch (error: any) {
|
||||
this.onerror({ error })
|
||||
} finally {
|
||||
this.removeAllListeners()
|
||||
}
|
||||
} else {
|
||||
console.debug(`${this.id} call close but state is ${this.readyStatus}`)
|
||||
close(code: number = 1000, reason: string = '', wasClean: boolean = false) {
|
||||
if (this.readyState === WebSocket.CLOSED) return;
|
||||
if (this.readyState === WebSocket.CONNECTING) {
|
||||
const msg = 'WebSocket was closed before the connection was established';
|
||||
this.abortHandshake(new Error(msg));
|
||||
return;
|
||||
}
|
||||
if (code != 1000 && (code < 3000 || code > 4999)) {
|
||||
throw new Error(`The code must be either 1000, or between 3000 and 4999. ${code} is neither.`)
|
||||
}
|
||||
this.readyState = WebSocket.CLOSING
|
||||
try {
|
||||
this.doClose(code, reason, wasClean)
|
||||
} catch (error: any) {
|
||||
this.onerror({ error })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,33 +73,44 @@ export abstract class Transport extends EventEmitter {
|
||||
}
|
||||
|
||||
onconnect(event: Event) {
|
||||
if (this.readyStatus != WebSocket.OPEN) {
|
||||
this.readyStatus = WebSocket.OPEN
|
||||
this.emit('open', event)
|
||||
if (this.readyState != WebSocket.OPEN) {
|
||||
this.readyState = WebSocket.OPEN
|
||||
this.emit(ClientEvent.open, event)
|
||||
} else {
|
||||
console.debug(`${this.id} call onconnect but state is ${this.readyStatus}`)
|
||||
console.debug(`WebSocket Transport ${this.id} call onconnect but state is ${this.readyState}`)
|
||||
}
|
||||
}
|
||||
|
||||
onmessage(event: MessageEvent) {
|
||||
this.emit('message', event)
|
||||
this.emit(ClientEvent.message, event)
|
||||
}
|
||||
|
||||
onerror(event: ErrorEvent) {
|
||||
this.emit('error', event)
|
||||
this.emit(ClientEvent.error, event)
|
||||
}
|
||||
|
||||
onclose(event: CloseEvent) {
|
||||
if (this.readyStatus != WebSocket.CLOSED) {
|
||||
this.readyStatus = WebSocket.CLOSED
|
||||
this.emit('close', event)
|
||||
this.removeAllListeners()
|
||||
console.debug(`WebSocket Transport ${this.id} call onclose CloseEvent[code: ${event.code}, reason: ${event.reason}]`)
|
||||
if (this.readyState != WebSocket.CLOSED) {
|
||||
this.readyState = WebSocket.CLOSED
|
||||
this.emit(ClientEvent.close, event)
|
||||
} else {
|
||||
console.debug(`${this.id} call onclose but state is ${this.readyStatus} CloseEvent[code: ${event.code}, reason: ${event.reason}]`)
|
||||
console.debug(`WebSocket Transport ${this.id} call onclose but state is ${this.readyState} CloseEvent[code: ${event.code}, reason: ${event.reason}]`)
|
||||
}
|
||||
}
|
||||
abstract getId()
|
||||
abstract doConnect()
|
||||
abstract doSend(text: string)
|
||||
abstract doClose(code: number, reason: string)
|
||||
|
||||
receiverClose(code: number, reason: string) {
|
||||
console.debug(`Netty Handler receeve close code: ${code} reason: ${reason}`)
|
||||
// if not set code then set code to 1000
|
||||
if (code === -1) { code = this._closeFrameSent ? 1005 : 1001 }
|
||||
this.readyState = WebSocket.CLOSING
|
||||
this._closeFrameReceived = true;
|
||||
this.doClose(code, reason)
|
||||
}
|
||||
|
||||
abstract getId(): string
|
||||
abstract doConnect(): void
|
||||
abstract doSend(text: string): void
|
||||
abstract doClose(code: number, reason: string, wasClean?: boolean): void
|
||||
abstract abortHandshake(reason: Error): void
|
||||
}
|
||||
|
||||
@@ -711,6 +711,7 @@ export class Socket extends Emitter<{}, {}, SocketReservedEvents> {
|
||||
* @api private
|
||||
*/
|
||||
private resetPingTimeout() {
|
||||
// @ts-ignore
|
||||
this.clearTimeoutFn(this.pingTimeoutTimer)
|
||||
this.pingTimeoutTimer = this.setTimeoutFn(() => {
|
||||
this.onClose("ping timeout")
|
||||
@@ -919,6 +920,7 @@ export class Socket extends Emitter<{}, {}, SocketReservedEvents> {
|
||||
) {
|
||||
debug('socket close with reason: "%s"', reason)
|
||||
|
||||
// @ts-ignore
|
||||
// clear timers
|
||||
this.clearTimeoutFn(this.pingTimeoutTimer)
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/// <reference types="@ccms/nashorn" />
|
||||
/// <reference types="@javatypes/tomcat-websocket-api" />
|
||||
|
||||
import * as server from './server'
|
||||
import { WebSocketServer } from './server'
|
||||
import { Server, ServerOptions } from './socket.io'
|
||||
|
||||
interface SocketIOStatic {
|
||||
@@ -45,7 +45,7 @@ let singletonServer: Server
|
||||
let io: SocketStatic = function io(pipeline: any, options: Partial<JavaServerOptions>, singleton = true) {
|
||||
if (singleton) {
|
||||
if (!singletonServer) {
|
||||
singletonServer = new Server(server.attach(pipeline, options), options)
|
||||
singletonServer = new Server(WebSocketServer.attach(pipeline, options), options)
|
||||
process.emit('websocket.create', singletonServer)
|
||||
process.on('exit', () => {
|
||||
singletonServer.close()
|
||||
@@ -53,7 +53,7 @@ let io: SocketStatic = function io(pipeline: any, options: Partial<JavaServerOpt
|
||||
}
|
||||
return singletonServer
|
||||
}
|
||||
return new Server(server.attach(pipeline, options), options)
|
||||
return new Server(WebSocketServer.attach(pipeline, options), options)
|
||||
}
|
||||
io.Instance = Symbol("@ccms/websocket")
|
||||
export default io
|
||||
|
||||
@@ -26,6 +26,24 @@ export abstract class WebSocketServer extends EventEmitter {
|
||||
protected instance: any
|
||||
protected options: JavaServerOptions
|
||||
private clients: Map<string, WebSocketClient>
|
||||
|
||||
public static attach(instance, options) {
|
||||
if (!instance) { throw new Error('instance can\'t be undefiend!') }
|
||||
options = Object.assign({
|
||||
event: new EventEmitter(),
|
||||
path: '/ws',
|
||||
root: root + Java.type("java.io.File").separatorChar + 'wwwroot',
|
||||
}, options)
|
||||
let WebSocketServerImpl = undefined
|
||||
if (instance.class.name.startsWith('io.netty.channel')) {
|
||||
WebSocketServerImpl = require("./netty").NettyWebSocketServer
|
||||
} else {
|
||||
WebSocketServerImpl = require("./tomcat").TomcatWebSocketServer
|
||||
}
|
||||
console.debug('create websocket server from ' + WebSocketServerImpl.name)
|
||||
return new WebSocketServerImpl(instance, options)
|
||||
}
|
||||
|
||||
constructor(instance: any, options: JavaServerOptions) {
|
||||
super()
|
||||
this.instance = instance
|
||||
@@ -69,20 +87,3 @@ export abstract class WebSocketServer extends EventEmitter {
|
||||
protected abstract getSocket(handler: any): WebSocketClient
|
||||
protected abstract doClose(): void
|
||||
}
|
||||
|
||||
export const attach = (instance, options) => {
|
||||
if (!instance) { throw new Error('instance can\'t be undefiend!') }
|
||||
options = Object.assign({
|
||||
event: new EventEmitter(),
|
||||
path: '/ws',
|
||||
root: root + Java.type("java.io.File").separatorChar + 'wwwroot',
|
||||
}, options)
|
||||
let WebSocketServerImpl = undefined
|
||||
if (instance.class.name.startsWith('io.netty.channel')) {
|
||||
WebSocketServerImpl = require("./netty").NettyWebSocketServer
|
||||
} else {
|
||||
WebSocketServerImpl = require("./tomcat").TomcatWebSocketServer
|
||||
}
|
||||
console.debug('create websocket server from ' + WebSocketServerImpl.name)
|
||||
return new WebSocketServerImpl(instance, options)
|
||||
}
|
||||
|
||||
4862
pnpm-lock.yaml
generated
Normal file
4862
pnpm-lock.yaml
generated
Normal file
File diff suppressed because it is too large
Load Diff
2
pnpm-workspace.yaml
Normal file
2
pnpm-workspace.yaml
Normal file
@@ -0,0 +1,2 @@
|
||||
packages:
|
||||
- "packages/*"
|
||||
@@ -1,6 +1,8 @@
|
||||
#!/bin/bash
|
||||
DISTTAG=${1:latest}
|
||||
for package in `ls packages`; do
|
||||
echo $package
|
||||
pushd packages/$package
|
||||
npm publish --access=public --registry https://registry.npmjs.org
|
||||
npm publish --tag ${DISTTAG} --access=public --registry https://registry.npmjs.org
|
||||
popd
|
||||
done
|
||||
|
||||
4
script/sync.sh
Executable file
4
script/sync.sh
Executable file
@@ -0,0 +1,4 @@
|
||||
#!/bin/bash
|
||||
for PACKAGE in `ls packages`;do
|
||||
echo "${PACKAGE} $(curl -s "https://registry-direct.npmmirror.com/@ccms/${PACKAGE}/sync?sync_upstream=true" -X 'PUT')"
|
||||
done
|
||||
Reference in New Issue
Block a user