feat: formatting code & remove chinese

Signed-off-by: MiaoWoo <admin@yumc.pw>
This commit is contained in:
MiaoWoo 2020-01-15 16:48:18 +08:00
parent 4d0c0122c7
commit eef0baa740
12 changed files with 111 additions and 61 deletions

View File

@ -5,7 +5,7 @@ export namespace command {
export abstract class Command { export abstract class Command {
on(plugin: any, name: string, exec: { cmd: Function, tab?: Function }) { on(plugin: any, name: string, exec: { cmd: Function, tab?: Function }) {
var cmd = this.create(plugin, name); var cmd = this.create(plugin, name);
console.debug(`插件 ${plugin.description.name} 创建命令 ${name}(${cmd})...`) console.debug(`[${plugin.description.name}] register command ${name}(${cmd})...`)
if (exec.cmd && typeof exec.cmd === "function") { if (exec.cmd && typeof exec.cmd === "function") {
this.onCommand(plugin, cmd, exec.cmd); this.onCommand(plugin, cmd, exec.cmd);
} else { } else {
@ -16,7 +16,7 @@ export namespace command {
} }
} }
off(plugin: any, name: string) { off(plugin: any, name: string) {
console.debug(`插件 ${plugin.description.name} 注销命令 ${name}...`) console.debug(`[${plugin.description.name}] unregister command ${name}...`)
this.remove(plugin, name); this.remove(plugin, name);
} }
/** /**
@ -28,7 +28,7 @@ export namespace command {
protected abstract onTabComplete(plugin: any, command: any, tabCompleter: Function); protected abstract onTabComplete(plugin: any, command: any, tabCompleter: Function);
protected setExecutor(plugin: any, command: any, executor: Function) { protected setExecutor(plugin: any, command: any, executor: Function) {
return (sender: any, _, command: string, args: string[]) => { return (sender: any, _: any, command: string, args: string[]) => {
try { try {
return executor(sender, command, Java.from(args)); return executor(sender, command, Java.from(args));
} catch (ex) { } catch (ex) {
@ -41,7 +41,7 @@ export namespace command {
} }
protected setTabCompleter(plugin: any, command: any, tabCompleter: Function) { protected setTabCompleter(plugin: any, command: any, tabCompleter: Function) {
return (sender: any, _, command: string, args: string[]) => { return (sender: any, _: any, command: string, args: string[]) => {
try { try {
var token = args[args.length - 1]; var token = args[args.length - 1];
var complete = tabCompleter(sender, command, Java.from(args)) || []; var complete = tabCompleter(sender, command, Java.from(args)) || [];

View File

@ -1,11 +1,23 @@
let Arrays = Java.type('java.util.Arrays'); let Arrays = Java.type('java.util.Arrays');
let Level = Java.type('java.util.logging.Level'); let Level = Java.type('java.util.logging.Level');
let ignoreLogPrefix = ['java.', 'net.minecraft.', 'org.bukkit.', 'jdk.nashorn.', 'io.netty.']; let ignoreLogPrefix = ['java.', 'net.minecraft.', 'org.bukkit.', 'jdk.nashorn.', 'io.netty.', 'org.spongepowered.'];
enum LogLevel {
ALL,
TRACE,
DEBUG,
INFO,
WARN,
ERROR,
FATAL,
OFF
}
export class MiaoScriptConsole implements Console { export class MiaoScriptConsole implements Console {
Console: NodeJS.ConsoleConstructor; Console: NodeJS.ConsoleConstructor;
private _name: string = ''; private _name: string = '';
private _level: LogLevel = global.debug ? LogLevel.DEBUG : LogLevel.INFO;
protected logger: any; protected logger: any;
protected prefix: string = '§6[§bMiaoScript§6]§r '; protected prefix: string = '§6[§bMiaoScript§6]§r ';
@ -26,23 +38,28 @@ export class MiaoScriptConsole implements Console {
this.prefix = `§6[§cMS§6][§b${name}§6]§r `; this.prefix = `§6[§cMS§6][§b${name}§6]§r `;
} }
} }
log(...args): void { log(...args: any[]): void {
this.logger.info(this.name + args.join(' ')); this.logger.info(this.name + args.join(' '));
} }
info(...args) { info(...args: any[]) {
this.logger.info(this.name + args.join(' ')); this.logger.info(this.name + args.join(' '));
}; }
warn(...args) { warn(...args: any[]) {
this.logger.warning(this.name + args.join(' ')); this.logger.warning(this.name + args.join(' '));
}; }
error(...args) { error(...args: any[]) {
this.logger.log(Level.SEVERE, this.name + args.join(' ')); this.logger.log(Level.SEVERE, this.name + args.join(' '));
}; }
debug(...args) { debug(...args: any[]) {
if (global.debug) { if (global.debug) {
this.logger.info(this.name + '[DEBUG] ' + args.join(' ')); this.logger.info(this.name + '[DEBUG] ' + args.join(' '));
} }
}; }
trace(...args: any[]): void {
if (this._level <= LogLevel.TRACE) {
this.logger.info(this.name + '[TRACE] ' + args.join(' '));
}
}
sender(...args) { sender(...args) {
this.info(args) this.info(args)
} }
@ -53,10 +70,10 @@ export class MiaoScriptConsole implements Console {
for (var i in obj) { for (var i in obj) {
this.logger(i, '=>', obj[i]) this.logger(i, '=>', obj[i])
} }
}; }
ex(ex: Error) { ex(ex: Error) {
this.stack(ex).forEach(line => this.console(line)) this.stack(ex).forEach(line => this.console(line))
}; }
stack(ex: Error): string[] { stack(ex: Error): string[] {
var stack = ex.getStackTrace(); var stack = ex.getStackTrace();
var cache = ['§4' + ex]; var cache = ['§4' + ex];
@ -126,9 +143,6 @@ export class MiaoScriptConsole implements Console {
timeLog(label?: string, ...data: any[]): void { timeLog(label?: string, ...data: any[]): void {
throw new Error("Method not implemented."); throw new Error("Method not implemented.");
} }
trace(message?: any, ...optionalParams: any[]): void {
throw new Error("Method not implemented.");
}
markTimeline(label?: string): void { markTimeline(label?: string): void {
throw new Error("Method not implemented."); throw new Error("Method not implemented.");
} }

View File

@ -9,6 +9,15 @@ import { injectable } from '@ms/container'
const Thread = Java.type('java.lang.Thread'); const Thread = Java.type('java.lang.Thread');
export namespace event { export namespace event {
export enum EventPriority {
LOWEST = "LOWEST",
LOW = "LOW",
NORMAL = "NORMAL",
HIGH = "HIGH",
HIGHEST = "HIGHEST",
MONITOR = "MONITOR",
}
@injectable() @injectable()
export abstract class Event { export abstract class Event {
private mapEvent = []; private mapEvent = [];
@ -21,12 +30,13 @@ export namespace event {
} }
/** /**
* org.bukkit.event * abstract event map function
* org.bukkit.event.player.PlayerLoginEvent => playerloginevent * ig: org.bukkit.event.player.PlayerLoginEvent => playerloginevent
* org.spongepowered.api.event.game.GameRegistryEvent.Register => gameregistryevent$register
*/ */
mapEventName() { mapEventName() {
if (this.baseEventDir === "") { if (this.baseEventDir === "") {
throw new Error("事件基础包名为空 无法进行事件映射!"); throw new Error("base event dir is empty, can't map event name !");
} }
let count = 0; let count = 0;
let jar = this.getJarFile(this.baseEventDir); let jar = this.getJarFile(this.baseEventDir);
@ -34,15 +44,14 @@ export namespace event {
while (entries.hasMoreElements()) { while (entries.hasMoreElements()) {
let entry = entries.nextElement(); let entry = entries.nextElement();
let name = entry.name; let name = entry.name;
// 以 org/bukkit/event 开头 并且以 .class 结尾
if (name.startsWith(this.baseEventDir) && name.endsWith(".class")) { if (name.startsWith(this.baseEventDir) && name.endsWith(".class")) {
// replace name to qualifiedName
let qualifiedName = name.replaceAll('/', '.'); let qualifiedName = name.replaceAll('/', '.');
try { try {
let clazz = base.getClass(qualifiedName.substring(0, qualifiedName.length - 6)); let clazz = base.getClass(qualifiedName.substring(0, qualifiedName.length - 6));
// 继承于 org.bukkit.event.Event 访问符为Public
if (this.isValidEvent(clazz)) { if (this.isValidEvent(clazz)) {
let simpleName = this.class2Name(clazz).toLowerCase(); let simpleName = this.class2Name(clazz).toLowerCase();
console.debug(`Mapping Event [${clazz.canonicalName}] => ${simpleName}`); console.trace(`Mapping Event [${clazz.canonicalName}] => ${simpleName}`);
this.mapEvent[simpleName] = clazz; this.mapEvent[simpleName] = clazz;
count++; count++;
} }
@ -63,11 +72,11 @@ export namespace event {
throw new Error(`Can't Mapping Event Because not found Resources ${resource}!`) throw new Error(`Can't Mapping Event Because not found Resources ${resource}!`)
} }
class2Name(clazz) { class2Name(clazz: any) {
return clazz.simpleName; return clazz.simpleName;
} }
name2Class(name, event) { name2Class(name: any, event: string) {
var eventCls = this.mapEvent[event.toLowerCase()] || this.mapEvent[event.toLowerCase() + 'event']; var eventCls = this.mapEvent[event.toLowerCase()] || this.mapEvent[event.toLowerCase() + 'event'];
if (!eventCls) { if (!eventCls) {
try { try {
@ -75,7 +84,7 @@ export namespace event {
this.mapEvent[event] = eventCls; this.mapEvent[event] = eventCls;
} catch (ex) { } catch (ex) {
console.console(`§6插件 §b${name} §6注册事件 §c${event} §6失败 §4事件未找到!`); console.console(`§6插件 §b${name} §6注册事件 §c${event} §6失败 §4事件未找到!`);
console.ex(new Error(`插件 ${name} 注册事件 ${event} 失败 事件未找到!`)); console.ex(new Error(`Plugin ${name} register event error ${event} not found!`));
return; return;
} }
} }
@ -83,7 +92,7 @@ export namespace event {
} }
execute(name, exec, eventCls) { execute(name, exec, eventCls) {
return (...args) => { return (...args: any[]) => {
try { try {
var time = new Date().getTime() var time = new Date().getTime()
exec(args[args.length - 1]); exec(args[args.length - 1]);
@ -100,31 +109,31 @@ export namespace event {
/** /**
* *
* @param plugin * @param plugin {any}
* @param event * @param event {string}
* @param exec {function} * @param exec {function}
* @param priority [LOWEST,LOW,NORMAL,HIGH,HIGHEST,MONITOR] * @param priority {string} [LOWEST,LOW,NORMAL,HIGH,HIGHEST,MONITOR]
* @param ignoreCancel * @param ignoreCancel
*/ */
listen(plugin, event, exec, priority = 'NORMAL', ignoreCancel = false) { listen(plugin: any, event: string, exec: () => void, priority: EventPriority = EventPriority.NORMAL, ignoreCancel = false) {
if (!plugin || !plugin.description || !plugin.description.name) throw new TypeError('插件名称为空 请检查传入参数!'); if (!plugin || !plugin.description || !plugin.description.name) throw new TypeError('插件名称为空 请检查传入参数!');
var name = plugin.description.name; var name = plugin.description.name;
var eventCls = this.name2Class(name, event); var eventCls = this.name2Class(name, event);
if (!eventCls) { return; } if (!eventCls) { return; }
if (typeof priority === 'boolean') { if (typeof priority === 'boolean') {
ignoreCancel = priority; ignoreCancel = priority;
priority = 'NORMAL'; priority = EventPriority.NORMAL;
} }
priority = priority || 'NORMAL'; priority = priority || EventPriority.NORMAL;
ignoreCancel = ignoreCancel || false; ignoreCancel = ignoreCancel || false;
// noinspection JSUnusedGlobalSymbols // 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; var listenerMap = this.listenerMap;
// 添加到缓存 用于关闭插件的时候关闭事件 // add to cache Be used for close plugin to close event
if (!listenerMap[name]) listenerMap[name] = []; if (!listenerMap[name]) listenerMap[name] = [];
var offExec = () => { var offExec = () => {
this.unregister(eventCls, listener); this.unregister(eventCls, listener);
console.debug(`插件 ${name} 注销事件 ${this.class2Name(eventCls)}`); console.debug(`[${name}] unregister event ${this.class2Name(eventCls)}`);
}; };
var off = { var off = {
event: eventCls, event: eventCls,
@ -133,7 +142,7 @@ export namespace event {
}; };
listenerMap[name].push(off); listenerMap[name].push(off);
// noinspection JSUnresolvedVariable // noinspection JSUnresolvedVariable
console.debug(`插件 ${name} 注册事件 ${this.class2Name(eventCls)} => ${exec.name || '匿名方法'}`); console.debug(`[${name}] register event ${this.class2Name(eventCls)} => ${exec.name || '[anonymous]'}`);
return off; return off;
} }

View File

@ -1,7 +1,23 @@
export namespace server { export namespace server {
/**
* Runtime ServerType
*/
export const ServerType = Symbol("ServerType"); export const ServerType = Symbol("ServerType");
/**
* Runtime Console
*/
export const Console = Symbol("Console"); export const Console = Symbol("Console");
/**
* MiaoScript Server
*/
export const Server = Symbol("Server"); export const Server = Symbol("Server");
/**
* Runtime Server Instance
*/
export const ServerInstance = Symbol("ServerInstance");
/**
* MiaoScript Server
*/
export interface Server { export interface Server {
getVersion(): string; getVersion(): string;
getPlayer(name: string): any; getPlayer(name: string): any;

View File

@ -5,7 +5,7 @@ let Bukkit = org.bukkit.Bukkit;
export class BukkitConsole extends MiaoScriptConsole { export class BukkitConsole extends MiaoScriptConsole {
sender(sender, ...args) { sender(sender, ...args) {
if (!(sender instanceof Java.type('org.bukkit.command.CommandSender'))) { if (!(sender instanceof Java.type('org.bukkit.command.CommandSender'))) {
this.error("第一个参数未实现 org.bukkit.command.CommandSender 无法发送消息!") this.error(`First parameter ${sender} not instanceof org.bukkit.command.CommandSender can't send message!`)
return; return;
} }
if (Object.prototype.toString.call(args[0]) === "[object Array]") { if (Object.prototype.toString.call(args[0]) === "[object Array]") {
@ -14,7 +14,7 @@ export class BukkitConsole extends MiaoScriptConsole {
sender.sendMessage(this.prefix + args.join(' ')); sender.sendMessage(this.prefix + args.join(' '));
} }
} }
console(...args): void { console(...args: string[]): void {
this.sender(Bukkit.getConsoleSender(), args.join(' ')); this.sender(Bukkit.getConsoleSender(), args.join(' '));
} }
} }

View File

@ -29,7 +29,7 @@ export class BukkitEvent extends event.Event {
// 不是抽象类 // 不是抽象类
!Modifier.isAbstract(clazz.getModifiers()); !Modifier.isAbstract(clazz.getModifiers());
} }
register(eventCls: any, exec: Function, priority: any, ignoreCancel: boolean) { register(eventCls: any, exec: Function, priority: event.EventPriority, ignoreCancel: boolean) {
let listener = new Listener({}); let listener = new Listener({});
Bukkit.pluginManager.registerEvent( Bukkit.pluginManager.registerEvent(
eventCls, eventCls,

View File

@ -14,7 +14,6 @@ let Bukkit = Java.type("org.bukkit.Bukkit");
container.bind(server.Console).toConstantValue(BukkitConsole); container.bind(server.Console).toConstantValue(BukkitConsole);
container.bind(server.ServerType).toConstantValue(BukkitServerType); container.bind(server.ServerType).toConstantValue(BukkitServerType);
container.bind(plugin.PluginInstance).toConstantValue(Bukkit.pluginManager.getPlugin('MiaoScript'));
container.bind(event.Event).to(BukkitEvent).inSingletonScope(); container.bind(event.Event).to(BukkitEvent).inSingletonScope();
container.bind(server.Server).to(BukkitServer).inSingletonScope(); container.bind(server.Server).to(BukkitServer).inSingletonScope();

View File

@ -1,6 +1,6 @@
import '@ms/nashorn' import '@ms/nashorn'
import { plugin, server, task } from '@ms/api' import { plugin, server, task, MiaoScriptConsole } from '@ms/api'
import { PluginManagerImpl } from '@ms/plugin' import { PluginManagerImpl } from '@ms/plugin'
import { XMLHttpRequest as xhr } from '@ms/ployfill' import { XMLHttpRequest as xhr } from '@ms/ployfill'
import { DefaultContainer as container, injectable, inject, postConstruct } from '@ms/container' import { DefaultContainer as container, injectable, inject, postConstruct } from '@ms/container'
@ -17,14 +17,9 @@ class MiaoScriptCore {
private pluginManager: plugin.PluginManager; private pluginManager: plugin.PluginManager;
enable() { enable() {
try {
this.loadServerConsole(); this.loadServerConsole();
this.loadTaskFunction(); this.loadTaskFunction();
this.loadPlugins(); this.loadPlugins();
} catch (error) {
console.console(`§cMiaoScript start error please contact plugin author!`);
console.ex(error);
}
console.log('MiaoScript engine loading completed... Done (' + (new Date().getTime() - startTime) / 1000 + 's)!'); console.log('MiaoScript engine loading completed... Done (' + (new Date().getTime() - startTime) / 1000 + 's)!');
return () => this.disable(); return () => this.disable();
} }
@ -54,21 +49,38 @@ class MiaoScriptCore {
} }
} }
function init() { function detectServer(){
let type = 'unknow'
try { try {
Java.type("org.bukkit.Bukkit"); Java.type("org.bukkit.Bukkit");
require('@ms/bukkit'); type = 'bukkit';
console.info(`Detect Bukkit Compatible set ServerType to ${type} ...`)
} catch (ex) { } catch (ex) {
} }
try { try {
Java.type("org.spongepowered.api.Sponge"); Java.type("org.spongepowered.api.Sponge");
require('@ms/sponge'); type = 'sponge';
console.info(`Detect Sponge Compatible set ServerType to ${type} ...`)
} catch (ex) { } catch (ex) {
} }
try {
Java.type("net.md_5.bungee.api.ProxyServer");
type = 'bungee';
console.info(`Detect Sponge Compatible set ServerType to ${type} ...`)
} catch (ex) {
}
if (type === 'unknow') { throw Error('Unknow Server Type...') }
return type;
}
function init() {
console.info('Initialization MiaoScript Core Package @ms/core. Please wait...')
container.bind(plugin.PluginInstance).toConstantValue(base.getInstance());
let type = detectServer();
require(`@ms/${type}`);
container.bind(plugin.PluginManager).to(PluginManagerImpl).inSingletonScope(); container.bind(plugin.PluginManager).to(PluginManagerImpl).inSingletonScope();
container.bind(MiaoScriptCore).to(MiaoScriptCore).inSingletonScope(); container.bind(MiaoScriptCore).to(MiaoScriptCore).inSingletonScope();
console.log(`Initialization MiaoScript Sub Package @ms/${type} loading completed... cost (${(new Date().getTime() - startTime) / 1000}s)!`);
} }
init(); init();

View File

@ -111,7 +111,7 @@ export class PluginManagerImpl implements plugin.PluginManager {
* *
* @param path * @param path
*/ */
private checkUpdateFolder(path) { private checkUpdateFolder(path: any) {
var update = fs.file(path, "update") var update = fs.file(path, "update")
if (!update.exists()) { if (!update.exists()) {
update.mkdirs() update.mkdirs()

View File

@ -12,11 +12,12 @@ var Optional = Java.type('java.util.Optional');
class SimpleCommandCallable { class SimpleCommandCallable {
public callable: any; public callable: any;
private name: string;
private executor: Function; private executor: Function;
private tabCompleter: Function; private tabCompleter: Function;
constructor(command: string, description: string = '暂无描述!') { constructor(command: string, description: string = '暂无描述!') {
this.name = command;
this.callable = new CommandCallable({ this.callable = new CommandCallable({
//CommandResult process(CommandSource source, String arguments) throws CommandException; //CommandResult process(CommandSource source, String arguments) throws CommandException;
process: (sender: any, args) => { process: (sender: any, args) => {
@ -47,7 +48,7 @@ class SimpleCommandCallable {
setExecutor = (executor: Function) => this.executor = executor; setExecutor = (executor: Function) => this.executor = executor;
setTabCompleter = (tabCompleter: Function) => this.tabCompleter = tabCompleter; setTabCompleter = (tabCompleter: Function) => this.tabCompleter = tabCompleter;
toString = () => `Sponge SimpleCommandCallable` toString = () => `Sponge SimpleCommandCallable(${this.name})`
} }
@injectable() @injectable()

View File

@ -40,7 +40,7 @@ export class SpongeEvent extends event.Event {
class2Name(clazz: any) { class2Name(clazz: any) {
return clazz.name.substring(clazz.name.lastIndexOf(".") + 1); return clazz.name.substring(clazz.name.lastIndexOf(".") + 1);
} }
register(eventCls: any, exec: Function, priority: any = 'NORMAL', ignoreCancel: boolean = true) { register(eventCls: any, exec: Function, priority: event.EventPriority = event.EventPriority.NORMAL, ignoreCancel: boolean = true) {
var listener = new EventListener({ var listener = new EventListener({
handle: exec handle: exec
}); });

View File

@ -14,7 +14,6 @@ let Sponge = Java.type("org.spongepowered.api.Sponge");
container.bind(server.Console).toConstantValue(SpongeConsole); container.bind(server.Console).toConstantValue(SpongeConsole);
container.bind(server.ServerType).toConstantValue(SpongeServerType); container.bind(server.ServerType).toConstantValue(SpongeServerType);
container.bind(plugin.PluginInstance).toConstantValue(Sponge.getPluginManager().getPlugin('MiaoScript').orElse(null));
container.bind(event.Event).to(SpongeEvent).inSingletonScope(); container.bind(event.Event).to(SpongeEvent).inSingletonScope();
container.bind(server.Server).to(SpongeServer).inSingletonScope(); container.bind(server.Server).to(SpongeServer).inSingletonScope();