@zenflux/core 0.1.7 → 0.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/dist/src/bases/controller-base.d.ts +4 -4
  2. package/dist/src/bases/index.d.ts +5 -2
  3. package/dist/src/bases/initialize-base.d.ts +8 -0
  4. package/dist/src/bases/object-base.d.ts +3 -22
  5. package/dist/src/clients/http.d.ts +3 -3
  6. package/dist/src/command-bases/command-base.d.ts +3 -3
  7. package/dist/src/command-bases/command-internal.d.ts +1 -1
  8. package/dist/src/command-bases/command-public.d.ts +1 -1
  9. package/dist/src/command-bases/command-restful.d.ts +1 -1
  10. package/dist/src/command-bases/index.d.ts +4 -4
  11. package/dist/src/errors/command-already-registered.d.ts +1 -1
  12. package/dist/src/errors/controller-already-registered.d.ts +1 -1
  13. package/dist/src/errors/controller-already-set.d.ts +1 -1
  14. package/dist/src/errors/error-with-metadata.d.ts +4 -0
  15. package/dist/src/errors/force-method-implementation.d.ts +1 -7
  16. package/dist/src/errors/index-public.d.ts +1 -1
  17. package/dist/src/errors/index.d.ts +9 -5
  18. package/dist/src/exports-index.d.ts +5 -5
  19. package/dist/src/exports.d.ts +3 -16
  20. package/dist/src/index.d.ts +2 -2
  21. package/dist/src/interfaces/index.d.ts +4 -4
  22. package/dist/src/interfaces/logger.d.ts +3 -2
  23. package/dist/src/managers/commands.d.ts +4 -4
  24. package/dist/src/managers/controllers.d.ts +2 -2
  25. package/dist/src/managers/export.d.ts +5 -5
  26. package/dist/src/managers/index.d.ts +4 -4
  27. package/dist/src/managers/internal.d.ts +1 -1
  28. package/dist/src/managers/restful.d.ts +5 -5
  29. package/dist/src/modules/debugger.d.ts +17 -0
  30. package/dist/src/modules/event-bus/event-bus.d.ts +28 -0
  31. package/dist/src/modules/logger/config.d.ts +6 -0
  32. package/dist/src/modules/logger/implementation.d.ts +46 -0
  33. package/dist/src/modules/logger/index.d.ts +2 -0
  34. package/dist/src/modules/logger/logger-browser-infra.d.ts +60 -0
  35. package/dist/src/modules/logger/utils/index.d.ts +2 -0
  36. package/dist/src/modules/logger/utils/object.d.ts +6 -0
  37. package/dist/src/modules/logger/utils/rgb.d.ts +6 -0
  38. package/dist/src/modules/mcp-server/mcp-server.d.ts +10 -0
  39. package/dist/src/modules/mcp-server/mcp-service.d.ts +13 -0
  40. package/dist/src/modules/service/service-base.d.ts +15 -0
  41. package/dist/src/modules/service/service-locator.d.ts +34 -0
  42. package/dist/src/modules/service/service-with-dependencies-base.d.ts +17 -0
  43. package/dist/zenflux-core.cjs +58 -14
  44. package/dist/zenflux-core.d.ts +508 -3
  45. package/dist/zenflux-core.mjs +58 -14
  46. package/package.json +11 -2
  47. package/src/bases/controller-base.ts +5 -5
  48. package/src/bases/index.ts +6 -2
  49. package/src/bases/initialize-base.ts +32 -0
  50. package/src/bases/object-base.ts +15 -43
  51. package/src/clients/http.ts +3 -3
  52. package/src/command-bases/command-base.ts +4 -4
  53. package/src/command-bases/command-internal.ts +1 -1
  54. package/src/command-bases/command-public.ts +1 -1
  55. package/src/command-bases/command-restful.ts +3 -3
  56. package/src/command-bases/index.ts +5 -4
  57. package/src/errors/command-already-registered.ts +1 -1
  58. package/src/errors/controller-already-registered.ts +1 -1
  59. package/src/errors/controller-already-set.ts +1 -1
  60. package/src/errors/error-with-metadata.ts +14 -0
  61. package/src/errors/force-method-implementation.ts +3 -11
  62. package/src/errors/index-public.ts +1 -1
  63. package/src/errors/index.ts +10 -5
  64. package/src/exports-index.ts +5 -5
  65. package/src/exports.ts +5 -16
  66. package/src/index.ts +3 -2
  67. package/src/interfaces/index.ts +5 -4
  68. package/src/interfaces/logger.ts +3 -2
  69. package/src/managers/commands.ts +6 -6
  70. package/src/managers/controllers.ts +3 -3
  71. package/src/managers/export.ts +5 -5
  72. package/src/managers/index.ts +5 -4
  73. package/src/managers/internal.ts +1 -1
  74. package/src/managers/restful.ts +5 -5
  75. package/src/modules/debugger.ts +89 -0
  76. package/src/modules/event-bus/event-bus.ts +204 -0
  77. package/src/modules/logger/config.ts +44 -0
  78. package/src/modules/logger/implementation.ts +287 -0
  79. package/src/modules/logger/index.ts +2 -0
  80. package/src/modules/logger/logger-browser-infra.ts +306 -0
  81. package/src/modules/logger/types/picocolors.d.ts +15 -0
  82. package/src/modules/logger/utils/index.ts +3 -0
  83. package/src/modules/logger/utils/object.ts +19 -0
  84. package/src/modules/logger/utils/rgb.ts +34 -0
  85. package/src/modules/mcp-server/mcp-server.ts +139 -0
  86. package/src/modules/mcp-server/mcp-service.ts +80 -0
  87. package/src/modules/service/service-base.ts +55 -0
  88. package/src/modules/service/service-locator.ts +205 -0
  89. package/src/modules/service/service-with-dependencies-base.ts +51 -0
@@ -0,0 +1,287 @@
1
+ import pc from "picocolors";
2
+
3
+ import { EventBus } from "../event-bus/event-bus";
4
+ import { ObjectBase } from "../../bases";
5
+
6
+ import {
7
+ getLoggerLogLevel,
8
+ getLoggerLogLevelString,
9
+ isLoggerDebugEnabled,
10
+ isLoggerDisabled,
11
+ isLoggerPreviousSourceDisabled
12
+ } from "./config";
13
+
14
+ import { LoggerBrowserInfra } from "./logger-browser-infra";
15
+
16
+ import { reduceCircularReferences } from "./utils";
17
+
18
+ import type * as interfaces from "../../interfaces";
19
+
20
+ const DEFAULT_LOG_PREFIX = pc.white( "⚪ - [LOG]" ),
21
+ DEFAULT_INFO_PREFIX = pc.blue( "🔵 - [INFO]" ),
22
+ DEFAULT_DEBUG_PREFIX = pc.gray( "🟤 - [DEBUG]" ),
23
+ DEFAULT_WARN_PREFIX = pc.yellow( "🟡 - [WARN]" ),
24
+ DEFAULT_ERROR_PREFIX = pc.red( "🔴 - [ERROR]" ),
25
+ DEFAULT_ADMIN_PREFIX = pc.bold( "🟣 - [ADMIN]" );
26
+
27
+ const registeredNames: Record<string, boolean> = {};
28
+
29
+ type ICaller = interfaces.TCaller;
30
+
31
+ interface LoggerOptions {
32
+ skipEventBusHook?: boolean;
33
+ repeatedly?: boolean;
34
+ }
35
+
36
+ export class Logger extends LoggerBrowserInfra implements interfaces.ILogger {
37
+ private static lastLogTime: number = Date.now();
38
+
39
+ private readonly ownerName: string;
40
+
41
+ private messagePrefixes: string[] = [];
42
+
43
+ private config: LoggerOptions = {};
44
+
45
+ public static getName(): string {
46
+ return "ZenFlux/Core/Modules/Logger";
47
+ }
48
+
49
+ public static getLogLevelString(): string {
50
+ return getLoggerLogLevelString();
51
+ }
52
+
53
+ public static getLogLevel(): number {
54
+ return getLoggerLogLevel();
55
+ }
56
+
57
+ public static isDebugEnabled() {
58
+ return isLoggerDebugEnabled();
59
+ }
60
+
61
+ public constructor( owner: any, options?: LoggerOptions ) {
62
+ const { repeatedly = false, skipEventBusHook } = options || {};
63
+
64
+ super( owner, { repeatedly } );
65
+
66
+ this.config = { skipEventBusHook };
67
+ this.ownerName = Logger.resolveOwnerName( owner );
68
+
69
+ if ( registeredNames[ this.ownerName ] ) {
70
+ throw new Error( `Logger for '${ this.ownerName }' already exists` );
71
+ }
72
+
73
+ registeredNames[ this.ownerName ] = true;
74
+
75
+ if ( isLoggerDisabled() ) {
76
+ this.disableLoggers();
77
+ return;
78
+ }
79
+
80
+ if ( isLoggerPreviousSourceDisabled() ) {
81
+ this.getPreviousSource = () => "";
82
+ }
83
+
84
+ switch ( getLoggerLogLevel() ) {
85
+ case 0:
86
+ this.error = () => {};
87
+ // falls through
88
+ case 1:
89
+ this.warn = () => {};
90
+ // falls through
91
+ case 2:
92
+ this.admin = () => {};
93
+ // falls through
94
+ case 3:
95
+ this.info = () => {};
96
+ // falls through
97
+ case 4:
98
+ this.log = () => {};
99
+ // falls through
100
+ case 5:
101
+ this.debug = () => {};
102
+ }
103
+
104
+ if ( !this.config.skipEventBusHook ) {
105
+ EventBus.$.registerMultiInstances( this, [ this.outputEvent ] );
106
+ }
107
+ }
108
+
109
+ public addMessagePrefix( prefix: string ) {
110
+ this.messagePrefixes.push( prefix );
111
+ }
112
+
113
+ public log( caller: ICaller, message: string, ...params: any[] ): void {
114
+ this.writeLog( DEFAULT_LOG_PREFIX, caller, message, ...params );
115
+ }
116
+
117
+ public info( caller: ICaller, message: string, ...params: any[] ): void {
118
+ this.writeLog( DEFAULT_INFO_PREFIX, caller, message, ...params );
119
+ }
120
+
121
+ public debug( caller: ICaller, message: string, ...params: any[] ): void {
122
+ this.writeLog( DEFAULT_DEBUG_PREFIX, caller, message, ...params );
123
+ }
124
+
125
+ public warn( caller: ICaller, message: string, ...params: any[] ): void {
126
+ this.writeLog( DEFAULT_WARN_PREFIX, caller, message, ...params );
127
+ }
128
+
129
+ public error( caller: ICaller, message: string, ...params: any[] ): void {
130
+ this.writeLog( DEFAULT_ERROR_PREFIX, caller, message, ...params );
131
+ }
132
+
133
+ public admin( caller: ICaller, message: string, ...params: any[] ): void {
134
+ this.writeLog( DEFAULT_ADMIN_PREFIX, caller, message, ...params );
135
+ }
136
+
137
+ public startsEmpty( caller: interfaces.TCaller ) {
138
+ this.printFunctionNotify( "▶", caller, "" );
139
+ }
140
+
141
+ public startsWith( caller: interfaces.TCaller, params: string | object ) {
142
+ this.printObjectEfficient( "▶", caller, params );
143
+ }
144
+
145
+ public dump( caller: interfaces.TCaller, params: { [ key: string ]: object | string } = {}, notice = "" ) {
146
+ for ( const key in params ) {
147
+ if ( typeof params[ key ] === "object" ) {
148
+ params[ key ] = JSON.stringify(
149
+ LoggerBrowserInfra.useObjectMapper( params[ key ] as object ),
150
+ reduceCircularReferences()
151
+ );
152
+ }
153
+
154
+ this.printInLineElement( "dp", caller, key, params[ key ], notice );
155
+ }
156
+ }
157
+
158
+ public drop( caller: interfaces.TCaller, according: { [ key: string ]: string }, data: any ) {
159
+ for ( const key in according ) {
160
+ this.printInLineElement( "dr", caller, key, according[ key ], "corresponding" );
161
+ }
162
+
163
+ this.output( data );
164
+ }
165
+
166
+ /**
167
+ * TODO: Should respect debug levels, when to throw...
168
+ */
169
+ public throw( caller: interfaces.TCaller, output: string, name: string = "null", params = {} ) {
170
+ this.printFunctionNotify( "tw", caller, output );
171
+
172
+ if ( params ) {
173
+ this.printInNextLineObject( "tw", caller, name, params );
174
+ }
175
+
176
+ throw new Error().stack;
177
+ }
178
+
179
+ public beep() {
180
+ console.log( "\x07" );
181
+ }
182
+
183
+ public clone() {
184
+ return Object.assign( Object.create( Object.getPrototypeOf( this ) ), this );
185
+ }
186
+
187
+ public outputEvent( _prefix: string, _timeDiff: string, _source: string, _messagePrefix: string, _message: string, _params: any[] ): void {
188
+ // Intentionally left blank, can be hooked via EventBus.
189
+ }
190
+
191
+ private static resolveOwnerName( owner: any ): string {
192
+ if ( typeof owner === "string" ) {
193
+ return owner;
194
+ }
195
+
196
+ if ( owner instanceof ObjectBase ) {
197
+ return owner.getName();
198
+ }
199
+
200
+ if ( owner && typeof owner.getName === "function" ) {
201
+ return owner.getName();
202
+ }
203
+
204
+ return "UnknownOwner";
205
+ }
206
+
207
+ private disableLoggers() {
208
+ this.error = () => {};
209
+ this.warn = () => {};
210
+ this.admin = () => {};
211
+ this.info = () => {};
212
+ this.log = () => {};
213
+ this.debug = () => {};
214
+ }
215
+
216
+ private getStackTrace(): any[] {
217
+ const stackTrace = ( new Error().stack || "" ).split( "\n" );
218
+ const stackLines = stackTrace.slice( 1 );
219
+
220
+ const stackRegex = / at (.+?) \((.+?)\)/;
221
+ const result = [];
222
+
223
+ for ( const line of stackLines ) {
224
+ const match = line.match( stackRegex );
225
+
226
+ if ( match ) {
227
+ const [ , context, file ] = match;
228
+ const parsedLine: any = { context, file };
229
+
230
+ if ( line.startsWith( "new" ) ) {
231
+ parsedLine.isNew = true;
232
+ parsedLine.object = context.split( " " )[ 1 ];
233
+ } else if ( context !== "Object.<anonymous>" ) {
234
+ parsedLine.object = context;
235
+ }
236
+
237
+ result.push( parsedLine );
238
+ }
239
+ }
240
+
241
+ return result;
242
+ }
243
+
244
+ public getPreviousSource(): string {
245
+ const stack = this.getStackTrace()
246
+ .filter( ( line: any ) => line.file.includes( "/src/" ) )
247
+ .filter( ( line: any ) => !line.file.includes( "logger.ts" ) )
248
+ .filter( ( line: any ) => !line.file.includes( "debugger.ts" ) )
249
+ .filter( ( line: any ) => !line.file.includes( "/node_modules/" ) );
250
+
251
+ let previousSource = "";
252
+
253
+ const previousCaller = stack[ 1 ]?.object?.split( "." );
254
+
255
+ if ( previousCaller?.length > 1 ) {
256
+ const previousCallerName = previousCaller[ 0 ],
257
+ previousCallerMethod = previousCaller[ 1 ];
258
+
259
+ previousSource = `${ previousCallerName }::${ previousCallerMethod }]` + "[";
260
+ }
261
+
262
+ return previousSource;
263
+ }
264
+
265
+ private writeLog( prefix: string, caller: ICaller, message: string, ...params: any[] ): void {
266
+ const source = this.getPreviousSource() + pc.white( `${ this.ownerName }::${ this.getCallerName( caller ) }` );
267
+
268
+ let messagePrefix = "";
269
+
270
+ if ( this.messagePrefixes.length ) {
271
+ messagePrefix = `[${ this.messagePrefixes.join( "][" ) }]`;
272
+ }
273
+
274
+ const timeDiff = ( Date.now() - Logger.lastLogTime ).toString().padStart( 4, "0" );
275
+
276
+ this.outputEvent( prefix, timeDiff, source, messagePrefix, message, params );
277
+
278
+ const output = `${ prefix }[+${ timeDiff }ms][${ source }]${ messagePrefix }: ${ message }`;
279
+
280
+ console.log( output, ...params );
281
+
282
+ Logger.lastLogTime = Date.now();
283
+ }
284
+ }
285
+
286
+ export default Logger;
287
+
@@ -0,0 +1,2 @@
1
+ export * from "./config";
2
+ export * from "./implementation";
@@ -0,0 +1,306 @@
1
+ /**
2
+ * @author Leonid Vinikov <leonidvinikov@gmail.com>
3
+ * @description a logger for web browser.
4
+ *
5
+ * TODO:
6
+ * - Add dark/light switch for chrome devtools.
7
+ * - https://stackoverflow.com/questions/41961037/is-there-a-way-to-detect-if-chromes-devtools-are-using-dark-mode
8
+ * - Maybe 'zenflux-logging` should be chrome extension.
9
+ */
10
+ import { ObjectBase } from "../../bases/object-base";
11
+
12
+ import { getHexColorDelta, reduceCircularReferences } from "./utils";
13
+
14
+ import type * as interfaces from "../../interfaces";
15
+
16
+ // TODO: Should by dynamic/configure-able.
17
+ const MAX_MAPPING_RECURSIVE_DEPTH = 4,
18
+ UNKNOWN_CALLER_NAME = "anonymous function";
19
+
20
+ // TODO: Should by dynamic/configure-able.
21
+ Error.stackTraceLimit = 50;
22
+
23
+ export abstract class LoggerBrowserInfra extends ObjectBase {
24
+ public static mappers: Function[] = [];
25
+ public static mapperDepth = 0;
26
+
27
+ public static colorsOwners: { [ key: string ]: string } = {};
28
+ public static colorsUsed: string[] = [];
29
+
30
+ public defaultStyle: string[];
31
+
32
+ protected readonly owner: ObjectBase | typeof ObjectBase | string;
33
+
34
+ protected args: {
35
+ repeatedly: boolean;
36
+ };
37
+
38
+ protected color: string;
39
+
40
+ private outputHandler: Function = console.log;
41
+
42
+ public static getName() {
43
+ return "ZenFlux/Logging/Modules/LoggerBrowserInfra";
44
+ }
45
+
46
+ /**
47
+ * Reset logger globals.
48
+ */
49
+ public static reset() {
50
+ LoggerBrowserInfra.mappers = [];
51
+ LoggerBrowserInfra.mapperDepth = 0;
52
+ LoggerBrowserInfra.colorsUsed = [];
53
+ LoggerBrowserInfra.colorsOwners = {};
54
+ }
55
+
56
+ /**
57
+ * Creates a custom mapper for a specific class type.
58
+ *
59
+ * The mapper is a callback function that can modify or enhance objects mapping.
60
+ */
61
+ public static createObjectMapper( callback: Function ) {
62
+ LoggerBrowserInfra.mappers.push( callback );
63
+ }
64
+
65
+ /**
66
+ * Gets mapped version of the object by using custom created object mapper.
67
+ */
68
+ public static useObjectMapper( obj: object, shouldHandleChildren = true ) {
69
+ if ( ! obj || Array.isArray( obj ) || "object" !== typeof obj ) {
70
+ return obj;
71
+ }
72
+
73
+ LoggerBrowserInfra.mapperDepth++;
74
+
75
+ // Result will lose typeof(obj), instanceOf will not work, now based on callback.
76
+ let result = { ... obj } as { [ key: string ]: any };
77
+
78
+ // Run all mappers.
79
+ LoggerBrowserInfra.mappers.forEach( ( mapper ) => {
80
+ result = mapper( obj ) || result;
81
+ } );
82
+
83
+ // Prevent infinite recursive.
84
+ if ( LoggerBrowserInfra.mapperDepth >= MAX_MAPPING_RECURSIVE_DEPTH ) {
85
+ LoggerBrowserInfra.mapperDepth--;
86
+ return result;
87
+ }
88
+
89
+ // Children handling.
90
+ if ( shouldHandleChildren && result ) {
91
+ Object.entries( result ).forEach( ( [ key, value ] ) => {
92
+ result[ key ] = this.useObjectMapper( value, true );
93
+ } );
94
+ }
95
+
96
+ LoggerBrowserInfra.mapperDepth--;
97
+
98
+ return result;
99
+ }
100
+
101
+ public constructor( owner: ObjectBase | typeof ObjectBase | string, args = {} ) {
102
+ super();
103
+
104
+ this.args = {
105
+ repeatedly: false,
106
+
107
+ ... args,
108
+ };
109
+
110
+ this.owner = owner;
111
+
112
+ this.initialize();
113
+ }
114
+
115
+ protected getOwnerName() {
116
+ if ( typeof this.owner === "string" ) {
117
+ return this.owner;
118
+ }
119
+
120
+ if ( this.owner instanceof ObjectBase ) {
121
+ return this.owner.getName();
122
+ }
123
+
124
+ if ( this.owner && typeof ( this.owner as typeof ObjectBase ).getName === "function" ) {
125
+ return ( this.owner as typeof ObjectBase ).getName();
126
+ }
127
+
128
+ return "UnknownOwner";
129
+ }
130
+
131
+ protected initialize() {
132
+ const ownerName = this.getOwnerName();
133
+
134
+ if ( this.args.repeatedly && LoggerBrowserInfra.colorsOwners[ ownerName ] ) {
135
+ this.color = LoggerBrowserInfra.colorsOwners[ ownerName ];
136
+ } else {
137
+ this.color = this.getRandomColor();
138
+
139
+ LoggerBrowserInfra.colorsUsed.push( this.color );
140
+ }
141
+
142
+ LoggerBrowserInfra.colorsOwners[ ownerName ] = this.color;
143
+
144
+ this.defaultStyle = [
145
+ "color: grey;font-size:7px",
146
+ "display: block",
147
+ `color: ${ this.color }`,
148
+ "color: grey",
149
+ "font-weight: bold",
150
+ "color: #607D8B",
151
+ "font-size: 16px;color: red;font-weight:800",
152
+ ];
153
+ }
154
+
155
+ public output( ... args: any ) {
156
+ this.outputHandler.apply( this, args );
157
+ }
158
+
159
+ protected setOutputHandler( outputHandler: Function ) {
160
+ this.outputHandler = outputHandler;
161
+ }
162
+
163
+ protected printFunctionNotify( prefix: string, caller: interfaces.TCaller, output: any ) {
164
+ const callerName = this.getCallerName( caller );
165
+
166
+ this.output.apply(
167
+ this,
168
+ [ `%c(${ prefix })-> %c%c${ this.getOwnerName() }%c::%c${ callerName }%c() ${ output }%c` ].concat(
169
+ this.defaultStyle
170
+ )
171
+ );
172
+ }
173
+
174
+ protected printObjectEfficient( prefix: string, caller: interfaces.TCaller, params: string|object ) {
175
+ params = Object.assign( {}, params );
176
+
177
+ if ( typeof params === "string" ) {
178
+ this.printInLineString( prefix, caller, params );
179
+
180
+ return;
181
+ }
182
+
183
+ if ( Object.keys( params ).length === 1 ) {
184
+ const key = Object.keys( params )[ 0 ];
185
+ let value = Object.values( params )[ 0 ];
186
+
187
+ // TODO: Check is repeated logic, handle it.
188
+ if ( "object" === typeof value ) {
189
+ this.printInNextLineObject( prefix, caller, key, value || {} );
190
+ } else if ( "function" === typeof value ) {
191
+ this.printInLineFunction( prefix, caller, key, value );
192
+ } else {
193
+ this.printInLineElement( prefix, caller, key, value );
194
+ }
195
+
196
+ return;
197
+ }
198
+
199
+ this.printMultiLineObject( prefix, caller, params as any );
200
+ }
201
+
202
+ protected printInLineElement( prefix: string, caller: interfaces.TCaller, key: string, value: any, notice = "" ) {
203
+ const callerName = this.getCallerName( caller ),
204
+ ownerName = this.getOwnerName(),
205
+ format = notice.length ?
206
+ `%c(${ prefix })-> %c%c${ ownerName }%c::%c${ callerName }%c() ->> [${ notice }] ->> ${ key }: '${ value }'%c` :
207
+ `%c(${ prefix })-> %c%c${ ownerName }%c::%c${ callerName }%c() ->> ${ key }: '${ value }'%c`;
208
+
209
+ this.output.apply( this, [ format ].concat( this.defaultStyle ) );
210
+ }
211
+
212
+ protected printInLineFunction( prefix: string, caller: interfaces.TCaller, key: string, fn: string | Function ) {
213
+ fn = this.getFunctionView( fn );
214
+
215
+ this.printInLineElement( prefix, caller, key, fn );
216
+ }
217
+
218
+ protected printInLineString( prefix: string, caller: interfaces.TCaller, string: string ) {
219
+ this.printInLineElement( prefix, caller, "(string)", string );
220
+ }
221
+
222
+ protected printInNextLineObject( prefix: string, caller: interfaces.TCaller, key: string, obj: object ) {
223
+ const mapped = LoggerBrowserInfra.useObjectMapper( obj ),
224
+ callerName = this.getCallerName( caller );
225
+
226
+ this.output.apply(
227
+ this,
228
+ [
229
+ `%c(${ prefix })-> %c%c${ this.getOwnerName() }%c::%c${ callerName }%c() ->> ${ key } %c↓`,
230
+ ].concat( this.defaultStyle )
231
+ );
232
+
233
+ // print in next line
234
+ this.output( mapped );
235
+ }
236
+
237
+ protected printMultiLineObject( prefix: string, caller: interfaces.TCaller, obj: { [ key: string ]: string | Function } ) {
238
+ const callerName = this.getCallerName( caller );
239
+
240
+ this.output.apply(
241
+ this,
242
+ [
243
+ `%c(${ prefix })-> %c%c${ this.getOwnerName() }%c::%c${ callerName }%c(${ Object.keys( obj )
244
+ .join( ", " ) }) %c↓`,
245
+ ].concat( this.defaultStyle )
246
+ );
247
+
248
+ for ( let key in obj ) {
249
+ let value = obj[ key ];
250
+
251
+ if ( typeof value === "object" ) {
252
+ const mapped = LoggerBrowserInfra.useObjectMapper( value );
253
+
254
+ value = JSON.stringify( mapped, reduceCircularReferences() );
255
+ } else if ( typeof obj[ key ] == "function" ) {
256
+ value = this.getFunctionView( value );
257
+ }
258
+
259
+ this.output.apply( this, [
260
+ "%c" + key + ": `" + value + "`",
261
+ "color: #a3a3a3",
262
+ ] );
263
+ }
264
+ }
265
+
266
+ private getRandomColor(): string {
267
+ const hex = "0123456789ABCDEF";
268
+ let color = "#";
269
+
270
+ for ( let i = 0 ; i < 6 ; i++ ) {
271
+ color += hex[ Math.floor( Math.random() * 16 ) ];
272
+ }
273
+
274
+ let similar = LoggerBrowserInfra.colorsUsed.some( ( value ) => {
275
+ // it returns the ratio of difference... closer to 1.0 is less difference.
276
+ return getHexColorDelta( color, value ) >= 0.8;
277
+ } );
278
+
279
+ // if the color is similar, try again.
280
+ if ( similar ) {
281
+ return this.getRandomColor();
282
+ }
283
+
284
+ return color;
285
+ }
286
+
287
+ protected getCallerName( caller: interfaces.TCaller ) {
288
+ if ( "function" === typeof caller ) {
289
+ return caller.prototype instanceof ObjectBase ? "constructor" : caller.name;
290
+ }
291
+
292
+ throw new Error( "Invalid caller" );
293
+ }
294
+
295
+ private getFunctionView( fn: string | Function ): ( string | Function ) {
296
+ let fReturn = UNKNOWN_CALLER_NAME;
297
+
298
+ // TODO: Check if needed.
299
+ if ( typeof fn !== "string" && fn.name.length !== 0 ) {
300
+ fReturn = fn.name.split( " " )[ 1 ] + "()";
301
+ }
302
+
303
+ return fReturn;
304
+ }
305
+ }
306
+
@@ -0,0 +1,15 @@
1
+ declare module "picocolors" {
2
+ const pc: {
3
+ ( input: string ): string;
4
+ red( input: string ): string;
5
+ blue( input: string ): string;
6
+ green( input: string ): string;
7
+ yellow( input: string ): string;
8
+ gray( input: string ): string;
9
+ white( input: string ): string;
10
+ bold( input: string ): string;
11
+ };
12
+
13
+ export default pc;
14
+ }
15
+
@@ -0,0 +1,3 @@
1
+ export * from "./object";
2
+ export * from "./rgb";
3
+
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Reduce circular references.
3
+ *
4
+ * @copyright https://stackoverflow.com/a/53731154
5
+ */
6
+ export const reduceCircularReferences = () => {
7
+ const seen = new WeakSet();
8
+
9
+ return ( key: any, value: any ) => {
10
+ if ( typeof value === "object" && value !== null ) {
11
+ if ( seen.has( value ) ) {
12
+ return;
13
+ }
14
+ seen.add( value );
15
+ }
16
+ return value;
17
+ };
18
+ };
19
+
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Function hexColorDelta() : Return color difference in ratio decimal point.
3
+ *
4
+ * @copyright http://jsfiddle.net/96sME/
5
+ */
6
+ export const getHexColorDelta = function ( hex1: string, hex2: string ): number {
7
+ hex1 = hex1.replace( "#", "" );
8
+ hex2 = hex2.replace( "#", "" );
9
+
10
+ // Get red/green/blue int values of hex1
11
+ const r1 = parseInt( hex1.substring( 0, 2 ), 16 );
12
+ const g1 = parseInt( hex1.substring( 2, 4 ), 16 );
13
+ const b1 = parseInt( hex1.substring( 4, 6 ), 16 );
14
+
15
+ // Get red/green/blue int values of hex2
16
+ const r2 = parseInt( hex2.substring( 0, 2 ), 16 );
17
+ const g2 = parseInt( hex2.substring( 2, 4 ), 16 );
18
+ const b2 = parseInt( hex2.substring( 4, 6 ), 16 );
19
+
20
+ // Calculate differences between reds, greens and blues
21
+ let r = 255 - Math.abs( r1 - r2 );
22
+ let g = 255 - Math.abs( g1 - g2 );
23
+ let b = 255 - Math.abs( b1 - b2 );
24
+
25
+ // Limit differences between 0 and 1
26
+
27
+ r /= 255;
28
+ g /= 255;
29
+ b /= 255;
30
+
31
+ // 0 means opposite colors, 1 means same colors
32
+ return ( r + g + b ) / 3;
33
+ };
34
+