@zenflux/core 0.1.23 → 0.1.24

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.
@@ -3,4 +3,5 @@ import * as commandBases from "./command-bases";
3
3
  import * as errors from "./errors/index-public";
4
4
  import * as interfaces from "./interfaces";
5
5
  import * as managers from "./managers/export";
6
- export { bases, commandBases, errors, interfaces, managers, };
6
+ import * as modules from "./modules/export";
7
+ export { bases, commandBases, errors, interfaces, managers, modules, };
@@ -1,16 +1,15 @@
1
1
  /**
2
2
  * @author Leonid Vinikov <leonidvinikov@gmail.com>
3
3
  */
4
- import { bases, commandBases, errors, interfaces, managers } from "./exports-index";
5
- import { Logger } from "./modules/logger";
4
+ import { bases, commandBases, errors, interfaces, managers, modules } from "./exports-index";
6
5
  declare global {
7
6
  var __ZEN_CORE__IS_INITIALIZED__: boolean;
8
7
  }
9
8
  export declare const classes: {
10
- Logger: typeof Logger;
9
+ Logger: typeof modules.Logger;
11
10
  };
12
11
  export declare function initialize(config?: Partial<interfaces.IAPIConfig>): void;
13
12
  export declare function destroy(): void;
14
13
  export declare function onAfterInitialize(callback: () => void): void;
15
14
  export declare const config: interfaces.IAPIConfig;
16
- export { bases, commandBases, errors, interfaces, managers };
15
+ export { bases, commandBases, errors, interfaces, managers, modules };
@@ -0,0 +1,6 @@
1
+ export { EventBus } from "./event-bus/event-bus";
2
+ export { Logger } from "./logger/implementation";
3
+ export { createLogger } from "./logger/create-logger";
4
+ export { ServiceBase } from "./service/service-base";
5
+ export { ServiceLocator } from "./service/service-locator";
6
+ export { ServiceWithDependenciesBase } from "./service/service-with-dependencies-base";
@@ -0,0 +1,17 @@
1
+ import Logger from "./implementation";
2
+ import type { TCaller } from "../../interfaces/index";
3
+ type LoggerOptions = {
4
+ skipEventBusHook?: boolean;
5
+ repeatedly?: boolean;
6
+ };
7
+ export declare class EyeNoteLogger extends Logger {
8
+ private prepareLog;
9
+ log(caller: TCaller, message: string, ...params: unknown[]): void;
10
+ info(caller: TCaller, message: string, ...params: unknown[]): void;
11
+ debug(caller: TCaller, message: string, ...params: unknown[]): void;
12
+ warn(caller: TCaller, message: string, ...params: unknown[]): void;
13
+ error(caller: TCaller, message: string, ...params: unknown[]): void;
14
+ admin(caller: TCaller, message: string, ...params: unknown[]): void;
15
+ }
16
+ export declare const createLogger: (owner: string | object, options?: LoggerOptions) => EyeNoteLogger;
17
+ export {};
@@ -1,2 +1,3 @@
1
1
  export * from "./config";
2
+ export * from "./create-logger";
2
3
  export * from "./implementation";
@@ -1,6 +1,6 @@
1
1
  /**
2
- * Bundled with love using the help of @zenflux/cli toolkit v0.1.42
3
- * Bundle name: @zenflux/core fileName: 'zenflux-core', built at Thu Dec 11 2025 21:10:31 GMT+0200 (Israel Standard Time)
2
+ * Bundled with love using the help of @zenflux/cli toolkit v0.1.43
3
+ * Bundle name: @zenflux/core fileName: 'zenflux-core', built at Mon Feb 02 2026 16:17:37 GMT+0200 (Israel Standard Time)
4
4
  */
5
5
 
6
6
  'use strict';
@@ -8,6 +8,7 @@
8
8
  Object.defineProperty(exports, '__esModule', { value: true });
9
9
 
10
10
  var util = require('util');
11
+ var EventEmitter = require('events');
11
12
 
12
13
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
13
14
  function _interopNamespaceDefault(e) {
@@ -63,7 +64,7 @@ class Internal extends Commands{static getName(){return "ZenFlux/Core/Managers/I
63
64
 
64
65
  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={};
65
66
 
66
- var _export = /*#__PURE__*/Object.freeze({
67
+ var _export$1 = /*#__PURE__*/Object.freeze({
67
68
  __proto__: null,
68
69
  afterInitializeCallbacks: afterInitializeCallbacks,
69
70
  get commands () { return commands; },
@@ -104,6 +105,8 @@ let SimpleEventEmitter=class SimpleEventEmitter{listeners=new Map;on(event,callb
104
105
 
105
106
  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)}}
106
107
 
108
+ const isError=value=>value instanceof Error;const isSerializableObject=value=>{if(value===null){return false}if(Array.isArray(value)){return true}return typeof value==="object"&&!isError(value)};const formatPrimitive=value=>{if(typeof value==="symbol"){return value.toString()}if(typeof value==="bigint"){return value.toString()}return value};const buildErrorMetadata=error=>{const typed=error;return {name:error.name,message:error.message,stack:error.stack,cause:typed.cause}};class EyeNoteLogger extends Logger{prepareLog(caller,message,params){this.startsEmpty(caller);this.startsWith(caller,{message});if(params.length===0){return}const dropEntries={};const dropPayload={};params.forEach((param,index)=>{const key=`arg_${index}`;if(isError(param)){dropEntries[key]=param.message;dropPayload[key]=buildErrorMetadata(param);return}if(isSerializableObject(param)){this.dump(caller,{[key]:param});return}this.startsWith(caller,{[key]:formatPrimitive(param)});});if(Object.keys(dropEntries).length>0){this.drop(caller,dropEntries,dropPayload);}}log(caller,message,...params){this.prepareLog(caller,message,params);super.log(caller,message,...params);}info(caller,message,...params){this.prepareLog(caller,message,params);super.info(caller,message,...params);}debug(caller,message,...params){this.prepareLog(caller,message,params);super.debug(caller,message,...params);}warn(caller,message,...params){this.prepareLog(caller,message,params);super.warn(caller,message,...params);}error(caller,message,...params){this.prepareLog(caller,message,params);super.error(caller,message,...params);}admin(caller,message,...params){this.prepareLog(caller,message,params);super.admin(caller,message,...params);}}const createLogger=(owner,options)=>{return new EyeNoteLogger(owner,options)};
109
+
107
110
  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);}}}
108
111
 
109
112
  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)}}
@@ -144,9 +147,26 @@ __proto__: null,
144
147
  ForceMethodImplementation: ForceMethodImplementation
145
148
  });
146
149
 
150
+ class ServiceBase extends ObjectBase{logger;initialization;static getName(){return "ZenFlux/Core/Modules/ServiceBase"}constructor(...args){super();this.logger=new Logger(this);if(this.initialize){this.initialization={promise:this.initialize(),state:"pending"};this.initialization.promise.then(()=>this.initialization.state="resolved").catch(reason=>{this.initialization.state="rejected";this.initialization.reason=reason;});return}this.initialization={promise:Promise.resolve(),state:"resolved"};}isWithDependencies(){return false}getInitialization(){return this.initialization}}
151
+
152
+ class ServiceLocator extends InitializeBase{static instance=null;emitter=new EventEmitter;services=new Map;initializing=new Set;static getName(){return "Modules/ServiceLocator"}static get $(){if(!global.__zenflux_base_service_locator__){global.__zenflux_base_service_locator__=new this;}return global.__zenflux_base_service_locator__}register(service,...args){const serviceAsClass=service;if(this.services.has(serviceAsClass.getName())){throw new Error(`Service '${serviceAsClass.getName()}' is already registered`)}const serviceInstance=new service(...args);this.services.set(serviceInstance.getName(),serviceInstance);if(serviceInstance.isWithDependencies()){this.validateCircularDependencies(serviceInstance);}this.emitter.emit("service-registered",serviceInstance.getName());}unregister(serviceName){return this.services.delete(serviceName)}get(serviceName,options={silent:false}){if(!options.silent&&!this.services.has(serviceName)){throw new Error(`Service '${serviceName}' is not registered`)}return this.services.get(serviceName)}async waitFor(serviceName,options={}){options={silent:false,timeout:0,...options};const service=this.get(serviceName,{silent:!!options.silent});if(service&&service.getInitialization().state==="resolved"){return service}this.initializing.add(serviceName);const waitForService=this.createServicePromise(serviceName),waitForTimeout=this.createTimeoutPromise(serviceName,options.timeout,options.metadata);try{return await Promise.race([waitForService,waitForTimeout])}finally{this.initializing.delete(serviceName);}}async waitForAll(options={}){options={timeout:0,...options};const waitForServices=Array.from(this.services.keys()).map(serviceName=>this.waitFor(serviceName,options));await Promise.all(waitForServices);}createServicePromise(serviceName){return new Promise((resolve,reject)=>{const listener=registeredServiceName=>{if(registeredServiceName===serviceName){this.emitter.off("service-registered",listener);const service=this.get(serviceName),initialization=service.getInitialization();if(initialization.state==="resolved"){resolve(service);return}if(initialization.state==="rejected"){reject(initialization.reason);return}initialization.promise.then(()=>resolve(service)).catch(reject);}};this.services.has(serviceName)?listener(serviceName):this.emitter.on("service-registered",listener);})}createTimeoutPromise(serviceName,timeout=0,metadata){return new Promise((_,reject)=>setTimeout(()=>{const error=new ErrorWithMetadata(`Service '${serviceName}' initialization timed out`,metadata);reject(error);},timeout))}validateCircularDependencies(service){const visited=new Set,stack=new Set;const serviceName=service.getName();const hasCircularDependency=this.performDepthFirstSearch(serviceName,stack,visited);if(hasCircularDependency){throw new Error(`Circular dependency detected stack: ${Array.from(stack).join(" -> ")}
153
+ -> [current] -> ${serviceName}`)}}performDepthFirstSearch(currentServiceName,stack,visited){if(visited.has(currentServiceName)){return stack.has(currentServiceName)}visited.add(currentServiceName);stack.add(currentServiceName);const service=this.get(currentServiceName,{silent:true}),dependencies=service?.isWithDependencies()?this.getDependencies(service):[];for(const dependency of dependencies){if(this.performDepthFirstSearch(dependency,stack,visited)){return true}}stack.delete(currentServiceName);return false}getDependencies(service){return Object.values(service.getDependencies())}}
154
+
155
+ class ServiceWithDependenciesBase extends ServiceBase{services={};static getName(){return "Modules/ServiceBaseWithDependencies"}async initialize(){await super.initialize?.();const dependencies=Object.entries(this.getDependencies()).map(async([alias,serviceName])=>{return ServiceLocator.$.waitFor(serviceName,{internal:true,metadata:{source:this,fulfilled:this.services}}).then(service=>{this.services[alias]=service;return service})});await Promise.all(dependencies);}isWithDependencies(){return true}getServices(){return this.services}}
156
+
157
+ var _export = /*#__PURE__*/Object.freeze({
158
+ __proto__: null,
159
+ EventBus: EventBus,
160
+ Logger: Logger,
161
+ ServiceBase: ServiceBase,
162
+ ServiceLocator: ServiceLocator,
163
+ ServiceWithDependenciesBase: ServiceWithDependenciesBase,
164
+ createLogger: createLogger
165
+ });
166
+
147
167
  var _package = {
148
168
  "name": "@zenflux/core",
149
- "version": "0.1.21",
169
+ "version": "0.1.23",
150
170
  "types": "dist/zenflux-core.d.ts",
151
171
  "type": "module",
152
172
  "files": [
@@ -194,7 +214,7 @@ var _package = {
194
214
  }
195
215
  };
196
216
  const name = "@zenflux/core";
197
- const version = "0.1.21";
217
+ const version = "0.1.23";
198
218
  const types = "dist/zenflux-core.d.ts";
199
219
  const type = "module";
200
220
  const files = ["dist","types"];
@@ -216,7 +236,8 @@ destroy: destroy,
216
236
  errors: indexPublic,
217
237
  initialize: initialize,
218
238
  interfaces: index$2,
219
- managers: _export,
239
+ managers: _export$1,
240
+ modules: _export,
220
241
  onAfterInitialize: onAfterInitialize
221
242
  });
222
243
 
@@ -227,4 +248,5 @@ exports.commandBases = index;
227
248
  exports.default = ZenCore;
228
249
  exports.errors = indexPublic;
229
250
  exports.interfaces = index$2;
230
- exports.managers = _export;
251
+ exports.managers = _export$1;
252
+ exports.modules = _export;
@@ -23,7 +23,7 @@ declare abstract class CacheBase<CacheResult> extends InitializeBase {
23
23
  }
24
24
 
25
25
  declare const classes: {
26
- Logger: typeof Logger;
26
+ Logger: typeof modules.Logger;
27
27
  };
28
28
 
29
29
  declare abstract class CommandBase extends ObjectBase {
@@ -203,6 +203,8 @@ declare class Controllers extends ObjectBase {
203
203
 
204
204
  declare let controllers: Controllers;
205
205
 
206
+ declare const createLogger: (owner: string | object, options?: LoggerOptions_2) => EyeNoteLogger;
207
+
206
208
  declare function destroy(): void;
207
209
 
208
210
  declare function destroy_2(): void;
@@ -230,6 +232,44 @@ declare namespace errors {
230
232
  }
231
233
  export { errors }
232
234
 
235
+ declare class EventBus extends ObjectBase {
236
+ protected static instance: EventBus | null;
237
+ private objects;
238
+ private eventEmitter;
239
+ private lastEmittedEvents;
240
+ static getName(): string;
241
+ static getInstance(): EventBus;
242
+ static get $(): EventBus;
243
+ getObjectNames(): string[];
244
+ getEventNames(): void;
245
+ getEventName(objectName: string, methodName: string): string;
246
+ on(objectName: string, methodName: string, callback: (...args: any[]) => void): void;
247
+ /**
248
+ * Function onCalledBeforeDoInvoke(): The difference between this function and on()
249
+ * is that this function will call the callback if the event already happened.
250
+ */
251
+ onCalledBeforeDoInvoke(objectName: string, methodName: string, callback: (...args: any[]) => void): void;
252
+ off(objectName: string, methodName: string, callback: (...args: any[]) => void): void;
253
+ register<T extends ObjectBase>(object: T, methods: Function[]): void;
254
+ registerMultiInstances<T extends ObjectBase>(object: T, methods: Function[]): void;
255
+ unregister(objectName: string): false | undefined;
256
+ private unhookObject;
257
+ private unhook;
258
+ private emit;
259
+ private hook;
260
+ private ensureFunction;
261
+ }
262
+
263
+ declare class EyeNoteLogger extends Logger {
264
+ private prepareLog;
265
+ log(caller: TCaller, message: string, ...params: unknown[]): void;
266
+ info(caller: TCaller, message: string, ...params: unknown[]): void;
267
+ debug(caller: TCaller, message: string, ...params: unknown[]): void;
268
+ warn(caller: TCaller, message: string, ...params: unknown[]): void;
269
+ error(caller: TCaller, message: string, ...params: unknown[]): void;
270
+ admin(caller: TCaller, message: string, ...params: unknown[]): void;
271
+ }
272
+
233
273
  declare class ForceMethodImplementation extends Error {
234
274
  constructor(context: ObjectBase | typeof ObjectBase | string, methodName: string);
235
275
  }
@@ -464,6 +504,11 @@ declare interface LoggerOptions {
464
504
  repeatedly?: boolean;
465
505
  }
466
506
 
507
+ declare type LoggerOptions_2 = {
508
+ skipEventBusHook?: boolean;
509
+ repeatedly?: boolean;
510
+ };
511
+
467
512
  declare interface LoggerOutputEvent {
468
513
  logger: LoggerBrowserInfra;
469
514
  namespace: string;
@@ -505,6 +550,18 @@ declare namespace managers {
505
550
  }
506
551
  export { managers }
507
552
 
553
+ declare namespace modules {
554
+ export {
555
+ EventBus,
556
+ Logger,
557
+ createLogger,
558
+ ServiceBase,
559
+ ServiceLocator,
560
+ ServiceWithDependenciesBase
561
+ }
562
+ }
563
+ export { modules }
564
+
508
565
  declare abstract class ObjectBase {
509
566
  private readonly id;
510
567
  private readonly name;
@@ -538,6 +595,61 @@ declare class Restful extends Commands {
538
595
 
539
596
  declare let restful: Restful;
540
597
 
598
+ declare abstract class ServiceBase extends ObjectBase {
599
+ protected logger: Logger;
600
+ private readonly initialization;
601
+ static getName(): string;
602
+ constructor(...args: any[]);
603
+ protected initialize?(): Promise<void>;
604
+ isWithDependencies(): boolean;
605
+ getInitialization(): {
606
+ promise: Promise<void>;
607
+ state: "pending" | "resolved" | "rejected";
608
+ reason?: Error;
609
+ };
610
+ }
611
+
612
+ declare class ServiceLocator extends InitializeBase {
613
+ protected static instance: ServiceLocator | null;
614
+ private emitter;
615
+ private services;
616
+ private initializing;
617
+ static getName(): string;
618
+ static get $(): ServiceLocator;
619
+ register<T extends ServiceBase>(service: new (...args: any[]) => T, ...args: any[]): void;
620
+ unregister(serviceName: string): boolean;
621
+ get<T extends ServiceBase>(serviceName: string, options?: {
622
+ silent: boolean;
623
+ }): T;
624
+ waitFor<T extends ServiceBase>(serviceName: string, options?: {
625
+ timeout?: number;
626
+ metadata?: any;
627
+ internal?: boolean;
628
+ silent?: boolean;
629
+ }): Promise<T>;
630
+ waitForAll(options?: {
631
+ timeout?: number;
632
+ metadata?: any;
633
+ internal?: boolean;
634
+ }): Promise<void>;
635
+ private createServicePromise;
636
+ private createTimeoutPromise;
637
+ private validateCircularDependencies;
638
+ private performDepthFirstSearch;
639
+ private getDependencies;
640
+ }
641
+
642
+ declare abstract class ServiceWithDependenciesBase<D extends {
643
+ [key: string]: ServiceBase;
644
+ }> extends ServiceBase {
645
+ protected services: Required<D>;
646
+ static getName(): string;
647
+ abstract getDependencies(): TServicesNonEmpty<TServiceNameDependencies<D>>;
648
+ protected initialize(): Promise<void>;
649
+ isWithDependencies(): boolean;
650
+ getServices(): Required<D>;
651
+ }
652
+
541
653
  declare abstract class SingletonBase extends InitializeBase {
542
654
  private static instances;
543
655
  protected constructor();
@@ -559,6 +671,14 @@ declare type TResponseFilterCallbackType = (text: string) => string;
559
671
 
560
672
  declare type TResponseHandlerCallbackType = (text: string) => boolean;
561
673
 
674
+ declare type TServiceName = string;
675
+
676
+ declare type TServiceNameDependencies<T> = {
677
+ [K in keyof T]: TServiceName;
678
+ };
679
+
680
+ declare type TServicesNonEmpty<T> = keyof T extends never ? "Error: Services are required" : T;
681
+
562
682
  declare namespace ZenCore {
563
683
  export {
564
684
  initialize,
@@ -570,7 +690,8 @@ declare namespace ZenCore {
570
690
  commandBases,
571
691
  errors,
572
692
  interfaces,
573
- managers
693
+ managers,
694
+ modules
574
695
  }
575
696
  }
576
697
  export default ZenCore;
@@ -1,9 +1,10 @@
1
1
  /**
2
- * Bundled with love using the help of @zenflux/cli toolkit v0.1.42
3
- * Bundle name: @zenflux/core fileName: 'zenflux-core', built at Thu Dec 11 2025 21:10:31 GMT+0200 (Israel Standard Time)
2
+ * Bundled with love using the help of @zenflux/cli toolkit v0.1.43
3
+ * Bundle name: @zenflux/core fileName: 'zenflux-core', built at Mon Feb 02 2026 16:17:37 GMT+0200 (Israel Standard Time)
4
4
  */
5
5
 
6
6
  import * as util from 'util';
7
+ import EventEmitter from 'events';
7
8
 
8
9
  class CommandAlreadyRegistered extends Error{constructor(command){super(`Command: '${command.getName()}' is already registered`);}}
9
10
 
@@ -39,7 +40,7 @@ class Internal extends Commands{static getName(){return "ZenFlux/Core/Managers/I
39
40
 
40
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={};
41
42
 
42
- var _export = /*#__PURE__*/Object.freeze({
43
+ var _export$1 = /*#__PURE__*/Object.freeze({
43
44
  __proto__: null,
44
45
  afterInitializeCallbacks: afterInitializeCallbacks,
45
46
  get commands () { return commands; },
@@ -80,6 +81,8 @@ let SimpleEventEmitter=class SimpleEventEmitter{listeners=new Map;on(event,callb
80
81
 
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)}}
82
83
 
84
+ const isError=value=>value instanceof Error;const isSerializableObject=value=>{if(value===null){return false}if(Array.isArray(value)){return true}return typeof value==="object"&&!isError(value)};const formatPrimitive=value=>{if(typeof value==="symbol"){return value.toString()}if(typeof value==="bigint"){return value.toString()}return value};const buildErrorMetadata=error=>{const typed=error;return {name:error.name,message:error.message,stack:error.stack,cause:typed.cause}};class EyeNoteLogger extends Logger{prepareLog(caller,message,params){this.startsEmpty(caller);this.startsWith(caller,{message});if(params.length===0){return}const dropEntries={};const dropPayload={};params.forEach((param,index)=>{const key=`arg_${index}`;if(isError(param)){dropEntries[key]=param.message;dropPayload[key]=buildErrorMetadata(param);return}if(isSerializableObject(param)){this.dump(caller,{[key]:param});return}this.startsWith(caller,{[key]:formatPrimitive(param)});});if(Object.keys(dropEntries).length>0){this.drop(caller,dropEntries,dropPayload);}}log(caller,message,...params){this.prepareLog(caller,message,params);super.log(caller,message,...params);}info(caller,message,...params){this.prepareLog(caller,message,params);super.info(caller,message,...params);}debug(caller,message,...params){this.prepareLog(caller,message,params);super.debug(caller,message,...params);}warn(caller,message,...params){this.prepareLog(caller,message,params);super.warn(caller,message,...params);}error(caller,message,...params){this.prepareLog(caller,message,params);super.error(caller,message,...params);}admin(caller,message,...params){this.prepareLog(caller,message,params);super.admin(caller,message,...params);}}const createLogger=(owner,options)=>{return new EyeNoteLogger(owner,options)};
85
+
83
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);}}}
84
87
 
85
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)}}
@@ -120,9 +123,26 @@ __proto__: null,
120
123
  ForceMethodImplementation: ForceMethodImplementation
121
124
  });
122
125
 
126
+ class ServiceBase extends ObjectBase{logger;initialization;static getName(){return "ZenFlux/Core/Modules/ServiceBase"}constructor(...args){super();this.logger=new Logger(this);if(this.initialize){this.initialization={promise:this.initialize(),state:"pending"};this.initialization.promise.then(()=>this.initialization.state="resolved").catch(reason=>{this.initialization.state="rejected";this.initialization.reason=reason;});return}this.initialization={promise:Promise.resolve(),state:"resolved"};}isWithDependencies(){return false}getInitialization(){return this.initialization}}
127
+
128
+ class ServiceLocator extends InitializeBase{static instance=null;emitter=new EventEmitter;services=new Map;initializing=new Set;static getName(){return "Modules/ServiceLocator"}static get $(){if(!global.__zenflux_base_service_locator__){global.__zenflux_base_service_locator__=new this;}return global.__zenflux_base_service_locator__}register(service,...args){const serviceAsClass=service;if(this.services.has(serviceAsClass.getName())){throw new Error(`Service '${serviceAsClass.getName()}' is already registered`)}const serviceInstance=new service(...args);this.services.set(serviceInstance.getName(),serviceInstance);if(serviceInstance.isWithDependencies()){this.validateCircularDependencies(serviceInstance);}this.emitter.emit("service-registered",serviceInstance.getName());}unregister(serviceName){return this.services.delete(serviceName)}get(serviceName,options={silent:false}){if(!options.silent&&!this.services.has(serviceName)){throw new Error(`Service '${serviceName}' is not registered`)}return this.services.get(serviceName)}async waitFor(serviceName,options={}){options={silent:false,timeout:0,...options};const service=this.get(serviceName,{silent:!!options.silent});if(service&&service.getInitialization().state==="resolved"){return service}this.initializing.add(serviceName);const waitForService=this.createServicePromise(serviceName),waitForTimeout=this.createTimeoutPromise(serviceName,options.timeout,options.metadata);try{return await Promise.race([waitForService,waitForTimeout])}finally{this.initializing.delete(serviceName);}}async waitForAll(options={}){options={timeout:0,...options};const waitForServices=Array.from(this.services.keys()).map(serviceName=>this.waitFor(serviceName,options));await Promise.all(waitForServices);}createServicePromise(serviceName){return new Promise((resolve,reject)=>{const listener=registeredServiceName=>{if(registeredServiceName===serviceName){this.emitter.off("service-registered",listener);const service=this.get(serviceName),initialization=service.getInitialization();if(initialization.state==="resolved"){resolve(service);return}if(initialization.state==="rejected"){reject(initialization.reason);return}initialization.promise.then(()=>resolve(service)).catch(reject);}};this.services.has(serviceName)?listener(serviceName):this.emitter.on("service-registered",listener);})}createTimeoutPromise(serviceName,timeout=0,metadata){return new Promise((_,reject)=>setTimeout(()=>{const error=new ErrorWithMetadata(`Service '${serviceName}' initialization timed out`,metadata);reject(error);},timeout))}validateCircularDependencies(service){const visited=new Set,stack=new Set;const serviceName=service.getName();const hasCircularDependency=this.performDepthFirstSearch(serviceName,stack,visited);if(hasCircularDependency){throw new Error(`Circular dependency detected stack: ${Array.from(stack).join(" -> ")}
129
+ -> [current] -> ${serviceName}`)}}performDepthFirstSearch(currentServiceName,stack,visited){if(visited.has(currentServiceName)){return stack.has(currentServiceName)}visited.add(currentServiceName);stack.add(currentServiceName);const service=this.get(currentServiceName,{silent:true}),dependencies=service?.isWithDependencies()?this.getDependencies(service):[];for(const dependency of dependencies){if(this.performDepthFirstSearch(dependency,stack,visited)){return true}}stack.delete(currentServiceName);return false}getDependencies(service){return Object.values(service.getDependencies())}}
130
+
131
+ class ServiceWithDependenciesBase extends ServiceBase{services={};static getName(){return "Modules/ServiceBaseWithDependencies"}async initialize(){await super.initialize?.();const dependencies=Object.entries(this.getDependencies()).map(async([alias,serviceName])=>{return ServiceLocator.$.waitFor(serviceName,{internal:true,metadata:{source:this,fulfilled:this.services}}).then(service=>{this.services[alias]=service;return service})});await Promise.all(dependencies);}isWithDependencies(){return true}getServices(){return this.services}}
132
+
133
+ var _export = /*#__PURE__*/Object.freeze({
134
+ __proto__: null,
135
+ EventBus: EventBus,
136
+ Logger: Logger,
137
+ ServiceBase: ServiceBase,
138
+ ServiceLocator: ServiceLocator,
139
+ ServiceWithDependenciesBase: ServiceWithDependenciesBase,
140
+ createLogger: createLogger
141
+ });
142
+
123
143
  var _package = {
124
144
  "name": "@zenflux/core",
125
- "version": "0.1.21",
145
+ "version": "0.1.23",
126
146
  "types": "dist/zenflux-core.d.ts",
127
147
  "type": "module",
128
148
  "files": [
@@ -170,7 +190,7 @@ var _package = {
170
190
  }
171
191
  };
172
192
  const name = "@zenflux/core";
173
- const version = "0.1.21";
193
+ const version = "0.1.23";
174
194
  const types = "dist/zenflux-core.d.ts";
175
195
  const type = "module";
176
196
  const files = ["dist","types"];
@@ -192,10 +212,11 @@ destroy: destroy,
192
212
  errors: indexPublic,
193
213
  initialize: initialize,
194
214
  interfaces: index$2,
195
- managers: _export,
215
+ managers: _export$1,
216
+ modules: _export,
196
217
  onAfterInitialize: onAfterInitialize
197
218
  });
198
219
 
199
220
  if(!globalThis?.zCore){globalThis.zCore=ZenCore;}
200
221
 
201
- export { index$1 as bases, index as commandBases, ZenCore as default, indexPublic as errors, index$2 as interfaces, _export as managers };
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 };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zenflux/core",
3
- "version": "0.1.23",
3
+ "version": "0.1.24",
4
4
  "types": "dist/zenflux-core.d.ts",
5
5
  "type": "module",
6
6
  "files": [