@zenflux/core 0.1.16 → 0.1.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
# @zenflux/core
|
|
2
|
+
|
|
3
|
+
Core runtime layer for the ZenFlux ecosystem. It provides the building blocks for registering controllers, running commands (public, internal, RESTful), HTTP client helpers, logging, and lifecycle hooks that wire everything together.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
- Command registry with before/after hooks (data + UI) and cross-command triggers.
|
|
7
|
+
- Controller base that auto-registers public, internal, and RESTful commands.
|
|
8
|
+
- RESTful manager built on `fetch`, with pluggable error/response handlers.
|
|
9
|
+
- Lightweight logger class exposed via `zCore.classes.Logger`.
|
|
10
|
+
- Simple lifecycle helpers: `initialize`, `destroy`, `onAfterInitialize`.
|
|
11
|
+
|
|
12
|
+
## Installation
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
bun add @zenflux/core
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Quick start
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
import Core, { initialize, managers, bases, commandBases } from "@zenflux/core";
|
|
22
|
+
|
|
23
|
+
initialize({
|
|
24
|
+
baseURL: "https://api.example.com",
|
|
25
|
+
requestInit: { credentials: "include" },
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
class UsersController extends bases.ControllerBase {
|
|
29
|
+
protected getRestful() {
|
|
30
|
+
return { GetUser };
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
class GetUser extends commandBases.CommandRestful {
|
|
35
|
+
static getName() {
|
|
36
|
+
return "users.get";
|
|
37
|
+
}
|
|
38
|
+
getEndpoint() {
|
|
39
|
+
return "/v1/users/{id}";
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
new UsersController();
|
|
44
|
+
|
|
45
|
+
const user = await managers.restful.get("users.get", { id: 42 });
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
### Lifecycle-aware hooks
|
|
49
|
+
|
|
50
|
+
```ts
|
|
51
|
+
import { managers } from "@zenflux/core";
|
|
52
|
+
|
|
53
|
+
managers.commands.onAfter("users.get", (_args) => {
|
|
54
|
+
console.info("User fetched, refresh UI");
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
managers.commands.onAfterAffect("users.get", "analytics.track");
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
## REST handlers
|
|
61
|
+
|
|
62
|
+
You can intercept every REST call made through `managers.restful`:
|
|
63
|
+
|
|
64
|
+
```ts
|
|
65
|
+
import { interfaces, managers } from "@zenflux/core";
|
|
66
|
+
|
|
67
|
+
const { E_RESPONSE_HANDLER_TYPE } = interfaces;
|
|
68
|
+
|
|
69
|
+
managers.restful.setHandler(E_RESPONSE_HANDLER_TYPE.ERROR_HANDLER, (error) => {
|
|
70
|
+
console.error("API error", error);
|
|
71
|
+
return false; // return true to swallow the error
|
|
72
|
+
});
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
## Configuration (initialize)
|
|
76
|
+
- `version` (string, required): usually pulled from `package.json`.
|
|
77
|
+
- `baseURL` (string, optional): prepended to every RESTful endpoint.
|
|
78
|
+
- `requestInit` (RequestInit, optional): defaults to `{ credentials: "include" }`; merged per request.
|
|
79
|
+
|
|
80
|
+
## Command types at a glance
|
|
81
|
+
- `CommandPublic`: UI/data commands callable via `managers.commands.run()`.
|
|
82
|
+
- `CommandRestful`: wraps an HTTP call; use `managers.restful.get|create|update|delete()`.
|
|
83
|
+
- `CommandInternal`: internal orchestration; accessed through `managers.internal`.
|
|
84
|
+
|
|
85
|
+
```ts
|
|
86
|
+
// Creating data via REST
|
|
87
|
+
await managers.restful.create("users.create", { name: "Ava" });
|
|
88
|
+
|
|
89
|
+
// Updating with PATCH
|
|
90
|
+
await managers.restful.update("users.update", { id: 5, name: "Ava B" });
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
### Public command example
|
|
94
|
+
|
|
95
|
+
```ts
|
|
96
|
+
import { bases, commandBases } from "@zenflux/core";
|
|
97
|
+
|
|
98
|
+
class PostsController extends bases.ControllerBase {
|
|
99
|
+
protected getCommands() {
|
|
100
|
+
return { ListPosts };
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
class ListPosts extends commandBases.CommandPublic {
|
|
105
|
+
static getName() {
|
|
106
|
+
return "posts.list";
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
protected async apply() {
|
|
110
|
+
// use managers, services, or fetch directly
|
|
111
|
+
return [{ id: 1, title: "Hello" }];
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
new PostsController();
|
|
116
|
+
const posts = await managers.commands.run("posts.list");
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
## TypeScript & bundling
|
|
120
|
+
- ESM-first (`"type": "module"`); CJS builds available via `exports.default`.
|
|
121
|
+
- Deep imports for debugging are exposed in `exports` (e.g. `@zenflux/core/src/bases`).
|
|
122
|
+
- Types are shipped at `dist/zenflux-core.d.ts`.
|
|
123
|
+
|
|
124
|
+
## Core concepts
|
|
125
|
+
- **Commands**: atomic units of work; can be public, internal, or RESTful.
|
|
126
|
+
- **Controllers**: group commands and register them with managers automatically.
|
|
127
|
+
- **Managers**: orchestrate command lookup, execution, hooks, and REST plumbing.
|
|
128
|
+
- **Logger**: structured logging with per-instance ids; available via `classes.Logger`.
|
|
129
|
+
- **Globals**: in dev, exported as `globalThis.zCore` for quick introspection.
|
|
130
|
+
|
|
131
|
+
## API surface (cheat sheet)
|
|
132
|
+
- `managers.commands.run(name, args?, options?)` – execute public/internal commands.
|
|
133
|
+
- `managers.restful.get|create|update|delete(name, args?, options?)` – HTTP-backed commands.
|
|
134
|
+
- `managers.commands.onBefore / onAfter / onAfterOnce / onAfterAffect / onBeforeUI / onAfterUI` – hook orchestration.
|
|
135
|
+
- `managers.commands.getLogger()` – logger bound to the command manager.
|
|
136
|
+
- `bases.ControllerBase` – subclass and override `getCommands/getRestful/getInternal`.
|
|
137
|
+
- `classes.Logger` – lightweight logger; supports `startsWith`, `drop`, `log`, etc.
|
|
138
|
+
|
|
139
|
+
## Command lifecycle (data + UI)
|
|
140
|
+
1) `managers.*.run()` attaches the command instance and stores args.
|
|
141
|
+
2) `onBefore` + `onBeforeUI` fire (UI hooks are kept separate).
|
|
142
|
+
3) `apply()` inside your command executes (do your work here).
|
|
143
|
+
4) `onAfter / onAfterUI` fire; `onAfterOnce` is consumed.
|
|
144
|
+
5) `onAfterAffect` triggers dependent commands (fan-out).
|
|
145
|
+
6) Command detaches; trace kept in `Commands.trace`.
|
|
146
|
+
|
|
147
|
+
## REST handlers (types)
|
|
148
|
+
- `ERROR_HANDLER` – inspect/stop errors (return `true` to swallow).
|
|
149
|
+
- `RESPONSE_FILTER` – transform raw text before JSON parse.
|
|
150
|
+
- `RESPONSE_HANDLER` – inspect parsed data (return `true` to swallow).
|
|
151
|
+
Register via `managers.restful.setHandler(E_RESPONSE_HANDLER_TYPE.*, cb)`.
|
|
152
|
+
|
|
153
|
+
### Internal command example
|
|
154
|
+
|
|
155
|
+
```ts
|
|
156
|
+
import { bases, commandBases } from "@zenflux/core";
|
|
157
|
+
|
|
158
|
+
class SystemController extends bases.ControllerBase {
|
|
159
|
+
protected getInternal() {
|
|
160
|
+
return { WarmCache };
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
class WarmCache extends commandBases.CommandInternal {
|
|
165
|
+
static getName() {
|
|
166
|
+
return "system.warmCache";
|
|
167
|
+
}
|
|
168
|
+
protected async apply() {
|
|
169
|
+
// populate LRU, prime REST calls, etc.
|
|
170
|
+
return true;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
new SystemController();
|
|
175
|
+
await managers.internal.run("system.warmCache");
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
## Controller checklist
|
|
179
|
+
- Define a controller per bounded context (e.g., Users, Billing).
|
|
180
|
+
- Implement `getCommands/getRestful/getInternal` returning plain object maps.
|
|
181
|
+
- Use `setupHooks` to wire UI/data hooks in one place.
|
|
182
|
+
- Keep RESTful commands thin—validation + endpoint, leave data shaping to callers.
|
|
183
|
+
- Prefer small, composable commands; fans out via `onAfterAffect`.
|
|
184
|
+
|
|
185
|
+
## Configuration defaults
|
|
186
|
+
```ts
|
|
187
|
+
initialize({
|
|
188
|
+
version: pkg.version,
|
|
189
|
+
baseURL: "http://localhost",
|
|
190
|
+
requestInit: { credentials: "include" },
|
|
191
|
+
});
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
## Performance & debugging
|
|
195
|
+
- Use `Commands.trace` to inspect recent command flow.
|
|
196
|
+
- Keep hooks side-effect free where possible; heavy work stays in commands.
|
|
197
|
+
- Logger spans (`startsWith`/`drop`) help spot slow sections.
|
|
198
|
+
- In dev, read `globalThis.zCore.managers` to poke running instances.
|
|
199
|
+
|
|
200
|
+
## Known limitations
|
|
201
|
+
- No built-in retries/backoff for REST; add in your handlers.
|
|
202
|
+
- Hooks are synchronous; await inside callbacks if you need async chaining.
|
|
203
|
+
- Global `zCore` is exposed only in development builds.
|
|
204
|
+
- REST client assumes `fetch` is available (polyfill in Node if needed).
|
|
205
|
+
|
|
206
|
+
## Folder map (high level)
|
|
207
|
+
- `src/bases` – abstract bases for objects, controllers, commands.
|
|
208
|
+
- `src/command-bases` – public/internal/RESTful command base classes.
|
|
209
|
+
- `src/managers` – command/REST/controller/internal managers + lifecycle.
|
|
210
|
+
- `src/clients` – HTTP client wrapper used by REST manager.
|
|
211
|
+
- `src/modules/logger` – logger implementation and config.
|
|
212
|
+
- `src/interfaces` – shared enums, types, and config contracts.
|
|
213
|
+
|
|
214
|
+
## Error handling patterns
|
|
215
|
+
- REST: set `ERROR_HANDLER` to normalize API errors into domain objects; throw to bubble.
|
|
216
|
+
- Commands: throw your own error classes; subscribe with `onAfter` to centralize toast/UI.
|
|
217
|
+
- Controllers: validate args in `apply` and short-circuit with informative errors.
|
|
218
|
+
- `CommandNotFound` / `CommandAlreadyRegistered` guard misconfiguration early.
|
|
219
|
+
|
|
220
|
+
## Logging tips
|
|
221
|
+
- Create one logger per service/command: `new classes.Logger(MyCommand)`.
|
|
222
|
+
- Use `startsWith` for timed spans and argument snapshots; `drop` to close them.
|
|
223
|
+
- In browsers, rely on `globalThis.zCore` to inspect `managers` and `Logger` output quickly.
|
|
224
|
+
|
|
225
|
+
## Minimal setup (repo)
|
|
226
|
+
```bash
|
|
227
|
+
# install deps
|
|
228
|
+
bun install
|
|
229
|
+
# build only core
|
|
230
|
+
bun run --filter @zenflux/core @z-core--build
|
|
231
|
+
# link locally in another package
|
|
232
|
+
bun link ./packages/zenflux-core
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
## Testing
|
|
236
|
+
- Unit/integration: `bun run --filter @zenflux/core @z-core--test`.
|
|
237
|
+
- Add new commands with small fixtures under `packages/zenflux-core/test`.
|
|
238
|
+
- Prefer deterministic tests; mock `fetch` for REST managers.
|
|
239
|
+
|
|
240
|
+
## FAQ
|
|
241
|
+
- *Do I have to call `initialize`?* Yes—managers rely on it; call once at app boot.
|
|
242
|
+
- *Can I skip globals?* In production bundlers, `zCore` is not required; ignore it.
|
|
243
|
+
- *How do I extend logging?* Wrap `classes.Logger` or pipe its output to your collector.
|
|
244
|
+
- *Is CJS supported?* Yes via `exports.default`; ESM is the primary target.
|
|
245
|
+
- *Can I deep-import source files?* Yes for debugging via `@zenflux/core/src/*` paths.
|
|
246
|
+
|
|
247
|
+
## Logging
|
|
248
|
+
|
|
249
|
+
```ts
|
|
250
|
+
import { classes } from "@zenflux/core";
|
|
251
|
+
|
|
252
|
+
const logger = new classes.Logger(MyService);
|
|
253
|
+
logger.log("Ready"); // includes class name and unique instance id
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
## Lifecycle
|
|
257
|
+
- `initialize(config)` – sets up managers; config accepts `version`, optional `baseURL`, and `requestInit`.
|
|
258
|
+
- `destroy()` – clears managers and global state.
|
|
259
|
+
- `onAfterInitialize(cb)` – run a callback after core initialization.
|
|
260
|
+
|
|
261
|
+
## Local development
|
|
262
|
+
|
|
263
|
+
Run from repo root:
|
|
264
|
+
|
|
265
|
+
```bash
|
|
266
|
+
bun run --filter @zenflux/core @z-core--build # build
|
|
267
|
+
bun run --filter @zenflux/core @z-core--test # tests
|
|
268
|
+
bun run --filter @zenflux/core @z-core--dev # watch
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
---
|
|
272
|
+
|
|
273
|
+
While developing, `@zenflux/core` exposes itself as `globalThis.zCore` to aid debugging in environments without import tooling. Use it only for development tooling or debugging.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { LoggerBrowserInfra } from "./logger-browser-infra";
|
|
1
|
+
import { LoggerBrowserInfra, type LoggerOutputSubscriber } from "./logger-browser-infra";
|
|
2
2
|
import type * as interfaces from "../../interfaces";
|
|
3
3
|
type ICaller = interfaces.TCaller;
|
|
4
4
|
interface LoggerOptions {
|
|
@@ -16,6 +16,7 @@ export declare class Logger extends LoggerBrowserInfra implements interfaces.ILo
|
|
|
16
16
|
static getName(): string;
|
|
17
17
|
static getLogLevelString(): string;
|
|
18
18
|
static getLogLevel(): number;
|
|
19
|
+
static attachOutputListener(listener: LoggerOutputSubscriber): () => void;
|
|
19
20
|
static isDebugEnabled(): boolean;
|
|
20
21
|
constructor(owner: any, options?: LoggerOptions);
|
|
21
22
|
addMessagePrefix(prefix: string): void;
|
|
@@ -45,6 +46,7 @@ export declare class Logger extends LoggerBrowserInfra implements interfaces.ILo
|
|
|
45
46
|
private getStackTrace;
|
|
46
47
|
getPreviousSource(): string;
|
|
47
48
|
private writeLog;
|
|
49
|
+
private createBrowserFormat;
|
|
48
50
|
private formatTime;
|
|
49
51
|
}
|
|
50
52
|
export default Logger;
|
|
@@ -1,5 +1,28 @@
|
|
|
1
1
|
import { ObjectBase } from "../../bases/object-base";
|
|
2
2
|
import type * as interfaces from "../../interfaces";
|
|
3
|
+
export type LoggerOutputLevel = "log" | "info" | "debug" | "warn" | "error" | "admin";
|
|
4
|
+
export interface LoggerOutputFormat {
|
|
5
|
+
format: string;
|
|
6
|
+
styles: string[];
|
|
7
|
+
}
|
|
8
|
+
export interface LoggerOutputMetadata {
|
|
9
|
+
id?: string;
|
|
10
|
+
level?: LoggerOutputLevel;
|
|
11
|
+
namespace?: string;
|
|
12
|
+
callerName?: string;
|
|
13
|
+
message?: string;
|
|
14
|
+
messagePrefix?: string;
|
|
15
|
+
payload?: unknown;
|
|
16
|
+
timestamp?: number;
|
|
17
|
+
formatted?: LoggerOutputFormat;
|
|
18
|
+
}
|
|
19
|
+
export interface LoggerOutputEvent {
|
|
20
|
+
logger: LoggerBrowserInfra;
|
|
21
|
+
namespace: string;
|
|
22
|
+
args: any[];
|
|
23
|
+
metadata?: LoggerOutputMetadata;
|
|
24
|
+
}
|
|
25
|
+
export type LoggerOutputSubscriber = (event: LoggerOutputEvent) => void;
|
|
3
26
|
export declare abstract class LoggerBrowserInfra extends ObjectBase {
|
|
4
27
|
static mappers: Function[];
|
|
5
28
|
static mapperDepth: number;
|
|
@@ -7,6 +30,7 @@ export declare abstract class LoggerBrowserInfra extends ObjectBase {
|
|
|
7
30
|
[key: string]: string;
|
|
8
31
|
};
|
|
9
32
|
static colorsUsed: string[];
|
|
33
|
+
private static outputSubscribers;
|
|
10
34
|
defaultStyle: string[];
|
|
11
35
|
protected readonly owner: ObjectBase | typeof ObjectBase | string;
|
|
12
36
|
protected args: {
|
|
@@ -14,11 +38,13 @@ export declare abstract class LoggerBrowserInfra extends ObjectBase {
|
|
|
14
38
|
};
|
|
15
39
|
protected color: string;
|
|
16
40
|
private outputHandler;
|
|
41
|
+
private pendingOutputMetadata?;
|
|
17
42
|
static getName(): string;
|
|
18
43
|
/**
|
|
19
44
|
* Reset logger globals.
|
|
20
45
|
*/
|
|
21
46
|
static reset(): void;
|
|
47
|
+
static attachOutputSubscriber(subscriber: LoggerOutputSubscriber): () => void;
|
|
22
48
|
/**
|
|
23
49
|
* Creates a custom mapper for a specific class type.
|
|
24
50
|
*
|
|
@@ -36,6 +62,7 @@ export declare abstract class LoggerBrowserInfra extends ObjectBase {
|
|
|
36
62
|
protected initialize(): void;
|
|
37
63
|
output(...args: any): void;
|
|
38
64
|
protected setOutputHandler(outputHandler: Function): void;
|
|
65
|
+
protected runWithOutputMetadata<T>(metadata: LoggerOutputMetadata | undefined, callback: () => T): T;
|
|
39
66
|
protected printFunctionNotify(prefix: string, caller: interfaces.TCaller, output: any): void;
|
|
40
67
|
protected printObjectEfficient(prefix: string, caller: interfaces.TCaller, params: string | object): void;
|
|
41
68
|
protected printInLineElement(prefix: string, caller: interfaces.TCaller, key: string, value: any, notice?: string): void;
|
package/dist/zenflux-core.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Bundled with love using the help of @zenflux/cli toolkit v0.1.
|
|
3
|
-
* Bundle name: @zenflux/core fileName: 'zenflux-core', built at Thu Nov 20 2025
|
|
2
|
+
* Bundled with love using the help of @zenflux/cli toolkit v0.1.38
|
|
3
|
+
* Bundle name: @zenflux/core fileName: 'zenflux-core', built at Thu Nov 20 2025 12:34:10 GMT+0200 (Israel Standard Time)
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
6
|
'use strict';
|
|
@@ -104,15 +104,15 @@ var picocolorsExports=requirePicocolors();var pc = getDefaultExportFromCjs(picoc
|
|
|
104
104
|
* @copyright http://jsfiddle.net/96sME/
|
|
105
105
|
*/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};
|
|
106
106
|
|
|
107
|
-
const MAX_MAPPING_RECURSIVE_DEPTH=4,UNKNOWN_CALLER_NAME="anonymous function";Error.stackTraceLimit=50;class LoggerBrowserInfra extends ObjectBase{static mappers=[];static mapperDepth=0;static colorsOwners={};static colorsUsed=[];defaultStyle;owner;args;color;outputHandler=console.log;static getName(){return "ZenFlux/Logging/Modules/LoggerBrowserInfra"}static reset(){LoggerBrowserInfra.mappers=[];LoggerBrowserInfra.mapperDepth=0;LoggerBrowserInfra.colorsUsed=[];LoggerBrowserInfra.colorsOwners={};}static createObjectMapper(callback){LoggerBrowserInfra.mappers.push(callback);}static useObjectMapper(obj,shouldHandleChildren=true){if(!obj||Array.isArray(obj)||"object"!==typeof obj){return obj}LoggerBrowserInfra.mapperDepth++;let result={...obj};LoggerBrowserInfra.mappers.forEach(mapper=>{result=mapper(obj)||result;});if(LoggerBrowserInfra.mapperDepth>=MAX_MAPPING_RECURSIVE_DEPTH){LoggerBrowserInfra.mapperDepth--;return result}if(shouldHandleChildren&&result){Object.entries(result).forEach(([key,value])=>{result[key]=this.useObjectMapper(value,true);});}LoggerBrowserInfra.mapperDepth--;return result}constructor(owner,args={}){super();this.args={repeatedly:false,...args};this.owner=owner;this.initialize();}getOwnerName(){if(typeof this.owner==="string"){return this.owner}if(this.owner instanceof ObjectBase){return this.owner.getName()}if(this.owner&&typeof this.owner.getName==="function"){return this.owner.getName()}return "UnknownOwner"}initialize(){const ownerName=this.getOwnerName();if(this.args.repeatedly&&LoggerBrowserInfra.colorsOwners[ownerName]){this.color=LoggerBrowserInfra.colorsOwners[ownerName];}else {this.color=this.getRandomColor();}LoggerBrowserInfra.colorsOwners[ownerName]=this.color;this.defaultStyle=["color: grey;font-size:7px","display: block",`color: ${this.color}`,"color: grey","font-weight: bold","color: #607D8B","font-size: 16px;color: red;font-weight:800"];}output(...args){this.outputHandler.apply(this,args);}setOutputHandler(outputHandler){this.outputHandler=outputHandler;}printFunctionNotify(prefix,caller,output){const callerName=this.getCallerName(caller);this.output.apply(this,[`%c(${prefix})-> %c%c${this.getOwnerName()}%c::%c${callerName}%c() ${output}%c`].concat(this.defaultStyle));}printObjectEfficient(prefix,caller,params){params=Object.assign({},params);if(typeof params==="string"){this.printInLineString(prefix,caller,params);return}if(Object.keys(params).length===1){const key=Object.keys(params)[0];let value=Object.values(params)[0];if("object"===typeof value){this.printInNextLineObject(prefix,caller,key,value||{});}else if("function"===typeof value){this.printInLineFunction(prefix,caller,key,value);}else {this.printInLineElement(prefix,caller,key,value);}return}this.printMultiLineObject(prefix,caller,params);}printInLineElement(prefix,caller,key,value,notice=""){const callerName=this.getCallerName(caller),ownerName=this.getOwnerName(),format=notice.length?`%c(${prefix})-> %c%c${ownerName}%c::%c${callerName}%c() ->> [${notice}] ->> ${key}: '${value}'%c`:`%c(${prefix})-> %c%c${ownerName}%c::%c${callerName}%c() ->> ${key}: '${value}'%c`;this.output.apply(this,[format].concat(this.defaultStyle));}printInLineFunction(prefix,caller,key,fn){fn=this.getFunctionView(fn);this.printInLineElement(prefix,caller,key,fn);}printInLineString(prefix,caller,string){this.printInLineElement(prefix,caller,"(string)",string);}printInNextLineObject(prefix,caller,key,obj){const mapped=LoggerBrowserInfra.useObjectMapper(obj),callerName=this.getCallerName(caller);this.output.apply(this,[`%c(${prefix})-> %c%c${this.getOwnerName()}%c::%c${callerName}%c() ->> ${key} %c↓`].concat(this.defaultStyle));this.output(mapped);}printMultiLineObject(prefix,caller,obj){const callerName=this.getCallerName(caller);this.output.apply(this,[`%c(${prefix})-> %c%c${this.getOwnerName()}%c::%c${callerName}%c(${Object.keys(obj).join(", ")}) %c↓`].concat(this.defaultStyle));for(let key in obj){let value=obj[key];if(typeof value==="object"){const mapped=LoggerBrowserInfra.useObjectMapper(value);value=JSON.stringify(mapped,reduceCircularReferences());}else if(typeof obj[key]=="function"){value=this.getFunctionView(value);}this.output.apply(this,["%c"+key+": `"+value+"`","color: #a3a3a3"]);}}getRandomColor(){const hex="0123456789ABCDEF";let color="#";for(let i=0;i<6;i++){color+=hex[Math.floor(Math.random()*16)];}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}}
|
|
107
|
+
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}}
|
|
108
108
|
|
|
109
109
|
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()}`)}}}
|
|
110
110
|
|
|
111
|
-
const DEFAULT_LOG_PREFIX=pc.white("⚪ - [LOG]"),DEFAULT_INFO_PREFIX=pc.blue("🔵 - [INFO]"),DEFAULT_DEBUG_PREFIX=pc.gray("🟤 - [DEBUG]"),DEFAULT_WARN_PREFIX=pc.yellow("🟡 - [WARN]"),DEFAULT_ERROR_PREFIX=pc.red("🔴 - [ERROR]"),DEFAULT_ADMIN_PREFIX=pc.bold("🟣 - [ADMIN]");const registeredNames={};class Logger extends LoggerBrowserInfra{static lastLogTime=Date.now();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 isDebugEnabled(){return isLoggerDebugEnabled()}constructor(owner,options){const{repeatedly=false,skipEventBusHook}=options||{};super(owner,{repeatedly});this.config={skipEventBusHook};this.ownerName=Logger.resolveOwnerName(owner);if(registeredNames[this.ownerName]){throw new Error(`Logger for '${this.ownerName}' already exists`)}registeredNames[this.ownerName]=true;if(isLoggerDisabled()){this.disableLoggers();return}if(isLoggerPreviousSourceDisabled()){this.getPreviousSource=()=>"";}switch(getLoggerLogLevel()){case 0:this.error=()=>{};case 1:this.warn=()=>{};case 2:this.admin=()=>{};case 3:this.info=()=>{};case 4:this.log=()=>{};case 5:this.debug=()=>{};}if(!this.config.skipEventBusHook){EventBus.$.registerMultiInstances(this,[this.outputEvent]);}}addMessagePrefix(prefix){this.messagePrefixes.push(prefix);}log(caller,message,...params){this.writeLog(DEFAULT_LOG_PREFIX,caller,message,...params);}info(caller,message,...params){this.writeLog(DEFAULT_INFO_PREFIX,caller,message,...params);}debug(caller,message,...params){this.writeLog(DEFAULT_DEBUG_PREFIX,caller,message,...params);}warn(caller,message,...params){this.writeLog(DEFAULT_WARN_PREFIX,caller,message,...params);}error(caller,message,...params){this.writeLog(DEFAULT_ERROR_PREFIX,caller,message,...params);}admin(caller,message,...params){this.writeLog(DEFAULT_ADMIN_PREFIX,caller,message,...params);}startsEmpty(caller){this.printFunctionNotify("▶",caller,"");}startsWith(caller,params){this.printObjectEfficient("▶",caller,params);}dump(caller,params={},notice=""){for(const key in params){if(typeof params[key]==="object"){params[key]=JSON.stringify(LoggerBrowserInfra.useObjectMapper(params[key]),reduceCircularReferences());}this.printInLineElement("dp",caller,key,params[key],notice);}}drop(caller,according,data){for(const key in according){this.printInLineElement("dr",caller,key,according[key],"corresponding");}this.output(data);}throw(caller,output,name="null",params={}){this.printFunctionNotify("tw",caller,output);if(params){this.printInNextLineObject("tw",caller,name,params);}throw new Error().stack}beep(){console.log("\x07");}clone(){return Object.assign(Object.create(Object.getPrototypeOf(this)),this)}outputEvent(_prefix,_timeDiff,_source,_messagePrefix,_message,_params){}static resolveOwnerName(owner){if(typeof owner==="string"){return owner}if(owner instanceof ObjectBase){return owner.getName()}if(owner&&typeof owner.getName==="function"){return owner.getName()}return "UnknownOwner"}disableLoggers(){this.error=()=>{};this.warn=()=>{};this.admin=()=>{};this.info=()=>{};this.log=()=>{};this.debug=()=>{};}getStackTrace(){const stackTrace=(new Error().stack||"").split("\n");const stackLines=stackTrace.slice(1);const stackRegex=/ at (.+?) \((.+?)\)/;const result=[];for(const line of stackLines){const match=line.match(stackRegex);if(match){const[,context,file]=match;const parsedLine={context,file};if(line.startsWith("new")){parsedLine.isNew=true;parsedLine.object=context.split(" ")[1];}else if(context!=="Object.<anonymous>"){parsedLine.object=context;}result.push(parsedLine);}}return result}getPreviousSource(){const stack=this.getStackTrace().filter(line=>line.file.includes("/src/")).filter(line=>!line.file.includes("logger.ts")).filter(line=>!line.file.includes("debugger.ts")).filter(line=>!line.file.includes("/node_modules/"));let previousSource="";const previousCaller=stack[1]?.object?.split(".");if(previousCaller?.length>1){const previousCallerName=previousCaller[0],previousCallerMethod=previousCaller[1];previousSource=`${previousCallerName}::${previousCallerMethod}]`+"[";}return previousSource}writeLog(prefix,caller,message,...params){const source=this.getPreviousSource()+pc.white(`${this.ownerName}::${
|
|
111
|
+
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)}}
|
|
112
112
|
|
|
113
113
|
var _package = {
|
|
114
114
|
"name": "@zenflux/core",
|
|
115
|
-
"version": "0.1.
|
|
115
|
+
"version": "0.1.16",
|
|
116
116
|
"types": "dist/zenflux-core.d.ts",
|
|
117
117
|
"type": "module",
|
|
118
118
|
"files": [
|
|
@@ -157,7 +157,7 @@ var _package = {
|
|
|
157
157
|
}
|
|
158
158
|
};
|
|
159
159
|
const name = "@zenflux/core";
|
|
160
|
-
const version = "0.1.
|
|
160
|
+
const version = "0.1.16";
|
|
161
161
|
const types = "dist/zenflux-core.d.ts";
|
|
162
162
|
const type = "module";
|
|
163
163
|
const files = ["dist","types"];
|
package/dist/zenflux-core.d.ts
CHANGED
|
@@ -350,6 +350,7 @@ declare class Logger extends LoggerBrowserInfra implements interfaces.ILogger {
|
|
|
350
350
|
static getName(): string;
|
|
351
351
|
static getLogLevelString(): string;
|
|
352
352
|
static getLogLevel(): number;
|
|
353
|
+
static attachOutputListener(listener: LoggerOutputSubscriber): () => void;
|
|
353
354
|
static isDebugEnabled(): boolean;
|
|
354
355
|
constructor(owner: any, options?: LoggerOptions);
|
|
355
356
|
addMessagePrefix(prefix: string): void;
|
|
@@ -379,6 +380,7 @@ declare class Logger extends LoggerBrowserInfra implements interfaces.ILogger {
|
|
|
379
380
|
private getStackTrace;
|
|
380
381
|
getPreviousSource(): string;
|
|
381
382
|
private writeLog;
|
|
383
|
+
private createBrowserFormat;
|
|
382
384
|
private formatTime;
|
|
383
385
|
}
|
|
384
386
|
|
|
@@ -389,6 +391,7 @@ declare abstract class LoggerBrowserInfra extends ObjectBase {
|
|
|
389
391
|
[key: string]: string;
|
|
390
392
|
};
|
|
391
393
|
static colorsUsed: string[];
|
|
394
|
+
private static outputSubscribers;
|
|
392
395
|
defaultStyle: string[];
|
|
393
396
|
protected readonly owner: ObjectBase | typeof ObjectBase | string;
|
|
394
397
|
protected args: {
|
|
@@ -396,11 +399,13 @@ declare abstract class LoggerBrowserInfra extends ObjectBase {
|
|
|
396
399
|
};
|
|
397
400
|
protected color: string;
|
|
398
401
|
private outputHandler;
|
|
402
|
+
private pendingOutputMetadata?;
|
|
399
403
|
static getName(): string;
|
|
400
404
|
/**
|
|
401
405
|
* Reset logger globals.
|
|
402
406
|
*/
|
|
403
407
|
static reset(): void;
|
|
408
|
+
static attachOutputSubscriber(subscriber: LoggerOutputSubscriber): () => void;
|
|
404
409
|
/**
|
|
405
410
|
* Creates a custom mapper for a specific class type.
|
|
406
411
|
*
|
|
@@ -418,6 +423,7 @@ declare abstract class LoggerBrowserInfra extends ObjectBase {
|
|
|
418
423
|
protected initialize(): void;
|
|
419
424
|
output(...args: any): void;
|
|
420
425
|
protected setOutputHandler(outputHandler: Function): void;
|
|
426
|
+
protected runWithOutputMetadata<T>(metadata: LoggerOutputMetadata | undefined, callback: () => T): T;
|
|
421
427
|
protected printFunctionNotify(prefix: string, caller: interfaces.TCaller, output: any): void;
|
|
422
428
|
protected printObjectEfficient(prefix: string, caller: interfaces.TCaller, params: string | object): void;
|
|
423
429
|
protected printInLineElement(prefix: string, caller: interfaces.TCaller, key: string, value: any, notice?: string): void;
|
|
@@ -437,6 +443,34 @@ declare interface LoggerOptions {
|
|
|
437
443
|
repeatedly?: boolean;
|
|
438
444
|
}
|
|
439
445
|
|
|
446
|
+
declare interface LoggerOutputEvent {
|
|
447
|
+
logger: LoggerBrowserInfra;
|
|
448
|
+
namespace: string;
|
|
449
|
+
args: any[];
|
|
450
|
+
metadata?: LoggerOutputMetadata;
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
declare interface LoggerOutputFormat {
|
|
454
|
+
format: string;
|
|
455
|
+
styles: string[];
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
declare type LoggerOutputLevel = "log" | "info" | "debug" | "warn" | "error" | "admin";
|
|
459
|
+
|
|
460
|
+
declare interface LoggerOutputMetadata {
|
|
461
|
+
id?: string;
|
|
462
|
+
level?: LoggerOutputLevel;
|
|
463
|
+
namespace?: string;
|
|
464
|
+
callerName?: string;
|
|
465
|
+
message?: string;
|
|
466
|
+
messagePrefix?: string;
|
|
467
|
+
payload?: unknown;
|
|
468
|
+
timestamp?: number;
|
|
469
|
+
formatted?: LoggerOutputFormat;
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
declare type LoggerOutputSubscriber = (event: LoggerOutputEvent) => void;
|
|
473
|
+
|
|
440
474
|
declare namespace managers {
|
|
441
475
|
export {
|
|
442
476
|
initialize_2 as initialize,
|
package/dist/zenflux-core.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Bundled with love using the help of @zenflux/cli toolkit v0.1.
|
|
3
|
-
* Bundle name: @zenflux/core fileName: 'zenflux-core', built at Thu Nov 20 2025
|
|
2
|
+
* Bundled with love using the help of @zenflux/cli toolkit v0.1.38
|
|
3
|
+
* Bundle name: @zenflux/core fileName: 'zenflux-core', built at Thu Nov 20 2025 12:34:10 GMT+0200 (Israel Standard Time)
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
6
|
class CommandAlreadyRegistered extends Error{constructor(command){super(`Command: '${command.getName()}' is already registered`);}}
|
|
@@ -99,15 +99,15 @@ var picocolorsExports=requirePicocolors();var pc = getDefaultExportFromCjs(picoc
|
|
|
99
99
|
* @copyright http://jsfiddle.net/96sME/
|
|
100
100
|
*/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};
|
|
101
101
|
|
|
102
|
-
const MAX_MAPPING_RECURSIVE_DEPTH=4,UNKNOWN_CALLER_NAME="anonymous function";Error.stackTraceLimit=50;class LoggerBrowserInfra extends ObjectBase{static mappers=[];static mapperDepth=0;static colorsOwners={};static colorsUsed=[];defaultStyle;owner;args;color;outputHandler=console.log;static getName(){return "ZenFlux/Logging/Modules/LoggerBrowserInfra"}static reset(){LoggerBrowserInfra.mappers=[];LoggerBrowserInfra.mapperDepth=0;LoggerBrowserInfra.colorsUsed=[];LoggerBrowserInfra.colorsOwners={};}static createObjectMapper(callback){LoggerBrowserInfra.mappers.push(callback);}static useObjectMapper(obj,shouldHandleChildren=true){if(!obj||Array.isArray(obj)||"object"!==typeof obj){return obj}LoggerBrowserInfra.mapperDepth++;let result={...obj};LoggerBrowserInfra.mappers.forEach(mapper=>{result=mapper(obj)||result;});if(LoggerBrowserInfra.mapperDepth>=MAX_MAPPING_RECURSIVE_DEPTH){LoggerBrowserInfra.mapperDepth--;return result}if(shouldHandleChildren&&result){Object.entries(result).forEach(([key,value])=>{result[key]=this.useObjectMapper(value,true);});}LoggerBrowserInfra.mapperDepth--;return result}constructor(owner,args={}){super();this.args={repeatedly:false,...args};this.owner=owner;this.initialize();}getOwnerName(){if(typeof this.owner==="string"){return this.owner}if(this.owner instanceof ObjectBase){return this.owner.getName()}if(this.owner&&typeof this.owner.getName==="function"){return this.owner.getName()}return "UnknownOwner"}initialize(){const ownerName=this.getOwnerName();if(this.args.repeatedly&&LoggerBrowserInfra.colorsOwners[ownerName]){this.color=LoggerBrowserInfra.colorsOwners[ownerName];}else {this.color=this.getRandomColor();}LoggerBrowserInfra.colorsOwners[ownerName]=this.color;this.defaultStyle=["color: grey;font-size:7px","display: block",`color: ${this.color}`,"color: grey","font-weight: bold","color: #607D8B","font-size: 16px;color: red;font-weight:800"];}output(...args){this.outputHandler.apply(this,args);}setOutputHandler(outputHandler){this.outputHandler=outputHandler;}printFunctionNotify(prefix,caller,output){const callerName=this.getCallerName(caller);this.output.apply(this,[`%c(${prefix})-> %c%c${this.getOwnerName()}%c::%c${callerName}%c() ${output}%c`].concat(this.defaultStyle));}printObjectEfficient(prefix,caller,params){params=Object.assign({},params);if(typeof params==="string"){this.printInLineString(prefix,caller,params);return}if(Object.keys(params).length===1){const key=Object.keys(params)[0];let value=Object.values(params)[0];if("object"===typeof value){this.printInNextLineObject(prefix,caller,key,value||{});}else if("function"===typeof value){this.printInLineFunction(prefix,caller,key,value);}else {this.printInLineElement(prefix,caller,key,value);}return}this.printMultiLineObject(prefix,caller,params);}printInLineElement(prefix,caller,key,value,notice=""){const callerName=this.getCallerName(caller),ownerName=this.getOwnerName(),format=notice.length?`%c(${prefix})-> %c%c${ownerName}%c::%c${callerName}%c() ->> [${notice}] ->> ${key}: '${value}'%c`:`%c(${prefix})-> %c%c${ownerName}%c::%c${callerName}%c() ->> ${key}: '${value}'%c`;this.output.apply(this,[format].concat(this.defaultStyle));}printInLineFunction(prefix,caller,key,fn){fn=this.getFunctionView(fn);this.printInLineElement(prefix,caller,key,fn);}printInLineString(prefix,caller,string){this.printInLineElement(prefix,caller,"(string)",string);}printInNextLineObject(prefix,caller,key,obj){const mapped=LoggerBrowserInfra.useObjectMapper(obj),callerName=this.getCallerName(caller);this.output.apply(this,[`%c(${prefix})-> %c%c${this.getOwnerName()}%c::%c${callerName}%c() ->> ${key} %c↓`].concat(this.defaultStyle));this.output(mapped);}printMultiLineObject(prefix,caller,obj){const callerName=this.getCallerName(caller);this.output.apply(this,[`%c(${prefix})-> %c%c${this.getOwnerName()}%c::%c${callerName}%c(${Object.keys(obj).join(", ")}) %c↓`].concat(this.defaultStyle));for(let key in obj){let value=obj[key];if(typeof value==="object"){const mapped=LoggerBrowserInfra.useObjectMapper(value);value=JSON.stringify(mapped,reduceCircularReferences());}else if(typeof obj[key]=="function"){value=this.getFunctionView(value);}this.output.apply(this,["%c"+key+": `"+value+"`","color: #a3a3a3"]);}}getRandomColor(){const hex="0123456789ABCDEF";let color="#";for(let i=0;i<6;i++){color+=hex[Math.floor(Math.random()*16)];}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}}
|
|
102
|
+
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}}
|
|
103
103
|
|
|
104
104
|
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()}`)}}}
|
|
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 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 isDebugEnabled(){return isLoggerDebugEnabled()}constructor(owner,options){const{repeatedly=false,skipEventBusHook}=options||{};super(owner,{repeatedly});this.config={skipEventBusHook};this.ownerName=Logger.resolveOwnerName(owner);if(registeredNames[this.ownerName]){throw new Error(`Logger for '${this.ownerName}' already exists`)}registeredNames[this.ownerName]=true;if(isLoggerDisabled()){this.disableLoggers();return}if(isLoggerPreviousSourceDisabled()){this.getPreviousSource=()=>"";}switch(getLoggerLogLevel()){case 0:this.error=()=>{};case 1:this.warn=()=>{};case 2:this.admin=()=>{};case 3:this.info=()=>{};case 4:this.log=()=>{};case 5:this.debug=()=>{};}if(!this.config.skipEventBusHook){EventBus.$.registerMultiInstances(this,[this.outputEvent]);}}addMessagePrefix(prefix){this.messagePrefixes.push(prefix);}log(caller,message,...params){this.writeLog(DEFAULT_LOG_PREFIX,caller,message,...params);}info(caller,message,...params){this.writeLog(DEFAULT_INFO_PREFIX,caller,message,...params);}debug(caller,message,...params){this.writeLog(DEFAULT_DEBUG_PREFIX,caller,message,...params);}warn(caller,message,...params){this.writeLog(DEFAULT_WARN_PREFIX,caller,message,...params);}error(caller,message,...params){this.writeLog(DEFAULT_ERROR_PREFIX,caller,message,...params);}admin(caller,message,...params){this.writeLog(DEFAULT_ADMIN_PREFIX,caller,message,...params);}startsEmpty(caller){this.printFunctionNotify("▶",caller,"");}startsWith(caller,params){this.printObjectEfficient("▶",caller,params);}dump(caller,params={},notice=""){for(const key in params){if(typeof params[key]==="object"){params[key]=JSON.stringify(LoggerBrowserInfra.useObjectMapper(params[key]),reduceCircularReferences());}this.printInLineElement("dp",caller,key,params[key],notice);}}drop(caller,according,data){for(const key in according){this.printInLineElement("dr",caller,key,according[key],"corresponding");}this.output(data);}throw(caller,output,name="null",params={}){this.printFunctionNotify("tw",caller,output);if(params){this.printInNextLineObject("tw",caller,name,params);}throw new Error().stack}beep(){console.log("\x07");}clone(){return Object.assign(Object.create(Object.getPrototypeOf(this)),this)}outputEvent(_prefix,_timeDiff,_source,_messagePrefix,_message,_params){}static resolveOwnerName(owner){if(typeof owner==="string"){return owner}if(owner instanceof ObjectBase){return owner.getName()}if(owner&&typeof owner.getName==="function"){return owner.getName()}return "UnknownOwner"}disableLoggers(){this.error=()=>{};this.warn=()=>{};this.admin=()=>{};this.info=()=>{};this.log=()=>{};this.debug=()=>{};}getStackTrace(){const stackTrace=(new Error().stack||"").split("\n");const stackLines=stackTrace.slice(1);const stackRegex=/ at (.+?) \((.+?)\)/;const result=[];for(const line of stackLines){const match=line.match(stackRegex);if(match){const[,context,file]=match;const parsedLine={context,file};if(line.startsWith("new")){parsedLine.isNew=true;parsedLine.object=context.split(" ")[1];}else if(context!=="Object.<anonymous>"){parsedLine.object=context;}result.push(parsedLine);}}return result}getPreviousSource(){const stack=this.getStackTrace().filter(line=>line.file.includes("/src/")).filter(line=>!line.file.includes("logger.ts")).filter(line=>!line.file.includes("debugger.ts")).filter(line=>!line.file.includes("/node_modules/"));let previousSource="";const previousCaller=stack[1]?.object?.split(".");if(previousCaller?.length>1){const previousCallerName=previousCaller[0],previousCallerMethod=previousCaller[1];previousSource=`${previousCallerName}::${previousCallerMethod}]`+"[";}return previousSource}writeLog(prefix,caller,message,...params){const source=this.getPreviousSource()+pc.white(`${this.ownerName}::${
|
|
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)}}
|
|
107
107
|
|
|
108
108
|
var _package = {
|
|
109
109
|
"name": "@zenflux/core",
|
|
110
|
-
"version": "0.1.
|
|
110
|
+
"version": "0.1.16",
|
|
111
111
|
"types": "dist/zenflux-core.d.ts",
|
|
112
112
|
"type": "module",
|
|
113
113
|
"files": [
|
|
@@ -152,7 +152,7 @@ var _package = {
|
|
|
152
152
|
}
|
|
153
153
|
};
|
|
154
154
|
const name = "@zenflux/core";
|
|
155
|
-
const version = "0.1.
|
|
155
|
+
const version = "0.1.16";
|
|
156
156
|
const types = "dist/zenflux-core.d.ts";
|
|
157
157
|
const type = "module";
|
|
158
158
|
const files = ["dist","types"];
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zenflux/core",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.18",
|
|
4
4
|
"types": "dist/zenflux-core.d.ts",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"files": [
|
|
@@ -32,7 +32,7 @@
|
|
|
32
32
|
},
|
|
33
33
|
"devDependencies": {
|
|
34
34
|
"@jest/globals": "^29.7.0",
|
|
35
|
-
"@zenflux/cli": "0.1.
|
|
35
|
+
"@zenflux/cli": "0.1.40"
|
|
36
36
|
},
|
|
37
37
|
"publishConfig": {
|
|
38
38
|
"access": "public"
|
|
@@ -41,6 +41,6 @@
|
|
|
41
41
|
"fastmcp": "^3.23.1",
|
|
42
42
|
"zod": "^4.1.12",
|
|
43
43
|
"picocolors": "^1.0.0",
|
|
44
|
-
"@zenflux/utils": "0.1.
|
|
44
|
+
"@zenflux/utils": "0.1.22"
|
|
45
45
|
}
|
|
46
46
|
}
|