Compare commits
6 Commits
v0.23.0-al
...
v0.19.5
| Author | SHA1 | Date | |
|---|---|---|---|
| dbecad996a | |||
| c4aded50f1 | |||
| 93b361a2ac | |||
| 923bf102de | |||
| 4a90455131 | |||
| 2ff57d1c0b |
@@ -1,4 +1,3 @@
|
||||
src
|
||||
test
|
||||
typings
|
||||
bundled
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"version": "0.23.0-alpha.0",
|
||||
"version": "0.19.5",
|
||||
"useWorkspaces": true,
|
||||
"npmClient": "yarn",
|
||||
"packages": [
|
||||
@@ -8,9 +8,10 @@
|
||||
"command": {
|
||||
"run": {
|
||||
"stream": true
|
||||
},
|
||||
"publish": {
|
||||
"access": "public",
|
||||
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
|
||||
}
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,8 +13,7 @@
|
||||
"ug": "yarn upgrade-interactive --latest",
|
||||
"np": "./script/push.sh",
|
||||
"lsp": "npm login --registry=https://registry.npmjs.org --scope=@ccms",
|
||||
"lp": "lerna publish --registry https://registry.npmjs.org",
|
||||
"lpb": "lerna publish --registry https://registry.npmjs.org --canary --preid beta --pre-dist-tag beta"
|
||||
"lp": "lerna publish --registry https://registry.npmjs.org"
|
||||
},
|
||||
"workspaces": [
|
||||
"packages/*"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/amqp",
|
||||
"version": "0.23.0-alpha.0",
|
||||
"version": "0.19.5",
|
||||
"description": "MiaoScript amqp package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,17 +19,17 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.23.0-alpha.0",
|
||||
"@ccms/common": "^0.23.0-alpha.0",
|
||||
"@ccms/container": "^0.22.0"
|
||||
"@ccms/api": "^0.19.5",
|
||||
"@ccms/common": "^0.19.0",
|
||||
"@ccms/container": "^0.19.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.22.0",
|
||||
"@ccms/nashorn": "^0.19.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"
|
||||
"typescript": "^4.5.5"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/api",
|
||||
"version": "0.23.0-alpha.0",
|
||||
"version": "0.19.5",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,9 +19,9 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/common": "^0.23.0-alpha.0",
|
||||
"@ccms/container": "^0.22.0",
|
||||
"@ccms/polyfill": "^0.23.0-alpha.0",
|
||||
"@ccms/common": "^0.19.0",
|
||||
"@ccms/container": "^0.19.0",
|
||||
"@ccms/polyfill": "^0.19.0",
|
||||
"base64-js": "^1.5.1",
|
||||
"source-map-builder": "^0.0.7"
|
||||
},
|
||||
@@ -29,6 +29,6 @@
|
||||
"@types/base64-js": "^1.3.0",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.6.3"
|
||||
"typescript": "^4.5.5"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ import * as base64 from 'base64-js'
|
||||
const Arrays = Java.type('java.util.Arrays')
|
||||
const Level = Java.type('java.util.logging.Level')
|
||||
const Paths = Java.type('java.nio.file.Paths')
|
||||
const ignoreLogPrefix = ['java.', 'javax.', 'sun.', 'net.minecraft.', 'org.bukkit.', 'jdk.internal.dynalink.', 'jdk.nashorn.', 'org.openjdk.nashorn', 'io.netty.', 'org.spongepowered.', 'org.apache', 'org.springframework']
|
||||
const ignoreLogPrefix = ['java.', 'javax.', 'sun.', 'net.minecraft.', 'org.bukkit.', 'jdk.nashorn.', 'org.openjdk.nashorn', 'io.netty.', 'org.spongepowered.', 'org.apache', 'org.springframework']
|
||||
|
||||
enum LogLevel {
|
||||
ALL,
|
||||
@@ -18,114 +18,12 @@ enum LogLevel {
|
||||
OFF
|
||||
}
|
||||
|
||||
const sourceMaps: { [key: string]: SourceMapBuilder } = {}
|
||||
const sourceFileMaps: { [key: string]: string } = {}
|
||||
|
||||
global.setGlobal('MiaoScriptSourceMaps', sourceMaps)
|
||||
global.setGlobal('MiaoScriptSourceFileMaps', sourceFileMaps)
|
||||
|
||||
export namespace jsconsole {
|
||||
export function readSourceMap(fileName: string, lineNumber: any) {
|
||||
try {
|
||||
if (fileName.endsWith('js') || fileName.endsWith('ms')) {
|
||||
if (sourceMaps[fileName] === undefined) {
|
||||
sourceMaps[fileName] = null
|
||||
let sourceLine = base.read(fileName).split('\n')
|
||||
let lastLine = sourceLine[sourceLine.length - 1] || sourceLine[sourceLine.length - 2]
|
||||
// lastLine is similar //# sourceMappingURL=data:application/json;base64,
|
||||
if (lastLine.startsWith('//# sourceMappingURL=')) {
|
||||
let sourceContent = null
|
||||
let sourceMappingURL = lastLine.split('sourceMappingURL=', 2)[1]
|
||||
if (sourceMappingURL.startsWith('data:application/json;base64,')) {
|
||||
sourceContent = String.fromCharCode(...Array.from(base64.toByteArray(sourceMappingURL.split(',', 2)[1])))
|
||||
} else if (sourceMappingURL.startsWith('http://') || sourceMappingURL.startsWith('https://')) {
|
||||
// TODO
|
||||
} else {
|
||||
let file = Paths.get(Paths.get(fileName, '..', sourceMappingURL).toFile().getCanonicalPath()).toFile()
|
||||
if (file.exists()) {
|
||||
sourceContent = base.read(file)
|
||||
} else if (global.debug) {
|
||||
console.debug('readSourceMap can\'t found', fileName, 'source map file', sourceMappingURL)
|
||||
}
|
||||
}
|
||||
if (sourceContent) {
|
||||
sourceMaps[fileName] = new SourceMapBuilder(JSON.parse(sourceContent))
|
||||
sourceFileMaps[fileName] = Paths.get(fileName, '..', sourceMaps[fileName].sources[0]).toFile().getCanonicalPath()
|
||||
}
|
||||
}
|
||||
}
|
||||
if (sourceMaps[fileName]) {
|
||||
let sourceMapping = sourceMaps[fileName].getSource(lineNumber, 25, true, true)
|
||||
if (sourceMapping) {
|
||||
fileName = Paths.get(fileName, '..', sourceMapping.sourcePath).toFile().getCanonicalPath()
|
||||
lineNumber = sourceMapping.mapping.sourceLine
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.debug('search source map', fileName, 'line', lineNumber, 'error:', error)
|
||||
if (global.debug) {
|
||||
console.ex(error)
|
||||
}
|
||||
}
|
||||
return {
|
||||
fileName,
|
||||
lineNumber
|
||||
}
|
||||
}
|
||||
|
||||
export function getStackTrace(ex: Error, color: boolean = true): string[] {
|
||||
if (!ex) return []
|
||||
let stack = ex.getStackTrace()
|
||||
let cache = [(color ? '§c' : '') + ex]
|
||||
//@ts-ignore
|
||||
if (stack.class) {
|
||||
stack = Arrays.asList(stack)
|
||||
}
|
||||
stack.forEach(trace => {
|
||||
if (!trace.fileName || trace.fileName.startsWith('jar:file:') || trace.fileName.startsWith('file:')) { return }
|
||||
if (trace.className.startsWith('<')) {
|
||||
let { fileName, lineNumber } = readSourceMap(trace.fileName, trace.lineNumber)
|
||||
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
|
||||
if (color) {
|
||||
cache.push(` §e->§c ${fileName}:${lineNumber} => §4${trace.methodName}`)
|
||||
} else {
|
||||
cache.push(` -> ${fileName}:${lineNumber} => ${trace.methodName}`)
|
||||
}
|
||||
} else {
|
||||
let className = trace.className
|
||||
var fileName = trace.fileName as string
|
||||
var lineNumber = trace.lineNumber
|
||||
if (className.startsWith('jdk.nashorn.internal.scripts') || className.startsWith('org.openjdk.nashorn.internal.scripts')) {
|
||||
className = className.substr(className.lastIndexOf('$') + 1)
|
||||
var { fileName, lineNumber } = readSourceMap(fileName, lineNumber)
|
||||
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
|
||||
} else {
|
||||
if (!global.debug) {
|
||||
for (let prefix in ignoreLogPrefix) {
|
||||
if (className.startsWith(ignoreLogPrefix[prefix])) {
|
||||
return
|
||||
}
|
||||
}
|
||||
} else if (className.startsWith('jdk.nashorn.internal.') || className.startsWith('org.openjdk.nashorn.internal.')) {
|
||||
return
|
||||
}
|
||||
}
|
||||
if (color) {
|
||||
cache.push(` §e->§c ${className}.${trace.methodName}(§4${fileName}:${lineNumber}§c)`)
|
||||
} else {
|
||||
cache.push(` -> ${className}.${trace.methodName}(${fileName}:${lineNumber})`)
|
||||
}
|
||||
}
|
||||
})
|
||||
return cache
|
||||
}
|
||||
}
|
||||
|
||||
export class MiaoScriptConsole implements Console {
|
||||
Console: any
|
||||
memory: any
|
||||
|
||||
private static sourceMaps: { [key: string]: SourceMapBuilder } = {}
|
||||
private static sourceFileMaps: { [key: string]: string } = {}
|
||||
private _name: string = ''
|
||||
private _level: LogLevel = LogLevel.INFO
|
||||
|
||||
@@ -194,8 +92,91 @@ export class MiaoScriptConsole implements Console {
|
||||
ex(ex: Error) {
|
||||
this.stack(ex).forEach(line => this.console(line))
|
||||
}
|
||||
readSourceMap(fileName: string, lineNumber: any) {
|
||||
try {
|
||||
if (fileName.endsWith('js')) {
|
||||
if (MiaoScriptConsole.sourceMaps[fileName] === undefined) {
|
||||
MiaoScriptConsole.sourceMaps[fileName] = null
|
||||
let sourceLine = base.read(fileName).split('\n')
|
||||
let lastLine = sourceLine[sourceLine.length - 1]
|
||||
// lastLine is similar //# sourceMappingURL=data:application/json;base64,
|
||||
if (lastLine.startsWith('//# sourceMappingURL=')) {
|
||||
let sourceContent = null
|
||||
let sourceMappingURL = lastLine.split('sourceMappingURL=', 2)[1]
|
||||
if (sourceMappingURL.startsWith('data:application/json;base64,')) {
|
||||
sourceContent = String.fromCharCode(...Array.from(base64.toByteArray(sourceMappingURL.split(',', 2)[1])))
|
||||
} else if (sourceMappingURL.startsWith('http://') || sourceMappingURL.startsWith('https://')) {
|
||||
// TODO
|
||||
} else {
|
||||
let file = Paths.get(Paths.get(fileName, '..', sourceMappingURL).toFile().getCanonicalPath()).toFile()
|
||||
if (file.exists()) { sourceContent = base.read(file) }
|
||||
}
|
||||
if (sourceContent) {
|
||||
MiaoScriptConsole.sourceMaps[fileName] = new SourceMapBuilder(JSON.parse(sourceContent))
|
||||
MiaoScriptConsole.sourceFileMaps[fileName] = Paths.get(fileName, '..', MiaoScriptConsole.sourceMaps[fileName].sources[0]).toFile().getCanonicalPath()
|
||||
}
|
||||
}
|
||||
}
|
||||
if (MiaoScriptConsole.sourceMaps[fileName]) {
|
||||
let sourceMapping = MiaoScriptConsole.sourceMaps[fileName].getSource(lineNumber, 25, true, true)
|
||||
fileName = MiaoScriptConsole.sourceFileMaps[fileName]
|
||||
if (sourceMapping && lineNumber != sourceMapping.mapping.sourceLine) { lineNumber = sourceMapping.mapping.sourceLine }
|
||||
}
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.debug('search source map', fileName, 'line', lineNumber, 'error:', error)
|
||||
if (global.debug) {
|
||||
console.ex(error)
|
||||
}
|
||||
}
|
||||
return {
|
||||
fileName,
|
||||
lineNumber
|
||||
}
|
||||
}
|
||||
stack(ex: Error, color: boolean = true): string[] {
|
||||
return jsconsole.getStackTrace(ex, color)
|
||||
if (!ex) return []
|
||||
let stack = ex.getStackTrace()
|
||||
let cache = [(color ? '§c' : '') + ex]
|
||||
//@ts-ignore
|
||||
if (stack.class) {
|
||||
stack = Arrays.asList(stack)
|
||||
}
|
||||
stack.forEach(trace => {
|
||||
if (!trace.fileName || trace.fileName.startsWith('jar:file:') || trace.fileName.startsWith('file:')) { return }
|
||||
if (trace.className.startsWith('<')) {
|
||||
let { fileName, lineNumber } = this.readSourceMap(trace.fileName, trace.lineNumber)
|
||||
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
|
||||
if (color) {
|
||||
cache.push(` §e->§c ${fileName}:${lineNumber} => §4${trace.methodName}`)
|
||||
} else {
|
||||
cache.push(` -> ${fileName}:${lineNumber} => ${trace.methodName}`)
|
||||
}
|
||||
} else {
|
||||
let className = trace.className
|
||||
var fileName = trace.fileName as string
|
||||
var lineNumber = trace.lineNumber
|
||||
if (className.startsWith('jdk.nashorn.internal.scripts') || className.startsWith('org.openjdk.nashorn.internal.scripts')) {
|
||||
className = className.substr(className.lastIndexOf('$') + 1)
|
||||
var { fileName, lineNumber } = this.readSourceMap(fileName, lineNumber)
|
||||
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
|
||||
} else {
|
||||
if (!global.debug) {
|
||||
for (let prefix in ignoreLogPrefix) {
|
||||
if (className.startsWith(ignoreLogPrefix[prefix])) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (color) {
|
||||
cache.push(` §e->§c ${className}.${trace.methodName}(§4${fileName}:${lineNumber}§c)`)
|
||||
} else {
|
||||
cache.push(` -> ${className}.${trace.methodName}(${fileName}:${lineNumber})`)
|
||||
}
|
||||
}
|
||||
})
|
||||
return cache
|
||||
}
|
||||
assert(value: any, message?: string, ...optionalParams: any[]): void {
|
||||
throw new Error("Method not implemented.")
|
||||
|
||||
@@ -11,21 +11,10 @@ export namespace constants {
|
||||
}
|
||||
export namespace Reflect {
|
||||
export const Method = {
|
||||
getServerConnection: [
|
||||
/*spigot 1.8.8*/'aq',
|
||||
/*spigot 1.12.2*/ 'an',
|
||||
/*spigot 1.14.4+*/'getServerConnection',
|
||||
/*spigot 1.19+*/'ad',
|
||||
/*catserver 1.12.2*/'func_147137_ag'
|
||||
]
|
||||
getServerConnection: [/*spigot 1.8.8*/'aq',/*spigot 1.12.2*/ 'an', /*spigot 1.14.4+*/'getServerConnection', /*catserver 1.12.2*/'func_147137_ag']
|
||||
}
|
||||
export const Field = {
|
||||
listeningChannels: [
|
||||
/*spigot 1.8.8-1.12.2*/'g',
|
||||
/*spigot 1.14.4*/'f',
|
||||
/*spigot 1.15.2+*/'listeningChannels',
|
||||
/*catserver 1.12.2*/'field_151274_e'
|
||||
]
|
||||
listeningChannels: [/*spigot 1.8.8-1.12.2*/'g', /*spigot 1.14.4*/'f', /*spigot 1.15.2+*/'listeningChannels', /*catserver 1.12.2*/'field_151274_e']
|
||||
}
|
||||
}
|
||||
export enum ServerType {
|
||||
|
||||
@@ -1,52 +1,5 @@
|
||||
import { injectable } from "@ccms/container"
|
||||
|
||||
export namespace database {
|
||||
export const DataSource = Symbol("DataSource")
|
||||
/**
|
||||
* 数据库配置
|
||||
*/
|
||||
export interface DataBaseConfig {
|
||||
/**
|
||||
* 数据库类型
|
||||
*/
|
||||
type: 'h2' | 'mysql' | 'mongodb' | 'sqlite' | 'postgres' | 'redis'
|
||||
/**
|
||||
* 数据库连接串
|
||||
*/
|
||||
url: string | javax.sql.DataSource
|
||||
/**
|
||||
* 数据库驱动
|
||||
*/
|
||||
driverClassName?: string
|
||||
/**
|
||||
* 用户名
|
||||
*/
|
||||
username?: string
|
||||
/**
|
||||
* 密码
|
||||
*/
|
||||
password?: string
|
||||
/**
|
||||
* 链接属性
|
||||
*/
|
||||
properties?: { [key: string]: any }
|
||||
}
|
||||
|
||||
@injectable()
|
||||
export abstract class DataBaseManager {
|
||||
abstract setMainDatabase(mainDatabase: DataBase): void
|
||||
abstract getMainDatabase(): DataBase
|
||||
abstract createDatabase(name: string, config: DataBaseConfig): DataBase
|
||||
abstract removeDatabase(name: string): boolean
|
||||
abstract getDatabase(name: string): DataBase
|
||||
abstract startWebManager(...args: string[])
|
||||
abstract stopWebManager()
|
||||
abstract shutdown()
|
||||
}
|
||||
@injectable()
|
||||
export abstract class DataBase {
|
||||
abstract query<T>(sql: string, ...args: any[]): Array<T>
|
||||
abstract update(sql: string, ...args: any[]): number
|
||||
abstract execute(sql: string): void
|
||||
}
|
||||
export const DataBaseManager = Symbol("DataBaseManager");
|
||||
export const DataSource = Symbol("DataSource");
|
||||
export const DataBase = Symbol("DataBase");
|
||||
}
|
||||
|
||||
@@ -133,12 +133,7 @@ export namespace event {
|
||||
// @ts-ignore
|
||||
let executor = exec.name || exec.executor || '[anonymous]'
|
||||
// noinspection JSUnusedGlobalSymbols
|
||||
var listener = this.register(
|
||||
eventCls,
|
||||
this.execute(name, exec, eventCls),
|
||||
priority,
|
||||
ignoreCancel
|
||||
)
|
||||
var listener = this.register(eventCls, this.execute(name, exec, eventCls), priority, ignoreCancel)
|
||||
var listenerMap = this.listenerMap
|
||||
// add to cache Be used for close plugin to close event
|
||||
if (!listenerMap[name]) listenerMap[name] = []
|
||||
@@ -146,21 +141,11 @@ export namespace event {
|
||||
if (off['offed']) return
|
||||
off['offed'] = true
|
||||
this.unregister(eventCls, listener)
|
||||
console.debug(i18n.translate("ms.api.event.unregister", {
|
||||
name,
|
||||
event: this.class2Name(eventCls),
|
||||
exec: executor
|
||||
}))
|
||||
console.debug(i18n.translate("ms.api.event.unregister", { name, event: this.class2Name(eventCls), exec: executor }))
|
||||
}
|
||||
listenerMap[name].push(off)
|
||||
// noinspection JSUnresolvedVariable
|
||||
console.debug(i18n.translate("ms.api.event.register", {
|
||||
name,
|
||||
event: this.class2Name(eventCls),
|
||||
exec: executor,
|
||||
priority,
|
||||
ignore: ignoreCancel
|
||||
}))
|
||||
console.debug(i18n.translate("ms.api.event.register", { name, event: this.class2Name(eventCls), exec: executor }))
|
||||
return off
|
||||
}
|
||||
|
||||
|
||||
@@ -4,13 +4,11 @@ export * from './web'
|
||||
export * from './amqp'
|
||||
export * from './chat'
|
||||
export * from './task'
|
||||
export * from './item'
|
||||
export * from './event'
|
||||
export * from './proxy'
|
||||
export * from './plugin'
|
||||
export * from './server'
|
||||
export * from './console'
|
||||
export { jsconsole as console } from './console'
|
||||
export * from './channel'
|
||||
export * from './command'
|
||||
export * from './database'
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
import { injectable } from '@ccms/container'
|
||||
|
||||
export namespace item {
|
||||
@injectable()
|
||||
export abstract class Item {
|
||||
abstract builder(): ItemBuilder
|
||||
abstract toJson(item: any): string
|
||||
abstract fromJSON(json: string): any
|
||||
}
|
||||
export interface ItemBuilder {
|
||||
from(item: any): ItemBuilder
|
||||
create(type: string | number): ItemBuilder
|
||||
name(name: string): ItemBuilder
|
||||
lore(...lores: string[]): ItemBuilder
|
||||
amount(amount: number): ItemBuilder
|
||||
durability(durability: number): ItemBuilder
|
||||
clone(): any
|
||||
build(): any
|
||||
}
|
||||
}
|
||||
@@ -20,7 +20,7 @@ export namespace plugin {
|
||||
export abstract class PluginManager {
|
||||
abstract scan(folder: string): void
|
||||
abstract build(): void
|
||||
abstract loadFromFile(file: string, ext?: any): Plugin
|
||||
abstract loadFromFile(file: string, ext: any): Plugin
|
||||
abstract load(...args: any[]): void
|
||||
abstract enable(...args: any[]): void
|
||||
abstract disable(...args: any[]): void
|
||||
@@ -149,15 +149,7 @@ export namespace plugin {
|
||||
/**
|
||||
* 插件名称 不填默认为类名
|
||||
*/
|
||||
name: string
|
||||
/**
|
||||
* 插件中文名称
|
||||
*/
|
||||
cname?: string
|
||||
/**
|
||||
* 插件等级 付费插件自动注入
|
||||
*/
|
||||
level?: number
|
||||
name?: string
|
||||
/**
|
||||
* 前缀
|
||||
*/
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/bukkit",
|
||||
"version": "0.23.0-alpha.0",
|
||||
"version": "0.19.5",
|
||||
"description": "MiaoScript bukkit package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -22,11 +22,11 @@
|
||||
"@javatypes/spigot-api": "^0.0.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.6.3"
|
||||
"typescript": "^4.5.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.23.0-alpha.0",
|
||||
"@ccms/common": "^0.23.0-alpha.0",
|
||||
"@ccms/container": "^0.22.0"
|
||||
"@ccms/api": "^0.19.5",
|
||||
"@ccms/common": "^0.19.0",
|
||||
"@ccms/container": "^0.19.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ import { event, plugin } from '@ccms/api'
|
||||
import { inject, provideSingleton } from '@ccms/container'
|
||||
import * as reflect from '@ccms/common/dist/reflect'
|
||||
|
||||
const URL = Java.type('java.net.URL')
|
||||
const Bukkit = Java.type("org.bukkit.Bukkit")
|
||||
const Event = Java.type("org.bukkit.event.Event")
|
||||
const Modifier = Java.type("java.lang.reflect.Modifier")
|
||||
@@ -20,15 +19,7 @@ export class BukkitEvent extends event.Event {
|
||||
}
|
||||
|
||||
getJarFile(resource: string) {
|
||||
try {
|
||||
return super.getJarFile('org/bukkit/Bukkit.class', Bukkit.class.classLoader)
|
||||
} catch (error) {
|
||||
// 兼容 LoliServer 的 Bukkit 包无法获取的问题
|
||||
let ModList = Java.type('net.minecraftforge.fml.ModList').get()
|
||||
let forgeFile = ModList.getModFileById("forge").getFile().getFilePath()
|
||||
let jarPath = `jar:file:${forgeFile}!/org/bukkit/Bukkit.class`
|
||||
return new URL(jarPath).openConnection().jarFile
|
||||
}
|
||||
return super.getJarFile('org/bukkit/Bukkit.class', Bukkit.class.classLoader)
|
||||
}
|
||||
isValidEvent(clazz: any): boolean {
|
||||
// 继承于 org.bukkit.event.Event
|
||||
|
||||
@@ -4,7 +4,6 @@ import { server } from '@ccms/api'
|
||||
import { Container } from '@ccms/container'
|
||||
|
||||
import { BukkitConsole } from './console'
|
||||
import './item'
|
||||
import './chat'
|
||||
import './task'
|
||||
import './event'
|
||||
|
||||
@@ -6,14 +6,12 @@ let bukkitChatInvoke: BukkitChatInvoke
|
||||
abstract class BukkitChatInvoke {
|
||||
private downgrade: boolean = false
|
||||
protected RemapUtils: any
|
||||
protected ComponentSerializer:any
|
||||
|
||||
protected ChatSerializer: any
|
||||
protected nmsChatSerializerMethodName: string
|
||||
protected PacketPlayOutChat: any
|
||||
protected chatMessageTypes: any
|
||||
protected playerConnectionFieldName: string
|
||||
protected playerFieldName: string
|
||||
protected sendPacketMethodName: string
|
||||
|
||||
constructor(private nmsVersion) {
|
||||
@@ -22,12 +20,12 @@ abstract class BukkitChatInvoke {
|
||||
init() {
|
||||
try {
|
||||
try {
|
||||
this.ComponentSerializer = Java.type('net.md_5.bungee.chat.ComponentSerializer')
|
||||
this.RemapUtils = Java.type('catserver.server.remapper.RemapUtils')
|
||||
} catch (ex: any) {
|
||||
}
|
||||
let nmsChatSerializerClass = this.getNmsChatSerializerClass()
|
||||
this.nmsChatSerializerMethodName = this.getNmsChatSerializerMethodName(nmsChatSerializerClass)
|
||||
let nmsChatSerializerMethod = this.remapMethod(nmsChatSerializerClass, 'a', 'func_150699_a', base.getClass('java.lang.String'))
|
||||
this.nmsChatSerializerMethodName = nmsChatSerializerMethod.getName()
|
||||
this.ChatSerializer = Java.type(nmsChatSerializerClass.getName())
|
||||
let packetTypeClass = this.getPacketPlayOutChatClass()
|
||||
this.PacketPlayOutChat = Java.type(packetTypeClass.getName())
|
||||
@@ -44,7 +42,7 @@ abstract class BukkitChatInvoke {
|
||||
}
|
||||
let playerConnectionField = this.getPlayerConnectionField()
|
||||
this.playerConnectionFieldName = playerConnectionField.getName()
|
||||
this.sendPacketMethodName = this.getSendPacketMethodName(playerConnectionField.getType())
|
||||
this.sendPacketMethodName = this.remapMethod(playerConnectionField.getType(), 'sendPacket', 'func_179290_a', this.getPacketClass()).getName()
|
||||
} catch (ex: any) {
|
||||
org.bukkit.Bukkit.getConsoleSender().sendMessage(`§6[§cMS§6][§bbukkit§6][§achat§6] §cNMS Inject Error §4${ex} §cDowngrade to Command Mode...`)
|
||||
this.downgrade = true
|
||||
@@ -52,12 +50,10 @@ abstract class BukkitChatInvoke {
|
||||
}
|
||||
|
||||
abstract getNmsChatSerializerClass()
|
||||
abstract getNmsChatSerializerMethodName(nmsChatSerializerClass: any)
|
||||
abstract getPacketPlayOutChatClass()
|
||||
abstract getPacketPlayOutChat(sender: any, json: any, type: number)
|
||||
abstract getPlayerConnectionField()
|
||||
abstract getPacketClass()
|
||||
abstract getSendPacketMethodName(playerConnectionClass: any)
|
||||
|
||||
nmsCls(name: string) {
|
||||
return base.getClass(['net.minecraft.server', this.nmsVersion, name].join('.'))
|
||||
@@ -87,9 +83,9 @@ abstract class BukkitChatInvoke {
|
||||
}
|
||||
}
|
||||
|
||||
json(sender: any, json: string) {
|
||||
json(sender: { name: string }, json: string) {
|
||||
if (this.downgrade) {
|
||||
return sender.spigot().sendMessage(this.ComponentSerializer.parse(json))
|
||||
return '/tellraw ' + sender.name + ' ' + json
|
||||
} else {
|
||||
this.send(sender, json, 0)
|
||||
return false
|
||||
@@ -104,13 +100,6 @@ abstract class BukkitChatInvoke {
|
||||
}
|
||||
|
||||
class BukkitChatInvokeBase extends BukkitChatInvoke {
|
||||
getSendPacketMethodName(playerConnectionClass: any) {
|
||||
return this.remapMethod(playerConnectionClass, 'sendPacket', 'func_179290_a', this.getPacketClass()).getName()
|
||||
}
|
||||
getNmsChatSerializerMethodName(nmsChatSerializerClass: any) {
|
||||
let nmsChatSerializerMethod = this.remapMethod(nmsChatSerializerClass, 'a', 'func_150699_a', base.getClass('java.lang.String'))
|
||||
return nmsChatSerializerMethod.getName()
|
||||
}
|
||||
getPacketPlayOutChat(sender: any, json: any, type: number) {
|
||||
return new this.PacketPlayOutChat(this.ChatSerializer[this.nmsChatSerializerMethodName](json), type)
|
||||
}
|
||||
@@ -160,31 +149,17 @@ class BukkitChatInvoke_1_17_1 extends BukkitChatInvoke_1_16_5 {
|
||||
}
|
||||
}
|
||||
|
||||
class BukkitChatInvoke_1_19 extends BukkitChatInvoke_1_17_1 {
|
||||
getSendPacketMethodName(playerConnectionClass: any) {
|
||||
return playerConnectionClass.getMethod('a', this.getPacketClass()).getName()
|
||||
}
|
||||
getPacketPlayOutChatClass() {
|
||||
return base.getClass('net.minecraft.network.protocol.game.ClientboundSystemChatPacket')
|
||||
}
|
||||
getPacketPlayOutChat(sender: any, json: any, type: number) {
|
||||
return new this.PacketPlayOutChat(this.ChatSerializer[this.nmsChatSerializerMethodName](json), type == 0 ? 1 : type)
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
let Bukkit: typeof org.bukkit.Bukkit = Java.type('org.bukkit.Bukkit')
|
||||
// @ts-ignore
|
||||
let nmsVersion = Bukkit.getServer().class.name.split('.')[3]
|
||||
let nmsSubVersion = nmsVersion.split("_")[1]
|
||||
if (nmsSubVersion >= 19) {
|
||||
bukkitChatInvoke = new BukkitChatInvoke_1_19(nmsVersion)
|
||||
} else if (nmsSubVersion >= 17) {
|
||||
bukkitChatInvoke = new BukkitChatInvoke_1_17_1(nmsVersion)
|
||||
if (nmsSubVersion >= 8) {
|
||||
bukkitChatInvoke = new BukkitChatInvoke_1_8(nmsVersion)
|
||||
} else if (nmsSubVersion >= 16) {
|
||||
bukkitChatInvoke = new BukkitChatInvoke_1_16_5(nmsVersion)
|
||||
} else if (nmsSubVersion >= 8) {
|
||||
bukkitChatInvoke = new BukkitChatInvoke_1_8(nmsVersion)
|
||||
} else if (nmsSubVersion >= 17) {
|
||||
bukkitChatInvoke = new BukkitChatInvoke_1_17_1(nmsVersion)
|
||||
} else {
|
||||
bukkitChatInvoke = new BukkitChatInvoke_1_7_10(nmsVersion)
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,126 +0,0 @@
|
||||
import { item } from "@ccms/api"
|
||||
import { provideSingleton } from "@ccms/container"
|
||||
|
||||
import { itemIds } from './internal/item'
|
||||
|
||||
const Material: typeof org.bukkit.Material = Java.type('org.bukkit.Material')
|
||||
const ItemStack: typeof org.bukkit.inventory.ItemStack = Java.type('org.bukkit.inventory.ItemStack')
|
||||
|
||||
@provideSingleton(item.Item)
|
||||
export class BukkitItem extends item.Item {
|
||||
private CraftItemStack: any
|
||||
private NBTTagCompound: any
|
||||
private nmsSaveNBTMethodName: any
|
||||
private MojangsonParser: any
|
||||
private mpParseMethodName: any
|
||||
private nmsVersion: any
|
||||
constructor() {
|
||||
super()
|
||||
this.reflect()
|
||||
}
|
||||
builder(): item.ItemBuilder {
|
||||
return new BukkitItemBuilder()
|
||||
}
|
||||
toJson(item: any): string {
|
||||
let nbt = new this.NBTTagCompound()
|
||||
return this.CraftItemStack.asNMSCopy(item)[this.nmsSaveNBTMethodName](nbt).toString()
|
||||
}
|
||||
fromJSON(json: string) {
|
||||
return this.CraftItemStack.asBukkitCopy(this.MojangsonParser[this.mpParseMethodName](json))
|
||||
}
|
||||
private obcCls(name: string) {
|
||||
return base.getClass(['org.bukkit.craftbukkit', this.nmsVersion, name].join('.'))
|
||||
}
|
||||
private nmsCls(name: string) {
|
||||
return base.getClass(['net.minecraft.server', this.nmsVersion, name].join('.'))
|
||||
}
|
||||
private reflect() {
|
||||
try {
|
||||
let Bukkit: typeof org.bukkit.Bukkit = Java.type('org.bukkit.Bukkit')
|
||||
// @ts-ignore
|
||||
this.nmsVersion = Bukkit.getServer().class.name.split('.')[3]
|
||||
let CraftItemStackClass = this.obcCls('inventory.CraftItemStack')
|
||||
this.CraftItemStack = Java.type(CraftItemStackClass.getName())
|
||||
// @ts-ignore
|
||||
let asNMSCopyMethod = CraftItemStackClass.getMethod('asNMSCopy', ItemStack.class)
|
||||
let nmsItemStackClass = asNMSCopyMethod.getReturnType()
|
||||
let nmsNBTTagCompoundClass = undefined
|
||||
for (let method of Java.from(nmsItemStackClass.getMethods())) {
|
||||
let rt = method.getReturnType()
|
||||
if (method.getParameterTypes().length == 0 && "NBTTagCompound" == rt.getSimpleName()) {
|
||||
nmsNBTTagCompoundClass = rt
|
||||
}
|
||||
}
|
||||
this.NBTTagCompound = Java.type(nmsNBTTagCompoundClass.getName())
|
||||
for (let method of Java.from(nmsItemStackClass.getMethods())) {
|
||||
let params = method.getParameterTypes()
|
||||
let rt = method.getReturnType()
|
||||
if (params.length == 1 && "NBTTagCompound" == params[0].getSimpleName() && "NBTTagCompound" == rt.getSimpleName()) {
|
||||
this.nmsSaveNBTMethodName = method.getName()
|
||||
break
|
||||
}
|
||||
}
|
||||
try {
|
||||
this.MojangsonParser = this.nmsCls('MojangsonParser')
|
||||
} catch (error) {
|
||||
this.MojangsonParser = Java.type('net.minecraft.nbt.MojangsonParser')
|
||||
}
|
||||
for (let method of Java.from(this.MojangsonParser.class.getMethods())) {
|
||||
let params = method.getParameterTypes()
|
||||
let rt = method.getReturnType()
|
||||
if (params.length == 1 && "String" == params[0].getSimpleName() && "NBTTagCompound" == rt.getSimpleName()) {
|
||||
this.mpParseMethodName = method.getName()
|
||||
}
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.log('Bukkit 物品管理器初始化失败:', error)
|
||||
if (global.debug) {
|
||||
console.ex(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class BukkitItemBuilder implements item.ItemBuilder {
|
||||
private itemStack: org.bukkit.inventory.ItemStack
|
||||
private itemMeta: org.bukkit.inventory.meta.ItemMeta
|
||||
|
||||
from(itemStack: any): item.ItemBuilder {
|
||||
this.itemStack = itemStack
|
||||
this.itemMeta = this.itemStack.getItemMeta()
|
||||
return this
|
||||
}
|
||||
create(type: string | number): item.ItemBuilder {
|
||||
let material = undefined
|
||||
if (typeof type == 'number') {
|
||||
type = itemIds[type]
|
||||
}
|
||||
material = Material[type] || Material[Material['LEGACY_PREFIX'] + type]
|
||||
this.itemStack = new ItemStack(material)
|
||||
this.itemMeta = this.itemStack.getItemMeta()
|
||||
return this
|
||||
}
|
||||
name(name: string): item.ItemBuilder {
|
||||
this.itemMeta.setDisplayName(name)
|
||||
return this
|
||||
}
|
||||
lore(...lores: string[]): item.ItemBuilder {
|
||||
this.itemMeta.setLore(lores)
|
||||
return this
|
||||
}
|
||||
amount(amount: number): item.ItemBuilder {
|
||||
this.itemStack.setAmount(amount)
|
||||
return this
|
||||
}
|
||||
durability(durability: number): item.ItemBuilder {
|
||||
this.itemStack.setDurability(durability)
|
||||
return this
|
||||
}
|
||||
clone() {
|
||||
return this.build().clone()
|
||||
}
|
||||
build() {
|
||||
this.itemStack.setItemMeta(this.itemMeta)
|
||||
return this.itemStack
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,6 @@
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"baseUrl": "src",
|
||||
"outDir": "dist",
|
||||
"resolveJsonModule": true
|
||||
"outDir": "dist"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/bungee",
|
||||
"version": "0.23.0-alpha.0",
|
||||
"version": "0.19.5",
|
||||
"description": "MiaoScript bungee package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -22,11 +22,11 @@
|
||||
"@javatypes/bungee-api": "^0.0.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.6.3"
|
||||
"typescript": "^4.5.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.23.0-alpha.0",
|
||||
"@ccms/common": "^0.23.0-alpha.0",
|
||||
"@ccms/container": "^0.22.0"
|
||||
"@ccms/api": "^0.19.5",
|
||||
"@ccms/common": "^0.19.0",
|
||||
"@ccms/container": "^0.19.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"private": true,
|
||||
"name": "@ccms/client",
|
||||
"version": "0.22.0",
|
||||
"version": "0.19.0",
|
||||
"description": "MiaoScript client package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -24,14 +24,14 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"axios": "^0.27.2",
|
||||
"minecraft-protocol": "^1.34.0",
|
||||
"axios": "^0.25.0",
|
||||
"minecraft-protocol": "^1.30.0",
|
||||
"minecraft-protocol-forge": "^1.0.0",
|
||||
"proxy-agent": "^5.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^17.0.25",
|
||||
"@types/node": "^17.0.17",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.6.3"
|
||||
"typescript": "^4.5.5"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@ccms/common",
|
||||
"version": "0.23.0-alpha.0",
|
||||
"description": "MiaoScript common package",
|
||||
"version": "0.19.0",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
"minecraft",
|
||||
@@ -19,11 +19,11 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.22.0",
|
||||
"@ccms/nashorn": "^0.19.0",
|
||||
"@javatypes/jdk": "^0.0.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.6.3"
|
||||
"typescript": "^4.5.5"
|
||||
},
|
||||
"gitHead": "562e2d00175c9d3a99c8b672aa07e6d92706a027"
|
||||
}
|
||||
|
||||
@@ -129,14 +129,12 @@ function declaredField(clazz: java.lang.Class<any>, name: string | java.lang.Str
|
||||
let field = null
|
||||
// noinspection JSUnresolvedVariable
|
||||
while (target !== JavaObject.class) {
|
||||
console.debug(`reflect field ${name} from ${target.getName()}`)
|
||||
try {
|
||||
field = target.getDeclaredField(name)
|
||||
if (field !== null) { break }
|
||||
} catch (error: any) {
|
||||
if (target === undefined) { break }
|
||||
target = target.getSuperclass()
|
||||
console.debug(`切换到超类: ${target.getName()}`)
|
||||
}
|
||||
}
|
||||
if (field === null) {
|
||||
@@ -148,32 +146,21 @@ function declaredField(clazz: java.lang.Class<any>, name: string | java.lang.Str
|
||||
function declaredMethod(clazz: java.lang.Class<any>, nameOrIndex: string | number, ...clazzs: java.lang.Class<any>[]): java.lang.reflect.Method {
|
||||
let key = clazz.getName() + '.' + nameOrIndex + ':' + (clazzs || []).map(c => c.getName()).join(':')
|
||||
if (methodCache.has(key)) { return methodCache.get(key) }
|
||||
let target = clazz
|
||||
if (typeof nameOrIndex === "number") {
|
||||
methodCache.set(key, declaredMethods(clazz)[nameOrIndex])
|
||||
} else {
|
||||
while (target !== JavaObject.class && !methodCache.has(key)) {
|
||||
try {
|
||||
methodCache.set(key, clazz.getMethod(nameOrIndex, clazzs as any))
|
||||
} catch (ex: any) {
|
||||
try {
|
||||
console.debug(`reflect method ${typeof nameOrIndex == "number" ? 'index' : 'name'} ${nameOrIndex} from ${target.getName()}`)
|
||||
try {
|
||||
methodCache.set(key, target.getMethod(nameOrIndex, clazzs as any))
|
||||
} catch (ex: any) {
|
||||
try {
|
||||
methodCache.set(key, target.getDeclaredMethod(nameOrIndex, clazzs as any))
|
||||
} catch (ex: any) {
|
||||
for (const m of Java.from(declaredMethods(target))) {
|
||||
if (m.getName() == nameOrIndex) {
|
||||
methodCache.set(key, m)
|
||||
break
|
||||
}
|
||||
}
|
||||
throw new Error(`method ${typeof nameOrIndex == "number" ? 'index' : 'name'} ${nameOrIndex} not found.`)
|
||||
methodCache.set(key, clazz.getDeclaredMethod(nameOrIndex, clazzs as any))
|
||||
} catch (ex: any) {
|
||||
for (const m of Java.from(declaredMethods(clazz))) {
|
||||
if (m.getName() == nameOrIndex) {
|
||||
methodCache.set(key, m)
|
||||
break
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (target === undefined) { break }
|
||||
target = target.getSuperclass()
|
||||
console.debug(`切换到超类: ${target.getName()}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,14 +17,14 @@ class ChatMessagePart {
|
||||
}
|
||||
|
||||
convert() {
|
||||
return this.internal
|
||||
return this.internal;
|
||||
}
|
||||
}
|
||||
|
||||
class Tellraw {
|
||||
static duplicateChar = '§卐'
|
||||
static create() {
|
||||
return new Tellraw().then(Tellraw.duplicateChar)
|
||||
return new Tellraw().then(Tellraw.duplicateChar);
|
||||
}
|
||||
|
||||
private cache: string = '';
|
||||
@@ -32,81 +32,77 @@ class Tellraw {
|
||||
|
||||
then(part: ChatMessagePart | string) {
|
||||
if (typeof part === "string") {
|
||||
var newPart = new ChatMessagePart()
|
||||
var newPart = new ChatMessagePart();
|
||||
newPart.text = part
|
||||
this.then(newPart)
|
||||
return this
|
||||
this.then(newPart);
|
||||
return this;
|
||||
}
|
||||
var last = this.latest()
|
||||
var last = this.latest();
|
||||
if (!last.text) {
|
||||
last.text = part.text
|
||||
last.text = part.text;
|
||||
} else {
|
||||
this.parts.push(part)
|
||||
this.parts.push(part);
|
||||
}
|
||||
this.cache = null
|
||||
this.cache = null;
|
||||
}
|
||||
|
||||
text(text: string) {
|
||||
this.latest().text = text
|
||||
return this
|
||||
this.latest().text = text;
|
||||
return this;
|
||||
}
|
||||
|
||||
tip(texts: string) {
|
||||
return this.hover(texts)
|
||||
tip(text: string) {
|
||||
this.latest().hover("show_text", text);
|
||||
return this;
|
||||
}
|
||||
|
||||
hover(texts: string) {
|
||||
this.latest().hover("show_text", texts)
|
||||
return this
|
||||
}
|
||||
|
||||
item(item: string) {
|
||||
this.latest().hover("show_item", item)
|
||||
return this
|
||||
item(text: string) {
|
||||
this.latest().hover("show_item", text);
|
||||
return this;
|
||||
}
|
||||
|
||||
command(command: string) {
|
||||
this.latest().click("run_command", command)
|
||||
return this
|
||||
this.latest().click("run_command", command);
|
||||
return this;
|
||||
}
|
||||
|
||||
suggest(url: string) {
|
||||
this.latest().click("suggest_command", url)
|
||||
return this
|
||||
this.latest().click("suggest_command", url);
|
||||
return this;
|
||||
}
|
||||
|
||||
file(path: string) {
|
||||
this.latest().click("open_file", path)
|
||||
return this
|
||||
this.latest().click("open_file", path);
|
||||
return this;
|
||||
}
|
||||
|
||||
link(url: string) {
|
||||
this.latest().click("open_url", url)
|
||||
return this
|
||||
this.latest().click("open_url", url);
|
||||
return this;
|
||||
}
|
||||
|
||||
latest() {
|
||||
return this.parts[this.parts.length - 1]
|
||||
return this.parts[this.parts.length - 1];
|
||||
}
|
||||
|
||||
json() {
|
||||
if (!this.cache) {
|
||||
var temp = []
|
||||
var temp = [];
|
||||
this.parts.forEach(t => {
|
||||
temp.push(t.convert())
|
||||
})
|
||||
this.cache = JSON.stringify(temp)
|
||||
console.trace(this.cache)
|
||||
temp.push(t.convert());
|
||||
});
|
||||
this.cache = JSON.stringify(temp);
|
||||
console.trace(this.cache);
|
||||
}
|
||||
return this.cache
|
||||
return this.cache;
|
||||
}
|
||||
|
||||
string() {
|
||||
var temp = ''
|
||||
var temp = '';
|
||||
this.parts.forEach(t => {
|
||||
temp += t.text
|
||||
})
|
||||
return temp
|
||||
});
|
||||
return temp;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
export type Version = [string, string, string]
|
||||
|
||||
export class VersionUtils {
|
||||
static isEqual(version: string, targetVersion: string): boolean {
|
||||
return version == targetVersion
|
||||
}
|
||||
static isGreaterOrEqual(version: string, targetVersion: string): boolean {
|
||||
const v1 = parseVersion(version)
|
||||
const v2 = parseVersion(targetVersion)
|
||||
|
||||
return (
|
||||
v1[0] > v2[0] ||
|
||||
(v1[0] === v2[0] && v1[1] > v2[1]) ||
|
||||
(v1[0] === v2[0] && v1[1] === v2[1] && v1[2] >= v2[2])
|
||||
)
|
||||
}
|
||||
static isGreater(version: string, targetVersion: string): boolean {
|
||||
const v1 = parseVersion(version)
|
||||
const v2 = parseVersion(targetVersion)
|
||||
|
||||
return (
|
||||
v1[0] > v2[0] ||
|
||||
(v1[0] === v2[0] && v1[1] > v2[1]) ||
|
||||
(v1[0] === v2[0] && v1[1] === v2[1] && v1[2] > v2[2])
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function parseVersion(version: string = ""): Version {
|
||||
const v: Version = ['0', '0', '0']
|
||||
|
||||
version.split(".").forEach((value, i) => (v[i] = value))
|
||||
|
||||
return v
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/compile",
|
||||
"version": "0.22.0",
|
||||
"version": "0.19.0",
|
||||
"description": "MiaoScript compile package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -21,6 +21,6 @@
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.6.3"
|
||||
"typescript": "^4.5.5"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/container",
|
||||
"version": "0.22.0",
|
||||
"version": "0.19.0",
|
||||
"description": "MiaoScript container package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,10 +19,10 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.22.0",
|
||||
"@ccms/nashorn": "^0.19.0",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.6.3"
|
||||
"typescript": "^4.5.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"inversify": "^6.0.1",
|
||||
|
||||
@@ -1,9 +1,38 @@
|
||||
import { interfaces, Container } from "inversify"
|
||||
import { _proxyGetter } from "./utils"
|
||||
|
||||
let _container: Container
|
||||
|
||||
const ContainerInstance = Symbol.for("@ccms/ioc:Container")
|
||||
const INJECTION = Symbol.for("INJECTION")
|
||||
|
||||
function _proxyGetter(
|
||||
proto: any,
|
||||
key: string,
|
||||
resolve: () => any,
|
||||
doCache: boolean
|
||||
) {
|
||||
function getter(this: object) {
|
||||
if (doCache && !Reflect.hasMetadata(INJECTION, this, key)) {
|
||||
Reflect.defineMetadata(INJECTION, resolve(), this, key)
|
||||
}
|
||||
if (Reflect.hasMetadata(INJECTION, this, key)) {
|
||||
return Reflect.getMetadata(INJECTION, this, key)
|
||||
} else {
|
||||
return resolve()
|
||||
}
|
||||
}
|
||||
|
||||
function setter(this: object, newVal: any) {
|
||||
Reflect.defineMetadata(INJECTION, newVal, this, key)
|
||||
}
|
||||
|
||||
Object.defineProperty(proto, key, {
|
||||
configurable: true,
|
||||
enumerable: true,
|
||||
get: getter,
|
||||
set: setter
|
||||
})
|
||||
}
|
||||
|
||||
function initContainer(container: Container) {
|
||||
Reflect.defineMetadata(ContainerInstance, container, Reflect)
|
||||
|
||||
@@ -5,7 +5,6 @@ import { initContainer, getContainer } from './decorators'
|
||||
import { interfaces, Container, inject, named } from 'inversify'
|
||||
import { fluentProvide } from 'inversify-binding-decorators'
|
||||
import { ioc } from "./constants"
|
||||
import { _proxyGetter } from "./utils"
|
||||
|
||||
/**
|
||||
* 注册一个命名对象
|
||||
@@ -50,11 +49,9 @@ export const JavaClass = (className: string) => {
|
||||
*/
|
||||
export const JSClass = (className: string) => {
|
||||
return function (target: object, propertyKey: string, index?: number) {
|
||||
_proxyGetter(target, propertyKey, () => {
|
||||
try { return Java.type(className) } catch (error: any) { }
|
||||
try { return base.getClass(className).static } catch (error: any) { }
|
||||
console.warn('JSClass', className, 'Inject target', target.constructor.name, 'propertyKey', propertyKey, 'failed!')
|
||||
}, true)
|
||||
try { target[propertyKey] = Java.type(className); return } catch (error: any) { }
|
||||
try { target[propertyKey] = base.getClass(className).static; return } catch (error: any) { }
|
||||
console.warn('JSClass', className, 'Inject target', target.constructor.name, 'propertyKey', propertyKey, 'failed!')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -91,59 +88,6 @@ export const Resource = (resourceName?: string | any) => {
|
||||
}
|
||||
}
|
||||
|
||||
const DocumentBuilderFactory = Java.type('javax.xml.parsers.DocumentBuilderFactory')
|
||||
|
||||
export const MavenDepend = (groupId: string, artifactId: string, version: string, recursion = false) => {
|
||||
return function (target: any) {
|
||||
loadMavenDepend(groupId, artifactId, version, recursion)
|
||||
}
|
||||
}
|
||||
|
||||
const loadedMavenDepend = new Set<string>()
|
||||
|
||||
export function loadMavenDepend(groupId: string, artifactId: string, version: string, recursion = false) {
|
||||
const key = `${groupId}:${artifactId}:${version}`
|
||||
try {
|
||||
if (loadedMavenDepend.has(key)) { return }
|
||||
console.info('loading maven dependency', key)
|
||||
let [pom, _] = base.loadMavenDepend(groupId, artifactId, version)
|
||||
loadedMavenDepend.add(key)
|
||||
if (recursion) {
|
||||
let doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(pom)
|
||||
let dependencies = doc.getElementsByTagName("dependency")
|
||||
let size = dependencies.length
|
||||
if (!size) { return }
|
||||
console.debug(key, 'found', size, 'dependencies loading...')
|
||||
for (let i = 0; i < size; i++) {
|
||||
const dependency = dependencies.item(i)
|
||||
const gav = dependency.getChildNodes()
|
||||
const length = gav.length
|
||||
const dependencyVersion = { groupId: '', artifactId: '', version: '' }
|
||||
for (let j = 0; j < length; j++) {
|
||||
const prop = gav.item(j)
|
||||
switch (prop.getNodeName()) {
|
||||
case "groupId":
|
||||
dependencyVersion.groupId = prop.getTextContent()
|
||||
break
|
||||
case "artifactId":
|
||||
dependencyVersion.artifactId = prop.getTextContent()
|
||||
break
|
||||
case "version":
|
||||
dependencyVersion.version = prop.getTextContent()
|
||||
break
|
||||
}
|
||||
}
|
||||
loadMavenDepend(dependencyVersion.groupId, dependencyVersion.artifactId, dependencyVersion.version, recursion)
|
||||
}
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.warn('load maven dependency', key, 'failed. Error:', error)
|
||||
if (global.debug) {
|
||||
console.ex(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const reduceMetadata = (ctx: interfaces.Context): any => {
|
||||
return ctx.currentRequest.target.metadata.reduce((result, entry, index) => {
|
||||
result[entry.key] = entry.value
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
const INJECTION = Symbol.for("INJECTION")
|
||||
|
||||
export function _proxyGetter(
|
||||
proto: any,
|
||||
key: string,
|
||||
resolve: () => any,
|
||||
doCache: boolean
|
||||
) {
|
||||
function getter(this: object) {
|
||||
if (doCache && !Reflect.hasMetadata(INJECTION, this, key)) {
|
||||
Reflect.defineMetadata(INJECTION, resolve(), this, key)
|
||||
}
|
||||
if (Reflect.hasMetadata(INJECTION, this, key)) {
|
||||
return Reflect.getMetadata(INJECTION, this, key)
|
||||
} else {
|
||||
return resolve()
|
||||
}
|
||||
}
|
||||
|
||||
function setter(this: object, newVal: any) {
|
||||
Reflect.defineMetadata(INJECTION, newVal, this, key)
|
||||
}
|
||||
|
||||
Object.defineProperty(proto, key, {
|
||||
configurable: true,
|
||||
enumerable: true,
|
||||
get: getter,
|
||||
set: setter
|
||||
})
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@ccms/core",
|
||||
"version": "0.23.0-alpha.0",
|
||||
"description": "MiaoScript core package",
|
||||
"version": "0.19.5",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
"minecraft",
|
||||
@@ -21,11 +21,11 @@
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.6.3"
|
||||
"typescript": "^4.5.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.23.0-alpha.0",
|
||||
"@ccms/container": "^0.22.0"
|
||||
"@ccms/api": "^0.19.5",
|
||||
"@ccms/container": "^0.19.0"
|
||||
},
|
||||
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
||||
}
|
||||
|
||||
4
packages/core/src/exit.js
Normal file
4
packages/core/src/exit.js
Normal file
@@ -0,0 +1,4 @@
|
||||
function exit() {
|
||||
console.debug('exit finish!')
|
||||
}
|
||||
exit()
|
||||
@@ -1,14 +1,9 @@
|
||||
let containerStartTime = Date.now()
|
||||
console.i18n("ms.core.ioc.initialize", { scope: global.scope })
|
||||
import { plugin, server, task, constants, console as jsconsole } from '@ccms/api'
|
||||
import { plugin, server, task, constants } from '@ccms/api'
|
||||
import { DefaultContainer as container, provideSingleton, ContainerInstance, buildProviderModule, Autowired } from '@ccms/container'
|
||||
console.i18n("ms.core.ioc.completed", { scope: global.scope, time: (Date.now() - containerStartTime) / 1000 })
|
||||
import * as yaml from 'js-yaml'
|
||||
import http from '@ccms/common/dist/http'
|
||||
import * as fs from '@ccms/common/dist/fs'
|
||||
import { VersionUtils } from '@ccms/common/dist/version'
|
||||
|
||||
const UUID = Java.type('java.util.UUID')
|
||||
|
||||
@provideSingleton(MiaoScriptCore)
|
||||
class MiaoScriptCore {
|
||||
@@ -26,11 +21,6 @@ class MiaoScriptCore {
|
||||
this.loadServerConsole()
|
||||
this.loadPlugins()
|
||||
process.emit('core.after.enable')
|
||||
console.i18n("ms.core.engine.completed", {
|
||||
loader: base.version,
|
||||
version: 'v' + global.ScriptEngineVersion,
|
||||
time: (Date.now() - global.ScriptEngineStartTime) / 1000
|
||||
})
|
||||
return () => this.disable()
|
||||
}
|
||||
|
||||
@@ -60,7 +50,14 @@ class MiaoScriptCore {
|
||||
this.pluginManager.disable(this.pluginManager.getPlugins())
|
||||
this.taskManager.disable()
|
||||
process.emit('core.after.disable')
|
||||
loadCoreScript('exit')
|
||||
try {
|
||||
engineLoad({
|
||||
script: http.get("https://ms.yumc.pw/api/plugin/download/name/exit"),
|
||||
name: 'core/exit.js'
|
||||
})
|
||||
} catch (error: any) {
|
||||
console.debug(error)
|
||||
}
|
||||
process.emit('core.before.exit')
|
||||
process.exit(0)
|
||||
console.i18n("ms.core.engine.disable.finish", {
|
||||
@@ -101,75 +98,52 @@ function detectServer(): constants.ServerType {
|
||||
throw Error('Unknow Server Type...')
|
||||
}
|
||||
|
||||
function loadCoreScript(name) {
|
||||
try {
|
||||
let scriptname = name + (global.debug ? '-debug' : '')
|
||||
engineLoad({
|
||||
script: http.get(`https://ms.yumc.pw/api/plugin/download/name/${scriptname}`),
|
||||
name: `core/${scriptname}.js`
|
||||
})
|
||||
} catch (error: any) {
|
||||
if (global.debug) {
|
||||
console.debug(error)
|
||||
console.ex(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function loadMiaoScriptConfig() {
|
||||
let configFile = fs.concat(root, 'config.yml')
|
||||
if (!fs.exists(configFile)) {
|
||||
global.ScriptEngineConfig = base.save(configFile, yaml.dump({
|
||||
uuid: UUID.randomUUID().toString(),
|
||||
slow_execute: 50
|
||||
}))
|
||||
} else {
|
||||
global.ScriptEngineConfig = yaml.load(base.read(configFile))
|
||||
}
|
||||
global.ScriptSlowExecuteTime = global.ScriptEngineConfig.slow_execute || 50
|
||||
}
|
||||
|
||||
function createCore() {
|
||||
let corePackageStartTime = new Date().getTime()
|
||||
container.bind(ContainerInstance).toConstantValue(container)
|
||||
container.bind(plugin.PluginInstance).toConstantValue(base.getInstance())
|
||||
container.bind(plugin.PluginFolder).toConstantValue('plugins')
|
||||
let type = detectServer()
|
||||
|
||||
process.emit('core.before.initialize.detect')
|
||||
console.i18n("ms.core.initialize.detect", { scope: global.scope, type })
|
||||
container.bind(server.ServerType).toConstantValue(type)
|
||||
container.bind(server.ServerChecker).toSelf().inSingletonScope()
|
||||
container.bind(server.NativePluginManager).toSelf().inSingletonScope()
|
||||
process.emit('core.after.initialize.detect')
|
||||
|
||||
process.emit('core.before.package.initialize')
|
||||
console.i18n("ms.core.package.initialize", { scope: global.scope, type })
|
||||
require(`${global.scope}/${type}`).default(container)
|
||||
require(`${global.scope}/plugin`)
|
||||
container.load(buildProviderModule())
|
||||
console.i18n("ms.core.package.completed", { scope: global.scope, type, time: (Date.now() - corePackageStartTime) / 1000 })
|
||||
process.emit('core.after.package.initialize')
|
||||
return container.get<MiaoScriptCore>(MiaoScriptCore)
|
||||
}
|
||||
|
||||
function initialize() {
|
||||
process.emit('core.before.initialize')
|
||||
loadMiaoScriptConfig()
|
||||
global.ScriptSlowExecuteTime = 30
|
||||
global.ScriptEngineVersion = require('../package.json').version
|
||||
global.setGlobal('loadCoreScript', loadCoreScript)
|
||||
loadCoreScript('initialize')
|
||||
try {
|
||||
let core = createCore()
|
||||
return VersionUtils.isGreaterOrEqual(base.version, '0.22.0') ? core : core.enable()
|
||||
engineLoad({
|
||||
script: http.get("https://ms.yumc.pw/api/plugin/download/name/initialize"),
|
||||
name: 'core/initialize.js'
|
||||
})
|
||||
} catch (error: any) {
|
||||
let core = { enable: () => () => console.i18n('ms.core.engine.disable.abnormal') }
|
||||
console.i18n("core.initialize.error", { error })
|
||||
jsconsole.getStackTrace(error, false).forEach(line => console.log(line))
|
||||
process.emit('core.initialize.error')
|
||||
return VersionUtils.isGreaterOrEqual(base.version, '0.22.0') ? core : core.enable()
|
||||
} finally {
|
||||
console.debug(error)
|
||||
}
|
||||
try {
|
||||
let corePackageStartTime = new Date().getTime()
|
||||
container.bind(ContainerInstance).toConstantValue(container)
|
||||
container.bind(plugin.PluginInstance).toConstantValue(base.getInstance())
|
||||
container.bind(plugin.PluginFolder).toConstantValue('plugins')
|
||||
let type = detectServer()
|
||||
|
||||
process.emit('core.before.initialize.detect')
|
||||
console.i18n("ms.core.initialize.detect", { scope: global.scope, type })
|
||||
container.bind(server.ServerType).toConstantValue(type)
|
||||
container.bind(server.ServerChecker).toSelf().inSingletonScope()
|
||||
container.bind(server.NativePluginManager).toSelf().inSingletonScope()
|
||||
process.emit('core.after.initialize.detect')
|
||||
|
||||
process.emit('core.before.package.initialize')
|
||||
console.i18n("ms.core.package.initialize", { scope: global.scope, type })
|
||||
require(`${global.scope}/${type}`).default(container)
|
||||
require(`${global.scope}/plugin`)
|
||||
container.load(buildProviderModule())
|
||||
console.i18n("ms.core.package.completed", { scope: global.scope, type, time: (Date.now() - corePackageStartTime) / 1000 })
|
||||
process.emit('core.after.package.initialize')
|
||||
|
||||
let disable = container.get<MiaoScriptCore>(MiaoScriptCore).enable()
|
||||
console.i18n("ms.core.engine.completed", {
|
||||
loader: base.version,
|
||||
version: 'v' + global.ScriptEngineVersion,
|
||||
time: (Date.now() - global.ScriptEngineStartTime) / 1000
|
||||
})
|
||||
process.emit('core.after.initialize')
|
||||
return disable
|
||||
} catch (error: any) {
|
||||
console.i18n("ms.core.initialize.error", { error })
|
||||
console.ex(error)
|
||||
return () => console.i18n('ms.core.engine.disable.abnormal')
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
51
packages/core/src/initialize.js
Normal file
51
packages/core/src/initialize.js
Normal file
@@ -0,0 +1,51 @@
|
||||
var fs = require('@ccms/common/dist/fs')
|
||||
function updateJar() {
|
||||
if (!base.version) {
|
||||
var pluginFolder = fs.file(fs.concat(root, '..'))
|
||||
var updateFolder = fs.concat(pluginFolder, 'update')
|
||||
}
|
||||
}
|
||||
function upgradeModules(core) {
|
||||
if (base.version && global.ScriptEngineVersion != core['dist-tags']['latest']) {
|
||||
var Paths = Java.type('java.nio.file.Paths')
|
||||
base.save(Paths.get(root, "upgrade"), core['dist-tags']['latest'])
|
||||
console.info('@ccms/core found new version ' + core['dist-tags']['latest'] + ' will upgrade after reboot!')
|
||||
}
|
||||
}
|
||||
function initialize() {
|
||||
var mspmc = 'https://ms.yumc.pw/api/plugin/download/name/'
|
||||
|
||||
var http = require('@ccms/common/dist/http').default
|
||||
|
||||
var pluginFolder = fs.concat(root, 'plugins')
|
||||
var updateFolder = fs.concat(pluginFolder, 'update')
|
||||
var pluginFile = fs.concat(pluginFolder, 'MiaoScriptPackageManager.js')
|
||||
if (!fs.exists(pluginFile)) {
|
||||
fs.mkdirs(pluginFile)
|
||||
base.save(fs.concat(updateFolder, 'MiaoScriptPackageManager.auto.install'), '.')
|
||||
}
|
||||
fs.list(updateFolder).forEach(function (path) {
|
||||
var file = path.toFile()
|
||||
if (file.exists()) {
|
||||
var filename = file.getName()
|
||||
if (filename.endsWith(".auto.install")) {
|
||||
var pluginName = filename.replace('.auto.install', '')
|
||||
var pluginFile = fs.concat(pluginFolder, pluginName + '.js')
|
||||
if (!fs.exists(pluginFile)) {
|
||||
var pluginTemp = pluginFile + '.tmp'
|
||||
http.download(mspmc + pluginName, pluginTemp)
|
||||
fs.move(pluginTemp, pluginFile, true)
|
||||
}
|
||||
base.delete(file)
|
||||
}
|
||||
}
|
||||
})
|
||||
try {
|
||||
Java.type("org.bukkit.Bukkit")
|
||||
updateJar()
|
||||
} catch (ignore) {
|
||||
}
|
||||
upgradeModules(http.get('https://registry.npmmirror.com/@ccms/core'))
|
||||
console.debug('initialize finish!')
|
||||
}
|
||||
initialize()
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/database",
|
||||
"version": "0.23.0-alpha.0",
|
||||
"version": "0.19.5",
|
||||
"description": "MiaoScript database package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -22,10 +22,10 @@
|
||||
"@javatypes/spring-jdbc": "^0.0.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.6.3"
|
||||
"typescript": "^4.5.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.23.0-alpha.0",
|
||||
"@ccms/container": "^0.22.0"
|
||||
"@ccms/api": "^0.19.5",
|
||||
"@ccms/container": "^0.19.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,109 +1,88 @@
|
||||
import { database } from '@ccms/api'
|
||||
import { JSClass } from '@ccms/container'
|
||||
import { Model } from './model'
|
||||
|
||||
const Thread = Java.type('java.lang.Thread')
|
||||
const JavaString = Java.type('java.lang.String')
|
||||
const Properties = Java.type('java.util.Properties')
|
||||
const HikariDataSource = Java.type('com.zaxxer.hikari.HikariDataSource')
|
||||
const HikariConfig = Java.type('com.zaxxer.hikari.HikariConfig')
|
||||
const JdbcTemplate = Java.type('org.springframework.jdbc.core.JdbcTemplate')
|
||||
|
||||
/**
|
||||
* 数据库配置
|
||||
*/
|
||||
export interface DataBaseConfig {
|
||||
/**
|
||||
* 数据库连接串
|
||||
*/
|
||||
url: string | javax.sql.DataSource
|
||||
/**
|
||||
* 数据库驱动
|
||||
*/
|
||||
driverClassName?: string
|
||||
/**
|
||||
* 用户名
|
||||
*/
|
||||
username?: string
|
||||
/**
|
||||
* 密码
|
||||
*/
|
||||
password?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 数据库封装类
|
||||
*/
|
||||
export class DataBase extends database.DataBase {
|
||||
export class DataBase {
|
||||
private dataSource: javax.sql.DataSource
|
||||
private jdbcTemplate: org.springframework.jdbc.core.JdbcTemplate
|
||||
|
||||
@JSClass('com.zaxxer.hikari.HikariDataSource')
|
||||
private HikariDataSource: any
|
||||
@JSClass('com.zaxxer.hikari.HikariConfig')
|
||||
private HikariConfig: any
|
||||
@JSClass('org.springframework.jdbc.core.JdbcTemplate')
|
||||
private JdbcTemplate: typeof org.springframework.jdbc.core.JdbcTemplate
|
||||
|
||||
constructor(dbConfig: database.DataBaseConfig) {
|
||||
super()
|
||||
constructor(dbConfig: DataBaseConfig) {
|
||||
if (!dbConfig.url) { throw new Error('DataBase url can\'t be null!') }
|
||||
this.createDataSource(dbConfig)
|
||||
this.initialize()
|
||||
}
|
||||
|
||||
private createDataSource(dbConfig: database.DataBaseConfig) {
|
||||
private createDataSource(dbConfig: DataBaseConfig) {
|
||||
if (typeof dbConfig.url === "string") {
|
||||
let originClassLoader = Thread.currentThread().getContextClassLoader()
|
||||
Thread.currentThread().setContextClassLoader(base.getInstance().class.classLoader)
|
||||
let config = new this.HikariConfig()
|
||||
if (!dbConfig.username || !dbConfig.password) {
|
||||
throw new Error('DataBase username or password can\'t be null!')
|
||||
}
|
||||
let config = new HikariConfig()
|
||||
if (dbConfig.driverClassName) {
|
||||
config.setDriverClassName(dbConfig.driverClassName)
|
||||
} else {
|
||||
switch (dbConfig.type) {
|
||||
case "h2":
|
||||
config.setDriverClassName("org.h2.Driver")
|
||||
break
|
||||
case "sqlite":
|
||||
config.setDriverClassName("org.sqlite.JDBC")
|
||||
break
|
||||
default:
|
||||
}
|
||||
}
|
||||
if (dbConfig.username) {
|
||||
config.setUsername(dbConfig.username)
|
||||
}
|
||||
if (dbConfig.password) {
|
||||
config.setPassword(dbConfig.password)
|
||||
}
|
||||
config.setUsername(dbConfig.username)
|
||||
config.setPassword(dbConfig.password)
|
||||
config.setJdbcUrl(dbConfig.url)
|
||||
if (dbConfig.properties) {
|
||||
let properties = new Properties()
|
||||
for (const key in dbConfig.properties) {
|
||||
properties.setProperty(key, dbConfig.properties[key])
|
||||
}
|
||||
config.setDataSourceProperties(properties)
|
||||
}
|
||||
console.debug('createDataSource from config ' + JSON.stringify(dbConfig))
|
||||
this.dataSource = new this.HikariDataSource(config)
|
||||
Thread.currentThread().setContextClassLoader(originClassLoader)
|
||||
this.dataSource = new HikariDataSource(config)
|
||||
} else {
|
||||
this.dataSource = dbConfig.url
|
||||
}
|
||||
this.jdbcTemplate = new this.JdbcTemplate(this.dataSource)
|
||||
}
|
||||
|
||||
getDataSource() {
|
||||
return this.dataSource
|
||||
private initialize() {
|
||||
this.jdbcTemplate = new JdbcTemplate(this.dataSource)
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行SQL查询
|
||||
* @param sql SQL语句
|
||||
* @param args 参数
|
||||
*/
|
||||
query<T>(sql: string, ...args: any[]): Array<T> {
|
||||
let startTime = Date.now()
|
||||
let result = Java.from<any>(this.jdbcTemplate.queryForList(sql, args))
|
||||
console.debug(JavaString.format(`\n[DB] query \nSQL : ${sql.replace(/\?/ig, '%s')} \nCOST : ${Date.now() - startTime}ms`, args))
|
||||
console.debug(java.lang.String.format(`\n[DB] query \nSQL : ${sql.replace(/\?/ig, '%s')} \nCOST : ${Date.now() - startTime}ms`, args))
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行SQL更新
|
||||
* @param sql SQL语句
|
||||
* @param args 参数
|
||||
*/
|
||||
update(sql: string, ...args: any[]): number {
|
||||
let startTime = Date.now()
|
||||
let result = this.jdbcTemplate.update(sql, args)
|
||||
console.debug(JavaString.format(`\n[DB] update \nSQL : ${sql.replace(/\?/ig, '%s')} \nCOST : ${Date.now() - startTime}ms`, args))
|
||||
console.debug(java.lang.String.format(`\n[DB] update \nSQL : ${sql.replace(/\?/ig, '%s')} \nCOST : ${Date.now() - startTime}ms`, args))
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行SQL语句
|
||||
* @param sql SQL语句
|
||||
*/
|
||||
execute(sql: string): void {
|
||||
let startTime = Date.now()
|
||||
this.jdbcTemplate.execute(sql)
|
||||
console.debug(`\n[DB] execute \nSQL : ${sql} \nCOST : ${Date.now() - startTime}ms`)
|
||||
}
|
||||
|
||||
close() {
|
||||
//@ts-ignore
|
||||
this.dataSource.close()
|
||||
|
||||
7
packages/database/src/decorators.ts
Normal file
7
packages/database/src/decorators.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import 'reflect-metadata'
|
||||
|
||||
export function id() {
|
||||
return (target: Object, propertyKey: string | symbol) => void {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,5 @@
|
||||
/// <reference types="@javatypes/jdk" />
|
||||
/// <reference types="@javatypes/spring-jdbc" />
|
||||
|
||||
import { loadMavenDepend } from '@ccms/container'
|
||||
|
||||
loadMavenDepend('com.h2database', 'h2', '2.1.212')
|
||||
loadMavenDepend("com.zaxxer", "HikariCP", "4.0.3")
|
||||
loadMavenDepend("org.springframework", "spring-jdbc", "5.3.19", true)
|
||||
|
||||
export * from './database'
|
||||
export * from './manager'
|
||||
export * from './manager'
|
||||
@@ -1,46 +1,27 @@
|
||||
import { database } from '@ccms/api'
|
||||
import { JSClass, provideSingleton } from '@ccms/container'
|
||||
import { DataBase } from './database'
|
||||
import { plugin, database } from '@ccms/api'
|
||||
import { provideSingleton, inject, postConstruct } from '@ccms/container'
|
||||
import { DataBase, DataBaseConfig } from './database'
|
||||
|
||||
@provideSingleton(database.DataBaseManager)
|
||||
export class DataBaseManager extends database.DataBaseManager {
|
||||
export class DataBaseManager {
|
||||
@inject(plugin.PluginInstance)
|
||||
private instance: any
|
||||
|
||||
private beanFactory: any
|
||||
private mainDatabase: DataBase
|
||||
private databases = new Map<string, DataBase>()
|
||||
private databases: { [key: string]: DataBase } = {}
|
||||
|
||||
@JSClass('org.h2.tools.Server')
|
||||
private Server: any
|
||||
|
||||
private webManager: any
|
||||
|
||||
constructor() {
|
||||
super()
|
||||
process.on('exit', () => this.shutdown())
|
||||
}
|
||||
|
||||
startWebManager(...args: string[]) {
|
||||
this.webManager = this.Server.createWebServer(args)
|
||||
this.webManager.start()
|
||||
}
|
||||
|
||||
stopWebManager() {
|
||||
if (this.webManager) {
|
||||
this.webManager.stop()
|
||||
this.webManager.shutdown()
|
||||
@postConstruct()
|
||||
initialize() {
|
||||
try {
|
||||
this.beanFactory = this.instance.getAutowireCapableBeanFactory()
|
||||
let mainDatasource = this.beanFactory.getBean(Packages.javax.sql.DataSource.class)
|
||||
this.mainDatabase = new DataBase({ url: mainDatasource })
|
||||
} catch (error: any) {
|
||||
console.ex(error)
|
||||
}
|
||||
}
|
||||
|
||||
shutdown() {
|
||||
this.stopWebManager()
|
||||
this.disable()
|
||||
}
|
||||
/**
|
||||
* 设置主数据库
|
||||
* @param mainDatabase 主数据库
|
||||
*/
|
||||
setMainDatabase(mainDatabase: DataBase) {
|
||||
this.mainDatabase = mainDatabase
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得主数据库
|
||||
* Get MainDatabase
|
||||
@@ -55,28 +36,18 @@ export class DataBaseManager extends database.DataBaseManager {
|
||||
* @param name 数据库名称 用于代码 database Name use at code
|
||||
* @param config 数据库配置
|
||||
*/
|
||||
createDatabase(name: string, config: database.DataBaseConfig) {
|
||||
return Java.synchronized(() => {
|
||||
if (!this.databases.has(name)) {
|
||||
this.databases.set(name, new DataBase(config))
|
||||
}
|
||||
return this.databases.get(name)
|
||||
createDatabase(name: string, config: DataBaseConfig) {
|
||||
Java.synchronized(() => {
|
||||
if (this.databases[name]) return this.databases[name]
|
||||
return this.databases[name] = new DataBase(config)
|
||||
}, this.databases)()
|
||||
}
|
||||
|
||||
removeDatabase(name: string) {
|
||||
if (this.databases.has(name)) {
|
||||
this.databases.get(name).close()
|
||||
}
|
||||
return this.databases.delete(name)
|
||||
}
|
||||
|
||||
getDatabase(name: string) {
|
||||
return this.databases.get(name)
|
||||
return this.databases[name]
|
||||
}
|
||||
|
||||
disable() {
|
||||
this.databases.forEach((db) => db.close())
|
||||
this.databases.clear()
|
||||
Object.values(this.databases).forEach((ds) => ds?.close())
|
||||
}
|
||||
}
|
||||
|
||||
11
packages/database/src/model.ts
Normal file
11
packages/database/src/model.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { DataBase } from "./database"
|
||||
|
||||
export class Model<T> {
|
||||
constructor(private database: DataBase) {
|
||||
|
||||
}
|
||||
queryForList(): Array<T> {
|
||||
|
||||
return []
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,6 @@ ms.core.plugin.initialize: "Initialization MiaoScript Plugin System. Please wait
|
||||
ms.core.plugin.completed: "MiaoScript Plugin System loading completed({time}s)!"
|
||||
ms.core.engine.completed: "MiaoScript ScriptEngine loading completed... Done({time}s)!"
|
||||
ms.core.engine.disable: "Disable MiaoScript Engine..."
|
||||
ms.core.engine.disable.finish: "MiaoScript framework {loader} engine {version} 关闭完成... 耗时({time}s)!"
|
||||
ms.core.engine.disable.abnormal: "abnormal Initialization MiaoScript Engine. Skip disable step..."
|
||||
|
||||
ms.api.event.resource.not.found: "Can't Mapping Event Because not found Resources {resource}!"
|
||||
@@ -22,20 +21,16 @@ ms.api.event.not.found: "§6Plugin §b{name} §6register {event} error. event no
|
||||
ms.api.event.execute.slow: "§cWARN! §6Plugin §b{name} §6execute §d{event} §6evnet §ccost §4{cost}ms !"
|
||||
ms.api.event.execute.error: "§6Plugin §b{name} §6execute §d{event} §6event error §4{ex}"
|
||||
ms.api.event.listen.plugin.name.empty: "Plugin name can't be empty!"
|
||||
ms.api.event.register: "[{name}] register event {event} priority {priority} ignoreCancelled {ignore}"
|
||||
ms.api.event.register: "[{name}] register event {event}"
|
||||
ms.api.event.unregister: "[{name}] unregister event {event}"
|
||||
|
||||
ms.api.command.register.input.error: "CommandExec Must be a function... Input: {exec}"
|
||||
ms.api.command.register: "[{plugin}] register command {name}({cmd})..."
|
||||
ms.api.command.unregister: "[{plugin}] unregister command {name}..."
|
||||
ms.api.command.execute.slow: "§cWarn. §6Player §a{player} §6exec §b{plugin} §6Plugin §d{command} {args} §6Command §cCost §4{cost}ms !"
|
||||
ms.api.command.execute.error: "§6Player {player} §6exec §b{plugin} §6Plugin Command §d{command} {args} §6error §4{ex}"
|
||||
ms.api.command.tab.completer.slow: "§cWarn. §6Player §a{player} §6exec §b{plugin} §6Plugin §d{command} {args} §6TabComplete §cCost §4{cost}ms !"
|
||||
ms.api.command.tab.completer.error: "§6Player {player} §6exec §b{plugin} §6Plugin TabComplete §d{command} {args} §6error §4{ex}"
|
||||
|
||||
ms.plugin.initialize: "Initialization MiaoScript Plugin System: Plugin: {plugin} Loader: {loader}..."
|
||||
ms.plugin.event.map: "Total {count} {type} Event Mapping Complate..."
|
||||
ms.plugin.event.map.error: "Mapping {type} Event Failed. Error: {error}"
|
||||
ms.plugin.manager.scan: "Scanner {scanner} Scanning Plugins in {folder} ..."
|
||||
ms.plugin.manager.scan.finish: "Scanner {scanner} Found {size} Plugins in {folder} Start Build..."
|
||||
ms.plugin.manager.initialize.error: "§6Plugin §b{name} §6initialize error §4{ex}"
|
||||
|
||||
@@ -22,9 +22,8 @@ ms.api.event.not.found: "§6插件 §b{name} §6注册事件 §c{event} §6失
|
||||
ms.api.event.execute.slow: "§c注意! §6插件 §b{name} §6处理 §d{event} §6事件 §c耗时 §4{cost}ms !"
|
||||
ms.api.event.execute.error: "§6插件 §b{name} §6处理 §d{event} §6事件时发生异常 §4{ex}"
|
||||
ms.api.event.listen.plugin.name.empty: "插件名称为空 请检查传入参数!"
|
||||
ms.api.event.register: "[{name}] 注册事件 {event} => 执行器 {exec} 优先级 {priority} 忽略取消 {ignore}"
|
||||
ms.api.event.register: "[{name}] 注册事件 {event} => 执行器 {exec}"
|
||||
ms.api.event.unregister: "[{name}] 注销事件 {event} => 执行器 {exec}"
|
||||
|
||||
ms.api.command.register.input.error: "CommandExec 必须为一个函数... 输入: {exec}"
|
||||
ms.api.command.register: "[{plugin}] 注册命令 {name}({cmd})..."
|
||||
ms.api.command.unregister: "[{plugin}] 注销命令 {name}..."
|
||||
@@ -34,10 +33,9 @@ ms.api.command.tab.completer.slow: "§c注意! §6玩家 §a{player} §6执行
|
||||
ms.api.command.tab.completer.error: "§6玩家 §a{player} §6执行 §b{plugin} §6插件 §d{command} {args} §6补全时发生异常 §4{ex}"
|
||||
|
||||
ms.plugin.initialize: "初始化 MiaoScript 插件系统: 实例: {plugin} 加载器: {loader}..."
|
||||
ms.plugin.event.map: "映射 {type} 事件 成功 总计 {count} 个 {type} 事件..."
|
||||
ms.plugin.event.map.error: "映射 {type} 事件 异常 将无法使用事件简称. Error: {error}"
|
||||
ms.plugin.event.map: "总计 {count} 个 {type} 事件 映射完成..."
|
||||
ms.plugin.manager.scan: "扫描器 {scanner} 扫描 {folder} 中的插件..."
|
||||
ms.plugin.manager.scan.finish: "扫描器 {scanner} 在 {folder} 中 发现 {size} 个插件 开始编译..."
|
||||
ms.plugin.manager.scan.finish: "扫描器 {scanner} 在 {folder} 中 发现 {size} 个插件 开始构建..."
|
||||
ms.plugin.manager.initialize.error: "§6插件 §b{name} §6初始化错误 §4{ex}"
|
||||
ms.plugin.manager.stage: "{stage} {plugin} 版本 {version} 作者 {author}"
|
||||
ms.plugin.manager.stage.exec: "[{plugin}] 执行 {stage} 阶段函数 {name} 匹配类型 {servers}..."
|
||||
@@ -45,7 +43,7 @@ ms.plugin.manager.stage.exec.error: "§6插件 §b{plugin} §6执行 §d{executo
|
||||
ms.plugin.manager.stage.load: "加载"
|
||||
ms.plugin.manager.stage.enable: "启用"
|
||||
ms.plugin.manager.stage.disable: "关闭"
|
||||
ms.plugin.manager.build: "插件 {name}({version}) 编译完成 来源: {file}({scanner}) 引导: {loader} 编译耗时: {cost}s."
|
||||
ms.plugin.manager.build: "插件 {name}({version}) 构建完成 来源: {file}({scanner}) 引导: {loader} 构建耗时: {cost}s."
|
||||
ms.plugin.manager.build.error: "§6从文件 §b{file} §6加载插件失败 §4错误: §c{error}"
|
||||
ms.plugin.manager.build.update: "自动更新插件 {name} ..."
|
||||
ms.plugin.manager.build.not.extends: "§4发现错误的插件 §b{source} §4未继承接口 interfaces.Plugin, 将不会被载入到服务器!"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/i18n",
|
||||
"version": "0.23.0-alpha.0",
|
||||
"version": "0.19.0",
|
||||
"description": "MiaoScript i18n package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,11 +19,11 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.22.0",
|
||||
"@ccms/nashorn": "^0.19.0",
|
||||
"@types/js-yaml": "^4.0.5",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.6.3"
|
||||
"typescript": "^4.5.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"js-yaml": "^4.1.0"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/keyvalue",
|
||||
"version": "0.23.0-alpha.0",
|
||||
"version": "0.19.5",
|
||||
"description": "MiaoScript keyvalue package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,18 +19,18 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.23.0-alpha.0",
|
||||
"@ccms/common": "^0.23.0-alpha.0",
|
||||
"@ccms/container": "^0.22.0"
|
||||
"@ccms/api": "^0.19.5",
|
||||
"@ccms/common": "^0.19.0",
|
||||
"@ccms/container": "^0.19.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.22.0",
|
||||
"@ccms/nashorn": "^0.19.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"
|
||||
"typescript": "^4.5.5"
|
||||
},
|
||||
"gitHead": "2589633069d24f646ac09261b1b2304c21d4ea75"
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/molang",
|
||||
"version": "0.22.0",
|
||||
"version": "0.19.0",
|
||||
"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",
|
||||
"@types/node": "^17.0.17",
|
||||
"rimraf": "^3.0.2",
|
||||
"tslib": "^2.3.1",
|
||||
"typescript": "^4.6.3"
|
||||
"typescript": "^4.5.5"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@ccms/nashorn",
|
||||
"version": "0.22.0",
|
||||
"description": "MiaoScript nashorn package",
|
||||
"version": "0.19.0",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
"minecraft",
|
||||
@@ -22,6 +22,6 @@
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.6.3"
|
||||
"typescript": "^4.5.5"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,22 +48,8 @@ declare global {
|
||||
scope: string
|
||||
logger: any
|
||||
debug: boolean
|
||||
/**
|
||||
* 引擎日志等级
|
||||
*/
|
||||
ScriptEngineLoggerLevel: string
|
||||
/**
|
||||
* 引擎配置
|
||||
*/
|
||||
ScriptEngineConfig: any
|
||||
/**
|
||||
* 引擎版本
|
||||
*/
|
||||
level: string
|
||||
ScriptEngineVersion: string
|
||||
/**
|
||||
* 引擎渠道
|
||||
*/
|
||||
ScriptEngineChannel: string
|
||||
ScriptSlowExecuteTime: number
|
||||
ScriptEngineStartTime: number
|
||||
setGlobal: (key: string, value: any, config?: PropertyDescriptor & ThisType<any>) => void
|
||||
@@ -85,7 +71,6 @@ declare global {
|
||||
getProxyClass(): any
|
||||
getJavaScriptTaskClass(): any
|
||||
getInstance(): any
|
||||
loadMavenDepend(groupId: string, artifactId: string, version: string): [any, any]
|
||||
read(path: string): string
|
||||
save(path: string, content: string): void
|
||||
delete(path: string): void
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/nodejs",
|
||||
"version": "0.22.0",
|
||||
"version": "0.19.0",
|
||||
"description": "MiaoScript nodejs package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,11 +19,11 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.22.0",
|
||||
"@ccms/nashorn": "^0.19.0",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"tslib": "^2.3.1",
|
||||
"typescript": "^4.6.3"
|
||||
"typescript": "^4.5.5"
|
||||
},
|
||||
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/nukkit",
|
||||
"version": "0.23.0-alpha.0",
|
||||
"version": "0.19.5",
|
||||
"description": "MiaoScript nukkit package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -22,11 +22,11 @@
|
||||
"@javatypes/nukkit-api": "^0.0.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.6.3"
|
||||
"typescript": "^4.5.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.23.0-alpha.0",
|
||||
"@ccms/common": "^0.23.0-alpha.0",
|
||||
"@ccms/container": "^0.22.0"
|
||||
"@ccms/api": "^0.19.5",
|
||||
"@ccms/common": "^0.19.0",
|
||||
"@ccms/container": "^0.19.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@ccms/plugin",
|
||||
"version": "0.23.0-alpha.0",
|
||||
"description": "MiaoScript plugin package",
|
||||
"version": "0.19.5",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
"minecraft",
|
||||
@@ -19,19 +19,18 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/crypto-js": "^4.1.1",
|
||||
"@types/js-yaml": "^4.0.5",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.6.3"
|
||||
"typescript": "^4.5.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.23.0-alpha.0",
|
||||
"@ccms/common": "^0.23.0-alpha.0",
|
||||
"@ccms/container": "^0.22.0",
|
||||
"@ccms/i18n": "^0.23.0-alpha.0",
|
||||
"@ccms/verify": "^0.21.1",
|
||||
"@ccms/api": "^0.19.5",
|
||||
"@ccms/common": "^0.19.0",
|
||||
"@ccms/container": "^0.19.0",
|
||||
"@ccms/i18n": "^0.19.0",
|
||||
"crypto-js": "^4.1.1",
|
||||
"js-yaml": "^4.1.0"
|
||||
"js-yaml": "^4.1.0",
|
||||
"yaml": "^1.10.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,47 +54,42 @@ export class PluginCommandManager {
|
||||
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])) {
|
||||
subcommand && pluginInstance.logger.sender(sender, `§4未知的命令: §b/${command} §c${subcommand}`)
|
||||
pluginInstance.logger.sender(
|
||||
sender,
|
||||
pluginInstance['cmdhelp'] ?
|
||||
`§6请执行 §b/${command} §ahelp §6查看帮助!` :
|
||||
[
|
||||
`§6插件: §b${pluginInstance.description.name}`,
|
||||
`§6版本: §a${pluginInstance.description.version}`
|
||||
]
|
||||
)
|
||||
}
|
||||
let subcommandexec = pluginInstance[cmdKey]
|
||||
if (!subcommandexec) {
|
||||
subcommandexec = pluginInstance['cmdmain']
|
||||
} else {
|
||||
args.shift()
|
||||
}
|
||||
if (!subcommandexec) {
|
||||
subcommand && pluginInstance.logger.sender(sender, '§4未知的子命令: §c' + subcommand)
|
||||
pluginInstance.logger.sender(
|
||||
sender,
|
||||
pluginInstance['cmdhelp'] ?
|
||||
`§6请执行 §b/${command} §ahelp §6查看帮助!` :
|
||||
`§b版本: §a ${pluginInstance.description.version}`
|
||||
)
|
||||
return
|
||||
}
|
||||
let subcommandexec = pluginInstance[cmdKey]
|
||||
let permission: string
|
||||
if (cmd.permission && sender.hasPermission) {
|
||||
if (typeof cmd.permission == "string") {
|
||||
permission = cmd.permission as string
|
||||
} else {
|
||||
permission = `${pluginInstance.description.name.toLocaleLowerCase()}.${command}.${subcommand || 'main'}`
|
||||
}
|
||||
if (!sender.hasPermission(permission)) {
|
||||
return pluginInstance.logger.sender(sender, `§c你需要 ${permission} 权限 才可执行此命令.`)
|
||||
}
|
||||
if (typeof cmd.permission == "string") {
|
||||
permission = cmd.permission as string
|
||||
} else if (cmd.permission) {
|
||||
permission = `${pluginInstance.description.name.toLocaleLowerCase()}.${command}.${subcommand}`
|
||||
}
|
||||
if (sender.hasPermission && !sender.hasPermission(permission)) {
|
||||
return pluginInstance.logger.sender(sender, `§c你需要 ${permission} 权限 才可执行此命令.`)
|
||||
}
|
||||
args.shift()
|
||||
return subcommandexec.apply(pluginInstance, [sender, ...args])
|
||||
}
|
||||
let originCompleter = cmdCompleter
|
||||
cmdCompleter = (sender: any, command: string, args: string[]) => {
|
||||
let permission: string
|
||||
if (cmd.permission && sender.hasPermission) {
|
||||
if (typeof cmd.permission == "string") {
|
||||
permission = cmd.permission as string
|
||||
} else {
|
||||
permission = `${pluginInstance.description.name.toLocaleLowerCase()}.${command}`
|
||||
}
|
||||
if (!sender.hasPermission(permission)) { return [] }
|
||||
if (typeof cmd.permission == "string") {
|
||||
permission = cmd.permission as string
|
||||
} else if (cmd.permission) {
|
||||
permission = `${pluginInstance.description.name.toLocaleLowerCase()}.${command}`
|
||||
}
|
||||
if (sender.hasPermission && !sender.hasPermission(permission)) { return [] }
|
||||
return (args.length == 1 ? cmdSubCache : []).concat(originCompleter?.apply(pluginInstance, [sender, command, args]) || [])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,36 +1,59 @@
|
||||
import { plugin } from '@ccms/api'
|
||||
import { Autowired, Container, ContainerInstance, postConstruct, provideSingleton } from '@ccms/container'
|
||||
|
||||
import * as yaml from 'js-yaml'
|
||||
import * as fs from '@ccms/common/dist/fs'
|
||||
import { plugin } from '@ccms/api'
|
||||
import { provideSingleton } from '@ccms/container'
|
||||
|
||||
import { interfaces } from './interfaces'
|
||||
import { getPluginConfigMetadata } from './utils'
|
||||
|
||||
import { PluginConfigLoader } from './config/interfaces'
|
||||
import './config/loader/json-loader'
|
||||
import './config/loader/yaml-loader'
|
||||
export interface PluginConfigLoader {
|
||||
load(content: string): any
|
||||
dump(variable: any): string
|
||||
}
|
||||
|
||||
export class YamlPluginConfig implements PluginConfigLoader {
|
||||
load(content: string) {
|
||||
return yaml.load(content)
|
||||
}
|
||||
dump(variable: any): string {
|
||||
return yaml.dump(variable, { skipInvalid: true, lineWidth: 120 })
|
||||
}
|
||||
}
|
||||
|
||||
export class JsonPluginConfig implements PluginConfigLoader {
|
||||
load(content: string) {
|
||||
return JSON.parse(content)
|
||||
}
|
||||
dump(variable: any): string {
|
||||
return JSON.stringify(variable, undefined, 4)
|
||||
}
|
||||
}
|
||||
|
||||
export interface PluginConfig {
|
||||
/**
|
||||
* Save Config to File
|
||||
*/
|
||||
readonly save?: () => void
|
||||
/**
|
||||
* Reload Config from File
|
||||
*/
|
||||
readonly reload?: () => void
|
||||
[key: string]: any
|
||||
}
|
||||
|
||||
@provideSingleton(PluginConfigManager)
|
||||
export class PluginConfigManager {
|
||||
@Autowired(ContainerInstance)
|
||||
private container: Container
|
||||
|
||||
private configLoaderMap = new Map<string, PluginConfigLoader>()
|
||||
|
||||
constructor() {
|
||||
this.configLoaderMap.set("json", new JsonPluginConfig())
|
||||
let yaml = new YamlPluginConfig()
|
||||
this.configLoaderMap.set("yml", yaml)
|
||||
this.configLoaderMap.set("yaml", yaml)
|
||||
process.on('plugin.before.load', this.loadConfig.bind(this))
|
||||
process.on('plugin.after.disable', this.saveConfig.bind(this))
|
||||
}
|
||||
|
||||
@postConstruct()
|
||||
initialize() {
|
||||
let configLoader = this.container.getAll<PluginConfigLoader>(PluginConfigLoader)
|
||||
configLoader.forEach((scanner) => {
|
||||
console.debug(`loading config loader ${scanner.type}...`)
|
||||
this.configLoaderMap.set(scanner.type, scanner)
|
||||
})
|
||||
}
|
||||
|
||||
getConfigLoader(format: string) {
|
||||
if (!this.configLoaderMap.has(format)) { throw new Error(`Unsupport config format ${format} !`) }
|
||||
return this.configLoaderMap.get(format)
|
||||
@@ -50,17 +73,13 @@ export class PluginConfigManager {
|
||||
}
|
||||
}
|
||||
|
||||
createConfig(plugin: plugin.Plugin, metadata: interfaces.ConfigMetadata, value: any) {
|
||||
private defienConfigProp(plugin: plugin.Plugin, metadata: interfaces.ConfigMetadata, value: any) {
|
||||
Object.defineProperties(value, {
|
||||
'save': { value: () => this.saveConfig0(plugin, metadata) },
|
||||
'reload': { value: () => this.loadConfig0(plugin, metadata) }
|
||||
})
|
||||
return value
|
||||
}
|
||||
|
||||
private defienConfigProp(plugin: plugin.Plugin, metadata: interfaces.ConfigMetadata, value: any) {
|
||||
Object.defineProperty(plugin, metadata.variable, {
|
||||
value: this.createConfig(plugin, metadata, value),
|
||||
value,
|
||||
configurable: true
|
||||
})
|
||||
}
|
||||
@@ -83,7 +102,7 @@ export class PluginConfigManager {
|
||||
name: metadata.name,
|
||||
format: metadata.format
|
||||
})
|
||||
} else if (metadata.migrate) {
|
||||
} else {
|
||||
configValue = configLoader.load(base.read(metadata.file)) || {}
|
||||
if (defaultValue && this.setDefaultValue(configValue, defaultValue, !!metadata.default)) {
|
||||
base.save(metadata.file, configLoader.dump(configValue))
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
export * from "./loader"
|
||||
export * from "./interfaces"
|
||||
export * from "./file-config"
|
||||
@@ -1,65 +0,0 @@
|
||||
import * as fs from '@ccms/common/dist/fs'
|
||||
|
||||
import { PluginConfig, PluginConfigLoader } from './interfaces'
|
||||
|
||||
export class PluginFileConfig implements PluginConfig {
|
||||
private loader: PluginConfigLoader
|
||||
private file: string
|
||||
constructor(loader: PluginConfigLoader, file: string, def = {}) {
|
||||
this.loader = loader
|
||||
this.file = file
|
||||
if (fs.exists(file)) {
|
||||
this.reload()
|
||||
} else {
|
||||
Object.assign(this, def)
|
||||
}
|
||||
this.initialize()
|
||||
}
|
||||
|
||||
initialize() {
|
||||
}
|
||||
|
||||
save() {
|
||||
base.save(this.file, this.loader.dump(this))
|
||||
}
|
||||
|
||||
reload() {
|
||||
Object.assign(this, this.loader.load(base.read(this.file)))
|
||||
}
|
||||
}
|
||||
|
||||
export class PluginConfigFolder {
|
||||
private loader: PluginConfigLoader
|
||||
private folder: string
|
||||
|
||||
private configCache = new Map<string, PluginFileConfig>()
|
||||
|
||||
constructor(loader: PluginConfigLoader, folder: string) {
|
||||
this.loader = loader
|
||||
this.folder = folder
|
||||
}
|
||||
|
||||
createConfig(path: string, def = {}) {
|
||||
return new PluginFileConfig(this.loader, path, def)
|
||||
}
|
||||
|
||||
getConfig(name: string, def = {}) {
|
||||
let path = fs.concat(this.folder, name)
|
||||
if (!this.configCache.has(path)) {
|
||||
this.configCache.set(path, this.createConfig(path, def))
|
||||
}
|
||||
return this.configCache.get(path)
|
||||
}
|
||||
|
||||
clear() {
|
||||
this.configCache.clear()
|
||||
}
|
||||
|
||||
save() {
|
||||
this.configCache.forEach((config) => config.save())
|
||||
}
|
||||
|
||||
reload() {
|
||||
this.configCache.forEach((config) => config.reload())
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
export const PluginConfigLoader = Symbol.for('PluginConfigLoader')
|
||||
export interface PluginConfigLoader {
|
||||
type: string
|
||||
load(content: string): any
|
||||
dump(variable: any): string
|
||||
}
|
||||
|
||||
export interface PluginConfig {
|
||||
/**
|
||||
* Save Config to File
|
||||
*/
|
||||
readonly save?: () => void
|
||||
/**
|
||||
* Reload Config from File
|
||||
*/
|
||||
readonly reload?: () => void
|
||||
[key: string]: any
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
export * from './json-loader'
|
||||
export * from './yaml-loader'
|
||||
@@ -1,18 +0,0 @@
|
||||
import { provideSingletonNamed } from '@ccms/container'
|
||||
|
||||
import { PluginConfigLoader } from '../interfaces'
|
||||
|
||||
const LOADER_TYPE_NAME = 'json'
|
||||
|
||||
@provideSingletonNamed(PluginConfigLoader, LOADER_TYPE_NAME)
|
||||
export class JsonPluginConfig implements PluginConfigLoader {
|
||||
type: string = LOADER_TYPE_NAME
|
||||
|
||||
load(content: string) {
|
||||
return JSON.parse(content)
|
||||
}
|
||||
|
||||
dump(variable: any): string {
|
||||
return JSON.stringify(variable, undefined, 4)
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
import * as yaml from 'js-yaml'
|
||||
import { provideSingletonNamed } from '@ccms/container'
|
||||
|
||||
import { PluginConfigLoader } from '../interfaces'
|
||||
|
||||
const LOADER_TYPE_NAME = 'yml'
|
||||
|
||||
@provideSingletonNamed(PluginConfigLoader, LOADER_TYPE_NAME)
|
||||
export class YamlPluginConfig implements PluginConfigLoader {
|
||||
type: string = LOADER_TYPE_NAME
|
||||
|
||||
load(content: string) {
|
||||
return yaml.load(content)
|
||||
}
|
||||
|
||||
dump(variable: any): string {
|
||||
return yaml.dump(variable, { skipInvalid: true, lineWidth: 120 })
|
||||
}
|
||||
}
|
||||
@@ -76,7 +76,6 @@ export function config(metadata: interfaces.ConfigMetadata = {}) {
|
||||
metadata.variable = key
|
||||
metadata.version = metadata.version ?? 1
|
||||
metadata.format = metadata.format ?? 'yml'
|
||||
metadata.migrate = metadata.migrate ?? true
|
||||
metadata.autosave = metadata.autosave ?? false
|
||||
metadata.filename = metadata.filename ?? metadata.name + '.' + metadata.format
|
||||
let previousMetadata = getPluginConfigMetadata(target)
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
import '@ccms/verify'
|
||||
import './scanner/js-scanner'
|
||||
import './scanner/mjs-scanner'
|
||||
|
||||
import './loader/ioc-loader'
|
||||
import './loader/basic-loader'
|
||||
|
||||
export * from './config'
|
||||
export * from './config/config'
|
||||
export * from './manager'
|
||||
export * from './decorators'
|
||||
export * from './interfaces'
|
||||
@@ -18,5 +17,3 @@ export {
|
||||
config as Config,
|
||||
playerdata as PlayerData
|
||||
} from './decorators'
|
||||
|
||||
import '@ccms/database'
|
||||
|
||||
@@ -91,10 +91,6 @@ export namespace interfaces {
|
||||
* 配置文件格式 默认 yml
|
||||
*/
|
||||
format?: string
|
||||
/**
|
||||
* 是否合并默认配置
|
||||
*/
|
||||
migrate?: boolean
|
||||
/**
|
||||
* 自动保存 默认为 false
|
||||
*/
|
||||
|
||||
@@ -63,13 +63,13 @@ export class IocLoader implements plugin.PluginLoader {
|
||||
}
|
||||
|
||||
private bindPlugin(metadata: plugin.PluginMetadata) {
|
||||
if (this.container.isBoundNamed(plugin.Plugin, metadata.name)) {
|
||||
try {
|
||||
let pluginInstance = this.container.getNamed<plugin.Plugin>(plugin.Plugin, metadata.name)
|
||||
if (pluginInstance.description.source + '' !== metadata.source + '') {
|
||||
console.i18n('ms.plugin.manager.build.duplicate', { exists: pluginInstance.description.source, source: metadata.source })
|
||||
}
|
||||
this.container.rebind(plugin.Plugin).to(metadata.target).inSingletonScope().whenTargetNamed(metadata.name)
|
||||
} else {
|
||||
} catch {
|
||||
this.container.bind(plugin.Plugin).to(metadata.target).inSingletonScope().whenTargetNamed(metadata.name)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,13 +64,9 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
||||
initialize() {
|
||||
if (this.pluginInstance === undefined) { throw new Error("Can't found Plugin Instance!") }
|
||||
if (this.initialized !== true) {
|
||||
process.emit('plugin.manager.before.initialize', this)
|
||||
process.emit('plugin.manager.before.initialize')
|
||||
console.i18n('ms.plugin.initialize', { plugin: this.pluginInstance, loader: Thread.currentThread().contextClassLoader })
|
||||
try {
|
||||
console.i18n('ms.plugin.event.map', { count: this.eventManager.mapEventName(), type: this.serverType })
|
||||
} catch (error) {
|
||||
console.i18n('ms.plugin.event.map.error', { type: this.serverType, error })
|
||||
}
|
||||
console.i18n('ms.plugin.event.map', { count: this.eventManager.mapEventName(), type: this.serverType })
|
||||
let pluginScanner = this.container.getAll<plugin.PluginScanner>(plugin.PluginScanner)
|
||||
pluginScanner.forEach((scanner) => {
|
||||
console.debug(`loading plugin sacnner ${scanner.type}...`)
|
||||
@@ -82,14 +78,14 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
||||
this.loaderMap.set(loader.type, loader)
|
||||
})
|
||||
this.initialized = true
|
||||
process.emit('plugin.manager.after.initialize', this)
|
||||
process.emit('plugin.manager.after.initialize')
|
||||
}
|
||||
}
|
||||
|
||||
scan(folder: string): void {
|
||||
if (!folder) { throw new Error('plugin scan folder can\'t be empty!') }
|
||||
this.initialize()
|
||||
process.emit('plugin.manager.before.scan', folder, this)
|
||||
process.emit('plugin.manager.before.scan', folder)
|
||||
for (const [, scanner] of this.sacnnerMap) {
|
||||
try {
|
||||
console.i18n('ms.plugin.manager.scan', { scanner: scanner.type, folder })
|
||||
@@ -108,13 +104,13 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
||||
console.ex(error)
|
||||
}
|
||||
}
|
||||
process.emit('plugin.manager.after.scan', folder, this)
|
||||
process.emit('plugin.manager.after.scan', folder)
|
||||
}
|
||||
|
||||
build(): void {
|
||||
process.emit('plugin.manager.before.build', this)
|
||||
process.emit('plugin.manager.before.build')
|
||||
this.buildPlugins()
|
||||
process.emit('plugin.manager.after.build', this)
|
||||
process.emit('plugin.manager.after.build')
|
||||
}
|
||||
|
||||
private logStage(plugin: plugin.Plugin, stage: string) {
|
||||
@@ -148,6 +144,7 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
||||
console.i18n("ms.plugin.manager.initialize.error", { name: loadMetadata.file, ex: error })
|
||||
console.ex(error)
|
||||
}
|
||||
console.console(`§6scanner: §b${loadMetadata.scanner.type} §ccan\'t load §6file §b${loadMetadata.file}. §eskip!`)
|
||||
}
|
||||
|
||||
private loaderRequirePlugin(loadMetadata: plugin.PluginLoadMetadata, loader: plugin.PluginLoader) {
|
||||
@@ -198,9 +195,7 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
||||
let scanner = this.sacnnerMap.get(ext)
|
||||
if (!scanner) { throw new Error(`plugin scanner ${ext} can't found in sacnnerMap.`) }
|
||||
let metadata = this.loadAndRequirePlugin(scanner.read(file))
|
||||
this.buildPlugin(metadata)
|
||||
let plugin = metadata.target
|
||||
if (!plugin) { throw new Error(`plugin scanner ${ext} can't found in sacnnerMap.`) }
|
||||
let plugin = this.buildPlugin(metadata)
|
||||
this.load(plugin)
|
||||
this.enable(plugin)
|
||||
return plugin
|
||||
@@ -260,10 +255,10 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
||||
if (metadata?.depends?.length) {
|
||||
this.lazyMetadataMap.set(key, metadata)
|
||||
} else {
|
||||
this.tryBuildPlugin(metadata)
|
||||
this.buildPlugin(metadata)
|
||||
}
|
||||
})
|
||||
this.lazyMetadataMap.forEach((metadata, key) => this.tryBuildPlugin(metadata))
|
||||
this.lazyMetadataMap.forEach((metadata, key) => this.buildPlugin(metadata))
|
||||
}
|
||||
|
||||
private checkDepends(depends: string | string[]) {
|
||||
@@ -278,29 +273,24 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
||||
for (const depend of depends) { if (!this.nativePluginManager.has(depend)) loseDepends.push(depend) }
|
||||
return loseDepends
|
||||
}
|
||||
|
||||
private tryBuildPlugin(metadata: plugin.PluginMetadata) {
|
||||
private buildPlugin(metadata: plugin.PluginMetadata) {
|
||||
process.emit(`plugin.before.build`, metadata)
|
||||
try {
|
||||
return this.buildPlugin(metadata)
|
||||
if (this.instanceMap.has(metadata.name)) { throw new Error(`Plugin ${metadata.name} is already load from ${metadata.source}...`) }
|
||||
if (!this.loaderMap.has(metadata.type)) { throw new Error(`§4无法加载插件 §b${metadata.name} §4请检查 §c${metadata.type} §4加载器是否正常启用!`) }
|
||||
if (!this.serverChecker.check(metadata.servers)) { throw new Error(`§6插件 §b${metadata.name} §c服务器类型不兼容(${metadata.servers.join(',')}) §6忽略加载...`) }
|
||||
let loseDepends = this.checkDepends(metadata.depends) || []
|
||||
if (loseDepends.length) { throw new Error(`§4无法加载插件 §b${metadata.name} §4请检查脚本依赖 §3[${loseDepends.join(',')}] §4是否安装完整!`) }
|
||||
let loseNativeDepends = this.checkNativeDepends(metadata.nativeDepends) || []
|
||||
if (loseNativeDepends.length) { throw new Error(`§4无法加载插件 §b${metadata.name} §4请检查插件依赖 §3[${loseNativeDepends.join(',')}] §4是否安装完整!`) }
|
||||
let pluginInstance = this.loaderMap.get(metadata.type).build(metadata)
|
||||
if (!pluginInstance) { throw new Error(`§4加载器 §c${metadata.type} §4加载插件 §c${metadata.name} §4失败!`) }
|
||||
this.instanceMap.set(metadata.name, pluginInstance)
|
||||
process.emit(`plugin.after.build`, metadata, pluginInstance)
|
||||
return pluginInstance
|
||||
} catch (error: any) {
|
||||
console.console(`§4无法加载插件 §b${metadata.name} §4构建插件失败!`)
|
||||
console.ex(error)
|
||||
}
|
||||
}
|
||||
|
||||
private buildPlugin(metadata: plugin.PluginMetadata) {
|
||||
process.emit(`plugin.before.build`, metadata)
|
||||
if (this.instanceMap.has(metadata.name)) { throw new Error(`Plugin ${metadata.name} is already load from ${metadata.source}...`) }
|
||||
if (!this.loaderMap.has(metadata.type)) { throw new Error(`§4无法加载插件 §b${metadata.name} §4请检查 §c${metadata.type} §4加载器是否正常启用!`) }
|
||||
if (!this.serverChecker.check(metadata.servers)) { throw new Error(`§6插件 §b${metadata.name} §c服务器类型不兼容(${metadata.servers.join(',')}) §6忽略加载...`) }
|
||||
let loseDepends = this.checkDepends(metadata.depends) || []
|
||||
if (loseDepends.length) { throw new Error(`§4无法加载插件 §b${metadata.name} §4请检查脚本依赖 §3[${loseDepends.join(',')}] §4是否安装完整!`) }
|
||||
let loseNativeDepends = this.checkNativeDepends(metadata.nativeDepends) || []
|
||||
if (loseNativeDepends.length) { throw new Error(`§4无法加载插件 §b${metadata.name} §4请检查插件依赖 §3[${loseNativeDepends.join(',')}] §4是否安装完整!`) }
|
||||
let pluginInstance = this.loaderMap.get(metadata.type).build(metadata)
|
||||
if (!pluginInstance) { throw new Error(`§4加载器 §c${metadata.type} §4加载插件 §c${metadata.name} §4失败!`) }
|
||||
metadata.target = pluginInstance
|
||||
this.instanceMap.set(metadata.name, pluginInstance)
|
||||
process.emit(`plugin.after.build`, metadata, pluginInstance)
|
||||
return pluginInstance
|
||||
}
|
||||
}
|
||||
|
||||
131
packages/plugin/src/scanner/mjs-scanner.ts
Normal file
131
packages/plugin/src/scanner/mjs-scanner.ts
Normal file
@@ -0,0 +1,131 @@
|
||||
import { plugin } from "@ccms/api"
|
||||
import http from '@ccms/common/dist/http'
|
||||
import { provideSingletonNamed } from "@ccms/container"
|
||||
|
||||
import * as fs from '@ccms/common/dist/fs'
|
||||
|
||||
import * as CryptoJS from "crypto-js"
|
||||
|
||||
const SCANNER_TYPE_NAME = 'mjs'
|
||||
|
||||
@provideSingletonNamed(plugin.PluginScanner, SCANNER_TYPE_NAME)
|
||||
export class SecretJSFileScanner implements plugin.PluginScanner {
|
||||
type: string = SCANNER_TYPE_NAME
|
||||
|
||||
constructor() {
|
||||
global.setGlobal('MiaoScriptPackageCenterTokenCache', {})
|
||||
global.setGlobal('MiaoScriptPackageCenterQQCache', {})
|
||||
}
|
||||
|
||||
scan(target: any): plugin.PluginLoadMetadata[] {
|
||||
return this.scanFolder(fs.concat(root, target)).map((file) => this.read(file))
|
||||
}
|
||||
|
||||
read(file: any): plugin.PluginLoadMetadata {
|
||||
return { file, type: this.type, scanner: this, loaded: false }
|
||||
}
|
||||
|
||||
load(metadata: plugin.PluginLoadMetadata): plugin.PluginLoadMetadata {
|
||||
if (metadata.type !== this.type) { return }
|
||||
this.updatePlugin(metadata.file)
|
||||
//@ts-ignore load plugin not use cache
|
||||
metadata.instance = require(metadata.file.toString(), {
|
||||
cache: false,
|
||||
hook: (origin) => {
|
||||
let info = JSON.parse(origin)
|
||||
if (!info || !info.encrypt) {
|
||||
return this.exportErrorPlugin(
|
||||
metadata.file,
|
||||
`console.console('§4无效的加密插件: §c${metadata.file}')`
|
||||
)
|
||||
}
|
||||
let qq = info.qq
|
||||
let encrypt = info.encrypt
|
||||
let token = this.decrypt(info.token, qq, info.timestamp)
|
||||
global.MiaoScriptPackageCenterQQCache[info.name] = qq
|
||||
global.MiaoScriptPackageCenterTokenCache[info.name] = token
|
||||
try {
|
||||
let result = http.post('https://ms.yumc.pw/api/plugin/check', `{
|
||||
"pid": ${info.pid},
|
||||
"qq": ${qq},
|
||||
"token": "${token}",
|
||||
"source": true
|
||||
}`)
|
||||
if (result.code != 200) {
|
||||
return this.exportErrorPlugin(
|
||||
info.name,
|
||||
`console.console('§6[§b圈云授权系统§6] §6插件: §b${info.name} §c授权效验失败: §4${result.msg}')`
|
||||
)
|
||||
}
|
||||
if (!result.data) {
|
||||
return this.exportErrorPlugin(
|
||||
info.name,
|
||||
`console.console('§6[§b圈云授权系统§6] §6插件: §b${info.name} §c服务器返回异常数据.')`
|
||||
)
|
||||
}
|
||||
base.save(metadata.file, result.data.encrypt)
|
||||
return result.data.source
|
||||
} catch (error) {
|
||||
}
|
||||
if (Date.now() / 1000 - info.timestamp > 7 * 24 * 60 * 60) {
|
||||
return this.exportErrorPlugin(
|
||||
info.name,
|
||||
`console.console('§6[§b圈云授权系统§6] §6插件: §b${info.name} §c离线授权已过期.')`
|
||||
)
|
||||
}
|
||||
return this.decrypt(encrypt, qq, token)
|
||||
}
|
||||
})
|
||||
return metadata
|
||||
}
|
||||
|
||||
private decrypt(encrypt, key, iv) {
|
||||
return CryptoJS.AES.decrypt(encrypt,
|
||||
CryptoJS.enc.Utf8.parse(`${key}`.padEnd(16, "\0").substring(0, 16)), {
|
||||
iv: CryptoJS.enc.Utf8.parse(`${iv}`.padEnd(16, "\0").substring(0, 16))
|
||||
}).toString(CryptoJS.enc.Utf8)
|
||||
}
|
||||
|
||||
private exportErrorPlugin(name, src) {
|
||||
return `module.exports = {
|
||||
description: {
|
||||
name: "${name}",
|
||||
version: "未授权",
|
||||
author: "未授权",
|
||||
type: "basic",
|
||||
source: __filename,
|
||||
target: this
|
||||
},
|
||||
load: function () { ${src} }
|
||||
}`
|
||||
}
|
||||
|
||||
private scanFolder(folder: any): string[] {
|
||||
var files = []
|
||||
this.checkUpdateFolder(folder)
|
||||
// must check file is exist maybe is a illegal symbolic link file
|
||||
fs.list(folder).forEach((path: any) => {
|
||||
let file = path.toFile()
|
||||
if (file.exists() && (file.getName().endsWith(".mjs.json") || file.getName().endsWith(".mjs"))) {
|
||||
files.push(file)
|
||||
}
|
||||
})
|
||||
return files
|
||||
}
|
||||
|
||||
private checkUpdateFolder(path: any) {
|
||||
var update = fs.file(path, "update")
|
||||
if (!update.exists()) {
|
||||
update.mkdirs()
|
||||
}
|
||||
}
|
||||
|
||||
private updatePlugin(file: any) {
|
||||
var update = fs.file(fs.file(fs.file(file).parentFile, 'update'), file.name)
|
||||
if (update.exists()) {
|
||||
console.i18n("ms.plugin.manager.build.update", { name: file.name })
|
||||
fs.move(update, file, true)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/polyfill",
|
||||
"version": "0.23.0-alpha.0",
|
||||
"version": "0.19.0",
|
||||
"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-alpha.0",
|
||||
"@ccms/nodejs": "^0.22.0",
|
||||
"core-js": "^3.22.1"
|
||||
"@ccms/i18n": "^0.19.0",
|
||||
"@ccms/nodejs": "^0.19.0",
|
||||
"core-js": "^3.21.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.22.0",
|
||||
"@ccms/nashorn": "^0.19.0",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.6.3"
|
||||
"typescript": "^4.5.5"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,4 +14,3 @@ global.setGlobal('Proxy', require('./proxy').Proxy)
|
||||
global.setGlobal('XMLHttpRequest', require('./xml-http-request').XMLHttpRequest)
|
||||
global.setGlobal('Blob', require('blob-polyfill').Blob)
|
||||
console.i18n("ms.polyfill.completed", { time: (new Date().getTime() - polyfillStartTime) / 1000 })
|
||||
export default true
|
||||
|
||||
@@ -2,7 +2,6 @@ import { EventEmitter } from 'events'
|
||||
|
||||
const System = Java.type('java.lang.System')
|
||||
const Thread = Java.type('java.lang.Thread')
|
||||
const ManagementFactory = Java.type('java.lang.management.ManagementFactory')
|
||||
const InterruptedException = Java.type('java.lang.InterruptedException')
|
||||
const ThreadGroup = Java.type("java.lang.ThreadGroup")
|
||||
const AtomicInteger = Java.type("java.util.concurrent.atomic.AtomicInteger")
|
||||
@@ -16,35 +15,19 @@ const DelayQueue = Java.type('java.util.concurrent.DelayQueue')
|
||||
const JavaScriptTask = Java.type(base.getJavaScriptTaskClass().name)
|
||||
|
||||
const threadCount = new AtomicInteger(0)
|
||||
const threadGroup = new ThreadGroup("@ccms/micro-task")
|
||||
const threadGroup = new ThreadGroup("@ccms/ployfill-micro-task")
|
||||
const microTaskPool = new ThreadPoolExecutor(
|
||||
100, 200, 60, TimeUnit.SECONDS,
|
||||
new LinkedBlockingQueue(1024),
|
||||
new LinkedBlockingQueue(300),
|
||||
new ThreadFactory((run: any) => new Thread(threadGroup, run, "@ccms/micro-task-" + threadCount.incrementAndGet()))
|
||||
)
|
||||
class Process extends EventEmitter {
|
||||
readonly version = base.version
|
||||
readonly versions = []
|
||||
readonly config = {}
|
||||
readonly pid: number = parseInt(ManagementFactory.getRuntimeMXBean().getName().split('@')[0])
|
||||
readonly ppid: number
|
||||
title: string
|
||||
readonly arch: string = System.getProperty("os.arch")
|
||||
readonly platform = System.getProperty("os.name")
|
||||
|
||||
env = {
|
||||
__noSuchProperty__: (prop) => {
|
||||
return System.getenv(prop)
|
||||
}
|
||||
}
|
||||
|
||||
stdout = System.out
|
||||
stderr = System.err
|
||||
stdin = System.in
|
||||
|
||||
execArgv = ''
|
||||
execPath = ''
|
||||
|
||||
platform = System.getProperty("os.name")
|
||||
constructor() {
|
||||
super()
|
||||
this.on('exit', () => {
|
||||
@@ -66,10 +49,10 @@ class Process extends EventEmitter {
|
||||
}
|
||||
})
|
||||
}
|
||||
nextTick(callback: Function, ...args: any[]): void {
|
||||
nextTick(func: Function, ...args: any[]) {
|
||||
microTaskPool.execute(() => {
|
||||
try {
|
||||
callback(args)
|
||||
func(args)
|
||||
} catch (origin: any) {
|
||||
try {
|
||||
super.emit('error', origin)
|
||||
@@ -82,44 +65,9 @@ class Process extends EventEmitter {
|
||||
}
|
||||
exit(code: number) {
|
||||
console.log(`process exit by code ${code}!`)
|
||||
this.emit('exit', this.exitCode = code)
|
||||
}
|
||||
exitCode = 0
|
||||
openStdin() {
|
||||
throw new Error('MiaoScript unsupport openStdin.')
|
||||
}
|
||||
chdir(directory: string): void {
|
||||
console.error('MiaoScript unsupport chdir. lock at ' + root)
|
||||
}
|
||||
cwd() {
|
||||
return root
|
||||
}
|
||||
getgid(): number {
|
||||
throw new Error('MiaoScript unsupport getgid.')
|
||||
}
|
||||
setgid(id: number | string) {
|
||||
throw new Error('MiaoScript unsupport setgid.')
|
||||
}
|
||||
getuid(): number {
|
||||
throw new Error('MiaoScript unsupport getuid.')
|
||||
}
|
||||
setuid(id: number | string) {
|
||||
throw new Error('MiaoScript unsupport setuid.')
|
||||
}
|
||||
setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null) {
|
||||
if (cb == null) {
|
||||
this.removeAllListeners('error')
|
||||
} else {
|
||||
this.on('error', cb)
|
||||
}
|
||||
}
|
||||
hasUncaughtExceptionCaptureCallback() {
|
||||
return this.listenerCount('error') > 0
|
||||
}
|
||||
kill(pid: number, signal?: string | number): true {
|
||||
throw new Error('MiaoScript unsupport kill.')
|
||||
return true
|
||||
this.emit('exit', code)
|
||||
}
|
||||
|
||||
toString() {
|
||||
return "[object process]"
|
||||
}
|
||||
@@ -128,16 +76,16 @@ class Process extends EventEmitter {
|
||||
class EventLoop {
|
||||
private eventLoopMainThread = undefined
|
||||
private eventLoopTaskQueue = new DelayQueue()
|
||||
private taskExecuteTimeout = 3000
|
||||
private taskExecTimeout = 3
|
||||
private fixedThreadPool = undefined
|
||||
|
||||
constructor() {
|
||||
this.taskExecuteTimeout = parseInt(process.env.MS_TASK_EXECUTE_TIMEOUT) || 3000
|
||||
this.taskExecTimeout = parseInt(process.env.MS_NODE_EVENT_LOOP_TIMEOUT) || 3
|
||||
this.fixedThreadPool = new ThreadPoolExecutor(
|
||||
1, 1, 0, TimeUnit.SECONDS,
|
||||
new LinkedBlockingQueue(1024),
|
||||
new LinkedBlockingQueue(300),
|
||||
new ThreadFactory((run: any) => {
|
||||
let thread = new Thread(run, "@ccms/event-loop")
|
||||
let thread = new Thread(run, "@ccms/node-shim/event-loop-exec")
|
||||
thread.setDaemon(true)
|
||||
return thread
|
||||
}))
|
||||
@@ -167,7 +115,7 @@ class EventLoop {
|
||||
this.intervalTasks = undefined
|
||||
this.eventLoopMainThread = undefined
|
||||
}
|
||||
}, "@ccms/event-loop")
|
||||
}, "@ccms/node-shim/event-loop")
|
||||
this.eventLoopMainThread.setDaemon(true)
|
||||
process.on('exit', () => {
|
||||
this.eventLoopMainThread.interrupt()
|
||||
@@ -189,9 +137,7 @@ class EventLoop {
|
||||
if (!callback) {
|
||||
throw new Error(`task ${name} callback function can't be null!`)
|
||||
}
|
||||
if (this.fixedThreadPool.isShutdown()) {
|
||||
return console.warn(`FixedThreadPool isTerminated! ignore Task ${name}!`)
|
||||
}
|
||||
if (this.fixedThreadPool.isShutdown()) { return console.warn(`FixedThreadPool isTerminated! ignore Task ${name}!`) }
|
||||
try {
|
||||
this.fixedThreadPool.submit(new Callable({
|
||||
call: () => {
|
||||
@@ -207,13 +153,13 @@ class EventLoop {
|
||||
}
|
||||
}
|
||||
}
|
||||
})).get(this.taskExecuteTimeout, TimeUnit.MILLISECONDS)
|
||||
})).get(this.taskExecTimeout, TimeUnit.SECONDS)
|
||||
} catch (error: any) {
|
||||
if (error instanceof InterruptedException) {
|
||||
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.taskExecTimeout}s!`)
|
||||
}
|
||||
throw error.getCause && error.getCause() || error
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/protocol",
|
||||
"version": "0.22.0",
|
||||
"version": "0.19.0",
|
||||
"description": "MiaoScript protocol package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -22,6 +22,6 @@
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.6.3"
|
||||
"typescript": "^4.5.5"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@ccms/sponge",
|
||||
"version": "0.23.0-alpha.0",
|
||||
"description": "MiaoScript sponge package",
|
||||
"version": "0.19.5",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
"minecraft",
|
||||
@@ -22,11 +22,11 @@
|
||||
"@javatypes/sponge-api": "^0.0.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.6.3"
|
||||
"typescript": "^4.5.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.23.0-alpha.0",
|
||||
"@ccms/common": "^0.23.0-alpha.0",
|
||||
"@ccms/container": "^0.22.0"
|
||||
"@ccms/api": "^0.19.5",
|
||||
"@ccms/common": "^0.19.0",
|
||||
"@ccms/container": "^0.19.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/spring",
|
||||
"version": "0.23.0-alpha.0",
|
||||
"version": "0.19.5",
|
||||
"description": "MiaoScript spring package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -21,12 +21,12 @@
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.6.3"
|
||||
"typescript": "^4.5.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.23.0-alpha.0",
|
||||
"@ccms/common": "^0.23.0-alpha.0",
|
||||
"@ccms/container": "^0.22.0",
|
||||
"@ccms/database": "^0.23.0-alpha.0"
|
||||
"@ccms/api": "^0.19.5",
|
||||
"@ccms/common": "^0.19.0",
|
||||
"@ccms/container": "^0.19.0",
|
||||
"@ccms/database": "^0.19.5"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/web",
|
||||
"version": "0.23.0-alpha.0",
|
||||
"version": "0.19.5",
|
||||
"description": "MiaoScript web package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -26,10 +26,10 @@
|
||||
"@javatypes/tomcat": "^0.0.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.6.3"
|
||||
"typescript": "^4.5.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.23.0-alpha.0",
|
||||
"@ccms/container": "^0.22.0"
|
||||
"@ccms/api": "^0.19.5",
|
||||
"@ccms/container": "^0.19.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/websocket",
|
||||
"version": "0.22.0",
|
||||
"version": "0.19.0",
|
||||
"description": "MiaoScript websocket package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -23,10 +23,10 @@
|
||||
"parseuri": "^0.0.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.22.0",
|
||||
"@ccms/nashorn": "^0.19.0",
|
||||
"@javatypes/tomcat-websocket-api": "^0.0.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.6.3"
|
||||
"typescript": "^4.5.5"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
import * as server from "../server"
|
||||
// const http = require("http")
|
||||
// const Server = require("./server")
|
||||
import { Server } from './server'
|
||||
@@ -17,7 +18,7 @@ import { Server } from './server'
|
||||
|
||||
function attach(srv, options) {
|
||||
const engine = new Server(options)
|
||||
engine.attach(srv, options)
|
||||
engine.attach(server.attach(srv, options), options)
|
||||
return engine
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
/// <reference types="@ccms/nashorn" />
|
||||
/// <reference types="@javatypes/tomcat-websocket-api" />
|
||||
|
||||
import * as server from './server'
|
||||
import { Server, ServerOptions } from './socket.io'
|
||||
|
||||
interface SocketIOStatic {
|
||||
@@ -39,21 +38,9 @@ interface SocketIOStatic {
|
||||
|
||||
type SocketStatic = SocketIOStatic & { Instance?: symbol }
|
||||
|
||||
let singletonServer: Server
|
||||
|
||||
// @ts-ignore
|
||||
let io: SocketStatic = function io(pipeline: any, options: Partial<JavaServerOptions>, singleton = true) {
|
||||
if (singleton) {
|
||||
if (!singletonServer) {
|
||||
singletonServer = new Server(server.attach(pipeline, options), options)
|
||||
process.emit('websocket.create', singletonServer)
|
||||
process.on('exit', () => {
|
||||
singletonServer.close()
|
||||
})
|
||||
}
|
||||
return singletonServer
|
||||
}
|
||||
return new Server(server.attach(pipeline, options), options)
|
||||
let io: SocketStatic = function (pipeline: any, options: Partial<ServerOptions>) {
|
||||
return new Server(pipeline, options)
|
||||
}
|
||||
io.Instance = Symbol("@ccms/websocket")
|
||||
export default io
|
||||
|
||||
@@ -19,7 +19,6 @@ export enum ServerEvent {
|
||||
export interface JavaServerOptions extends ServerOptions {
|
||||
event?: EventEmitter
|
||||
root?: string
|
||||
httpRequestHandler?: (ctx, request) => void
|
||||
}
|
||||
|
||||
export abstract class WebSocketServer extends EventEmitter {
|
||||
@@ -31,6 +30,7 @@ export abstract class WebSocketServer extends EventEmitter {
|
||||
this.instance = instance
|
||||
this.options = options
|
||||
this.clients = new Map()
|
||||
console.debug('create websocket server from ' + this.constructor.name)
|
||||
this.initialize()
|
||||
}
|
||||
protected onconnect(handler: any) {
|
||||
@@ -56,7 +56,7 @@ export abstract class WebSocketServer extends EventEmitter {
|
||||
if (this.clients.has(id)) {
|
||||
this.clients.has(id) && callback(this.clients.get(id))
|
||||
} else {
|
||||
console.trace('ignore execute', handler, 'callback', callback)
|
||||
console.debug('ignore execute', handler, 'callback', callback)
|
||||
}
|
||||
}
|
||||
public close() {
|
||||
@@ -75,7 +75,7 @@ export const attach = (instance, options) => {
|
||||
options = Object.assign({
|
||||
event: new EventEmitter(),
|
||||
path: '/ws',
|
||||
root: root + Java.type("java.io.File").separatorChar + 'wwwroot',
|
||||
root: root + '/wwwroot',
|
||||
}, options)
|
||||
let WebSocketServerImpl = undefined
|
||||
if (instance.class.name.startsWith('io.netty.channel')) {
|
||||
@@ -83,6 +83,5 @@ export const attach = (instance, options) => {
|
||||
} else {
|
||||
WebSocketServerImpl = require("./tomcat").TomcatWebSocketServer
|
||||
}
|
||||
console.debug('create websocket server from ' + WebSocketServerImpl.name)
|
||||
return new WebSocketServerImpl(instance, options)
|
||||
}
|
||||
|
||||
@@ -23,46 +23,40 @@ export class HttpRequestHandler extends HttpRequestHandlerAdapter {
|
||||
super()
|
||||
this.root = options.root
|
||||
this.ws = options.path
|
||||
if (options.httpRequestHandler) {
|
||||
this.httpRequestHandler = options.httpRequestHandler
|
||||
}
|
||||
}
|
||||
channelRead0(ctx: any, request: any) {
|
||||
if (request.getUri().startsWith(this.ws)) {
|
||||
ctx.channel().attr(AttributeKeys.Request).set(request)
|
||||
ctx.fireChannelRead(request.retain())
|
||||
} else {
|
||||
this.httpRequestHandler(ctx, request)
|
||||
ctx.executor().execute(new Runnable({
|
||||
run: () => {
|
||||
if (HttpHeaders.is100ContinueExpected(request)) {
|
||||
ctx.writeAndFlush(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE))
|
||||
}
|
||||
let filename = request.getUri().split('?')[0].substr(1)
|
||||
let file = new File(this.root, filename || 'index.html')
|
||||
if (!file.exists() || !file.isFile()) {
|
||||
ctx.write(new DefaultHttpResponse(request.getProtocolVersion(), HttpResponseStatus.NOT_FOUND))
|
||||
ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT).addListener(ChannelFutureListener.CLOSE)
|
||||
return
|
||||
}
|
||||
let response = new DefaultHttpResponse(request.getProtocolVersion(), HttpResponseStatus.OK)
|
||||
response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/html charset=UTF-8")
|
||||
let raf = new RandomAccessFile(file, 'r')
|
||||
let keepAlive = HttpHeaders.isKeepAlive(request)
|
||||
if (keepAlive) {
|
||||
response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, file.length())
|
||||
response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE)
|
||||
}
|
||||
ctx.write(response)
|
||||
ctx.write(new DefaultFileRegion(raf.getChannel(), 0, raf.length()))
|
||||
let future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT)
|
||||
if (!keepAlive) {
|
||||
future.addListener(ChannelFutureListener.CLOSE)
|
||||
}
|
||||
}
|
||||
}))
|
||||
}
|
||||
}
|
||||
httpRequestHandler(ctx: any, request: any) {
|
||||
ctx.executor().execute(new Runnable({
|
||||
run: () => {
|
||||
if (HttpHeaders.is100ContinueExpected(request)) {
|
||||
ctx.writeAndFlush(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE))
|
||||
}
|
||||
let filename = request.getUri().split('?')[0].substr(1)
|
||||
let file = new File(this.root, filename || 'index.html')
|
||||
if (!file.exists() || !file.isFile()) {
|
||||
ctx.write(new DefaultHttpResponse(request.getProtocolVersion(), HttpResponseStatus.NOT_FOUND))
|
||||
ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT).addListener(ChannelFutureListener.CLOSE)
|
||||
return
|
||||
}
|
||||
let response = new DefaultHttpResponse(request.getProtocolVersion(), HttpResponseStatus.OK)
|
||||
response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/html charset=UTF-8")
|
||||
let raf = new RandomAccessFile(file, 'r')
|
||||
let keepAlive = HttpHeaders.isKeepAlive(request)
|
||||
if (keepAlive) {
|
||||
response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, file.length())
|
||||
response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE)
|
||||
}
|
||||
ctx.write(response)
|
||||
ctx.write(new DefaultFileRegion(raf.getChannel(), 0, raf.length()))
|
||||
let future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT)
|
||||
if (!keepAlive) {
|
||||
future.addListener(ChannelFutureListener.CLOSE)
|
||||
}
|
||||
}
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user