@zenflux/core 0.1.8 → 0.1.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/src/bases/controller-base.d.ts +4 -4
- package/dist/src/bases/index.d.ts +5 -2
- package/dist/src/bases/initialize-base.d.ts +8 -0
- package/dist/src/bases/object-base.d.ts +3 -22
- package/dist/src/clients/http.d.ts +3 -3
- package/dist/src/command-bases/command-base.d.ts +3 -3
- package/dist/src/command-bases/command-internal.d.ts +1 -1
- package/dist/src/command-bases/command-public.d.ts +1 -1
- package/dist/src/command-bases/command-restful.d.ts +1 -1
- package/dist/src/command-bases/index.d.ts +4 -4
- package/dist/src/errors/command-already-registered.d.ts +1 -1
- package/dist/src/errors/controller-already-registered.d.ts +1 -1
- package/dist/src/errors/controller-already-set.d.ts +1 -1
- package/dist/src/errors/error-with-metadata.d.ts +4 -0
- package/dist/src/errors/force-method-implementation.d.ts +1 -7
- package/dist/src/errors/index-public.d.ts +1 -1
- package/dist/src/errors/index.d.ts +9 -5
- package/dist/src/exports-index.d.ts +5 -5
- package/dist/src/exports.d.ts +3 -16
- package/dist/src/index.d.ts +2 -2
- package/dist/src/interfaces/index.d.ts +4 -4
- package/dist/src/interfaces/logger.d.ts +3 -2
- package/dist/src/managers/commands.d.ts +4 -4
- package/dist/src/managers/controllers.d.ts +2 -2
- package/dist/src/managers/export.d.ts +5 -5
- package/dist/src/managers/index.d.ts +4 -4
- package/dist/src/managers/internal.d.ts +1 -1
- package/dist/src/managers/restful.d.ts +5 -5
- package/dist/src/modules/debugger.d.ts +17 -0
- package/dist/src/modules/event-bus/event-bus.d.ts +28 -0
- package/dist/src/modules/logger/config.d.ts +6 -0
- package/dist/src/modules/logger/implementation.d.ts +46 -0
- package/dist/src/modules/logger/index.d.ts +2 -0
- package/dist/src/modules/logger/logger-browser-infra.d.ts +60 -0
- package/dist/src/modules/logger/utils/index.d.ts +2 -0
- package/dist/src/modules/logger/utils/object.d.ts +6 -0
- package/dist/src/modules/logger/utils/rgb.d.ts +6 -0
- package/dist/src/modules/mcp-server/mcp-server.d.ts +10 -0
- package/dist/src/modules/mcp-server/mcp-service.d.ts +13 -0
- package/dist/src/modules/service/service-base.d.ts +15 -0
- package/dist/src/modules/service/service-locator.d.ts +34 -0
- package/dist/src/modules/service/service-with-dependencies-base.d.ts +17 -0
- package/dist/zenflux-core.cjs +58 -14
- package/dist/zenflux-core.d.ts +102 -42
- package/dist/zenflux-core.mjs +58 -14
- package/package.json +3 -3
- package/src/errors/index.ts +1 -0
- package/src/exports.ts +3 -15
- package/src/modules/debugger.ts +0 -24
- package/src/modules/logger/implementation.ts +287 -0
- package/src/modules/logger/index.ts +2 -82
- package/src/modules/logger/logger-browser-infra.ts +306 -0
- package/src/modules/logger/types/picocolors.d.ts +15 -0
- package/src/modules/logger/utils/index.ts +3 -0
- package/src/modules/logger/utils/object.ts +19 -0
- package/src/modules/logger/utils/rgb.ts +34 -0
package/dist/zenflux-core.mjs
CHANGED
|
@@ -1,19 +1,27 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Bundled with love using the help of @zenflux/cli toolkit v0.1.
|
|
3
|
-
* Bundle name: @zenflux/core fileName: 'zenflux-core', built at Wed Nov 19 2025
|
|
2
|
+
* Bundled with love using the help of @zenflux/cli toolkit v0.1.30
|
|
3
|
+
* Bundle name: @zenflux/core fileName: 'zenflux-core', built at Wed Nov 19 2025 20:35:22 GMT+0200 (Israel Standard Time)
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
|
-
|
|
6
|
+
import util from 'node:util';
|
|
7
|
+
import process$1 from 'process';
|
|
8
|
+
import EventEmitter from 'events';
|
|
7
9
|
|
|
8
|
-
class
|
|
10
|
+
class CommandAlreadyRegistered extends Error{constructor(command){super(`Command: '${command.getName()}' is already registered`);}}
|
|
9
11
|
|
|
10
12
|
class CommandNotFound extends Error{constructor(command){super(`Command: '${command}' is not found`);}}
|
|
11
13
|
|
|
12
|
-
class
|
|
14
|
+
class ControllerAlreadyRegistered extends Error{constructor(controller){super(`Controller: '${controller.getName()}' is already registered`);}}
|
|
13
15
|
|
|
14
|
-
class
|
|
16
|
+
class ControllerAlreadySet extends Error{constructor(controller){super(`Controller: '${controller.getName()}' is already set`);}}
|
|
15
17
|
|
|
16
|
-
class
|
|
18
|
+
class ForceMethodBase extends Error{constructor(className,methodName){super(`ForceMethod implementation: at '${className}' method: '${methodName}'`);}}class ForceMethodImplementation extends Error{constructor(context,methodName){super(`ForceMethod implementation: at '${"string"===typeof context?context:context.getName()}' method: '${methodName}'`);}}
|
|
19
|
+
|
|
20
|
+
class ErrorWithMetadata extends Error{metadata;constructor(message,metadata=null){super(message);this.metadata=metadata;this.message=null!==metadata?`${message} - Metadata: ${util.inspect(metadata)}`:message;Object.setPrototypeOf(this,new.target.prototype);}}
|
|
21
|
+
|
|
22
|
+
class ObjectBase{id;name="__UNDEFINED_NAME__";constructor(){this.name=this.getName();const timestamp=performance.now()*1e6;const random1=BigInt(Math.floor(Math.random()*1e6));const random2=BigInt(Math.floor(Math.random()*1e6));this.id=`${timestamp}${random1}${random2}`;}static getName(){throw new ForceMethodBase(this.name,"getName")}static getSourcePath(){throw new ForceMethodBase(this.name,"getSourcePath")}getName(){return this.constructor.getName()}getUniqueId(){return this.id}getInitialName(){return this.name}getHierarchyNames(){const classNames=[];let obj=Object.getPrototypeOf(this);let className;while((className=obj.getName())!=="Object"){classNames.push(className);obj=Object.getPrototypeOf(obj);if(obj.constructor===ObjectBase){break}}return classNames}}
|
|
23
|
+
|
|
24
|
+
class Commands extends ObjectBase{static trace=[];current={};currentArgs={};trace=[];commands={};onBeforeHooks={};onBeforeUIHooks={};onAfterHooks={};onAfterOnceHooks={};onAfterUIHooks={};onAfterAffectHooks={};logger;static getName(){return "ZenFlux/Core/Managers/Commands"}static async runCallbacks(callbacks,args={},options={}){const callbacksLength=callbacks?.length||0;for(let i=0;i<callbacksLength;++i){const callback=options.pop===true?callbacks.pop():callbacks[i];if(!callback){throw new Error("Callback is not defined.")}await callback(args,options);}}static hookCommand(stack,hookCommand,context){if(!stack[hookCommand]){stack[hookCommand]=[];}stack[hookCommand].push(context);}constructor(){super();const type=this.constructor;this.logger=new zCore.classes.Logger(type);this.logger.startsEmpty(this.constructor);}async run(command,args={},options={}){if(typeof command==="string"){command=this.getCommandInstance(command,args,options);}this.attachCurrent(command,args);const result=await this.runInstance(command,args,options);this.detachCurrent(command);return result}register(commands,controller){const result={};Object.values(commands).forEach(command=>{const commandName=command.getName();if(this.commands[commandName]){throw new CommandAlreadyRegistered(command)}command.setController(controller);this.commands[commandName]=command;result[commandName]=command;});return result}getAll(){return this.commands}getByName(name){return this.commands[name]}getLogger(){return this.logger}getCommandInstance(name,args={},options={}){const CommandClass=this.commands[name];if(!CommandClass){throw new CommandNotFound(name)}return new CommandClass(args,options)}onBefore(hookCommand,callback){Commands.hookCommand(this.onBeforeHooks,hookCommand,callback);}onBeforeUI(hookCommand,callback){Commands.hookCommand(this.onBeforeUIHooks,hookCommand,callback);}onAfter(hookCommand,callback){Commands.hookCommand(this.onAfterHooks,hookCommand,callback);}onAfterUI(command,callback){Commands.hookCommand(this.onAfterUIHooks,command,callback);}onAfterOnce(command,callback){Commands.hookCommand(this.onAfterOnceHooks,command,callback);}onAfterAffect(hookCommand,affectCommand){Commands.hookCommand(this.onAfterAffectHooks,hookCommand,affectCommand);}onBeforeRun(command,args={},options={}){if(this.onBeforeHooks[command.getName()]){const callbacks=this.onBeforeHooks[command.getName()];callbacks.forEach(callback=>callback(args,options));}if(this.onBeforeUIHooks[command.getName()]){const callbacks=this.onBeforeUIHooks[command.getName()];callbacks.forEach(callback=>callback(args,options));}}async runInstance(command,args={},options={}){let result=null;this.logger.startsWith(this.runInstance,{command:command.getName(),options,args});this.onBeforeRun(command,args,options);result=await command.run();await this.onAfterRun(command,args,options,result);return result}async onAfterRun(command,args,options,result){options=Object.assign({},options);if(this.onAfterAffectHooks[command.getName()]){this.onAfterAffectHooks[command.getName()].forEach(command=>{args.result=result;result=this.run(command.toString(),args,options);});result=await result;}if(this.onAfterHooks){args.result=result;await Commands.runCallbacks(Object.assign([],this.onAfterHooks[command.getName()]),args,options);}if(this.onAfterOnceHooks){await Commands.runCallbacks(this.onAfterOnceHooks[command.getName()],args,{...options,pop:true});}if(this.onAfterUIHooks){Commands.runCallbacks(Object.assign([],this.onAfterUIHooks[command.getName()]),args,options);}return result}attachCurrent(command,args={}){this.current[command.getName()]=command;this.currentArgs[command.getName()]=args;this.trace.push(command.getName());Commands.trace.push(command.getName());}detachCurrent(command){delete this.current[command.getName()];delete this.currentArgs[command.getName()];Commands.trace.pop();this.trace.pop();}}
|
|
17
25
|
|
|
18
26
|
class Controllers extends ObjectBase{controllers={};constructor(){super();}static getName(){return "ZenFlux/Core/Managers/Controllers"}get(name){return this.controllers[name]}getAll(){return this.controllers}register(controller){if(this.controllers[controller.getName()]){throw new ControllerAlreadyRegistered(controller)}this.controllers[controller.getName()]=controller;return controller}}
|
|
19
27
|
|
|
@@ -52,8 +60,6 @@ ControllerBase: ControllerBase,
|
|
|
52
60
|
ObjectBase: ObjectBase
|
|
53
61
|
});
|
|
54
62
|
|
|
55
|
-
class ControllerAlreadySet extends Error{constructor(controller){super(`Controller: '${controller.getName()}' is already set`);}}
|
|
56
|
-
|
|
57
63
|
class CommandBase extends ObjectBase{static controller;args={};options={};logger;static getName(){return "ZenFlux/Core/CommandBases/CommandBase"}static setController(controller){if(this.controller){throw new ControllerAlreadySet(this.controller)}this.controller=controller;}static getController(){return this.controller}constructor(args={},options={}){super();const type=this.constructor;this.logger=new zCore.classes.Logger(type,{repeatedly:true});this.logger.startsWith(this.constructor,{args,options});this.initialize(args,options);}initialize(args,options){this.args=args;this.options=options;}apply(args=this.args,options=this.options){throw new ForceMethodImplementation(this,"apply")}async run(){return this.runInternal()}async runInternal(){this.onBeforeApply&&this.onBeforeApply();const result=await this.apply(this.args,this.options);this.onAfterApply&&this.onAfterApply();return result}}
|
|
58
64
|
|
|
59
65
|
class CommandPublic extends CommandBase{static getName(){return "ZenFlux/Core/CommandBases/CommandPublic"}}
|
|
@@ -75,9 +81,37 @@ __proto__: null,
|
|
|
75
81
|
ForceMethodImplementation: ForceMethodImplementation
|
|
76
82
|
});
|
|
77
83
|
|
|
84
|
+
const DEFAULT_LOG_LEVEL="5";function getLoggerDefaultLevel(){return DEFAULT_LOG_LEVEL}function getLoggerLogLevel(){return parseInt(process$1.env.LOGGER_LOG_LEVEL||DEFAULT_LOG_LEVEL,10)}function getLoggerLogLevelString(){switch(getLoggerLogLevel()){case 0:return "NONE";case 1:return "ERROR";case 2:return "WARN";case 3:return "ADMIN";case 4:return "INFO";case 5:return "LOG";case 6:return "DEBUG";default:return "UNKNOWN"}}function isLoggerDebugEnabled(){return getLoggerLogLevel()>=6}function isLoggerDisabled(){return process$1.env.LOGGER_DISABLED==="true"}function isLoggerPreviousSourceDisabled(){return process$1.env.LOGGER_LOG_PREVIOUS_CALLER_SOURCE_DISABLED==="true"}
|
|
85
|
+
|
|
86
|
+
var commonjsGlobal=typeof globalThis!=="undefined"?globalThis:typeof window!=="undefined"?window:typeof global!=="undefined"?global:typeof self!=="undefined"?self:{};function getDefaultExportFromCjs(x){return x&&x.__esModule&&Object.prototype.hasOwnProperty.call(x,"default")?x["default"]:x}function getDefaultExportFromNamespaceIfPresent(n){return n&&Object.prototype.hasOwnProperty.call(n,"default")?n["default"]:n}function getDefaultExportFromNamespaceIfNotNamed(n){return n&&Object.prototype.hasOwnProperty.call(n,"default")&&Object.keys(n).length===1?n["default"]:n}function getAugmentedNamespace(n){if(Object.prototype.hasOwnProperty.call(n,"__esModule"))return n;var f=n.default;if(typeof f=="function"){var a=function a(){var isInstance=false;try{isInstance=this instanceof a;}catch{}if(isInstance){return Reflect.construct(f,arguments,this.constructor)}return f.apply(this,arguments)};a.prototype=f.prototype;}else a={};Object.defineProperty(a,"__esModule",{value:true});Object.keys(n).forEach(function(k){var d=Object.getOwnPropertyDescriptor(n,k);Object.defineProperty(a,k,d.get?d:{enumerable:true,get:function(){return n[k]}});});return a}
|
|
87
|
+
|
|
88
|
+
var picocolors$1={exports:{}};
|
|
89
|
+
|
|
90
|
+
var picocolors=picocolors$1.exports;var hasRequiredPicocolors;function requirePicocolors(){if(hasRequiredPicocolors)return picocolors$1.exports;hasRequiredPicocolors=1;let p=process||{},argv=p.argv||[],env=p.env||{};let isColorSupported=!(!!env.NO_COLOR||argv.includes("--no-color"))&&(!!env.FORCE_COLOR||argv.includes("--color")||p.platform==="win32"||(p.stdout||{}).isTTY&&env.TERM!=="dumb"||!!env.CI);let formatter=(open,close,replace=open)=>input=>{let string=""+input,index=string.indexOf(close,open.length);return ~index?open+replaceClose(string,close,replace,index)+close:open+string+close};let replaceClose=(string,close,replace,index)=>{let result="",cursor=0;do{result+=string.substring(cursor,index)+replace;cursor=index+close.length;index=string.indexOf(close,cursor);}while(~index)return result+string.substring(cursor)};let createColors=(enabled=isColorSupported)=>{let f=enabled?formatter:()=>String;return {isColorSupported:enabled,reset:f("\x1b[0m","\x1b[0m"),bold:f("\x1b[1m","\x1b[22m","\x1b[22m\x1b[1m"),dim:f("\x1b[2m","\x1b[22m","\x1b[22m\x1b[2m"),italic:f("\x1b[3m","\x1b[23m"),underline:f("\x1b[4m","\x1b[24m"),inverse:f("\x1b[7m","\x1b[27m"),hidden:f("\x1b[8m","\x1b[28m"),strikethrough:f("\x1b[9m","\x1b[29m"),black:f("\x1b[30m","\x1b[39m"),red:f("\x1b[31m","\x1b[39m"),green:f("\x1b[32m","\x1b[39m"),yellow:f("\x1b[33m","\x1b[39m"),blue:f("\x1b[34m","\x1b[39m"),magenta:f("\x1b[35m","\x1b[39m"),cyan:f("\x1b[36m","\x1b[39m"),white:f("\x1b[37m","\x1b[39m"),gray:f("\x1b[90m","\x1b[39m"),bgBlack:f("\x1b[40m","\x1b[49m"),bgRed:f("\x1b[41m","\x1b[49m"),bgGreen:f("\x1b[42m","\x1b[49m"),bgYellow:f("\x1b[43m","\x1b[49m"),bgBlue:f("\x1b[44m","\x1b[49m"),bgMagenta:f("\x1b[45m","\x1b[49m"),bgCyan:f("\x1b[46m","\x1b[49m"),bgWhite:f("\x1b[47m","\x1b[49m"),blackBright:f("\x1b[90m","\x1b[39m"),redBright:f("\x1b[91m","\x1b[39m"),greenBright:f("\x1b[92m","\x1b[39m"),yellowBright:f("\x1b[93m","\x1b[39m"),blueBright:f("\x1b[94m","\x1b[39m"),magentaBright:f("\x1b[95m","\x1b[39m"),cyanBright:f("\x1b[96m","\x1b[39m"),whiteBright:f("\x1b[97m","\x1b[39m"),bgBlackBright:f("\x1b[100m","\x1b[49m"),bgRedBright:f("\x1b[101m","\x1b[49m"),bgGreenBright:f("\x1b[102m","\x1b[49m"),bgYellowBright:f("\x1b[103m","\x1b[49m"),bgBlueBright:f("\x1b[104m","\x1b[49m"),bgMagentaBright:f("\x1b[105m","\x1b[49m"),bgCyanBright:f("\x1b[106m","\x1b[49m"),bgWhiteBright:f("\x1b[107m","\x1b[49m")}};picocolors$1.exports=createColors();picocolors$1.exports.createColors=createColors;return picocolors$1.exports}
|
|
91
|
+
|
|
92
|
+
var picocolorsExports=requirePicocolors();var pc = getDefaultExportFromCjs(picocolorsExports);
|
|
93
|
+
|
|
94
|
+
class EventBus extends ObjectBase{static instance=null;objects=new Map;eventEmitter=new EventEmitter;lastEmittedEvents=new Map;static getName(){return "ZenFlux/Core/Modules/EventBus"}static getInstance(){if(!EventBus.instance){EventBus.instance=new EventBus;}return EventBus.instance}static get $(){return EventBus.getInstance()}getObjectNames(){return Array.from(this.objects.keys())}getEventNames(){this.eventEmitter.eventNames();}getEventName(objectName,methodName){return `${objectName}::${methodName}`}on(objectName,methodName,callback){if(!this.objects.has(objectName)){throw new Error(`Object ${objectName} is not registered`)}this.eventEmitter.on(this.getEventName(objectName,methodName),callback);}onCalledBeforeDoInvoke(objectName,methodName,callback){this.on(objectName,methodName,callback);if(this.objects.has(objectName)){const objectEntry=this.objects.get(objectName);if(objectEntry){const method=objectEntry.methods.find(method=>method.name===methodName);if(method&&this.lastEmittedEvents.has(this.getEventName(objectName,methodName))){callback(...this.lastEmittedEvents.get(this.getEventName(objectName,methodName)));}}}}off(objectName,methodName,callback){this.eventEmitter.off(this.getEventName(objectName,methodName),callback);}register(object,methods){if(this.objects.has(object.getName())){throw new Error(`Error in: '${this.getName()}', object: '${object.getName()}' is already registered`)}this.objects.set(object.getName(),{object,methods});this.hook(object,methods);}registerMultiInstances(object,methods){const objectName=object.getName();if(this.objects.has(objectName)){const existingEntry=this.objects.get(objectName);if(Array.isArray(existingEntry.object)){existingEntry.object.push(object);}else {existingEntry.object=[existingEntry.object,object];}}else {this.objects.set(objectName,{object,methods});}this.hook(object,methods);}unregister(objectName){const entry=this.objects.get(objectName);if(!entry){return false}if(Array.isArray(entry.object)){entry.object.forEach(obj=>{this.unhookObject(obj,entry.methods);});}else {this.unhookObject(entry.object,entry.methods);}this.objects.delete(objectName);}unhookObject(object,methods){methods.forEach(method=>{this.ensureFunction(object,method);this.eventEmitter.removeAllListeners(this.getEventName(object.getName(),method.name));object[method.name]=method;});}unhook(entry){if(Array.isArray(entry.object)){entry.object.forEach(obj=>{this.unhookObject(obj,entry.methods);});}else {this.unhookObject(entry.object,entry.methods);}}emit(object,method,...args){const eventName=this.getEventName(object.getName(),method.name);this.lastEmittedEvents.set(eventName,args);return this.eventEmitter.emit(eventName,...args)}hook(object,methods){methods.forEach(method=>{this.ensureFunction(object,method);const originalMethod=method;const eventBusHook=async(...args)=>{const result=await originalMethod.apply(object,args);this.emit(object,method,...args);return result};object[method.name]=new Proxy(eventBusHook,{get(target,prop){if(prop==="name"){return method.name}return target[prop]}});});}ensureFunction(object,method){if("function"!==typeof method){throw new Error(`Method ${method} is not a function on ${object.getName()}`)}}}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Reduce circular references.
|
|
98
|
+
*
|
|
99
|
+
* @copyright https://stackoverflow.com/a/53731154
|
|
100
|
+
*/const reduceCircularReferences=()=>{const seen=new WeakSet;return (key,value)=>{if(typeof value==="object"&&value!==null){if(seen.has(value)){return}seen.add(value);}return value}};
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Function hexColorDelta() : Return color difference in ratio decimal point.
|
|
104
|
+
*
|
|
105
|
+
* @copyright http://jsfiddle.net/96sME/
|
|
106
|
+
*/const getHexColorDelta=function(hex1,hex2){hex1=hex1.replace("#","");hex2=hex2.replace("#","");const r1=parseInt(hex1.substring(0,2),16);const g1=parseInt(hex1.substring(2,4),16);const b1=parseInt(hex1.substring(4,6),16);const r2=parseInt(hex2.substring(0,2),16);const g2=parseInt(hex2.substring(2,4),16);const b2=parseInt(hex2.substring(4,6),16);let r=255-Math.abs(r1-r2);let g=255-Math.abs(g1-g2);let b=255-Math.abs(b1-b2);r/=255;g/=255;b/=255;return (r+g+b)/3};
|
|
107
|
+
|
|
108
|
+
const MAX_MAPPING_RECURSIVE_DEPTH=4,UNKNOWN_CALLER_NAME="anonymous function";Error.stackTraceLimit=50;class LoggerBrowserInfra extends ObjectBase{static mappers=[];static mapperDepth=0;static colorsOwners={};static colorsUsed=[];defaultStyle;owner;args;color;outputHandler=console.log;static getName(){return "ZenFlux/Logging/Modules/LoggerBrowserInfra"}static reset(){LoggerBrowserInfra.mappers=[];LoggerBrowserInfra.mapperDepth=0;LoggerBrowserInfra.colorsUsed=[];LoggerBrowserInfra.colorsOwners={};}static createObjectMapper(callback){LoggerBrowserInfra.mappers.push(callback);}static useObjectMapper(obj,shouldHandleChildren=true){if(!obj||Array.isArray(obj)||"object"!==typeof obj){return obj}LoggerBrowserInfra.mapperDepth++;let result={...obj};LoggerBrowserInfra.mappers.forEach(mapper=>{result=mapper(obj)||result;});if(LoggerBrowserInfra.mapperDepth>=MAX_MAPPING_RECURSIVE_DEPTH){LoggerBrowserInfra.mapperDepth--;return result}if(shouldHandleChildren&&result){Object.entries(result).forEach(([key,value])=>{result[key]=this.useObjectMapper(value,true);});}LoggerBrowserInfra.mapperDepth--;return result}constructor(owner,args={}){super();this.args={repeatedly:false,...args};this.owner=owner;this.initialize();}getOwnerName(){if(typeof this.owner==="string"){return this.owner}if(this.owner instanceof ObjectBase){return this.owner.getName()}if(this.owner&&typeof this.owner.getName==="function"){return this.owner.getName()}return "UnknownOwner"}initialize(){const ownerName=this.getOwnerName();if(this.args.repeatedly&&LoggerBrowserInfra.colorsOwners[ownerName]){this.color=LoggerBrowserInfra.colorsOwners[ownerName];}else {this.color=this.getRandomColor();LoggerBrowserInfra.colorsUsed.push(this.color);}LoggerBrowserInfra.colorsOwners[ownerName]=this.color;this.defaultStyle=["color: grey;font-size:7px","display: block",`color: ${this.color}`,"color: grey","font-weight: bold","color: #607D8B","font-size: 16px;color: red;font-weight:800"];}output(...args){this.outputHandler.apply(this,args);}setOutputHandler(outputHandler){this.outputHandler=outputHandler;}printFunctionNotify(prefix,caller,output){const callerName=this.getCallerName(caller);this.output.apply(this,[`%c(${prefix})-> %c%c${this.getOwnerName()}%c::%c${callerName}%c() ${output}%c`].concat(this.defaultStyle));}printObjectEfficient(prefix,caller,params){params=Object.assign({},params);if(typeof params==="string"){this.printInLineString(prefix,caller,params);return}if(Object.keys(params).length===1){const key=Object.keys(params)[0];let value=Object.values(params)[0];if("object"===typeof value){this.printInNextLineObject(prefix,caller,key,value||{});}else if("function"===typeof value){this.printInLineFunction(prefix,caller,key,value);}else {this.printInLineElement(prefix,caller,key,value);}return}this.printMultiLineObject(prefix,caller,params);}printInLineElement(prefix,caller,key,value,notice=""){const callerName=this.getCallerName(caller),ownerName=this.getOwnerName(),format=notice.length?`%c(${prefix})-> %c%c${ownerName}%c::%c${callerName}%c() ->> [${notice}] ->> ${key}: '${value}'%c`:`%c(${prefix})-> %c%c${ownerName}%c::%c${callerName}%c() ->> ${key}: '${value}'%c`;this.output.apply(this,[format].concat(this.defaultStyle));}printInLineFunction(prefix,caller,key,fn){fn=this.getFunctionView(fn);this.printInLineElement(prefix,caller,key,fn);}printInLineString(prefix,caller,string){this.printInLineElement(prefix,caller,"(string)",string);}printInNextLineObject(prefix,caller,key,obj){const mapped=LoggerBrowserInfra.useObjectMapper(obj),callerName=this.getCallerName(caller);this.output.apply(this,[`%c(${prefix})-> %c%c${this.getOwnerName()}%c::%c${callerName}%c() ->> ${key} %c↓`].concat(this.defaultStyle));this.output(mapped);}printMultiLineObject(prefix,caller,obj){const callerName=this.getCallerName(caller);this.output.apply(this,[`%c(${prefix})-> %c%c${this.getOwnerName()}%c::%c${callerName}%c(${Object.keys(obj).join(", ")}) %c↓`].concat(this.defaultStyle));for(let key in obj){let value=obj[key];if(typeof value==="object"){const mapped=LoggerBrowserInfra.useObjectMapper(value);value=JSON.stringify(mapped,reduceCircularReferences());}else if(typeof obj[key]=="function"){value=this.getFunctionView(value);}this.output.apply(this,["%c"+key+": `"+value+"`","color: #a3a3a3"]);}}getRandomColor(){const hex="0123456789ABCDEF";let color="#";for(let i=0;i<6;i++){color+=hex[Math.floor(Math.random()*16)];}let similar=LoggerBrowserInfra.colorsUsed.some(value=>{return getHexColorDelta(color,value)>=.8});if(similar){return this.getRandomColor()}return color}getCallerName(caller){if("function"===typeof caller){return caller.prototype instanceof ObjectBase?"constructor":caller.name}throw new Error("Invalid caller")}getFunctionView(fn){let fReturn=UNKNOWN_CALLER_NAME;if(typeof fn!=="string"&&fn.name.length!==0){fReturn=fn.name.split(" ")[1]+"()";}return fReturn}}
|
|
109
|
+
|
|
110
|
+
const DEFAULT_LOG_PREFIX=pc.white("⚪ - [LOG]"),DEFAULT_INFO_PREFIX=pc.blue("🔵 - [INFO]"),DEFAULT_DEBUG_PREFIX=pc.gray("🟤 - [DEBUG]"),DEFAULT_WARN_PREFIX=pc.yellow("🟡 - [WARN]"),DEFAULT_ERROR_PREFIX=pc.red("🔴 - [ERROR]"),DEFAULT_ADMIN_PREFIX=pc.bold("🟣 - [ADMIN]");const registeredNames={};class Logger extends LoggerBrowserInfra{static lastLogTime=Date.now();ownerName;messagePrefixes=[];config={};static getName(){return "ZenFlux/Core/Modules/Logger"}static getLogLevelString(){return getLoggerLogLevelString()}static getLogLevel(){return getLoggerLogLevel()}static isDebugEnabled(){return isLoggerDebugEnabled()}constructor(owner,options){const{repeatedly=false,skipEventBusHook}=options||{};super(owner,{repeatedly});this.config={skipEventBusHook};this.ownerName=Logger.resolveOwnerName(owner);if(registeredNames[this.ownerName]){throw new Error(`Logger for '${this.ownerName}' already exists`)}registeredNames[this.ownerName]=true;if(isLoggerDisabled()){this.disableLoggers();return}if(isLoggerPreviousSourceDisabled()){this.getPreviousSource=()=>"";}switch(getLoggerLogLevel()){case 0:this.error=()=>{};case 1:this.warn=()=>{};case 2:this.admin=()=>{};case 3:this.info=()=>{};case 4:this.log=()=>{};case 5:this.debug=()=>{};}if(!this.config.skipEventBusHook){EventBus.$.registerMultiInstances(this,[this.outputEvent]);}}addMessagePrefix(prefix){this.messagePrefixes.push(prefix);}log(caller,message,...params){this.writeLog(DEFAULT_LOG_PREFIX,caller,message,...params);}info(caller,message,...params){this.writeLog(DEFAULT_INFO_PREFIX,caller,message,...params);}debug(caller,message,...params){this.writeLog(DEFAULT_DEBUG_PREFIX,caller,message,...params);}warn(caller,message,...params){this.writeLog(DEFAULT_WARN_PREFIX,caller,message,...params);}error(caller,message,...params){this.writeLog(DEFAULT_ERROR_PREFIX,caller,message,...params);}admin(caller,message,...params){this.writeLog(DEFAULT_ADMIN_PREFIX,caller,message,...params);}startsEmpty(caller){this.printFunctionNotify("▶",caller,"");}startsWith(caller,params){this.printObjectEfficient("▶",caller,params);}dump(caller,params={},notice=""){for(const key in params){if(typeof params[key]==="object"){params[key]=JSON.stringify(LoggerBrowserInfra.useObjectMapper(params[key]),reduceCircularReferences());}this.printInLineElement("dp",caller,key,params[key],notice);}}drop(caller,according,data){for(const key in according){this.printInLineElement("dr",caller,key,according[key],"corresponding");}this.output(data);}throw(caller,output,name="null",params={}){this.printFunctionNotify("tw",caller,output);if(params){this.printInNextLineObject("tw",caller,name,params);}throw new Error().stack}beep(){console.log("\x07");}clone(){return Object.assign(Object.create(Object.getPrototypeOf(this)),this)}outputEvent(_prefix,_timeDiff,_source,_messagePrefix,_message,_params){}static resolveOwnerName(owner){if(typeof owner==="string"){return owner}if(owner instanceof ObjectBase){return owner.getName()}if(owner&&typeof owner.getName==="function"){return owner.getName()}return "UnknownOwner"}disableLoggers(){this.error=()=>{};this.warn=()=>{};this.admin=()=>{};this.info=()=>{};this.log=()=>{};this.debug=()=>{};}getStackTrace(){const stackTrace=(new Error().stack||"").split("\n");const stackLines=stackTrace.slice(1);const stackRegex=/ at (.+?) \((.+?)\)/;const result=[];for(const line of stackLines){const match=line.match(stackRegex);if(match){const[,context,file]=match;const parsedLine={context,file};if(line.startsWith("new")){parsedLine.isNew=true;parsedLine.object=context.split(" ")[1];}else if(context!=="Object.<anonymous>"){parsedLine.object=context;}result.push(parsedLine);}}return result}getPreviousSource(){const stack=this.getStackTrace().filter(line=>line.file.includes("/src/")).filter(line=>!line.file.includes("logger.ts")).filter(line=>!line.file.includes("debugger.ts")).filter(line=>!line.file.includes("/node_modules/"));let previousSource="";const previousCaller=stack[1]?.object?.split(".");if(previousCaller?.length>1){const previousCallerName=previousCaller[0],previousCallerMethod=previousCaller[1];previousSource=`${previousCallerName}::${previousCallerMethod}]`+"[";}return previousSource}writeLog(prefix,caller,message,...params){const source=this.getPreviousSource()+pc.white(`${this.ownerName}::${this.getCallerName(caller)}`);let messagePrefix="";if(this.messagePrefixes.length){messagePrefix=`[${this.messagePrefixes.join("][")}]`;}const timeDiff=(Date.now()-Logger.lastLogTime).toString().padStart(4,"0");this.outputEvent(prefix,timeDiff,source,messagePrefix,message,params);const output=`${prefix}[+${timeDiff}ms][${source}]${messagePrefix}: ${message}`;console.log(output,...params);Logger.lastLogTime=Date.now();}}
|
|
111
|
+
|
|
78
112
|
var _package = {
|
|
79
113
|
"name": "@zenflux/core",
|
|
80
|
-
"version": "0.1.
|
|
114
|
+
"version": "0.1.8",
|
|
81
115
|
"types": "dist/zenflux-core.d.ts",
|
|
82
116
|
"type": "module",
|
|
83
117
|
"files": [
|
|
@@ -98,32 +132,42 @@ var _package = {
|
|
|
98
132
|
"types": "./dist/zenflux-core.d.ts"
|
|
99
133
|
},
|
|
100
134
|
"./dist/src/*": "./src/*",
|
|
135
|
+
"./src/*": "./src/*",
|
|
101
136
|
"./src/bases": "./src/bases/index.ts",
|
|
102
137
|
"./src/clients": "./src/clients/index.ts",
|
|
103
138
|
"./src/command-bases": "./src/command-bases/index.ts",
|
|
104
139
|
"./src/errors": "./src/errors/index.ts",
|
|
105
140
|
"./src/interfaces": "./src/interfaces/index.ts",
|
|
106
141
|
"./src/managers": "./src/managers/index.ts",
|
|
142
|
+
"./src/modules/logger": "./src/modules/logger/index.ts",
|
|
107
143
|
"./package.json": "./package.json"
|
|
108
144
|
},
|
|
109
145
|
"devDependencies": {
|
|
146
|
+
"@jest/globals": "^29.7.0",
|
|
110
147
|
"@zenflux/cli": "workspace:*"
|
|
111
148
|
},
|
|
112
149
|
"publishConfig": {
|
|
113
150
|
"access": "public"
|
|
151
|
+
},
|
|
152
|
+
"dependencies": {
|
|
153
|
+
"fastmcp": "^3.23.1",
|
|
154
|
+
"zod": "^4.1.12",
|
|
155
|
+
"picocolors": "^1.0.0",
|
|
156
|
+
"@zenflux/utils": "workspace:*"
|
|
114
157
|
}
|
|
115
158
|
};
|
|
116
159
|
const name = "@zenflux/core";
|
|
117
|
-
const version = "0.1.
|
|
160
|
+
const version = "0.1.8";
|
|
118
161
|
const types = "dist/zenflux-core.d.ts";
|
|
119
162
|
const type = "module";
|
|
120
163
|
const files = ["dist","src","types"];
|
|
121
164
|
const scripts = {"@z-core--test":"jest","@z-core--build":"@z-cli @build","@z-core--dev":"@z-cli @watch --dev"};
|
|
122
|
-
const exports = {".":{"import":"./dist/zenflux-core.mjs","default":"./dist/zenflux-core.cjs","require":"./dist/zenflux-core.mjs.js","types":"./dist/zenflux-core.d.ts"},"./dist/src/*":"./src/*","./src/bases":"./src/bases/index.ts","./src/clients":"./src/clients/index.ts","./src/command-bases":"./src/command-bases/index.ts","./src/errors":"./src/errors/index.ts","./src/interfaces":"./src/interfaces/index.ts","./src/managers":"./src/managers/index.ts","./package.json":"./package.json"};
|
|
123
|
-
const devDependencies = {"@zenflux/cli":"workspace:*"};
|
|
165
|
+
const exports$1 = {".":{"import":"./dist/zenflux-core.mjs","default":"./dist/zenflux-core.cjs","require":"./dist/zenflux-core.mjs.js","types":"./dist/zenflux-core.d.ts"},"./dist/src/*":"./src/*","./src/*":"./src/*","./src/bases":"./src/bases/index.ts","./src/clients":"./src/clients/index.ts","./src/command-bases":"./src/command-bases/index.ts","./src/errors":"./src/errors/index.ts","./src/interfaces":"./src/interfaces/index.ts","./src/managers":"./src/managers/index.ts","./src/modules/logger":"./src/modules/logger/index.ts","./package.json":"./package.json"};
|
|
166
|
+
const devDependencies = {"@jest/globals":"^29.7.0","@zenflux/cli":"workspace:*"};
|
|
124
167
|
const publishConfig = {"access":"public"};
|
|
168
|
+
const dependencies = {"fastmcp":"^3.23.1","zod":"^4.1.12","picocolors":"^1.0.0","@zenflux/utils":"workspace:*"};
|
|
125
169
|
|
|
126
|
-
const classes={Logger
|
|
170
|
+
const classes={Logger};let exportedConfig={version:version};function initialize(config){if("undefined"!==typeof __ZEN_CORE__IS_INITIALIZED__&&__ZEN_CORE__IS_INITIALIZED__){throw new Error("ZenCore is already initialized.")}exportedConfig=config||exportedConfig;initialize$1(exportedConfig);globalThis.__ZEN_CORE__IS_INITIALIZED__=true;}function destroy(){destroy$1();globalThis.__ZEN_CORE__IS_INITIALIZED__=false;}function onAfterInitialize(callback){afterInitializeCallbacks.push(callback);}const config=exportedConfig;
|
|
127
171
|
|
|
128
172
|
var ZenCore = /*#__PURE__*/Object.freeze({
|
|
129
173
|
__proto__: null,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zenflux/core",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.9",
|
|
4
4
|
"types": "dist/zenflux-core.d.ts",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"files": [
|
|
@@ -33,7 +33,7 @@
|
|
|
33
33
|
},
|
|
34
34
|
"devDependencies": {
|
|
35
35
|
"@jest/globals": "^29.7.0",
|
|
36
|
-
"@zenflux/cli": "0.1.
|
|
36
|
+
"@zenflux/cli": "0.1.31"
|
|
37
37
|
},
|
|
38
38
|
"publishConfig": {
|
|
39
39
|
"access": "public"
|
|
@@ -42,6 +42,6 @@
|
|
|
42
42
|
"fastmcp": "^3.23.1",
|
|
43
43
|
"zod": "^4.1.12",
|
|
44
44
|
"picocolors": "^1.0.0",
|
|
45
|
-
"@zenflux/utils": "0.1.
|
|
45
|
+
"@zenflux/utils": "0.1.13"
|
|
46
46
|
}
|
|
47
47
|
}
|
package/src/errors/index.ts
CHANGED
|
@@ -7,3 +7,4 @@ export { CommandNotFound } from "./command-not-found";
|
|
|
7
7
|
export { ControllerAlreadyRegistered } from "./controller-already-registered";
|
|
8
8
|
export { ControllerAlreadySet } from "./controller-already-set";
|
|
9
9
|
export { ForceMethodImplementation, ForceMethodBase } from "./force-method-implementation";
|
|
10
|
+
export { ErrorWithMetadata } from "./error-with-metadata";
|
package/src/exports.ts
CHANGED
|
@@ -4,6 +4,8 @@
|
|
|
4
4
|
// @ts-ignore - TODO handle error in jest
|
|
5
5
|
import { bases, commandBases, errors, interfaces, managers, } from "./exports-index";
|
|
6
6
|
|
|
7
|
+
import { Logger } from "./modules/logger";
|
|
8
|
+
|
|
7
9
|
import * as pkg from "../package.json" assert { type: "json" };
|
|
8
10
|
|
|
9
11
|
declare global {
|
|
@@ -14,21 +16,7 @@ export const classes = {
|
|
|
14
16
|
/* eslint-disable @typescript-eslint/no-unused-vars */
|
|
15
17
|
/* eslint-disable @typescript-eslint/explicit-member-accessibility */
|
|
16
18
|
|
|
17
|
-
Logger
|
|
18
|
-
constructor( owner: typeof bases.ObjectBase | bases.ObjectBase | string, params: any = {} ) {
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
log( caller: interfaces.TCaller, message: string, ... params: any[] ) {}
|
|
22
|
-
warn( caller: interfaces.TCaller, message: string, ... params: any[] ) {}
|
|
23
|
-
error( caller: interfaces.TCaller, message: string, ... params: any[] ) {}
|
|
24
|
-
info( caller: interfaces.TCaller, message: string, ... params: any[] ) {}
|
|
25
|
-
debug( caller: interfaces.TCaller, message: string, ... params: any[] ) {}
|
|
26
|
-
addMessagePrefix( prefix: string ) {}
|
|
27
|
-
startsEmpty( caller: interfaces.TCaller ) {}
|
|
28
|
-
startsWith( caller: interfaces.TCaller, params: object | string ) {}
|
|
29
|
-
dump( caller: interfaces.TCaller, data: any, notice?: string ) {}
|
|
30
|
-
drop( caller: interfaces.TCaller, according: { [ key: string ]: string }, data: any ) {}
|
|
31
|
-
}
|
|
19
|
+
Logger,
|
|
32
20
|
|
|
33
21
|
/* eslint-enable */
|
|
34
22
|
};
|
package/src/modules/debugger.ts
CHANGED
|
@@ -8,8 +8,6 @@ import { Logger } from "./logger";
|
|
|
8
8
|
|
|
9
9
|
import { ObjectBase } from "../bases/object-base";
|
|
10
10
|
|
|
11
|
-
import type { PermissionOverwriteManager, PermissionOverwrites } from "discord.js";
|
|
12
|
-
|
|
13
11
|
// Define options interface for Debugger
|
|
14
12
|
interface DebuggerOptions {
|
|
15
13
|
skipEventBusHook?: boolean;
|
|
@@ -44,8 +42,6 @@ export class Debugger extends ObjectBase {
|
|
|
44
42
|
// Bypass all the methods
|
|
45
43
|
this.log = () => {};
|
|
46
44
|
this.dumpDown = () => {};
|
|
47
|
-
this.debugPermission = () => {};
|
|
48
|
-
this.debugPermissions = () => {};
|
|
49
45
|
this.enableCleanupDebug = () => {};
|
|
50
46
|
}
|
|
51
47
|
}
|
|
@@ -81,26 +77,6 @@ export class Debugger extends ObjectBase {
|
|
|
81
77
|
);
|
|
82
78
|
}
|
|
83
79
|
|
|
84
|
-
public debugPermission( source: Function, overwrite: PermissionOverwrites ) {
|
|
85
|
-
let { id, allow, deny, type } = overwrite;
|
|
86
|
-
|
|
87
|
-
this.log(
|
|
88
|
-
source,
|
|
89
|
-
JSON.stringify( {
|
|
90
|
-
id,
|
|
91
|
-
allow: allow.toArray(),
|
|
92
|
-
deny: deny.toArray(),
|
|
93
|
-
type
|
|
94
|
-
} )
|
|
95
|
-
);
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
public debugPermissions( source: Function, permissionOverwrites: PermissionOverwriteManager ) {
|
|
99
|
-
for ( const overwrite of permissionOverwrites.cache.values() ) {
|
|
100
|
-
this.debugPermission( source, overwrite );
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
|
|
104
80
|
public isEnabled() {
|
|
105
81
|
return this.shouldDebug;
|
|
106
82
|
}
|
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
import pc from "picocolors";
|
|
2
|
+
|
|
3
|
+
import { EventBus } from "../event-bus/event-bus";
|
|
4
|
+
import { ObjectBase } from "../../bases";
|
|
5
|
+
|
|
6
|
+
import {
|
|
7
|
+
getLoggerLogLevel,
|
|
8
|
+
getLoggerLogLevelString,
|
|
9
|
+
isLoggerDebugEnabled,
|
|
10
|
+
isLoggerDisabled,
|
|
11
|
+
isLoggerPreviousSourceDisabled
|
|
12
|
+
} from "./config";
|
|
13
|
+
|
|
14
|
+
import { LoggerBrowserInfra } from "./logger-browser-infra";
|
|
15
|
+
|
|
16
|
+
import { reduceCircularReferences } from "./utils";
|
|
17
|
+
|
|
18
|
+
import type * as interfaces from "../../interfaces";
|
|
19
|
+
|
|
20
|
+
const DEFAULT_LOG_PREFIX = pc.white( "⚪ - [LOG]" ),
|
|
21
|
+
DEFAULT_INFO_PREFIX = pc.blue( "🔵 - [INFO]" ),
|
|
22
|
+
DEFAULT_DEBUG_PREFIX = pc.gray( "🟤 - [DEBUG]" ),
|
|
23
|
+
DEFAULT_WARN_PREFIX = pc.yellow( "🟡 - [WARN]" ),
|
|
24
|
+
DEFAULT_ERROR_PREFIX = pc.red( "🔴 - [ERROR]" ),
|
|
25
|
+
DEFAULT_ADMIN_PREFIX = pc.bold( "🟣 - [ADMIN]" );
|
|
26
|
+
|
|
27
|
+
const registeredNames: Record<string, boolean> = {};
|
|
28
|
+
|
|
29
|
+
type ICaller = interfaces.TCaller;
|
|
30
|
+
|
|
31
|
+
interface LoggerOptions {
|
|
32
|
+
skipEventBusHook?: boolean;
|
|
33
|
+
repeatedly?: boolean;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export class Logger extends LoggerBrowserInfra implements interfaces.ILogger {
|
|
37
|
+
private static lastLogTime: number = Date.now();
|
|
38
|
+
|
|
39
|
+
private readonly ownerName: string;
|
|
40
|
+
|
|
41
|
+
private messagePrefixes: string[] = [];
|
|
42
|
+
|
|
43
|
+
private config: LoggerOptions = {};
|
|
44
|
+
|
|
45
|
+
public static getName(): string {
|
|
46
|
+
return "ZenFlux/Core/Modules/Logger";
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
public static getLogLevelString(): string {
|
|
50
|
+
return getLoggerLogLevelString();
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
public static getLogLevel(): number {
|
|
54
|
+
return getLoggerLogLevel();
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
public static isDebugEnabled() {
|
|
58
|
+
return isLoggerDebugEnabled();
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
public constructor( owner: any, options?: LoggerOptions ) {
|
|
62
|
+
const { repeatedly = false, skipEventBusHook } = options || {};
|
|
63
|
+
|
|
64
|
+
super( owner, { repeatedly } );
|
|
65
|
+
|
|
66
|
+
this.config = { skipEventBusHook };
|
|
67
|
+
this.ownerName = Logger.resolveOwnerName( owner );
|
|
68
|
+
|
|
69
|
+
if ( registeredNames[ this.ownerName ] ) {
|
|
70
|
+
throw new Error( `Logger for '${ this.ownerName }' already exists` );
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
registeredNames[ this.ownerName ] = true;
|
|
74
|
+
|
|
75
|
+
if ( isLoggerDisabled() ) {
|
|
76
|
+
this.disableLoggers();
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
if ( isLoggerPreviousSourceDisabled() ) {
|
|
81
|
+
this.getPreviousSource = () => "";
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
switch ( getLoggerLogLevel() ) {
|
|
85
|
+
case 0:
|
|
86
|
+
this.error = () => {};
|
|
87
|
+
// falls through
|
|
88
|
+
case 1:
|
|
89
|
+
this.warn = () => {};
|
|
90
|
+
// falls through
|
|
91
|
+
case 2:
|
|
92
|
+
this.admin = () => {};
|
|
93
|
+
// falls through
|
|
94
|
+
case 3:
|
|
95
|
+
this.info = () => {};
|
|
96
|
+
// falls through
|
|
97
|
+
case 4:
|
|
98
|
+
this.log = () => {};
|
|
99
|
+
// falls through
|
|
100
|
+
case 5:
|
|
101
|
+
this.debug = () => {};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
if ( !this.config.skipEventBusHook ) {
|
|
105
|
+
EventBus.$.registerMultiInstances( this, [ this.outputEvent ] );
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
public addMessagePrefix( prefix: string ) {
|
|
110
|
+
this.messagePrefixes.push( prefix );
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
public log( caller: ICaller, message: string, ...params: any[] ): void {
|
|
114
|
+
this.writeLog( DEFAULT_LOG_PREFIX, caller, message, ...params );
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
public info( caller: ICaller, message: string, ...params: any[] ): void {
|
|
118
|
+
this.writeLog( DEFAULT_INFO_PREFIX, caller, message, ...params );
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
public debug( caller: ICaller, message: string, ...params: any[] ): void {
|
|
122
|
+
this.writeLog( DEFAULT_DEBUG_PREFIX, caller, message, ...params );
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
public warn( caller: ICaller, message: string, ...params: any[] ): void {
|
|
126
|
+
this.writeLog( DEFAULT_WARN_PREFIX, caller, message, ...params );
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
public error( caller: ICaller, message: string, ...params: any[] ): void {
|
|
130
|
+
this.writeLog( DEFAULT_ERROR_PREFIX, caller, message, ...params );
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
public admin( caller: ICaller, message: string, ...params: any[] ): void {
|
|
134
|
+
this.writeLog( DEFAULT_ADMIN_PREFIX, caller, message, ...params );
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
public startsEmpty( caller: interfaces.TCaller ) {
|
|
138
|
+
this.printFunctionNotify( "▶", caller, "" );
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
public startsWith( caller: interfaces.TCaller, params: string | object ) {
|
|
142
|
+
this.printObjectEfficient( "▶", caller, params );
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
public dump( caller: interfaces.TCaller, params: { [ key: string ]: object | string } = {}, notice = "" ) {
|
|
146
|
+
for ( const key in params ) {
|
|
147
|
+
if ( typeof params[ key ] === "object" ) {
|
|
148
|
+
params[ key ] = JSON.stringify(
|
|
149
|
+
LoggerBrowserInfra.useObjectMapper( params[ key ] as object ),
|
|
150
|
+
reduceCircularReferences()
|
|
151
|
+
);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
this.printInLineElement( "dp", caller, key, params[ key ], notice );
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
public drop( caller: interfaces.TCaller, according: { [ key: string ]: string }, data: any ) {
|
|
159
|
+
for ( const key in according ) {
|
|
160
|
+
this.printInLineElement( "dr", caller, key, according[ key ], "corresponding" );
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
this.output( data );
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* TODO: Should respect debug levels, when to throw...
|
|
168
|
+
*/
|
|
169
|
+
public throw( caller: interfaces.TCaller, output: string, name: string = "null", params = {} ) {
|
|
170
|
+
this.printFunctionNotify( "tw", caller, output );
|
|
171
|
+
|
|
172
|
+
if ( params ) {
|
|
173
|
+
this.printInNextLineObject( "tw", caller, name, params );
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
throw new Error().stack;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
public beep() {
|
|
180
|
+
console.log( "\x07" );
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
public clone() {
|
|
184
|
+
return Object.assign( Object.create( Object.getPrototypeOf( this ) ), this );
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
public outputEvent( _prefix: string, _timeDiff: string, _source: string, _messagePrefix: string, _message: string, _params: any[] ): void {
|
|
188
|
+
// Intentionally left blank, can be hooked via EventBus.
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
private static resolveOwnerName( owner: any ): string {
|
|
192
|
+
if ( typeof owner === "string" ) {
|
|
193
|
+
return owner;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
if ( owner instanceof ObjectBase ) {
|
|
197
|
+
return owner.getName();
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
if ( owner && typeof owner.getName === "function" ) {
|
|
201
|
+
return owner.getName();
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
return "UnknownOwner";
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
private disableLoggers() {
|
|
208
|
+
this.error = () => {};
|
|
209
|
+
this.warn = () => {};
|
|
210
|
+
this.admin = () => {};
|
|
211
|
+
this.info = () => {};
|
|
212
|
+
this.log = () => {};
|
|
213
|
+
this.debug = () => {};
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
private getStackTrace(): any[] {
|
|
217
|
+
const stackTrace = ( new Error().stack || "" ).split( "\n" );
|
|
218
|
+
const stackLines = stackTrace.slice( 1 );
|
|
219
|
+
|
|
220
|
+
const stackRegex = / at (.+?) \((.+?)\)/;
|
|
221
|
+
const result = [];
|
|
222
|
+
|
|
223
|
+
for ( const line of stackLines ) {
|
|
224
|
+
const match = line.match( stackRegex );
|
|
225
|
+
|
|
226
|
+
if ( match ) {
|
|
227
|
+
const [ , context, file ] = match;
|
|
228
|
+
const parsedLine: any = { context, file };
|
|
229
|
+
|
|
230
|
+
if ( line.startsWith( "new" ) ) {
|
|
231
|
+
parsedLine.isNew = true;
|
|
232
|
+
parsedLine.object = context.split( " " )[ 1 ];
|
|
233
|
+
} else if ( context !== "Object.<anonymous>" ) {
|
|
234
|
+
parsedLine.object = context;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
result.push( parsedLine );
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
return result;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
public getPreviousSource(): string {
|
|
245
|
+
const stack = this.getStackTrace()
|
|
246
|
+
.filter( ( line: any ) => line.file.includes( "/src/" ) )
|
|
247
|
+
.filter( ( line: any ) => !line.file.includes( "logger.ts" ) )
|
|
248
|
+
.filter( ( line: any ) => !line.file.includes( "debugger.ts" ) )
|
|
249
|
+
.filter( ( line: any ) => !line.file.includes( "/node_modules/" ) );
|
|
250
|
+
|
|
251
|
+
let previousSource = "";
|
|
252
|
+
|
|
253
|
+
const previousCaller = stack[ 1 ]?.object?.split( "." );
|
|
254
|
+
|
|
255
|
+
if ( previousCaller?.length > 1 ) {
|
|
256
|
+
const previousCallerName = previousCaller[ 0 ],
|
|
257
|
+
previousCallerMethod = previousCaller[ 1 ];
|
|
258
|
+
|
|
259
|
+
previousSource = `${ previousCallerName }::${ previousCallerMethod }]` + "[";
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
return previousSource;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
private writeLog( prefix: string, caller: ICaller, message: string, ...params: any[] ): void {
|
|
266
|
+
const source = this.getPreviousSource() + pc.white( `${ this.ownerName }::${ this.getCallerName( caller ) }` );
|
|
267
|
+
|
|
268
|
+
let messagePrefix = "";
|
|
269
|
+
|
|
270
|
+
if ( this.messagePrefixes.length ) {
|
|
271
|
+
messagePrefix = `[${ this.messagePrefixes.join( "][" ) }]`;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
const timeDiff = ( Date.now() - Logger.lastLogTime ).toString().padStart( 4, "0" );
|
|
275
|
+
|
|
276
|
+
this.outputEvent( prefix, timeDiff, source, messagePrefix, message, params );
|
|
277
|
+
|
|
278
|
+
const output = `${ prefix }[+${ timeDiff }ms][${ source }]${ messagePrefix }: ${ message }`;
|
|
279
|
+
|
|
280
|
+
console.log( output, ...params );
|
|
281
|
+
|
|
282
|
+
Logger.lastLogTime = Date.now();
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
export default Logger;
|
|
287
|
+
|