Compare commits

...

41 Commits

Author SHA1 Message Date
0e4ae5d74f v0.28.0-beta.3 2023-08-16 11:50:54 +08:00
bdad4136ec fix: websocket close logic 2023-08-16 11:47:36 +08:00
a0866c1085 feat: add plugin self method 2023-08-12 17:14:57 +08:00
afd3f91a3f delete: amqp kv web spring package 2023-08-12 17:13:41 +08:00
e70c78a255 v0.28.0-beta.2 2023-08-08 18:11:44 +08:00
9cfac1672a feat: optimize websocket client 2023-08-08 18:06:34 +08:00
9126ec8035 v0.28.0-beta.1 2023-07-30 16:46:42 +08:00
23bc6068b5 feat: optimize websocket client 2023-07-30 16:46:34 +08:00
27b428fbe2 v0.28.0-beta.0 2023-07-26 17:37:26 +08:00
c07f1131c4 refactor: optimize plugin system 2023-07-26 17:35:33 +08:00
002f2c47c6 v0.27.6 2023-07-19 18:22:35 +08:00
8633d9ea95 fix: particle spawner error 2023-07-19 18:21:56 +08:00
07a5d0c8de feat: add plugin checker
Signed-off-by: MiaoWoo <admin@yumc.pw>
2023-02-18 16:01:15 +08:00
dd76e563c8 feat: add qrcode package
Signed-off-by: MiaoWoo <admin@yumc.pw>
2023-02-18 15:21:42 +08:00
7b85ff5b7c feat: 同步 socket.io 上游代码
Signed-off-by: MiaoWoo <admin@yumc.pw>
2023-02-09 13:49:48 +08:00
359aeb9d63 chore: remove client package
Signed-off-by: MiaoWoo <admin@yumc.pw>
2023-02-09 12:44:04 +08:00
3901d9fb5f feat: 更新依赖版本
Signed-off-by: MiaoWoo <admin@yumc.pw>
2023-02-08 17:03:17 +08:00
c2867da047 v0.26.0 2023-02-08 16:24:09 +08:00
65832c9fae feat: 完善粒子播放
Signed-off-by: MiaoWoo <admin@yumc.pw>
2023-02-08 16:23:05 +08:00
d9dffa704d v2.25.1 2022-11-28 17:30:45 +08:00
b39f29de6a v2.25.1-beta.1 2022-11-28 17:18:50 +08:00
56334c6f6e v0.25.1-beta.0 2022-11-28 17:15:39 +08:00
72673b2a67 feat: optimize event slow exec cache
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-11-28 17:14:29 +08:00
597bdb721a v0.25.0 2022-11-22 17:37:54 +08:00
6e0456d777 feat: 添加注释
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-11-22 17:35:13 +08:00
fb67b06230 v0.25.0-beta.0 2022-11-22 17:12:22 +08:00
203560dcf2 chore: add --verify-access
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-11-22 17:10:15 +08:00
3f58f5992c style: xml-http-request.ts
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-11-22 15:50:54 +08:00
ac16754c9c fix: buffer polyfill error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-11-22 13:48:41 +08:00
42d637dd63 fix: rename Buffer to BufferPolyfill
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-11-21 23:27:12 +08:00
df0d246136 feat: upgrade socket.io to v4
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-11-21 23:18:39 +08:00
e563e1b507 feat: update chat to 1.19.2
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-11-21 23:17:14 +08:00
3b822c613a dep: update dependencies
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-11-21 14:29:17 +08:00
2967c2a1fe v0.24.3 2022-10-14 14:12:02 +08:00
1c579c9789 feat: framework optimization
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-10-14 10:07:36 +08:00
2fe9bce2ea v0.24.2 2022-07-17 07:13:54 +08:00
496d278a93 fix: item fromJson error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-07-17 07:11:36 +08:00
bdf674b678 v0.24.1 2022-07-07 00:54:16 +08:00
67fe13deac fix: migrate config error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-07-07 00:51:10 +08:00
30846cdc87 v0.24.0 2022-07-06 22:01:09 +08:00
d8d03149df fix: some bug
Signed-off-by: MiaoWoo <admin@yumc.pw>
2022-07-06 21:57:36 +08:00
161 changed files with 13221 additions and 7608 deletions

1
.gitignore vendored
View File

@@ -1,3 +1,4 @@
.yarn*
.vscode
.theia
node_modules

View File

@@ -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
```

View File

@@ -1,16 +1,15 @@
{
"version": "0.23.0",
"useWorkspaces": true,
"npmClient": "yarn",
"packages": [
"packages/*"
],
"command": {
"run": {
"stream": true
}
},
"publishConfig": {
"access": "public"
"version": "0.28.0-beta.3",
"npmClient": "yarn",
"packages": [
"packages/*"
],
"command": {
"run": {
"stream": true
}
},
"publishConfig": {
"access": "public"
}
}

View File

@@ -10,16 +10,19 @@
"clean": "lerna run clean",
"watch": "lerna run watch --parallel",
"build": "lerna run build",
"ug": "yarn upgrade-interactive --latest",
"ug": "yarn upgrade-interactive",
"np": "./script/push.sh",
"lsp": "npm login --registry=https://registry.npmjs.org --scope=@ccms",
"lp": "lerna publish --registry https://registry.npmjs.org",
"lpb": "lerna publish --registry https://registry.npmjs.org --canary --preid beta --pre-dist-tag beta"
"lsp": "npm login -scope=@ccms",
"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": "^4.0.0"
"lerna": "^7.1.4"
}
}

View File

@@ -1,35 +0,0 @@
{
"name": "@ccms/amqp",
"version": "0.23.0",
"description": "MiaoScript amqp package",
"keywords": [
"miaoscript",
"minecraft",
"bukkit",
"sponge"
],
"author": "MiaoWoo <admin@yumc.pw>",
"homepage": "https://github.com/circlecloud/ms.git",
"license": "ISC",
"main": "dist/index.js",
"scripts": {
"clean": "rimraf dist",
"watch": "tsc --watch",
"build": "yarn clean && tsc",
"test": "echo \"Error: run tests from root\" && exit 1"
},
"dependencies": {
"@ccms/api": "^0.23.0",
"@ccms/common": "^0.23.0",
"@ccms/container": "^0.23.0"
},
"devDependencies": {
"@ccms/nashorn": "^0.23.0",
"@javatypes/amqp-client": "^0.0.3",
"@javatypes/spring-amqp": "^0.0.3",
"@javatypes/spring-rabbit": "^0.0.3",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^4.6.3"
}
}

View File

@@ -1,17 +0,0 @@
import { ConnectionFactoryAdapter } from "./connection"
import { RabbitTemplateAdapter } from "./template"
import { JSClass } from "@ccms/container"
export const RabbitAdmin = Java.type('org.springframework.amqp.rabbit.core.RabbitAdmin')
export class RabbitAdminAdapter {
@JSClass('org.springframework.amqp.rabbit.core.RabbitAdmin')
private RabbitAdmin: org.springframework.amqp.rabbit.core.RabbitAdmin
private _Handler: org.springframework.amqp.rabbit.core.RabbitAdmin
constructor(config: RabbitTemplateAdapter | org.springframework.amqp.rabbit.core.RabbitTemplate | ConnectionFactoryAdapter | org.springframework.amqp.rabbit.connection.ConnectionFactory) {
this._Handler = new RabbitAdmin((config instanceof RabbitTemplateAdapter || config instanceof ConnectionFactoryAdapter) ? config.getHandler() : config)
}
getHandler(): org.springframework.amqp.rabbit.core.RabbitAdmin {
return this._Handler
}
}

View File

@@ -1,30 +0,0 @@
export const ConfirmCallback = Java.type('org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback')
export const ReturnCallback = Java.type('org.springframework.amqp.rabbit.core.RabbitTemplate.ReturnCallback')
export abstract class ConfirmCallbackAdapter {
private _Handler: org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback
constructor() {
let ConfirmCallbackImpl = Java.extend(ReturnCallback, {
confirm: (correlationData: org.springframework.amqp.rabbit.connection.CorrelationData, ack: boolean, cause: string) => this.confirm(correlationData, ack, cause)
})
this._Handler = new ConfirmCallbackImpl()
}
abstract confirm(correlationData: org.springframework.amqp.rabbit.connection.CorrelationData, ack: boolean, cause: string)
getHandler() {
return this._Handler
}
}
export abstract class ReturnCallbackAdapter {
private _Handler: org.springframework.amqp.rabbit.core.RabbitTemplate.ReturnCallback
constructor() {
let ReturnCallbackImpl = Java.extend(ReturnCallback, {
returnedMessage: (message: org.springframework.amqp.core.Message, replyCode: number, replyText: string, exchange: string, routingKey: string) => this.returnedMessage(message, replyCode, replyText, exchange, routingKey)
})
this._Handler = new ReturnCallbackImpl()
}
abstract returnedMessage(message: org.springframework.amqp.core.Message, replyCode: number, replyText: string, exchange: string, routingKey: string)
getHandler() {
return this._Handler
}
}

View File

@@ -1,31 +0,0 @@
import threadPool from '@ccms/common/dist/thread-pool'
export const ConnectionFactory = Java.type('org.springframework.amqp.rabbit.connection.ConnectionFactory')
const CachingConnectionFactory = Java.type('org.springframework.amqp.rabbit.connection.CachingConnectionFactory')
interface ConnectionConfig {
url: string,
username?: string,
password?: string,
publisherConfirms?: boolean
cacheSize?: number
}
export class ConnectionFactoryAdapter {
private _Handler: org.springframework.amqp.rabbit.connection.CachingConnectionFactory
constructor(config: ConnectionConfig) {
if (!config.url) { throw new Error('Connection UrI Can\'t be undefiend!') }
config = { publisherConfirms: true, cacheSize: 50, ...config }
this._Handler = new CachingConnectionFactory(new java.net.URI(config.url))
config.username && this._Handler.setUsername(config.username)
config.password && this._Handler.setPassword(config.password)
this._Handler.setPublisherConfirms(config.publisherConfirms)
this._Handler.setExecutor(threadPool.create({
groupName: '@ccms/amqp-rabbit'
}))
this._Handler.setChannelCacheSize(config.cacheSize)
}
getHandler() {
return this._Handler
}
}

View File

@@ -1,30 +0,0 @@
import { ConnectionFactoryAdapter, ConnectionFactory } from "./connection"
import { ChannelAwareMessageListenerAdapter, ChannelAwareMessageListener } from "./listener"
export const SimpleMessageListenerContainer = org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer
export const AcknowledgeMode = org.springframework.amqp.core.AcknowledgeMode
interface ContainerConfig {
connectionFactory: ConnectionFactoryAdapter | typeof ConnectionFactory
queueNames: string[]
messageListener: ChannelAwareMessageListenerAdapter | typeof ChannelAwareMessageListener
maxConcurrentConsumers?: number
concurrentConsumers?: number
acknowledgeMode?: org.springframework.amqp.core.AcknowledgeMode
}
export class MessageListenerContainerAdapter {
private _Handler: org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer
constructor(config: ContainerConfig) {
config = { concurrentConsumers: 5, maxConcurrentConsumers: 10, acknowledgeMode: AcknowledgeMode.AUTO, ...config }
this._Handler = new SimpleMessageListenerContainer(config.connectionFactory instanceof ConnectionFactoryAdapter ? config.connectionFactory.getHandler() : config.connectionFactory)
//@ts-ignore
this._Handler.setQueueNames(config.queueNames)
this._Handler.setMaxConcurrentConsumers(config.maxConcurrentConsumers)
this._Handler.setConcurrentConsumers(config.concurrentConsumers)
this._Handler.setAcknowledgeMode(config.acknowledgeMode)
this._Handler.setMessageListener(config.messageListener instanceof ChannelAwareMessageListenerAdapter ? config.messageListener.getHandler() : config.messageListener)
}
getHandler() {
return this._Handler
}
}

View File

@@ -1,37 +0,0 @@
const JavaString = Java.type('java.lang.String')
const MessageProperties = org.springframework.amqp.core.MessageProperties
const Message = org.springframework.amqp.core.Message
export const MessageConverter = Java.type('org.springframework.amqp.support.converter.MessageConverter')
export class MessageConverterAdapter {
private _Handler: org.springframework.amqp.support.converter.MessageConverter
constructor() {
var MessageConverterImpl = Java.extend(MessageConverter, {
toMessage: (object: any, messageProperties: org.springframework.amqp.core.MessageProperties) => this.toMessage(object, messageProperties),
fromMessage: (message: org.springframework.amqp.core.Message) => this.fromMessage(message)
})
this._Handler = new MessageConverterImpl()
}
toMessage(object: any, messageProperties: org.springframework.amqp.core.MessageProperties) {
if (typeof object == "string") {
messageProperties.setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN)
return new Message(new JavaString(object).getBytes(), messageProperties)
} else {
messageProperties.setContentType(MessageProperties.CONTENT_TYPE_JSON)
return new Message(new JavaString(JSON.stringify(object)).getBytes(), messageProperties)
}
}
fromMessage(message: org.springframework.amqp.core.Message) {
if (message.getMessageProperties().getContentType() == MessageProperties.CONTENT_TYPE_TEXT_PLAIN) {
return new JavaString(message.getBody(), message.getMessageProperties().getContentEncoding())
}
if (message.getMessageProperties().getContentType() == MessageProperties.CONTENT_TYPE_JSON) {
return JSON.parse(new JavaString(message.getBody(), message.getMessageProperties().getContentEncoding()))
}
return message
}
getHandler() {
return this._Handler
}
}

View File

@@ -1,7 +0,0 @@
export * from './admin'
export * from './callback'
export * from './connection'
export * from './container'
export * from './converter'
export * from './listener'
export * from './template'

View File

@@ -1,49 +0,0 @@
const JavaString = Java.type('java.lang.String')
export const MessageProperties = org.springframework.amqp.core.MessageProperties
export const ChannelAwareMessageListener = Java.type('org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener')
export const AmqpRejectAndDontRequeueException = org.springframework.amqp.AmqpRejectAndDontRequeueException
export const Channel: com.rabbitmq.client.Channel = Java.type('com.rabbitmq.client.Channel')
export const Message = org.springframework.amqp.core.Message
export type MessageHandler<T> = (content: T, message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel) => any
export abstract class ChannelAwareMessageListenerAdapter<T = any> {
private _Handler: org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener
constructor(manual: boolean = false) {
let ChannelAwareMessageListenerImpl = Java.extend(ChannelAwareMessageListener, {
onMessage: (message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel) => {
let content = new JavaString(message.getBody(), message.getMessageProperties().getContentEncoding() || "UTF-8")
try {
if (message.getMessageProperties().getContentType() == MessageProperties.CONTENT_TYPE_JSON) {
content = JSON.parse(content)
}
} catch (error: any) {
if (manual) {
channel.basicReject(message.getMessageProperties().getDeliveryTag(), true)
} else {
throw new AmqpRejectAndDontRequeueException(`${error}`, error)
}
}
manual ? this.manualOnMessage(content, message, channel) : this.onMessage(content, message, channel)
}
})
this._Handler = new ChannelAwareMessageListenerImpl()
}
abstract onMessage(content: T, message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel): any
onError(error: Error, message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel): any { }
getHandler() {
return this._Handler
}
private manualOnMessage(content: T, message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel) {
let deliveryTag = message.getMessageProperties().getDeliveryTag()
try {
if (this.onMessage(content, message, channel)) {
channel.basicAck(deliveryTag, false)
} else if (message.getMessageProperties().getRedelivered()) {
channel.basicReject(deliveryTag, true)
} else {
channel.basicNack(deliveryTag, false, true)
}
} catch (error: any) {
channel.basicReject(deliveryTag, this.onError(error, message, channel))
}
}
}

View File

@@ -1,27 +0,0 @@
import { MessageConverterAdapter } from "./converter"
import { ConnectionFactoryAdapter } from "./connection"
import { ConfirmCallbackAdapter, ReturnCallbackAdapter } from "./callback"
export const RabbitTemplate = Java.type('org.springframework.amqp.rabbit.core.RabbitTemplate')
interface TemplateConfig {
connectionFactory: ConnectionFactoryAdapter | org.springframework.amqp.rabbit.connection.ConnectionFactory
confirmCallback?: ConfirmCallbackAdapter
returnCallback?: ReturnCallbackAdapter
messageConverter?: MessageConverterAdapter
}
export class RabbitTemplateAdapter {
private _Handler: org.springframework.amqp.rabbit.core.RabbitTemplate
constructor(config: TemplateConfig) {
config = { messageConverter: new MessageConverterAdapter(), ...config }
console.debug(JSON.stringify(config))
this._Handler = new RabbitTemplate(config.connectionFactory instanceof ConnectionFactoryAdapter ? config.connectionFactory.getHandler() : config.connectionFactory)
config.returnCallback && this._Handler.setReturnCallback(config.returnCallback.getHandler())
config.confirmCallback && this._Handler.setConfirmCallback(config.confirmCallback.getHandler())
config.messageConverter && this._Handler.setMessageConverter(config.messageConverter.getHandler())
}
getHandler() {
return this._Handler
}
}

View File

@@ -1,89 +0,0 @@
import { JSClass } from "@ccms/container"
import { RabbitAdminAdapter, MessageListenerContainerAdapter, AcknowledgeMode, MessageHandler, ChannelAwareMessageListenerAdapter } from "./adapter"
export class AmqpAdmin {
@JSClass('org.springframework.amqp.core.TopicExchange')
private TopicExchange: typeof org.springframework.amqp.core.TopicExchange
@JSClass('org.springframework.amqp.core.Queue')
private Queue: typeof org.springframework.amqp.core.Queue
@JSClass('org.springframework.amqp.core.Binding')
private Binding: typeof org.springframework.amqp.core.Binding
@JSClass('org.springframework.amqp.rabbit.core.RabbitAdmin')
private RabbitAdmin: typeof org.springframework.amqp.rabbit.core.RabbitAdmin
@JSClass('org.springframework.amqp.core.Binding.DestinationType')
private DestinationType: org.springframework.amqp.core.Binding.DestinationType
private amqpAdmin: org.springframework.amqp.rabbit.core.RabbitAdmin
constructor(amqpAdmin: org.springframework.amqp.rabbit.core.RabbitAdmin | any) {
if (amqpAdmin instanceof this.RabbitAdmin) {
this.amqpAdmin = amqpAdmin
} else if (amqpAdmin instanceof RabbitAdminAdapter) {
this.amqpAdmin = amqpAdmin.getHandler()
} else {
this.amqpAdmin = new RabbitAdminAdapter(amqpAdmin).getHandler()
}
}
getHandler() {
return this.amqpAdmin
}
getQueueProperties(name: string) {
return this.amqpAdmin.getQueueProperties(name)
}
declareExchange(name: string) {
let exchange = new this.TopicExchange(name, true, false)
this.amqpAdmin.declareExchange(exchange)
return this
}
declareQueue(name: string) {
let queue = new this.Queue(name, true)
this.amqpAdmin.declareQueue(queue)
return this
}
declareBinding(queue: string, exchange: string, routerKey: string, argument: any = null) {
let binding = new this.Binding(queue, org.springframework.amqp.core.Binding.DestinationType.QUEUE, exchange, routerKey, argument)
this.amqpAdmin.declareBinding(binding)
return this
}
declareQueueAndBindExchange(queue: string, exchange: string, routerKey: string) {
return this.declareQueue(queue).declareExchange(exchange).declareBinding(queue, exchange, routerKey)
}
createContainer<T>(queue: string, listener: MessageHandler<T>, acknowledgeMode = AcknowledgeMode.AUTO) {
let connection = this.amqpAdmin.getRabbitTemplate().getConnectionFactory()
return new MessageListenerContainerAdapter({
connectionFactory: connection,
queueNames: [queue],
messageListener: new SimpleMessageHandler(listener),
acknowledgeMode: acknowledgeMode
}).getHandler()
}
send()
send() {
}
getTemplate() {
return this.amqpAdmin.getRabbitTemplate()
}
close() {
this.getTemplate().stop()
}
}
export class SimpleMessageHandler extends ChannelAwareMessageListenerAdapter {
constructor(private handler: MessageHandler<any>) {
super()
}
onMessage(content: any, message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel) {
return this.handler(content, message, channel)
}
}

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/api",
"version": "0.23.0",
"version": "0.28.0-beta.3",
"description": "MiaoScript api package",
"keywords": [
"miaoscript",
@@ -19,16 +19,16 @@
"test": "echo \"Error: run tests from root\" && exit 1"
},
"dependencies": {
"@ccms/common": "^0.23.0",
"@ccms/container": "^0.23.0",
"@ccms/polyfill": "^0.23.0",
"@ccms/common": "^0.28.0-beta.3",
"@ccms/container": "^0.28.0-beta.3",
"@ccms/polyfill": "^0.28.0-beta.3",
"base64-js": "^1.5.1",
"source-map-builder": "^0.0.7"
},
"devDependencies": {
"@types/base64-js": "^1.3.0",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^4.6.3"
"rimraf": "^4.1.2",
"typescript": "^4.9.5"
}
}

View File

@@ -1,7 +0,0 @@
export namespace amqp {
export const Manager = Symbol('AmqpManager')
export namespace rabbit {
export const Admin = Symbol('RabbitAdmin')
export const Template = Symbol('RabbitTemplate')
}
}

View File

@@ -5,6 +5,13 @@ 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 cacheSlowCommandKey = {};
private cacheSlowCompleteKey = {};
/**
* 注册插件命令
* @param plugin 插件
@@ -48,6 +55,8 @@ export namespace command {
let result = executor(sender, command, Java.from(args))
let cost = Date.now() - time
if (cost > global.ScriptSlowExecuteTime) {
let commandKey = `${plugin.description.name}-${command}-${sender.name}`
if (!this.cacheSlowCommandKey[commandKey]) { return this.cacheSlowCommandKey[commandKey] = cost }
console.i18n("ms.api.command.execute.slow", {
player: sender.name,
plugin: plugin.description.name,
@@ -58,23 +67,17 @@ export namespace command {
}
return result
} catch (ex: any) {
console.i18n("ms.api.command.execute.error", {
let message = i18n.translate("ms.api.command.execute.error", {
player: sender.name,
plugin: plugin.description.name,
command,
args: Java.from(args).join(' '),
ex
})
console.console(message)
console.ex(ex)
if (sender.name != 'CONSOLE') {
console.sender(sender, [i18n.translate("ms.api.command.execute.error", {
player: sender.name,
plugin: plugin.description.name,
command,
args: Java.from(args).join(' '),
ex
}),
...console.stack(ex)])
console.sender(sender, [message, ...console.stack(ex)])
}
return true
}
@@ -89,6 +92,8 @@ export namespace command {
let result = this.copyPartialMatches(complete, token)
let cost = Date.now() - time
if (cost > global.ScriptSlowExecuteTime) {
let completerKey = `${plugin.description.name}-${command}-${sender.name}`
if (!this.cacheSlowCompleteKey[completerKey]) { return this.cacheSlowCompleteKey[completerKey] = cost }
console.i18n("ms.api.command.tab.completer.slow", {
player: sender.name,
plugin: plugin.description.name,
@@ -99,25 +104,17 @@ export namespace command {
}
return result
} catch (ex: any) {
console.i18n("ms.api.command.tab.completer.error", {
let message = i18n.translate("ms.api.command.tab.completer.error", {
player: sender.name,
plugin: plugin.description.name,
command,
args: Java.from(args).join(' '),
ex
})
console.console(message)
console.ex(ex)
if (sender.name != 'CONSOLE') {
console.sender(sender, [
i18n.translate("ms.api.command.tab.completer.error", {
player: sender.name,
plugin: plugin.description.name,
command,
args: Java.from(args).join(' '),
ex
}),
...console.stack(ex)
])
console.sender(sender, [message, ...console.stack(ex)])
}
return []
}

View File

@@ -44,13 +44,13 @@ export namespace jsconsole {
let file = Paths.get(Paths.get(fileName, '..', sourceMappingURL).toFile().getCanonicalPath()).toFile()
if (file.exists()) {
sourceContent = base.read(file)
sourceFileMaps[fileName] = file.getCanonicalPath()
} else if (global.debug) {
console.debug('readSourceMap can\'t found', fileName, 'source map file', sourceMappingURL)
}
}
if (sourceContent) {
sourceMaps[fileName] = new SourceMapBuilder(JSON.parse(sourceContent))
sourceFileMaps[fileName] = Paths.get(fileName, '..', sourceMaps[fileName].sources[0]).toFile().getCanonicalPath()
}
}
}
@@ -88,9 +88,9 @@ export namespace jsconsole {
let { fileName, lineNumber } = readSourceMap(trace.fileName, trace.lineNumber)
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
if (color) {
cache.push(` §e->§c ${fileName}:${lineNumber} => §4${trace.methodName}`)
cache.push(` §e->§c ${fileName}:${lineNumber}(${trace.lineNumber}) => §4${trace.methodName}`)
} else {
cache.push(` -> ${fileName}:${lineNumber} => ${trace.methodName}`)
cache.push(` -> ${fileName}:${lineNumber}(${trace.lineNumber}) => ${trace.methodName}`)
}
} else {
let className = trace.className

View File

@@ -30,6 +30,10 @@ export namespace database {
* 链接属性
*/
properties?: { [key: string]: any }
/**
* 调试模式
*/
debug?: boolean
}
@injectable()

View File

@@ -25,7 +25,8 @@ export namespace event {
public EventPriority = EventPriority;
private mapEvent = [];
private listenerMap = [];
private pluginEventMap = [];
private cacheSlowEventKey = {};
protected baseEventDir = '';
@@ -92,17 +93,23 @@ export namespace event {
return eventCls
}
execute(name, exec, eventCls) {
/**
* 创建命令执行器
* @param name 插件名称
* @param exec 执行方法
* @param eventCls 事件类
* @returns
*/
createExecute(name, exec, eventCls) {
return (...args: any[]) => {
let event = args[args.length - 1]
try {
let event = args[args.length - 1]
if (eventCls.isAssignableFrom(event.getClass())) {
let time = Date.now()
exec(event)
let cost = Date.now() - time
if (cost > global.ScriptSlowExecuteTime) {
console.i18n("ms.api.event.execute.slow", { name, event: this.class2Name(eventCls), cost })
}
if (!eventCls.isAssignableFrom(event.getClass())) { return }
let time = Date.now(); exec(event); let cost = Date.now() - time
if (cost > global.ScriptSlowExecuteTime && !event.async) {
let eventKey = `${name}-${this.class2Name(eventCls)}`
if (!this.cacheSlowEventKey[eventKey]) { return this.cacheSlowEventKey[eventKey] = cost }
console.i18n("ms.api.event.execute.slow", { name, event: this.class2Name(eventCls), cost })
}
} catch (ex: any) {
console.i18n("ms.api.event.execute.error", { name, event: this.class2Name(eventCls), ex })
@@ -113,17 +120,17 @@ export namespace event {
/**
* 添加事件监听
* @param plugin {any}
* @param event {string}
* @param exec {function}
* @param priority {string} [LOWEST,LOW,NORMAL,HIGH,HIGHEST,MONITOR]
* @param ignoreCancel
* @param plugin {any} 插件
* @param event {string} 事件名称
* @param exec {function} 事件执行器
* @param priority {string} [LOWEST,LOW,NORMAL,HIGH,HIGHEST,MONITOR] 优先级
* @param ignoreCancel 是否忽略已取消事件
*/
listen(plugin: any, event: string, exec: (event: any) => void, priority: EventPriority = EventPriority.NORMAL, ignoreCancel = false) {
if (!plugin || !plugin.description || !plugin.description.name) throw new TypeError(i18n.translate("ms.api.event.listen.plugin.name.empty"))
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
@@ -133,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.execute(name, exec, 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)
@@ -152,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,
@@ -169,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 => off())
delete this.listenerMap[plugin.description.name]
eventCache.forEach((off: () => any) => off())
delete this.pluginEventMap[plugin.description.name]
}
}

View File

@@ -1,7 +1,5 @@
import "@ccms/nashorn"
export * from './web'
export * from './amqp'
export * from './chat'
export * from './task'
export * from './item'

View File

@@ -5,7 +5,7 @@ export namespace item {
export abstract class Item {
abstract builder(): ItemBuilder
abstract toJson(item: any): string
abstract fromJSON(json: string): any
abstract fromJson(json: string): any
}
export interface ItemBuilder {
from(item: any): ItemBuilder

View File

@@ -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)
}
/**
* 表示一个特效对象
*
@@ -23,6 +29,11 @@ export namespace particle {
private extra: number = 0;
private data: Object = null;
/**
* Only Show To Player
*/
private player: any
constructor() {
this.uuid = UUID.randomUUID().toString()
}
@@ -105,6 +116,15 @@ export namespace particle {
return this
}
getPlayer() {
return this.player
}
setPlayer(player) {
this.player = player
return this
}
/**
* 通过给定一个坐标就可以使用已经指定的参数来播放粒子
*
@@ -112,9 +132,14 @@ export namespace particle {
*/
spawn(location: any) {
if (!this.spawner) throw new Error(`particle ${this.uuid} not set spawner can't spawn!`)
this.spawner.spawn(location, this)
if (this.player) {
this.spawner.spawnToPlayer(this.player, location, this)
} else {
this.spawner.spawn(location, this)
}
}
}
/**
* 表示一条线
*
@@ -158,8 +183,7 @@ export namespace particle {
show() {
for (let i = 0; i < this.length; i += this.step) {
let vectorTemp = this.vector.clone().multiply(i)
this.spawn(this.start.clone().add(vectorTemp))
this.spawn(this.start.clone().add(this.vector.clone().multiply(i)))
}
}
@@ -234,15 +258,6 @@ export namespace particle {
this.length = this.vector.length()
this.vector.normalize()
}
public static buildLine(locA: any, locB: any, step: number, particle: any) {
let vectorAB = locB.clone().subtract(locA).toVector()
let vectorLength = vectorAB.length()
vectorAB.normalize()
for (let i = 0; i < vectorLength; i += step) {
ParticleManager.globalSpawner.spawn(locA.clone().add(vectorAB.clone().multiply(i)), particle)
}
}
}
/**
* 表示一个弧
@@ -331,9 +346,10 @@ export namespace particle {
@injectable()
export abstract class ParticleManager {
public static globalSpawner: ParticleSpawner = undefined
@Autowired()
private taskManager: task.TaskManager
@Autowired()
private particleSpawner: particle.ParticleSpawner
protected taskId: java.util.concurrent.atomic.AtomicInteger
protected cacheTasks = new Map<string, ParticleTask>()
@@ -354,6 +370,10 @@ export namespace particle {
return this.taskManager
}
public getParticleSpawner() {
return this.particleSpawner
}
public create(particle: Particle, plugin?: plugin.Plugin) {
let uuid = particle.getUUID()
if (this.cacheTasks.has(uuid)) {
@@ -389,14 +409,12 @@ export namespace particle {
}
}
protected create0(owner: plugin.Plugin, particle: Particle): ParticleTask {
particle.setSpawner(this.getGlobalSpawner())
particle.setSpawner(this.getParticleSpawner())
return new ParticleTask(owner, particle, this)
}
protected abstract getGlobalSpawner(): ParticleSpawner
}
export class ParticleTask {
private particle: Particle
private isAsync: boolean = false
private interval: number = 0
@@ -486,9 +504,4 @@ export namespace particle {
}
}
}
export abstract class ParticleSpawner {
abstract spawnParticle(location: any, particle: any, count: number)
abstract spawn(location: any, particle: Particle)
}
}

View File

@@ -155,7 +155,11 @@ export namespace plugin {
*/
cname?: string
/**
* 插件等级 付费插件自动注入
* 付费插件ID
*/
pid?: number
/**
* 付费插件等级 付费插件自动注入
*/
level?: number
/**

View File

@@ -29,6 +29,7 @@ export namespace server {
origin: any
[key: string]: any
}
@injectable()
export abstract class NativePluginManager {
list(): NativePlugin[] {
@@ -53,6 +54,7 @@ export namespace server {
throw new Error("Method not implemented.")
}
}
/**
* MiaoScript Server
*/
@@ -98,6 +100,7 @@ export namespace server {
throw new Error("Method not implemented.")
}
}
@injectable()
export class ServerChecker {
@Autowired(ServerType)
@@ -116,6 +119,22 @@ export namespace server {
}
}
}
@injectable()
export class NativePluginChecker {
@Autowired(NativePluginManager)
private nativePluginManager: NativePluginManager
check(plugins: string[]) {
// Not set plugins -> allow
if (!plugins || !plugins.length) return true
for (const plugin of plugins) {
if (!this.nativePluginManager.has(plugin)) { return false }
}
return true
}
}
@injectable()
export abstract class ReflectServer extends server.Server {
@Autowired(ContainerInstance)
@@ -172,13 +191,23 @@ export namespace server {
}
protected reflectRootLogger(consoleServer: any) {
try {
this.rootLogger = reflect.on(consoleServer).get('LOGGER').get().parent
this.rootLogger = reflect.on(consoleServer).get('LOGGER').get()
} catch (error: any) {
if (global.debug) {
console.ex(error)
}
try {
this.rootLogger = reflect.on(consoleServer).get(0).get().parent
this.rootLogger = reflect.on(consoleServer).get(0).get()
} catch (error: any) {
if (global.debug) {
console.ex(error)
}
}
}
if (this.rootLogger.class.name.indexOf('slf4j') !== -1) {
try {
let LogManager = Java.type('org.apache.logging.log4j.LogManager')
this.rootLogger = LogManager.getLogger('ROOT')
} catch (error: any) {
if (global.debug) {
console.ex(error)
@@ -189,11 +218,11 @@ export namespace server {
console.error('Error Logger Class: ' + this.rootLogger.class.name)
this.rootLogger = undefined
}
if (!this.rootLogger) { console.error("Can't found rootLogger!") }
// get root logger
for (let index = 0; index < 5 && this.rootLogger.parent; index++) {
this.rootLogger = this.rootLogger.parent
}
if (!this.rootLogger) { console.error("Can't found rootLogger!") }
this.container.bind(constants.ServiceIdentifier.RootLogger).toConstantValue(this.rootLogger)
}
}

View File

@@ -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 {
@@ -79,7 +81,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 +90,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 +139,35 @@ 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) {
this.emit('error', error)
if (!error.processed) {
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 任务参数

View File

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

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/bukkit",
"version": "0.23.0",
"version": "0.28.0-beta.3",
"description": "MiaoScript bukkit package",
"keywords": [
"miaoscript",
@@ -21,12 +21,12 @@
"devDependencies": {
"@javatypes/spigot-api": "^0.0.3",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^4.6.3"
"rimraf": "^4.1.2",
"typescript": "^4.9.5"
},
"dependencies": {
"@ccms/api": "^0.23.0",
"@ccms/common": "^0.23.0",
"@ccms/container": "^0.23.0"
"@ccms/api": "^0.28.0-beta.3",
"@ccms/common": "^0.28.0-beta.3",
"@ccms/container": "^0.28.0-beta.3"
}
}

View File

@@ -6,7 +6,7 @@ let bukkitChatInvoke: BukkitChatInvoke
abstract class BukkitChatInvoke {
private downgrade: boolean = false
protected RemapUtils: any
protected ComponentSerializer:any
protected ComponentSerializer: any
protected ChatSerializer: any
protected nmsChatSerializerMethodName: string
@@ -39,6 +39,8 @@ abstract class BukkitChatInvoke {
if (nmsChatMessageTypeClass.isEnum()) {
this.chatMessageTypes = nmsChatMessageTypeClass.getEnumConstants()
break
} else if (nmsChatMessageTypeClass.getName() == 'int') {
break
}
}
}
@@ -159,16 +161,17 @@ class BukkitChatInvoke_1_17_1 extends BukkitChatInvoke_1_16_5 {
return base.getClass('net.minecraft.network.protocol.Packet')
}
}
class BukkitChatInvoke_1_19 extends BukkitChatInvoke_1_17_1 {
class BukkitChatInvoke_1_18_2 extends BukkitChatInvoke_1_17_1 {
getSendPacketMethodName(playerConnectionClass: any) {
return playerConnectionClass.getMethod('a', this.getPacketClass()).getName()
}
}
class BukkitChatInvoke_1_19 extends BukkitChatInvoke_1_18_2 {
getPacketPlayOutChatClass() {
return base.getClass('net.minecraft.network.protocol.game.ClientboundSystemChatPacket')
}
getPacketPlayOutChat(sender: any, json: any, type: number) {
return new this.PacketPlayOutChat(this.ChatSerializer[this.nmsChatSerializerMethodName](json), type == 0 ? 1 : type)
return new this.PacketPlayOutChat(this.ChatSerializer[this.nmsChatSerializerMethodName](json), type)
}
}
@@ -179,6 +182,8 @@ try {
let nmsSubVersion = nmsVersion.split("_")[1]
if (nmsSubVersion >= 19) {
bukkitChatInvoke = new BukkitChatInvoke_1_19(nmsVersion)
} else if (nmsSubVersion >= 18) {
bukkitChatInvoke = new BukkitChatInvoke_1_18_2(nmsVersion)
} else if (nmsSubVersion >= 17) {
bukkitChatInvoke = new BukkitChatInvoke_1_17_1(nmsVersion)
} else if (nmsSubVersion >= 16) {

View File

@@ -12,6 +12,7 @@ export class BukkitItem extends item.Item {
private NBTTagCompound: any
private nmsSaveNBTMethodName: any
private MojangsonParser: any
private nmsItemStack: any
private mpParseMethodName: any
private nmsVersion: any
constructor() {
@@ -25,8 +26,8 @@ export class BukkitItem extends item.Item {
let nbt = new this.NBTTagCompound()
return this.CraftItemStack.asNMSCopy(item)[this.nmsSaveNBTMethodName](nbt).toString()
}
fromJSON(json: string) {
return this.CraftItemStack.asBukkitCopy(this.MojangsonParser[this.mpParseMethodName](json))
fromJson(json: string) {
return this.CraftItemStack.asBukkitCopy(new this.nmsItemStack(this.MojangsonParser[this.mpParseMethodName](json)))
}
private obcCls(name: string) {
return base.getClass(['org.bukkit.craftbukkit', this.nmsVersion, name].join('.'))
@@ -44,6 +45,7 @@ export class BukkitItem extends item.Item {
// @ts-ignore
let asNMSCopyMethod = CraftItemStackClass.getMethod('asNMSCopy', ItemStack.class)
let nmsItemStackClass = asNMSCopyMethod.getReturnType()
this.nmsItemStack = Java.type(nmsItemStackClass.getName())
let nmsNBTTagCompoundClass = undefined
for (let method of Java.from(nmsItemStackClass.getMethods())) {
let rt = method.getReturnType()
@@ -61,7 +63,7 @@ export class BukkitItem extends item.Item {
}
}
try {
this.MojangsonParser = this.nmsCls('MojangsonParser')
this.MojangsonParser = this.nmsCls('MojangsonParser').static
} catch (error) {
this.MojangsonParser = Java.type('net.minecraft.nbt.MojangsonParser')
}

View File

@@ -3,20 +3,11 @@ import { particle } from '@ccms/api'
@provideSingleton(particle.ParticleManager)
export class BukkitParticleManager extends particle.ParticleManager {
private globalSpawner = new BukkitParticleSpawner()
constructor() {
super()
particle.ParticleManager.globalSpawner = this.globalSpawner
}
protected getGlobalSpawner() {
return this.globalSpawner
}
}
@provideSingleton(particle.ParticleSpawner)
export class BukkitParticleSpawner extends particle.ParticleSpawner {
spawnParticle(location: any, particle: any, count: number = 1) {
location.getWorld().spawnParticle(particle, location, count)
}
spawn(location: any, particle: particle.Particle) {
spawn(location: org.bukkit.Location, particle: particle.Particle) {
location.getWorld().spawnParticle(
particle.getParticle(),
location,
@@ -28,4 +19,15 @@ export class BukkitParticleSpawner extends particle.ParticleSpawner {
particle.getData()
)
}
spawnToPlayer(player: org.bukkit.entity.Player, location: org.bukkit.Location, particle: particle.Particle) {
player.spawnParticle(
particle.getParticle(),
location,
particle.getCount(),
particle.getOffsetX(),
particle.getOffsetY(),
particle.getOffsetZ(),
particle.getExtra(),
particle.getData())
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/bungee",
"version": "0.23.0",
"version": "0.28.0-beta.3",
"description": "MiaoScript bungee package",
"keywords": [
"miaoscript",
@@ -21,12 +21,12 @@
"devDependencies": {
"@javatypes/bungee-api": "^0.0.3",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^4.6.3"
"rimraf": "^4.1.2",
"typescript": "^4.9.5"
},
"dependencies": {
"@ccms/api": "^0.23.0",
"@ccms/common": "^0.23.0",
"@ccms/container": "^0.23.0"
"@ccms/api": "^0.28.0-beta.3",
"@ccms/common": "^0.28.0-beta.3",
"@ccms/container": "^0.28.0-beta.3"
}
}

View File

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

View File

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

View File

@@ -1,37 +0,0 @@
{
"private": true,
"name": "@ccms/client",
"version": "0.23.0",
"description": "MiaoScript client 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": {
"dev": "ts-node-dev --respawn --debounce=1500 src/index.ts",
"clean": "rimraf dist",
"watch": "tsc --watch",
"build": "yarn clean && tsc",
"start": "node dist/index.js",
"debug": "DEBUG=minecraft-protocol node dist/index.js",
"emp": "node dist/emp.js",
"test": "echo \"Error: run tests from root\" && exit 1"
},
"dependencies": {
"axios": "^0.27.2",
"minecraft-protocol": "^1.34.0",
"minecraft-protocol-forge": "^1.0.0",
"proxy-agent": "^5.0.0"
},
"devDependencies": {
"@types/node": "^17.0.25",
"rimraf": "^3.0.2",
"typescript": "^4.6.3"
}
}

View File

@@ -1,101 +0,0 @@
class MessagePart {
text: string
color: string
clickEvent: MessagePartEvent
hoverEvent: MessagePartEvent
translate: string
with: MessagePart[]
extra: MessagePart[]
}
class MessagePartEvent {
action: string
value: string
}
var colorMap = []
colorMap['0'] = '38;5;0'
colorMap['1'] = '38;5;4'
colorMap['2'] = '38;5;2'
colorMap['3'] = '38;5;6'
colorMap['4'] = '38;5;1'
colorMap['5'] = '38;5;5'
colorMap['6'] = '38;5;3'
colorMap['7'] = '38;5;7'
colorMap['8'] = '38;5;8'
colorMap['9'] = '38;5;12'
colorMap['a'] = '38;5;10'
colorMap['b'] = '38;5;14'
colorMap['c'] = '38;5;9'
colorMap['d'] = '38;5;13'
colorMap['e'] = '38;5;11'
colorMap['f'] = '38;5;15'
colorMap['r'] = '0'
colorMap['l'] = '1'
colorMap['n'] = '4'
var regexMap = []
for (const c in colorMap) {
regexMap[colorMap[c]] = new RegExp(`§${c}`, "g")
}
function mcColor2ANSI(str) {
for (const regex in regexMap) {
str = str.replace(regexMap[regex], `\u001b[${regex}m`)
}
return str;
}
let jsonColorMap = {
"black": '0',
"dark_blue": '1',
"dark_green": '2',
"dark_aqua": '3',
"dark_red": '4',
"dark_purple": '5',
"gold": '6',
"gray": '7',
"dark_gray": '8',
"blue": '9',
"green": 'a',
"aqua": 'b',
"red": 'c',
"light_purple": 'd',
"yellow": 'e',
"white": 'f',
"obfuscated": 'k',
"bold": 'l',
"strikethrough": 'm',
"underline": 'n',
"italic": 'o',
"reset": 'r',
};
function json2text(json: MessagePart): string {
let temp = "";
if (json.color) {
temp += `§${jsonColorMap[json.color]}`
}
temp += json.text || json.translate || ''
if (json.extra) {
json.extra.forEach((ext) => {
temp += json2text(ext)
})
}
return temp += '§r'
}
function $(input: any) {
if (typeof input === "string") {
input = JSON.parse(input)
}
input = json2text(input) + '§r'
if (input.startsWith('§卐')) {
input = input.substring(2)
}
return mcColor2ANSI(input)
}
export {
json2text,
mcColor2ANSI,
$
}

View File

@@ -1,33 +0,0 @@
import { $ } from './color'
export function attachEvents(client) {
client.on('chat', (packet) => {
// Listen for chat messages and echo them back.
var jsonMsg = JSON.parse(packet.message)
console.log($(jsonMsg))
})
client.on('state', (newState, oldState) => {
console.log('Client Change State', oldState, 'to', newState)
let targetServer = process.argv[6]
if (newState == "play" && targetServer) {
setTimeout(() => {
client.write('chat', {
message: '/server ' + targetServer
})
}, 3000)
}
})
client.on('update_health', (packet) => {
if (packet.health <= 0) {
console.log("Player Dead Auto Respawn...")
client.write('client_command', { payload: 0 })
} else if (packet.health > 0) {
}
})
client.on('kick_disconnect', (packet) => {
console.log($(packet.reason))
})
client.on('disconnect', (packet) => {
console.log($(packet.reason))
})
}

View File

@@ -1,14 +0,0 @@
export function attachForge(client) {
client.on('custom_payload', function(packet) {
if (packet.channel === 'FML|HS') {
client.write('custom_payload', {
channel: 'FML|HS',
data: Buffer.of(0x01, 0x02)
});
client.write('custom_payload', {
channel: 'FML|HS',
data: Buffer.of(0x02, 0x00)
});
}
});
}

View File

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

View File

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

View File

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

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/common",
"version": "0.23.0",
"version": "0.28.0-beta.3",
"description": "MiaoScript common package",
"keywords": [
"miaoscript",
@@ -19,11 +19,11 @@
"test": "echo \"Error: run tests from root\" && exit 1"
},
"devDependencies": {
"@ccms/nashorn": "^0.23.0",
"@ccms/nashorn": "^0.28.0-beta.3",
"@javatypes/jdk": "^0.0.3",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^4.6.3"
"rimraf": "^4.1.2",
"typescript": "^4.9.5"
},
"gitHead": "562e2d00175c9d3a99c8b672aa07e6d92706a027"
}

View File

@@ -19,12 +19,20 @@ interface RequestConfig {
method?: Method
headers?: { [key: string]: string }
params?: { [key: string]: string }
data?: any
data?: any,
connectTimeout?: number,
readTimeout?: number,
}
function request(config: RequestConfig) {
// @ts-ignore XMLHttpRequest class only exist nashorn polyfill
let xhr = new XMLHttpRequest()
if (config.connectTimeout) {
xhr.connectTimeout = config.connectTimeout
}
if (config.readTimeout) {
xhr.readTimeout = config.readTimeout
}
xhr.open(config.method, config.url, false)
for (const header in config.headers) {
xhr.setRequestHeader(header, config.headers[header])

View File

@@ -54,6 +54,7 @@ class Reflect {
}
}
if (!field) throw new Error(`can't reflect field ${typeof nameOrIndex == "number" ? 'index' : 'name'} ${nameOrIndex} from ${this.class.getName()}!`)
fieldCache.set(key, field)
return accessible(field)
}
@@ -136,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) {
@@ -173,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()}`)
}
}
}
@@ -186,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]() }
})

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/compile",
"version": "0.23.0",
"version": "0.28.0-beta.3",
"description": "MiaoScript compile package",
"keywords": [
"miaoscript",
@@ -20,7 +20,7 @@
},
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^4.6.3"
"rimraf": "^4.1.2",
"typescript": "^4.9.5"
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/container",
"version": "0.23.0",
"version": "0.28.0-beta.3",
"description": "MiaoScript container package",
"keywords": [
"miaoscript",
@@ -19,10 +19,10 @@
"test": "echo \"Error: run tests from root\" && exit 1"
},
"devDependencies": {
"@ccms/nashorn": "^0.23.0",
"@ccms/nashorn": "^0.28.0-beta.3",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^4.6.3"
"rimraf": "^4.1.2",
"typescript": "^4.9.5"
},
"dependencies": {
"inversify": "^6.0.1",

View File

@@ -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
})
}

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/core",
"version": "0.23.0",
"version": "0.28.0-beta.3",
"description": "MiaoScript core package",
"keywords": [
"miaoscript",
@@ -20,12 +20,12 @@
},
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^4.6.3"
"rimraf": "^4.1.2",
"typescript": "^4.9.5"
},
"dependencies": {
"@ccms/api": "^0.23.0",
"@ccms/container": "^0.23.0"
"@ccms/api": "^0.28.0-beta.3",
"@ccms/container": "^0.28.0-beta.3"
},
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
}

1
packages/core/src/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
script

View File

@@ -9,6 +9,7 @@ import * as fs from '@ccms/common/dist/fs'
import { VersionUtils } from '@ccms/common/dist/version'
const UUID = Java.type('java.util.UUID')
const MiaoScriptAPI = Java.type('pw.yumc.MiaoScript.api.MiaoScriptAPI')
@provideSingleton(MiaoScriptCore)
class MiaoScriptCore {
@@ -24,6 +25,10 @@ class MiaoScriptCore {
enable() {
process.emit('core.before.enable')
this.loadServerConsole()
try {
MiaoScriptAPI.setPluginManager(this.pluginManager)
} catch (error) {
}
this.loadPlugins()
process.emit('core.after.enable')
console.i18n("ms.core.engine.completed", {
@@ -105,7 +110,7 @@ function loadCoreScript(name) {
try {
let scriptname = name + (global.debug ? '-debug' : '')
engineLoad({
script: http.get(`https://ms.yumc.pw/api/plugin/download/name/${scriptname}`),
script: http.get(`https://mscript.yumc.pw/api/plugin/download/name/${scriptname}`),
name: `core/${scriptname}.js`
})
} catch (error: any) {
@@ -141,6 +146,7 @@ function createCore() {
container.bind(server.ServerType).toConstantValue(type)
container.bind(server.ServerChecker).toSelf().inSingletonScope()
container.bind(server.NativePluginManager).toSelf().inSingletonScope()
container.bind(server.NativePluginChecker).toSelf().inSingletonScope()
process.emit('core.after.initialize.detect')
process.emit('core.before.package.initialize')

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/database",
"version": "0.23.0",
"version": "0.28.0-beta.3",
"description": "MiaoScript database package",
"keywords": [
"miaoscript",
@@ -21,11 +21,11 @@
"devDependencies": {
"@javatypes/spring-jdbc": "^0.0.3",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^4.6.3"
"rimraf": "^4.1.2",
"typescript": "^4.9.5"
},
"dependencies": {
"@ccms/api": "^0.23.0",
"@ccms/container": "^0.23.0"
"@ccms/api": "^0.28.0-beta.3",
"@ccms/container": "^0.28.0-beta.3"
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/i18n",
"version": "0.23.0",
"version": "0.28.0-beta.3",
"description": "MiaoScript i18n package",
"keywords": [
"miaoscript",
@@ -19,11 +19,11 @@
"test": "echo \"Error: run tests from root\" && exit 1"
},
"devDependencies": {
"@ccms/nashorn": "^0.23.0",
"@ccms/nashorn": "^0.28.0-beta.3",
"@types/js-yaml": "^4.0.5",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^4.6.3"
"rimraf": "^4.1.2",
"typescript": "^4.9.5"
},
"dependencies": {
"js-yaml": "^4.1.0"

View File

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

View File

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

View File

@@ -1,3 +0,0 @@
/// <reference types="@ccms/nashorn" />
/// <reference types="@javatypes/jdk" />
export { }

View File

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

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/molang",
"version": "0.23.0",
"version": "0.28.0-beta.3",
"description": "A fast parser for Minecraft's MoLang",
"main": "dist/index.js",
"types": "dist/index.d.ts",
@@ -21,9 +21,9 @@
},
"homepage": "https://github.com/solvedDev/MoLang#readme",
"devDependencies": {
"@types/node": "^17.0.25",
"rimraf": "^3.0.2",
"tslib": "^2.3.1",
"typescript": "^4.6.3"
"@types/node": "^18.13.0",
"rimraf": "^4.1.2",
"tslib": "^2.5.0",
"typescript": "^4.9.5"
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/nashorn",
"version": "0.23.0",
"version": "0.28.0-beta.3",
"description": "MiaoScript nashorn package",
"keywords": [
"miaoscript",
@@ -21,7 +21,7 @@
},
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^4.6.3"
"rimraf": "^4.1.2",
"typescript": "^4.9.5"
}
}

View File

@@ -64,8 +64,18 @@ declare global {
* 引擎渠道
*/
ScriptEngineChannel: string
/**
* 慢执行检测时间
*/
ScriptSlowExecuteTime: number
ScriptEngineStartTime: number
/**
* 设置全局对象
* @param key 对象名称
* @param value 对象值
* @param config 对象属性
* @returns
*/
setGlobal: (key: string, value: any, config?: PropertyDescriptor & ThisType<any>) => void
noop: () => void
console: Console

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/nodejs",
"version": "0.23.0",
"version": "0.28.0-beta.3",
"description": "MiaoScript nodejs package",
"keywords": [
"miaoscript",
@@ -19,11 +19,11 @@
"test": "echo \"Error: run tests from root\" && exit 1"
},
"devDependencies": {
"@ccms/nashorn": "^0.23.0",
"@ccms/nashorn": "^0.28.0-beta.3",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"tslib": "^2.3.1",
"typescript": "^4.6.3"
"rimraf": "^4.1.2",
"tslib": "^2.5.0",
"typescript": "^4.9.5"
},
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
}

View File

@@ -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.error instanceof Throwable) {
throw er.error; // 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

View File

@@ -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() {

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/nukkit",
"version": "0.23.0",
"version": "0.28.0-beta.3",
"description": "MiaoScript nukkit package",
"keywords": [
"miaoscript",
@@ -21,12 +21,12 @@
"devDependencies": {
"@javatypes/nukkit-api": "^0.0.3",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^4.6.3"
"rimraf": "^4.1.2",
"typescript": "^4.9.5"
},
"dependencies": {
"@ccms/api": "^0.23.0",
"@ccms/common": "^0.23.0",
"@ccms/container": "^0.23.0"
"@ccms/api": "^0.28.0-beta.3",
"@ccms/common": "^0.28.0-beta.3",
"@ccms/container": "^0.28.0-beta.3"
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/plugin",
"version": "0.23.0",
"version": "0.28.0-beta.3",
"description": "MiaoScript plugin package",
"keywords": [
"miaoscript",
@@ -22,15 +22,15 @@
"@types/crypto-js": "^4.1.1",
"@types/js-yaml": "^4.0.5",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^4.6.3"
"rimraf": "^4.1.2",
"typescript": "^4.9.5"
},
"dependencies": {
"@ccms/api": "^0.23.0",
"@ccms/common": "^0.23.0",
"@ccms/container": "^0.23.0",
"@ccms/i18n": "^0.23.0",
"@ccms/verify": "^0.21.1",
"@ccms/api": "^0.28.0-beta.3",
"@ccms/common": "^0.28.0-beta.3",
"@ccms/container": "^0.28.0-beta.3",
"@ccms/i18n": "^0.28.0-beta.3",
"@ccms/verify": "^0.26.1",
"crypto-js": "^4.1.1",
"js-yaml": "^4.1.0"
}

View File

@@ -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") {
@@ -78,11 +78,11 @@ export class PluginCommandManager {
permission = `${pluginInstance.description.name.toLocaleLowerCase()}.${command}.${subcommand || 'main'}`
}
if (!sender.hasPermission(permission)) {
return pluginInstance.logger.sender(sender, `§c你需要 ${permission} 权限 才可执行此命令.`)
return pluginInstance.logger.sender(sender, `§c你需要 §4${permission} §c权限 才可执行此命令.`)
}
}
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,10 +95,10 @@ 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.warn(`[${pluginInstance.description.name}] command ${cmd.name} is not registry tabCompleter`) }
if (!cmdCompleter) { console.debug(`[${pluginInstance.description.name}] command ${cmd.name} is not registry tabCompleter`) }
return [cmdExecutor, cmdCompleter]
}
}

View File

@@ -7,8 +7,7 @@ import { interfaces } from './interfaces'
import { getPluginConfigMetadata } from './utils'
import { PluginConfigLoader } from './config/interfaces'
import './config/loader/json-loader'
import './config/loader/yaml-loader'
import './config/loader'
@provideSingleton(PluginConfigManager)
export class PluginConfigManager {
@@ -68,30 +67,25 @@ export class PluginConfigManager {
private loadConfig0(plugin: plugin.Plugin, metadata: interfaces.ConfigMetadata) {
try {
let defaultValue = metadata.default ?? plugin[metadata.variable]
let configValue = defaultValue || {}
if (defaultValue) {
metadata.file = fs.concat(
fs.file(plugin.description.loadMetadata.file).parent,
plugin.description.name,
metadata.filename
)
let configLoader = this.getConfigLoader(metadata.format)
if (!fs.exists(metadata.file)) {
base.save(metadata.file, configLoader.dump(defaultValue))
console.i18n("ms.plugin.manager.config.save.default", {
plugin: plugin.description.name,
name: metadata.name,
format: metadata.format
})
} else if (metadata.migrate) {
configValue = configLoader.load(base.read(metadata.file)) || {}
if (defaultValue && this.setDefaultValue(configValue, defaultValue, !!metadata.default)) {
base.save(metadata.file, configLoader.dump(configValue))
}
console.debug(`[${plugin.description.name}] Load Config ${metadata.variable} from file ${metadata.file} =>
${JSON.stringify(configValue, undefined, 4).substring(0, 500)}`)
}
metadata.file = fs.concat(
fs.file(plugin.description.loadMetadata.file).parent,
plugin.description.name,
metadata.filename
)
let configLoader = this.getConfigLoader(metadata.format)
if (!fs.exists(metadata.file) && defaultValue) {
base.save(metadata.file, configLoader.dump(defaultValue))
console.i18n("ms.plugin.manager.config.save.default", {
plugin: plugin.description.name,
name: metadata.name,
format: metadata.format
})
}
let configValue = configLoader.load(base.read(metadata.file)) || {}
if (metadata.migrate && defaultValue && this.setDefaultValue(configValue, defaultValue, !!metadata.default)) {
base.save(metadata.file, configLoader.dump(configValue))
}
console.debug(`[${plugin.description.name}] Load Config ${metadata.variable} from file ${metadata.file}`)
this.defienConfigProp(plugin, metadata, configValue)
} catch (error: any) {
console.i18n("ms.plugin.manager.config.load.error", {

View File

@@ -5,9 +5,13 @@ import { getPluginListenerMetadata } from './utils'
@provideSingleton(PluginEventManager)
export class PluginEventManager {
@Autowired()
private EventManager: event.Event
private eventManager: event.Event
@Autowired()
private ServerChecker: server.ServerChecker
private serverChecker: server.ServerChecker
@Autowired()
private nativePluginChecker: server.NativePluginChecker
private listenerMap = [];
constructor() {
process.on('plugin.before.enable', this.registryListener.bind(this))
@@ -15,26 +19,44 @@ export class PluginEventManager {
}
mapEventName() {
return this.EventManager.mapEventName().toFixed(0)
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)) {
console.debug(`[${pluginInstance.description.name}] ${event.target.constructor.name} incompatible event ${event.name} server(${event.servers}) ignore.`)
if (!this.serverChecker.check(event.servers)) {
console.debug(`[${pluginInstance.description.name}] ${event.target.constructor.name} incompatible server(${event.servers}) ignore event ${event.name}.`)
continue
}
// ignore space listener
if (!this.nativePluginChecker.check(event.plugins)) {
console.debug(`[${pluginInstance.description.name}] ${event.target.constructor.name} require native plugins(${event.plugins}) ignore event ${event.name}.`)
continue
}
// 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)
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)
}
}
}

View File

@@ -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,

View File

@@ -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() { }
@@ -73,6 +118,10 @@ export namespace interfaces {
* 是否忽略已取消的事件
*/
ignoreCancel?: boolean
/**
* 依赖插件 没有就不加载
*/
plugins?: string[]
}
export interface ConfigMetadata extends plugin.BaseMetadata {
/**

View File

@@ -2,12 +2,11 @@ import i18n from '@ccms/i18n'
import { plugin, server } from '@ccms/api'
import { provideSingleton, Container, ContainerInstance, Autowired } from '@ccms/container'
import './config'
import { interfaces } from './interfaces'
import { PluginTaskManager } from './task'
import { PluginEventManager } from './event'
import { PluginCommandManager } from './command'
import { PluginConfigManager } from './config'
import { PluginCommandManager } from './command'
const Thread = Java.type('java.lang.Thread')
@@ -93,18 +92,17 @@ export class PluginManagerImpl implements plugin.PluginManager {
for (const [, scanner] of this.sacnnerMap) {
try {
console.i18n('ms.plugin.manager.scan', { scanner: scanner.type, folder })
let plugins = scanner.scan(folder)
console.i18n('ms.plugin.manager.scan.finish', { scanner: scanner.type, folder, size: plugins.length })
plugins.forEach(loadMetadata => {
let loadMetadatas = scanner.scan(folder)
console.i18n('ms.plugin.manager.scan.finish', { scanner: scanner.type, folder, size: loadMetadatas.length })
for (const loadMetadata of loadMetadatas) {
try {
this.loadAndRequirePlugin(loadMetadata)
} catch (error: any) {
console.error(`plugin scanner ${scanner.type} load ${loadMetadata.file} occurred error ${error}`)
console.console(`§c扫描器 §4${scanner.type} §c文件 §4${loadMetadata.file.toString().replace(root, '')} §c编译失败 请提供下列错误给开发者`)
console.ex(error)
}
})
}
} catch (error: any) {
console.error(`plugin scanner ${scanner.type} occurred error ${error}`)
console.ex(error)
}
}
@@ -229,8 +227,16 @@ export class PluginManagerImpl implements plugin.PluginManager {
})
}
has(name: string) {
return this.instanceMap.has(name)
}
get(name: string) {
return this.instanceMap.get(name) || null
}
getPlugin(name: string) {
return this.instanceMap.get(name)
return this.instanceMap.get(name) || null
}
getPlugins() {

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/polyfill",
"version": "0.23.0",
"version": "0.28.0-beta.3",
"description": "MiaoScript polyfill package",
"author": "MiaoWoo <admin@yumc.pw>",
"homepage": "https://github.com/circlecloud/ms.git",
@@ -14,14 +14,14 @@
"test": "echo \"Error: run tests from root\" && exit 1"
},
"dependencies": {
"@ccms/i18n": "^0.23.0",
"@ccms/nodejs": "^0.23.0",
"core-js": "^3.22.1"
"@ccms/i18n": "^0.28.0-beta.3",
"@ccms/nodejs": "^0.28.0-beta.3",
"core-js": "^3.27.2"
},
"devDependencies": {
"@ccms/nashorn": "^0.23.0",
"@ccms/nashorn": "^0.28.0-beta.3",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^4.6.3"
"rimraf": "^4.1.2",
"typescript": "^4.9.5"
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -12,6 +12,7 @@ import 'core-js'
process.on('exit', () => require.disable())
global.setGlobal('Proxy', require('./proxy').Proxy)
global.setGlobal('XMLHttpRequest', require('./xml-http-request').XMLHttpRequest)
global.setGlobal('Buffer', require('./buffer').Buffer)
global.setGlobal('Blob', require('blob-polyfill').Blob)
console.i18n("ms.polyfill.completed", { time: (new Date().getTime() - polyfillStartTime) / 1000 })
export default true

View File

@@ -126,6 +126,7 @@ class Process extends EventEmitter {
}
class EventLoop {
private threadCount = new AtomicInteger(0)
private eventLoopMainThread = undefined
private eventLoopTaskQueue = new DelayQueue()
private taskExecuteTimeout = 3000
@@ -134,10 +135,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
}))
@@ -198,7 +199,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 +214,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
}

View File

@@ -68,13 +68,14 @@ type EventType =
| 'timeout'
| 'loadend'
| 'loadstart'
type HttpHeader = { [key: string]: string }
type RequestHttpHeader = { [key: string]: string }
type HttpHeader = { [key: string]: string[] }
const executor = Executors.newCachedThreadPool()
export class XMLHttpRequest {
private _timeout: number = 120000;
private _connectTimeout: number = 5000;
private _readTimeout: number = 120000;
private _responseType: ResponseType = 'text';
private _withCredentials: boolean
@@ -84,7 +85,7 @@ export class XMLHttpRequest {
private _url: string
private _async: boolean
private _mimeType: string
private _requestHeaders: HttpHeader = {};
private _requestHeaders: RequestHttpHeader = {};
private _status: number = 0;
private _statusText: string = null;
@@ -96,10 +97,22 @@ export class XMLHttpRequest {
private _connection = null;
get timeout() {
return this._timeout
return this._readTimeout
}
set timeout(timeout: number) {
this._timeout = timeout
this._readTimeout = timeout
}
get connectTimeout() {
return this._connectTimeout
}
set connectTimeout(timeout: number) {
this._connectTimeout = timeout
}
get readTimeout() {
return this._readTimeout
}
set readTimeout(timeout: number) {
this._readTimeout = timeout
}
get readyState() {
return this._readyState
@@ -143,7 +156,7 @@ export class XMLHttpRequest {
this._requestHeaders[key] = val
}
getResponseHeader(key: string): string {
return this._responseHeaders[key]
return this._responseHeaders[key]?.[0]
}
getAllResponseHeaders(): any {
return this._responseHeaders
@@ -169,8 +182,8 @@ export class XMLHttpRequest {
this._connection.setRequestMethod(this._method)
this._connection.setDoOutput(true)
this._connection.setDoInput(true)
this._connection.setConnectTimeout(this._timeout)
this._connection.setReadTimeout(this._timeout)
this._connection.setConnectTimeout(this._connectTimeout)
this._connection.setReadTimeout(this._readTimeout)
this.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
this.setReadyState(ReadyState.OPENED)
@@ -181,7 +194,7 @@ export class XMLHttpRequest {
}
if (this._readyState !== ReadyState.OPENED) { throw new Error(`Error Status ${this._readyState}!`) }
let future = executor.submit(new Callable({ call: () => this._send(body) }))
if (!this._async) { future.get(this._timeout, TimeUnit.MILLISECONDS) }
if (!this._async) { future.get(this._connectTimeout + this._readTimeout + 100, TimeUnit.MILLISECONDS) }
return future
}
get() {
@@ -199,22 +212,23 @@ export class XMLHttpRequest {
}
abort() {
this._connection.disconnect()
this.onabort && this.onabort()
this.onabort?.()
}
private _send(body?: string | object) {
try {
this._connection.connect()
this.onloadstart && this.onloadstart()
this.onloadstart?.()
if (body) {
let bodyType = Object.prototype.toString.call(body)
if (typeof body !== "string") { throw new Error(`body(${bodyType}) must be string!`) }
if (typeof body !== "string") { throw new Error(`body(${bodyType}) must be string.`) }
var out = this._connection.getOutputStream()
out.write(new JavaString(body).getBytes(UTF_8))
out.flush()
out.close()
}
this.setReadyState(ReadyState.LOADING)
this.onload?.()
this._status = this._connection.getResponseCode()
this._statusText = this._connection.getResponseMessage()
if (this._status >= 0 && this._status < 300) {
@@ -224,8 +238,8 @@ export class XMLHttpRequest {
} else {
this._responseText = this.readOutput(this._connection.getErrorStream())
}
this.setResponseHeaders(this._connection.getHeaderFields())
this.onloadend && this.onloadend()
this.setResponseHeaders()
this.onloadend?.()
} catch (ex: any) {
if (ex instanceof SocketTimeoutException && this.ontimeout) {
return this.ontimeout(ex)
@@ -239,15 +253,15 @@ export class XMLHttpRequest {
}
}
private setResponseHeaders(header: any) {
header.forEach((key: string | number, value: string | any[]) => {
this._responseHeaders[key + ''] = value[value.length - 1] + ''
private setResponseHeaders() {
this._connection.getHeaderFields().forEach((key: string | number, value: any[]) => {
this._responseHeaders[key + ''] = Java.from(value)
})
}
private setReadyState(state: ReadyState) {
this._readyState = state
this.onreadystatechange && this.onreadystatechange()
this.onreadystatechange?.()
}
private readOutput(input: any) {

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/protocol",
"version": "0.23.0",
"version": "0.28.0-beta.3",
"description": "MiaoScript protocol package",
"keywords": [
"miaoscript",
@@ -21,7 +21,7 @@
},
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^4.6.3"
"rimraf": "^4.1.2",
"typescript": "^4.9.5"
}
}

View File

@@ -1,7 +1,7 @@
{
"name": "@ccms/spring",
"version": "0.23.0",
"description": "MiaoScript spring package",
"name": "@ccms/qrcode",
"version": "0.28.0-beta.3",
"description": "MiaoScript qrcode package",
"keywords": [
"miaoscript",
"minecraft",
@@ -20,13 +20,7 @@
},
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^4.6.3"
},
"dependencies": {
"@ccms/api": "^0.23.0",
"@ccms/common": "^0.23.0",
"@ccms/container": "^0.23.0",
"@ccms/database": "^0.23.0"
"rimraf": "^4.1.2",
"typescript": "^4.9.5"
}
}

1243
packages/qrcode/src/index.ts Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/sponge",
"version": "0.23.0",
"version": "0.28.0-beta.3",
"description": "MiaoScript sponge package",
"keywords": [
"miaoscript",
@@ -21,12 +21,12 @@
"devDependencies": {
"@javatypes/sponge-api": "^0.0.3",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^4.6.3"
"rimraf": "^4.1.2",
"typescript": "^4.9.5"
},
"dependencies": {
"@ccms/api": "^0.23.0",
"@ccms/common": "^0.23.0",
"@ccms/container": "^0.23.0"
"@ccms/api": "^0.28.0-beta.3",
"@ccms/common": "^0.28.0-beta.3",
"@ccms/container": "^0.28.0-beta.3"
}
}

View File

@@ -1,32 +1,15 @@
import { provideSingleton } from '@ccms/container'
import { particle, plugin } from '@ccms/api'
import { particle } from '@ccms/api'
@provideSingleton(particle.ParticleManager)
export class SpongeParticleManager extends particle.ParticleManager {
private globalSpawner = new SpongeParticleSpawner()
constructor() {
super()
particle.ParticleManager.globalSpawner = this.globalSpawner
}
protected getGlobalSpawner() {
return this.globalSpawner
}
}
@provideSingleton(particle.ParticleSpawner)
export class SpongeParticleSpawner extends particle.ParticleSpawner {
spawnParticle(location: org.spongepowered.api.world.Location<any>, particle: any, count: number = 1) {
location.getPosition()
// location.getWorld().spawnParticle(particle, location, count)
}
spawn(location: any, particle: particle.Particle) {
location.getWorld().spawnParticle(
particle.getParticle(),
location,
particle.getCount(),
particle.getOffsetX(),
particle.getOffsetY(),
particle.getOffsetZ(),
particle.getExtra(),
particle.getData()
)
throw new Error('Not Impl.')
}
spawnToPlayer(player: any, location: any, particle: particle.Particle) {
throw new Error('Not Impl.')
}
}

View File

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

View File

@@ -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))
}
}

View File

@@ -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'))
}
}

View File

@@ -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.");
}
}

View File

@@ -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)
})
}

View File

@@ -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})`
}

View File

@@ -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
}
}

View File

@@ -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
}
}

View File

@@ -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))
}
}

View File

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

View File

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

View File

@@ -1,35 +0,0 @@
{
"name": "@ccms/web",
"version": "0.23.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": "^3.0.2",
"typescript": "^4.6.3"
},
"dependencies": {
"@ccms/api": "^0.23.0",
"@ccms/container": "^0.23.0"
}
}

View File

@@ -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',
}

View File

@@ -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'

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