@zenflux/core 0.1.29 → 0.1.30

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.
Files changed (59) hide show
  1. package/dist/.tsconfig.probe.tsbuildinfo +1 -0
  2. package/dist/src/exports.d.ts +0 -3
  3. package/dist/src/index.d.ts +0 -5
  4. package/dist/src/modules/logger/implementation.d.ts +1 -0
  5. package/dist/zenflux-core.cjs +37 -119
  6. package/dist/zenflux-core.d.ts +3 -32
  7. package/dist/zenflux-core.mjs +38 -117
  8. package/package.json +2 -2
  9. package/src/bases/cache-base.ts +64 -0
  10. package/src/bases/controller-base.ts +96 -0
  11. package/src/bases/index.ts +9 -0
  12. package/src/bases/initialize-base.ts +32 -0
  13. package/src/bases/object-base.ts +55 -0
  14. package/src/bases/singleton-base.ts +18 -0
  15. package/src/clients/http.ts +152 -0
  16. package/src/command-bases/command-base.ts +80 -0
  17. package/src/command-bases/command-internal.ts +11 -0
  18. package/src/command-bases/command-public.ts +12 -0
  19. package/src/command-bases/command-restful.ts +55 -0
  20. package/src/command-bases/index.ts +8 -0
  21. package/src/errors/command-already-registered.ts +13 -0
  22. package/src/errors/command-not-found.ts +12 -0
  23. package/src/errors/controller-already-registered.ts +13 -0
  24. package/src/errors/controller-already-set.ts +13 -0
  25. package/src/errors/error-with-metadata.ts +29 -0
  26. package/src/errors/force-method-implementation.ts +15 -0
  27. package/src/errors/index-public.ts +1 -0
  28. package/src/errors/index.ts +10 -0
  29. package/src/exports-index.ts +15 -0
  30. package/src/exports.ts +55 -0
  31. package/src/index.ts +18 -0
  32. package/src/interfaces/commands.ts +17 -0
  33. package/src/interfaces/config.ts +23 -0
  34. package/src/interfaces/index.ts +8 -0
  35. package/src/interfaces/logger.ts +19 -0
  36. package/src/interfaces/restful.ts +23 -0
  37. package/src/managers/commands.ts +269 -0
  38. package/src/managers/controllers.ts +40 -0
  39. package/src/managers/export.ts +30 -0
  40. package/src/managers/index.ts +8 -0
  41. package/src/managers/internal.ts +11 -0
  42. package/src/managers/restful.ts +117 -0
  43. package/src/modules/debugger.ts +86 -0
  44. package/src/modules/event-bus/event-bus.ts +238 -0
  45. package/src/modules/export.ts +6 -0
  46. package/src/modules/logger/config.ts +66 -0
  47. package/src/modules/logger/create-logger.ts +38 -0
  48. package/src/modules/logger/implementation.ts +371 -0
  49. package/src/modules/logger/index.ts +3 -0
  50. package/src/modules/logger/logger-browser-infra.ts +364 -0
  51. package/src/modules/logger/types/picocolors.d.ts +15 -0
  52. package/src/modules/logger/utils/index.ts +3 -0
  53. package/src/modules/logger/utils/object.ts +19 -0
  54. package/src/modules/logger/utils/rgb.ts +34 -0
  55. package/src/modules/mcp-server/mcp-server.ts +139 -0
  56. package/src/modules/mcp-server/mcp-service.ts +80 -0
  57. package/src/modules/service/service-base.ts +55 -0
  58. package/src/modules/service/service-locator.ts +205 -0
  59. package/src/modules/service/service-with-dependencies-base.ts +51 -0
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Bundled with love using the help of @zenflux/cli toolkit v0.1.43
3
- * Bundle name: @zenflux/core fileName: 'zenflux-core', built at Tue Feb 03 2026 12:19:23 GMT+0200 (Israel Standard Time)
3
+ * Bundle name: @zenflux/core fileName: 'zenflux-core', built at Tue Sep 01 2026 19:12:30 GMT+0300 (Israel Daylight Time)
4
4
  */
5
5
 
6
6
  import * as util from 'util';
@@ -20,7 +20,37 @@ class ErrorWithMetadata extends Error{metadata;constructor(message,metadata=null
20
20
 
21
21
  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}}
22
22
 
23
- 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();}}
23
+ 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}
24
+
25
+ var picocolors$1={exports:{}};
26
+
27
+ 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}
28
+
29
+ var picocolorsExports=requirePicocolors();var pc = getDefaultExportFromCjs(picocolorsExports);
30
+
31
+ const DEFAULT_LOG_LEVEL="5";function getEnvVar(key){if(typeof process!=="undefined"&&process?.env){return process.env[key]??process.env[`VITE_${key}`]}if(typeof import.meta!=="undefined"&&import.meta.env){const env=import.meta.env;return env[key]??env[`VITE_${key}`]}return undefined}function getLoggerDefaultLevel(){return DEFAULT_LOG_LEVEL}function getLoggerLogLevel(){const raw=getEnvVar("LOGGER_LOG_LEVEL");return parseInt(raw??DEFAULT_LOG_LEVEL,10)}function getLoggerTimeFormat(){return (getEnvVar("LOGGER_TIME_FORMAT")||"").trim()}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 getEnvVar("LOGGER_DISABLED")==="true"}function isLoggerPreviousSourceDisabled(){return getEnvVar("LOGGER_LOG_PREVIOUS_CALLER_SOURCE_DISABLED")==="true"}
32
+
33
+ /**
34
+ * Reduce circular references.
35
+ *
36
+ * @copyright https://stackoverflow.com/a/53731154
37
+ */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}};
38
+
39
+ /**
40
+ * Function hexColorDelta() : Return color difference in ratio decimal point.
41
+ *
42
+ * @copyright http://jsfiddle.net/96sME/
43
+ */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};
44
+
45
+ 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=[];static outputSubscribers=new Set;defaultStyle;owner;args;color;outputHandler=console.log;pendingOutputMetadata;static getName(){return "ZenFlux/Logging/Modules/LoggerBrowserInfra"}static reset(){LoggerBrowserInfra.mappers=[];LoggerBrowserInfra.mapperDepth=0;LoggerBrowserInfra.colorsUsed=[];LoggerBrowserInfra.colorsOwners={};LoggerBrowserInfra.outputSubscribers.clear();}static attachOutputSubscriber(subscriber){LoggerBrowserInfra.outputSubscribers.add(subscriber);return ()=>{LoggerBrowserInfra.outputSubscribers.delete(subscriber);}}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.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);if(LoggerBrowserInfra.outputSubscribers.size===0){return}const event={logger:this,namespace:this.getOwnerName(),args,metadata:this.pendingOutputMetadata};LoggerBrowserInfra.outputSubscribers.forEach(subscriber=>{try{subscriber(event);}catch(error){console.error("[ZenFlux][Logger] output subscriber failed",error);}});}setOutputHandler(outputHandler){this.outputHandler=outputHandler;}runWithOutputMetadata(metadata,callback){const previous=this.pendingOutputMetadata;this.pendingOutputMetadata=metadata;try{return callback()}finally{this.pendingOutputMetadata=previous;}}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)];}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}}
46
+
47
+ let SimpleEventEmitter=class SimpleEventEmitter{listeners=new Map;on(event,callback){if(!this.listeners.has(event)){this.listeners.set(event,new Set);}this.listeners.get(event).add(callback);}off(event,callback){this.listeners.get(event)?.delete(callback);}emit(event,...args){const callbacks=this.listeners.get(event);if(!callbacks||callbacks.size===0){return false}callbacks.forEach(cb=>cb(...args));return true}removeAllListeners(event){this.listeners.delete(event);}eventNames(){return Array.from(this.listeners.keys())}};class EventBus extends ObjectBase{static instance=null;objects=new Map;eventEmitter=new SimpleEventEmitter;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()}`)}}}
48
+
49
+ 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 LEVEL_LABELS={log:"LOG",info:"INFO",debug:"DEBUG",warn:"WARN",error:"ERROR",admin:"ADMIN"};const registeredNames={};function resetLoggerRegistry(){for(const key in registeredNames){delete registeredNames[key];}}class Logger extends LoggerBrowserInfra{static lastLogTime=Date.now();static timestampFormat=getLoggerTimeFormat();ownerName;messagePrefixes=[];config={};static setTimestampFormat(format){Logger.timestampFormat=(format||"").trim();}static getTimestampFormat(){return Logger.timestampFormat}static getName(){return "ZenFlux/Core/Modules/Logger"}static getLogLevelString(){return getLoggerLogLevelString()}static getLogLevel(){return getLoggerLogLevel()}static attachOutputListener(listener){return LoggerBrowserInfra.attachOutputSubscriber(listener)}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("log",DEFAULT_LOG_PREFIX,caller,message,...params);}info(caller,message,...params){this.writeLog("info",DEFAULT_INFO_PREFIX,caller,message,...params);}debug(caller,message,...params){this.writeLog("debug",DEFAULT_DEBUG_PREFIX,caller,message,...params);}warn(caller,message,...params){this.writeLog("warn",DEFAULT_WARN_PREFIX,caller,message,...params);}error(caller,message,...params){this.writeLog("error",DEFAULT_ERROR_PREFIX,caller,message,...params);}admin(caller,message,...params){this.writeLog("admin",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(level,prefix,caller,message,...params){const callerName=this.getCallerName(caller);const source=this.getPreviousSource()+pc.white(`${this.ownerName}::${callerName}`);let messagePrefix="";if(this.messagePrefixes.length){messagePrefix=`[${this.messagePrefixes.join("][")}]`;}const timestampValue=Date.now();const timeDiff=(timestampValue-Logger.lastLogTime).toString().padStart(4,"0");const timeFormat=Logger.getTimestampFormat();const timestamp=timeFormat?this.formatTime(new Date(timestampValue),timeFormat):"";this.outputEvent(prefix,timeDiff,source,messagePrefix,message,params);const timestampPart=timestamp?`${timestamp} `:"";const output=`${timestampPart}${prefix}[+${timeDiff}ms][${source}]${messagePrefix}: ${message}`;const formatted=this.createBrowserFormat(level,callerName,messagePrefix,message);const metadata={id:`${timestampValue}-${Math.random().toString(16).slice(2)}`,level,namespace:this.ownerName,callerName,message,messagePrefix,payload:params.length===0?undefined:params.length===1?params[0]:params,timestamp:timestampValue,formatted};this.runWithOutputMetadata(metadata,()=>{this.output(output,...params);});Logger.lastLogTime=timestampValue;}createBrowserFormat(level,callerName,messagePrefix,message){const prefixLabel=LEVEL_LABELS[level]||level.toUpperCase();const prefixPart=messagePrefix?`${messagePrefix} `:"";return {format:`%c(${prefixLabel})-> %c%c${this.ownerName}%c::%c${callerName}%c() ${prefixPart}${message}%c`,styles:[...this.defaultStyle]}}formatTime(date,format){const pad=(num,size=2)=>num.toString().padStart(size,"0");const tokens={"YYYY":date.getFullYear().toString(),"Y":date.getFullYear().toString(),"M":pad(date.getMonth()+1),"D":pad(date.getDate()),"HH":pad(date.getHours()),"hh":pad(date.getHours()),"mm":pad(date.getMinutes()),"ss":pad(date.getSeconds()),"SSS":pad(date.getMilliseconds(),3),"S":pad(date.getMilliseconds(),3)};return format.replace(/YYYY|HH|hh|mm|ss|SSS|Y|M|D|S|h|m|s/g,token=>tokens[token]??token)}}
50
+
51
+ class ZenFluxLogger extends Logger{}const loggerCache=new Map;const resolveOwnerName=owner=>{if(typeof owner==="string"){return owner}if(owner&&typeof owner.getName==="function"){return owner.getName()}return "UnknownOwner"};const createLogger=(owner,options)=>{const ownerName=resolveOwnerName(owner);const cached=loggerCache.get(ownerName);if(cached){return cached}const logger=new ZenFluxLogger(owner,options);loggerCache.set(ownerName,logger);return logger};
52
+
53
+ 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=createLogger(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();}}
24
54
 
25
55
  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}}
26
56
 
@@ -32,57 +62,27 @@ E_HTTP_METHOD_TYPE: E_HTTP_METHOD_TYPE,
32
62
  E_RESPONSE_HANDLER_TYPE: E_RESPONSE_HANDLER_TYPE
33
63
  });
34
64
 
35
- class Http extends ObjectBase{logger;apiBaseUrl;requestInit;errorHandler=undefined;responseFilter=undefined;responseHandler=undefined;static getName(){return "ZenFlux/Core/Clients/Http"}constructor(apiBaseUrl="http://localhost",requestInit={"credentials":"include"}){super();this.logger=new zCore.classes.Logger(Http);this.logger.startsWith(this.constructor,{apiBaseUrl});this.apiBaseUrl=apiBaseUrl+"/";this.requestInit=requestInit;}async fetch(path,method,body={}){this.logger.startsWith(this.constructor,{path,method,body});const params=Object.assign({},this.requestInit);const headers={};if(method===E_HTTP_METHOD_TYPE.GET){Object.assign(params,{headers});}else {Object.assign(headers,{"Content-Type":"application/json"});Object.assign(params,{method,headers:headers,body:JSON.stringify(body)});}const fetchPromise=globalThis.fetch(this.apiBaseUrl+path,params);let response=await fetchPromise;if(!response){return false}let data=undefined;try{if(!response.ok){throw new Error(response.statusText)}let responseText=await response.text();responseText=this.applyResponseFilter(responseText);if(response.headers?.get("Content-Type")?.includes("application/json")){data=JSON.parse(responseText);}else {data=responseText;}if(this.applyResponseHandler(data)){return false}}catch(e){if(this.applyErrorHandler(e)){return false}await Promise.reject(e);}this.logger.drop(this.fetch,{path},data);return data}setErrorHandler(callback){if(this.errorHandler){throw new Error("Error handler already set.")}this.errorHandler=callback;}setResponseFilter(callback){if(this.responseFilter){throw new Error("Response filter already set.")}this.responseFilter=callback;}setResponseHandler(callback){if(this.responseHandler){throw new Error("Response handler already set.")}this.responseHandler=callback;}applyErrorHandler(error){return !!this.errorHandler&&this.errorHandler(error)}applyResponseFilter(text){return this.responseFilter&&this.responseFilter(text)||text}applyResponseHandler(text){return !!this.responseHandler&&this.responseHandler(text)}}
65
+ class Http extends ObjectBase{logger;apiBaseUrl;requestInit;errorHandler=undefined;responseFilter=undefined;responseHandler=undefined;static getName(){return "ZenFlux/Core/Clients/Http"}constructor(apiBaseUrl="http://localhost",requestInit={"credentials":"include"}){super();this.logger=new Logger(Http);this.logger.startsWith(this.constructor,{apiBaseUrl});this.apiBaseUrl=apiBaseUrl+"/";this.requestInit=requestInit;}async fetch(path,method,body={}){this.logger.startsWith(this.constructor,{path,method,body});const params=Object.assign({},this.requestInit);const headers={};if(method===E_HTTP_METHOD_TYPE.GET){Object.assign(params,{headers});}else {Object.assign(headers,{"Content-Type":"application/json"});Object.assign(params,{method,headers:headers,body:JSON.stringify(body)});}const fetchPromise=globalThis.fetch(this.apiBaseUrl+path,params);let response=await fetchPromise;if(!response){return false}let data=undefined;try{if(!response.ok){throw new Error(response.statusText)}let responseText=await response.text();responseText=this.applyResponseFilter(responseText);if(response.headers?.get("Content-Type")?.includes("application/json")){data=JSON.parse(responseText);}else {data=responseText;}if(this.applyResponseHandler(data)){return false}}catch(e){if(this.applyErrorHandler(e)){return false}await Promise.reject(e);}this.logger.drop(this.fetch,{path},data);return data}setErrorHandler(callback){if(this.errorHandler){throw new Error("Error handler already set.")}this.errorHandler=callback;}setResponseFilter(callback){if(this.responseFilter){throw new Error("Response filter already set.")}this.responseFilter=callback;}setResponseHandler(callback){if(this.responseHandler){throw new Error("Response handler already set.")}this.responseHandler=callback;}applyErrorHandler(error){return !!this.errorHandler&&this.errorHandler(error)}applyResponseFilter(text){return this.responseFilter&&this.responseFilter(text)||text}applyResponseHandler(text){return !!this.responseHandler&&this.responseHandler(text)}}
36
66
 
37
67
  class Restful extends Commands{static client;currentHttpMethod;static getName(){return "ZenFlux/Core/Managers/Restful"}constructor(Config){super();Restful.client=new Http(Config.baseURL,Config.requestInit);}getClient(){return Restful.client}get(command,args={},options={}){this.currentHttpMethod=E_HTTP_METHOD_TYPE.GET;return super.run(command,args,options)}update(command,args={},options={}){this.currentHttpMethod=E_HTTP_METHOD_TYPE.PATCH;return super.run(command,args,options)}delete(command,args={},options={}){this.currentHttpMethod=E_HTTP_METHOD_TYPE.DELETE;return super.run(command,args,options)}create(command,args={},options={}){this.currentHttpMethod=E_HTTP_METHOD_TYPE.POST;return super.run(command,args,options)}async runInstance(command,args={},options={}){if(!this.currentHttpMethod){throw new Error('Cannot run directly use one of the http methods: "get", "update", "delete, "create')}const newArgs={type:this.currentHttpMethod,args:{query:{},data:{}}};if(E_HTTP_METHOD_TYPE.GET===this.currentHttpMethod){newArgs.args.query=args;}else {newArgs.args.data=args;}args.result=await super.runInstance(command,newArgs,options);this.currentHttpMethod=E_HTTP_METHOD_TYPE.__EMPTY__;return args.result}setHandler(type,callback){switch(type){case E_RESPONSE_HANDLER_TYPE.ERROR_HANDLER:Restful.client.setErrorHandler(callback);break;case E_RESPONSE_HANDLER_TYPE.RESPONSE_FILTER:Restful.client.setResponseFilter(callback);break;case E_RESPONSE_HANDLER_TYPE.RESPONSE_HANDLER:Restful.client.setResponseHandler(callback);break;default:throw new Error(`Unknown handler type: '${type}'`)}}}
38
68
 
39
69
  class Internal extends Commands{static getName(){return "ZenFlux/Core/Managers/Internal"}}
40
70
 
41
- const afterInitializeCallbacks=[];function initialize$1(config){commands=new Commands;controllers=new Controllers;restful=new Restful(config);internal=new Internal;}function destroy$1(){commands={};controllers={};restful={};internal={};}let commands={};let controllers={};let restful={};let internal={};
71
+ const afterInitializeCallbacks=[];function initialize(config){commands=new Commands;controllers=new Controllers;restful=new Restful(config);internal=new Internal;}function destroy(){commands={};controllers={};restful={};internal={};}let commands={};let controllers={};let restful={};let internal={};
42
72
 
43
73
  var _export$1 = /*#__PURE__*/Object.freeze({
44
74
  __proto__: null,
45
75
  afterInitializeCallbacks: afterInitializeCallbacks,
46
76
  get commands () { return commands; },
47
77
  get controllers () { return controllers; },
48
- destroy: destroy$1,
49
- initialize: initialize$1,
78
+ destroy: destroy,
79
+ initialize: initialize,
50
80
  get internal () { return internal; },
51
81
  get restful () { return restful; }
52
82
  });
53
83
 
54
84
  class ControllerBase extends ObjectBase{commands;restful;internal;static getName(){return "ZenFlux/Core/ControllerBase"}constructor(){super();this.initialize();}initialize(){this.register();this.setupHooks&&this.setupHooks();}register(){this.commands=commands.register(this.getCommands(),this);this.restful=restful.register(this.getRestful(),this);this.internal=internal.register(this.getInternal(),this);}getCommands(){return {}}getRestful(){return {}}getInternal(){return {}}setupHooks(){}}
55
85
 
56
- const DEFAULT_LOG_LEVEL="5";function getEnvVar(key){if(typeof process!=="undefined"&&process?.env){return process.env[key]??process.env[`VITE_${key}`]}if(typeof import.meta!=="undefined"&&import.meta.env){const env=import.meta.env;return env[key]??env[`VITE_${key}`]}return undefined}function getLoggerDefaultLevel(){return DEFAULT_LOG_LEVEL}function getLoggerLogLevel(){const raw=getEnvVar("LOGGER_LOG_LEVEL");return parseInt(raw??DEFAULT_LOG_LEVEL,10)}function getLoggerTimeFormat(){return (getEnvVar("LOGGER_TIME_FORMAT")||"").trim()}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 getEnvVar("LOGGER_DISABLED")==="true"}function isLoggerPreviousSourceDisabled(){return getEnvVar("LOGGER_LOG_PREVIOUS_CALLER_SOURCE_DISABLED")==="true"}
57
-
58
- 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}
59
-
60
- var picocolors$1={exports:{}};
61
-
62
- 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}
63
-
64
- var picocolorsExports=requirePicocolors();var pc = getDefaultExportFromCjs(picocolorsExports);
65
-
66
- /**
67
- * Reduce circular references.
68
- *
69
- * @copyright https://stackoverflow.com/a/53731154
70
- */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}};
71
-
72
- /**
73
- * Function hexColorDelta() : Return color difference in ratio decimal point.
74
- *
75
- * @copyright http://jsfiddle.net/96sME/
76
- */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};
77
-
78
- 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=[];static outputSubscribers=new Set;defaultStyle;owner;args;color;outputHandler=console.log;pendingOutputMetadata;static getName(){return "ZenFlux/Logging/Modules/LoggerBrowserInfra"}static reset(){LoggerBrowserInfra.mappers=[];LoggerBrowserInfra.mapperDepth=0;LoggerBrowserInfra.colorsUsed=[];LoggerBrowserInfra.colorsOwners={};LoggerBrowserInfra.outputSubscribers.clear();}static attachOutputSubscriber(subscriber){LoggerBrowserInfra.outputSubscribers.add(subscriber);return ()=>{LoggerBrowserInfra.outputSubscribers.delete(subscriber);}}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.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);if(LoggerBrowserInfra.outputSubscribers.size===0){return}const event={logger:this,namespace:this.getOwnerName(),args,metadata:this.pendingOutputMetadata};LoggerBrowserInfra.outputSubscribers.forEach(subscriber=>{try{subscriber(event);}catch(error){console.error("[ZenFlux][Logger] output subscriber failed",error);}});}setOutputHandler(outputHandler){this.outputHandler=outputHandler;}runWithOutputMetadata(metadata,callback){const previous=this.pendingOutputMetadata;this.pendingOutputMetadata=metadata;try{return callback()}finally{this.pendingOutputMetadata=previous;}}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)];}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}}
79
-
80
- let SimpleEventEmitter=class SimpleEventEmitter{listeners=new Map;on(event,callback){if(!this.listeners.has(event)){this.listeners.set(event,new Set);}this.listeners.get(event).add(callback);}off(event,callback){this.listeners.get(event)?.delete(callback);}emit(event,...args){const callbacks=this.listeners.get(event);if(!callbacks||callbacks.size===0){return false}callbacks.forEach(cb=>cb(...args));return true}removeAllListeners(event){this.listeners.delete(event);}eventNames(){return Array.from(this.listeners.keys())}};class EventBus extends ObjectBase{static instance=null;objects=new Map;eventEmitter=new SimpleEventEmitter;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()}`)}}}
81
-
82
- 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 LEVEL_LABELS={log:"LOG",info:"INFO",debug:"DEBUG",warn:"WARN",error:"ERROR",admin:"ADMIN"};const registeredNames={};class Logger extends LoggerBrowserInfra{static lastLogTime=Date.now();static timestampFormat=getLoggerTimeFormat();ownerName;messagePrefixes=[];config={};static setTimestampFormat(format){Logger.timestampFormat=(format||"").trim();}static getTimestampFormat(){return Logger.timestampFormat}static getName(){return "ZenFlux/Core/Modules/Logger"}static getLogLevelString(){return getLoggerLogLevelString()}static getLogLevel(){return getLoggerLogLevel()}static attachOutputListener(listener){return LoggerBrowserInfra.attachOutputSubscriber(listener)}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("log",DEFAULT_LOG_PREFIX,caller,message,...params);}info(caller,message,...params){this.writeLog("info",DEFAULT_INFO_PREFIX,caller,message,...params);}debug(caller,message,...params){this.writeLog("debug",DEFAULT_DEBUG_PREFIX,caller,message,...params);}warn(caller,message,...params){this.writeLog("warn",DEFAULT_WARN_PREFIX,caller,message,...params);}error(caller,message,...params){this.writeLog("error",DEFAULT_ERROR_PREFIX,caller,message,...params);}admin(caller,message,...params){this.writeLog("admin",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(level,prefix,caller,message,...params){const callerName=this.getCallerName(caller);const source=this.getPreviousSource()+pc.white(`${this.ownerName}::${callerName}`);let messagePrefix="";if(this.messagePrefixes.length){messagePrefix=`[${this.messagePrefixes.join("][")}]`;}const timestampValue=Date.now();const timeDiff=(timestampValue-Logger.lastLogTime).toString().padStart(4,"0");const timeFormat=Logger.getTimestampFormat();const timestamp=timeFormat?this.formatTime(new Date(timestampValue),timeFormat):"";this.outputEvent(prefix,timeDiff,source,messagePrefix,message,params);const timestampPart=timestamp?`${timestamp} `:"";const output=`${timestampPart}${prefix}[+${timeDiff}ms][${source}]${messagePrefix}: ${message}`;const formatted=this.createBrowserFormat(level,callerName,messagePrefix,message);const metadata={id:`${timestampValue}-${Math.random().toString(16).slice(2)}`,level,namespace:this.ownerName,callerName,message,messagePrefix,payload:params.length===0?undefined:params.length===1?params[0]:params,timestamp:timestampValue,formatted};this.runWithOutputMetadata(metadata,()=>{this.output(output,...params);});Logger.lastLogTime=timestampValue;}createBrowserFormat(level,callerName,messagePrefix,message){const prefixLabel=LEVEL_LABELS[level]||level.toUpperCase();const prefixPart=messagePrefix?`${messagePrefix} `:"";return {format:`%c(${prefixLabel})-> %c%c${this.ownerName}%c::%c${callerName}%c() ${prefixPart}${message}%c`,styles:[...this.defaultStyle]}}formatTime(date,format){const pad=(num,size=2)=>num.toString().padStart(size,"0");const tokens={"YYYY":date.getFullYear().toString(),"Y":date.getFullYear().toString(),"M":pad(date.getMonth()+1),"D":pad(date.getDate()),"HH":pad(date.getHours()),"hh":pad(date.getHours()),"mm":pad(date.getMinutes()),"ss":pad(date.getSeconds()),"SSS":pad(date.getMilliseconds(),3),"S":pad(date.getMilliseconds(),3)};return format.replace(/YYYY|HH|hh|mm|ss|SSS|Y|M|D|S|h|m|s/g,token=>tokens[token]??token)}}
83
-
84
- class ZenFluxLogger extends Logger{}const loggerCache=new Map;const resolveOwnerName=owner=>{if(typeof owner==="string"){return owner}if(owner&&typeof owner.getName==="function"){return owner.getName()}return "UnknownOwner"};const createLogger=(owner,options)=>{const ownerName=resolveOwnerName(owner);const cached=loggerCache.get(ownerName);if(cached){return cached}const logger=new ZenFluxLogger(owner,options);loggerCache.set(ownerName,logger);return logger};
85
-
86
86
  class InitializeBase extends ObjectBase{logger;constructor(shouldInitialize=true){super();this.logger=new Logger(this);if(this.initialize&&shouldInitialize){this.initialize();}}debounce(func,delay){let timeoutId;return (...args)=>{clearTimeout(timeoutId);timeoutId=setTimeout(()=>{func.apply(this,args);},delay);}}}
87
87
 
88
88
  class SingletonBase extends InitializeBase{static instances=new Map;constructor(){super();}static getInstance(){if(!SingletonBase.instances.has(this)){SingletonBase.instances.set(this,new this);}return SingletonBase.instances.get(this)}}
@@ -102,7 +102,7 @@ ObjectBase: ObjectBase,
102
102
  SingletonBase: SingletonBase
103
103
  });
104
104
 
105
- 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}}
105
+ 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=createLogger(type);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}}
106
106
 
107
107
  class CommandPublic extends CommandBase{static getName(){return "ZenFlux/Core/CommandBases/CommandPublic"}}
108
108
 
@@ -140,83 +140,4 @@ ServiceWithDependenciesBase: ServiceWithDependenciesBase,
140
140
  createLogger: createLogger
141
141
  });
142
142
 
143
- var _package = {
144
- "name": "@zenflux/core",
145
- "version": "0.1.27",
146
- "types": "dist/zenflux-core.d.ts",
147
- "type": "module",
148
- "files": [
149
- "dist",
150
- "types"
151
- ],
152
- "scripts": {
153
- "@z-core--test": "jest",
154
- "@z-core--build": "@z-cli @build",
155
- "@z-core--dev": "@z-cli @watch --dev"
156
- },
157
- "exports": {
158
- ".": {
159
- "import": "./dist/zenflux-core.mjs",
160
- "default": "./dist/zenflux-core.cjs",
161
- "require": "./dist/zenflux-core.mjs.js",
162
- "types": "./dist/zenflux-core.d.ts"
163
- },
164
- "./dist/src/*": "./src/*",
165
- "./src/*.ts": "./src/*.ts",
166
- "./src/*": "./src/*.ts",
167
- "./src/bases": "./src/bases/index.ts",
168
- "./src/bases/*": "./src/bases/*.ts",
169
- "./src/clients": "./src/clients/index.ts",
170
- "./src/command-bases": "./src/command-bases/index.ts",
171
- "./src/errors": "./src/errors/index.ts",
172
- "./src/interfaces": "./src/interfaces/index.ts",
173
- "./src/managers": "./src/managers/index.ts",
174
- "./src/modules/logger": "./src/modules/logger/index.ts",
175
- "./src/modules/*": "./src/modules/*.ts",
176
- "./package.json": "./package.json"
177
- },
178
- "devDependencies": {
179
- "@jest/globals": "^29.7.0",
180
- "@zenflux/cli": "workspace:*"
181
- },
182
- "publishConfig": {
183
- "access": "public"
184
- },
185
- "dependencies": {
186
- "fastmcp": "^3.23.1",
187
- "zod": "^4.1.12",
188
- "picocolors": "^1.0.0",
189
- "@zenflux/utils": "workspace:*"
190
- }
191
- };
192
- const name = "@zenflux/core";
193
- const version = "0.1.27";
194
- const types = "dist/zenflux-core.d.ts";
195
- const type = "module";
196
- const files = ["dist","types"];
197
- const scripts = {"@z-core--test":"jest","@z-core--build":"@z-cli @build","@z-core--dev":"@z-cli @watch --dev"};
198
- 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/*.ts":"./src/*.ts","./src/*":"./src/*.ts","./src/bases":"./src/bases/index.ts","./src/bases/*":"./src/bases/*.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","./src/modules/*":"./src/modules/*.ts","./package.json":"./package.json"};
199
- const devDependencies = {"@jest/globals":"^29.7.0","@zenflux/cli":"workspace:*"};
200
- const publishConfig = {"access":"public"};
201
- const dependencies = {"fastmcp":"^3.23.1","zod":"^4.1.12","picocolors":"^1.0.0","@zenflux/utils":"workspace:*"};
202
-
203
- 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;
204
-
205
- var ZenCore = /*#__PURE__*/Object.freeze({
206
- __proto__: null,
207
- bases: index$1,
208
- classes: classes,
209
- commandBases: index,
210
- config: config,
211
- destroy: destroy,
212
- errors: indexPublic,
213
- initialize: initialize,
214
- interfaces: index$2,
215
- managers: _export$1,
216
- modules: _export,
217
- onAfterInitialize: onAfterInitialize
218
- });
219
-
220
- if(!globalThis?.zCore){globalThis.zCore=ZenCore;}
221
-
222
- export { index$1 as bases, index as commandBases, ZenCore as default, indexPublic as errors, index$2 as interfaces, _export$1 as managers, _export as modules };
143
+ export { index$1 as bases, index as commandBases, indexPublic as errors, index$2 as interfaces, _export$1 as managers, _export as modules };
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "@zenflux/core",
3
- "version": "0.1.29",
3
+ "version": "0.1.30",
4
4
  "types": "dist/zenflux-core.d.ts",
5
5
  "type": "module",
6
6
  "files": [
7
7
  "dist",
8
- "types"
8
+ "src"
9
9
  ],
10
10
  "scripts": {
11
11
  "@z-core--test": "jest",
@@ -0,0 +1,64 @@
1
+ import { InitializeBase } from "@zenflux/core/src/bases/initialize-base";
2
+ import { Debugger } from "@zenflux/core/src/modules/debugger";
3
+
4
+ export abstract class CacheBase<CacheResult> extends InitializeBase {
5
+ private readonly cache: Map<string, CacheResult>;
6
+
7
+ private cacheDebugger: Debugger;
8
+
9
+ protected constructor( shouldDebugCache = true ) {
10
+ super();
11
+
12
+ this.cacheDebugger = new Debugger( this, undefined, shouldDebugCache );
13
+
14
+ this.cache = new Map<string, CacheResult>();
15
+ }
16
+
17
+ protected getCache( key: string ) {
18
+ this.cacheDebugger.log( this.getCache, `Getting cache for key: '${ key }'` );
19
+
20
+ const result = this.cache.get( key );
21
+
22
+ if ( result ) {
23
+ this.cacheDebugger.log( this.getCache, `Got cache for key: '${ key }'` );
24
+ this.cacheDebugger.dumpDown( this.setCache, result );
25
+ }
26
+
27
+ return result;
28
+ }
29
+
30
+ protected getCacheMap() {
31
+ return this.cache;
32
+ }
33
+
34
+ protected setCache( key: string, value: CacheResult ): void {
35
+ this.cacheDebugger.log( this.setCache, `Setting cache for key: '${ key }'` );
36
+
37
+ this.cacheDebugger.dumpDown( this.setCache, value );
38
+
39
+ this.cache.set( key, value );
40
+ }
41
+
42
+ protected deleteCache( key: string ): boolean {
43
+ this.cacheDebugger.log( this.deleteCache, `Deleting cache for key: '${ key }'` );
44
+
45
+ if ( !this.cache.has( key ) ) {
46
+ this.cacheDebugger.log( this.deleteCache, `Cache for key: '${ key }' does not exist` );
47
+
48
+ return false;
49
+ }
50
+
51
+ return this.cache.delete( key );
52
+ }
53
+
54
+ protected deleteCacheWithPrefix( prefix: string ): void {
55
+ this.cacheDebugger.log( this.deleteCacheWithPrefix, `Deleting cache prefix: '${ prefix }'` );
56
+
57
+ for ( const key of this.cache.keys() ) {
58
+ if ( key.startsWith( prefix ) ) {
59
+ this.deleteCache( key );
60
+ }
61
+ }
62
+ }
63
+ }
64
+
@@ -0,0 +1,96 @@
1
+ /**
2
+ * The `ControllerBase` class is an abstract base class responsible for managing commands and providing a structure
3
+ * for controllers or command spaces.
4
+ *
5
+ * @author Leonid Vinikov <leonidvinikov@gmail.com>
6
+ */
7
+ import { ObjectBase } from "./object-base";
8
+
9
+ import * as managers from "../managers/export";
10
+
11
+ import type { CommandPublic } from "../command-bases/command-public";
12
+ import type { CommandRestful } from "../command-bases/command-restful";
13
+ import type { CommandInternal } from "../command-bases/command-internal";
14
+
15
+ // noinspection TypeScriptAbstractClassConstructorCanBeMadeProtected
16
+
17
+ export abstract class ControllerBase extends ObjectBase {
18
+ private commands: { [ key: string ]: typeof CommandPublic };
19
+ private restful: { [ key: string ]: typeof CommandRestful };
20
+ private internal: { [ key: string ]: typeof CommandInternal };
21
+
22
+ public static getName() {
23
+ return "ZenFlux/Core/ControllerBase";
24
+ }
25
+
26
+ /**
27
+ * Constructor for `ControllerBase` instances.
28
+ * Initializes the base class and invokes the `initialize()` method.
29
+ */
30
+ public constructor() {
31
+ super();
32
+
33
+ // Initialize the controller
34
+ this.initialize();
35
+ }
36
+
37
+ /**
38
+ * Initializes the controller by calling the `register()` method and optionally the `setupHooks()` method.
39
+ */
40
+ protected initialize() {
41
+ // Register commands and command types
42
+ this.register();
43
+
44
+ // Optionally, set up hooks if the `setupHooks()` method is defined in derived classes
45
+ this.setupHooks && this.setupHooks();
46
+ }
47
+
48
+ /**
49
+ * Registers commands and command types by calling manager functions.
50
+ */
51
+ protected register() {
52
+ // Register public commands
53
+ this.commands = managers.commands.register( this.getCommands(), this ) as {
54
+ [ key: string ]: typeof CommandPublic
55
+ };
56
+
57
+ // Register RESTful commands
58
+ this.restful = managers.restful.register( this.getRestful(), this ) as {
59
+ [ key: string ]: typeof CommandRestful
60
+ };
61
+
62
+ // Register internal commands
63
+ this.internal = managers.internal.register( this.getInternal(), this ) as {
64
+ [ key: string ]: typeof CommandInternal
65
+ };
66
+ }
67
+
68
+ /**
69
+ * Retrieve the public commands associated with this controller.
70
+ * Derived classes can override this method to specify their own commands.
71
+ */
72
+ protected getCommands(): { [ key: string ]: typeof CommandPublic } {
73
+ return {};
74
+ }
75
+
76
+ /**
77
+ * Retrieve the RESTful commands associated with this controller.
78
+ * Derived classes can override this method to specify their own RESTful commands.
79
+ */
80
+ protected getRestful(): { [ key: string ]: typeof CommandRestful } {
81
+ return {};
82
+ }
83
+
84
+ /**
85
+ * Retrieve the internal commands associated with this controller.
86
+ * Derived classes can override this method to specify their own internal commands.
87
+ */
88
+ protected getInternal(): { [ key: string ]: typeof CommandInternal } {
89
+ return {};
90
+ }
91
+
92
+ /**
93
+ * A hook method that can be optionally overridden in derived classes to set up hooks or event listeners.
94
+ */
95
+ protected setupHooks?() {}
96
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * @author Leonid Vinikov <leonidvinikov@gmail.com>
3
+ */
4
+
5
+ export { ControllerBase } from "./controller-base";
6
+ export { ObjectBase } from "./object-base";
7
+ export { InitializeBase } from "./initialize-base";
8
+ export { SingletonBase } from "./singleton-base";
9
+ export { CacheBase } from "./cache-base";
@@ -0,0 +1,32 @@
1
+ import { ObjectBase } from "@zenflux/core/src/bases/object-base";
2
+
3
+ import { Logger } from "@zenflux/core/src/modules/logger";
4
+
5
+ export abstract class InitializeBase extends ObjectBase {
6
+ protected logger: Logger;
7
+
8
+ protected constructor( shouldInitialize = true ) {
9
+ super();
10
+
11
+ this.logger = new Logger( this );
12
+
13
+ if ( this.initialize && shouldInitialize ) {
14
+ this.initialize();
15
+ }
16
+ }
17
+
18
+ protected initialize?(): void;
19
+
20
+ // TODO: Find better place for this
21
+ protected debounce<T extends ( ...args: any[] ) => any>( func: T, delay: number ) {
22
+ let timeoutId: ReturnType<typeof setTimeout>;
23
+
24
+ return ( ...args: Parameters<T> ) => {
25
+ clearTimeout( timeoutId );
26
+
27
+ timeoutId = setTimeout( () => {
28
+ func.apply( this, args );
29
+ }, delay );
30
+ };
31
+ }
32
+ }
@@ -0,0 +1,55 @@
1
+ import { ForceMethodBase } from "../errors";
2
+
3
+ export abstract class ObjectBase {
4
+ private readonly id: string;
5
+ private readonly name: string = "__UNDEFINED_NAME__";
6
+
7
+ protected constructor() {
8
+ this.name = this.getName();
9
+
10
+ const timestamp = performance.now() * 1000000;
11
+ const random1 = BigInt( Math.floor( Math.random() * 1000000 ) );
12
+ const random2 = BigInt( Math.floor( Math.random() * 1000000 ) );
13
+
14
+ this.id = `${ timestamp }${ random1 }${ random2 }`;
15
+ }
16
+
17
+ public static getName(): string {
18
+ throw new ForceMethodBase( this.name, "getName" );
19
+ }
20
+
21
+ public static getSourcePath(): string {
22
+ throw new ForceMethodBase( this.name, "getSourcePath" );
23
+ }
24
+
25
+ public getName(): string {
26
+ return ( this.constructor as typeof ObjectBase ).getName();
27
+ }
28
+
29
+ public getUniqueId(): string {
30
+ return this.id;
31
+ }
32
+
33
+ public getInitialName(): string {
34
+ return this.name;
35
+ }
36
+
37
+ public getHierarchyNames(): string[] {
38
+ const classNames = [];
39
+ let obj = Object.getPrototypeOf( this );
40
+ let className: string;
41
+
42
+ while ( ( className = obj.getName() ) !== "Object" ) {
43
+ classNames.push( className );
44
+ obj = Object.getPrototypeOf( obj );
45
+
46
+ if ( obj.constructor === ObjectBase ) {
47
+ break;
48
+ }
49
+ }
50
+
51
+ return classNames;
52
+ }
53
+ }
54
+
55
+ export default ObjectBase;
@@ -0,0 +1,18 @@
1
+ import { InitializeBase } from "@zenflux/core/src/bases/initialize-base";
2
+
3
+ export abstract class SingletonBase extends InitializeBase {
4
+ private static instances: Map<any, any> = new Map();
5
+
6
+ protected constructor() {
7
+ super();
8
+ }
9
+
10
+ protected static getInstance<T extends SingletonBase>( this: new () => T ): T {
11
+ if ( !SingletonBase.instances.has( this ) ) {
12
+ SingletonBase.instances.set( this, new this() );
13
+ }
14
+
15
+ return SingletonBase.instances.get( this );
16
+ }
17
+ }
18
+