@zenflux/core 0.0.0-devlopment.0 → 0.0.1-dev.0

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 (99) hide show
  1. package/dist/es/clients/http.d.ts +30 -0
  2. package/dist/es/clients/http.d.ts.map +1 -0
  3. package/dist/es/{src/command-bases → command-bases}/command-base.d.ts +7 -2
  4. package/dist/es/command-bases/command-base.d.ts.map +1 -0
  5. package/dist/es/{src/command-bases → command-bases}/command-data.d.ts +2 -1
  6. package/dist/es/command-bases/command-data.d.ts.map +1 -0
  7. package/dist/es/{src/command-bases → command-bases}/command-internal.d.ts +2 -1
  8. package/dist/es/command-bases/command-internal.d.ts.map +1 -0
  9. package/dist/es/{src/command-bases → command-bases}/command-public.d.ts +2 -1
  10. package/dist/es/command-bases/command-public.d.ts.map +1 -0
  11. package/dist/es/{src/command-bases → command-bases}/index.d.ts +4 -0
  12. package/dist/es/command-bases/index.d.ts.map +1 -0
  13. package/dist/es/{src/core → core}/controller.d.ts +2 -1
  14. package/dist/es/core/controller.d.ts.map +1 -0
  15. package/dist/es/{src/core → core}/index.d.ts +1 -0
  16. package/dist/es/core/index.d.ts.map +1 -0
  17. package/dist/es/{src/core → core}/object-base.d.ts +2 -1
  18. package/dist/es/core/object-base.d.ts.map +1 -0
  19. package/dist/es/{src/errors → errors}/command-already-registered.d.ts +2 -1
  20. package/dist/es/errors/command-already-registered.d.ts.map +1 -0
  21. package/dist/es/{src/errors → errors}/command-not-found.d.ts +2 -1
  22. package/dist/es/errors/command-not-found.d.ts.map +1 -0
  23. package/dist/es/{src/errors → errors}/controller-already-registered.d.ts +2 -1
  24. package/dist/es/errors/controller-already-registered.d.ts.map +1 -0
  25. package/dist/es/errors/controller-already-set.d.ts +8 -0
  26. package/dist/es/errors/controller-already-set.d.ts.map +1 -0
  27. package/dist/es/{src/errors → errors}/force-method.d.ts +2 -1
  28. package/dist/es/errors/force-method.d.ts.map +1 -0
  29. package/dist/es/{src/errors → errors}/index.d.ts +2 -0
  30. package/dist/es/errors/index.d.ts.map +1 -0
  31. package/dist/es/{src/exports.d.ts → exports.d.ts} +5 -0
  32. package/dist/es/exports.d.ts.map +1 -0
  33. package/dist/es/index.d.ts +6 -0
  34. package/dist/es/index.d.ts.map +1 -0
  35. package/dist/es/{src/initializer.d.ts → initializer.d.ts} +4 -1
  36. package/dist/es/initializer.d.ts.map +1 -0
  37. package/dist/es/{src/interfaces → interfaces}/commands.d.ts +1 -0
  38. package/dist/es/interfaces/commands.d.ts.map +1 -0
  39. package/dist/es/{src/interfaces → interfaces}/config.d.ts +1 -0
  40. package/dist/es/interfaces/config.d.ts.map +1 -0
  41. package/dist/es/interfaces/data.d.ts +19 -0
  42. package/dist/es/interfaces/data.d.ts.map +1 -0
  43. package/dist/es/interfaces/index.d.ts +9 -0
  44. package/dist/es/interfaces/index.d.ts.map +1 -0
  45. package/dist/es/interfaces/managers.d.ts +14 -0
  46. package/dist/es/interfaces/managers.d.ts.map +1 -0
  47. package/dist/es/{src/interfaces → interfaces}/object-base.d.ts +1 -0
  48. package/dist/es/interfaces/object-base.d.ts.map +1 -0
  49. package/dist/es/{src/manager-bases → manager-bases}/commands.d.ts +5 -3
  50. package/dist/es/manager-bases/commands.d.ts.map +1 -0
  51. package/dist/es/{src/manager-bases → manager-bases}/controllers.d.ts +4 -2
  52. package/dist/es/manager-bases/controllers.d.ts.map +1 -0
  53. package/dist/es/{src/manager-bases → manager-bases}/data.d.ts +8 -5
  54. package/dist/es/manager-bases/data.d.ts.map +1 -0
  55. package/dist/es/{src/manager-bases → manager-bases}/index.d.ts +4 -0
  56. package/dist/es/manager-bases/index.d.ts.map +1 -0
  57. package/dist/es/{src/manager-bases → manager-bases}/internal.d.ts +2 -1
  58. package/dist/es/manager-bases/internal.d.ts.map +1 -0
  59. package/dist/es/managers/index.d.ts +16 -0
  60. package/dist/es/managers/index.d.ts.map +1 -0
  61. package/dist/es/{src/modules → modules}/index.d.ts +1 -0
  62. package/dist/es/modules/index.d.ts.map +1 -0
  63. package/dist/es/{src/modules → modules}/logger.d.ts +1 -0
  64. package/dist/es/modules/logger.d.ts.map +1 -0
  65. package/dist/es/{src/utils → utils}/index.d.ts +1 -0
  66. package/dist/es/utils/index.d.ts.map +1 -0
  67. package/dist/es/{src/utils → utils}/object.d.ts +1 -0
  68. package/dist/es/utils/object.d.ts.map +1 -0
  69. package/dist/es/{src/utils → utils}/rgb.d.ts +1 -0
  70. package/dist/es/utils/rgb.d.ts.map +1 -0
  71. package/dist/es/zenflux-core.js +2053 -890
  72. package/package.json +29 -35
  73. package/src/clients/http.ts +74 -18
  74. package/src/command-bases/command-base.ts +25 -8
  75. package/src/command-bases/command-data.ts +3 -3
  76. package/src/core/object-base.ts +1 -1
  77. package/src/errors/controller-already-set.ts +10 -0
  78. package/src/errors/index.ts +1 -0
  79. package/src/exports.ts +1 -1
  80. package/src/index.ts +2 -1
  81. package/src/initializer.ts +14 -21
  82. package/src/interfaces/data.ts +23 -0
  83. package/src/interfaces/index.ts +8 -0
  84. package/src/interfaces/managers.ts +16 -0
  85. package/src/manager-bases/commands.ts +9 -4
  86. package/src/manager-bases/controllers.ts +2 -1
  87. package/src/manager-bases/data.ts +40 -13
  88. package/src/managers/index.ts +26 -5
  89. package/src/modules/logger.ts +53 -7
  90. package/types/index.d.ts +6 -2
  91. package/dist/cjs/zenflux-core.js +0 -1082
  92. package/dist/es/rollup.config.d.ts +0 -23
  93. package/dist/es/src/clients/http.d.ts +0 -20
  94. package/dist/es/src/enums/http.d.ts +0 -9
  95. package/dist/es/src/index.d.ts +0 -2
  96. package/dist/es/src/managers/index.d.ts +0 -5
  97. package/dist/es/zenflux-core.mjs +0 -12
  98. package/dist/umd/zenflux-core.js +0 -12
  99. package/src/enums/http.ts +0 -12
@@ -1,1082 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- class ForceMethodBase extends Error {
6
- constructor(className, methodName) {
7
- super(`ForeMethod implementation: at '${className}' method: '${methodName}'`);
8
- }
9
- }
10
- class ForceMethod extends Error {
11
- constructor(context, methodName) {
12
- super(`ForeMethod implementation: at '${context.getName()}' method: '${methodName}'`);
13
- }
14
- }
15
-
16
- /**
17
- * @author: Leonid Vinikov <czf.leo123@gmail.com>
18
- * @description: is base class/object for all classes, responsible for: 'getName', implementation.
19
- */
20
- let IdCounter = 0;
21
- /**
22
- * Base class 4 *
23
- */
24
- class ObjectBase {
25
- virtualId = 0;
26
- static getName() {
27
- throw new ForceMethodBase("ObjectBase", "getName");
28
- }
29
- constructor() {
30
- this.virtualId = IdCounter;
31
- APIIncreaseIdCounter();
32
- }
33
- getName() {
34
- return this.constructor.getName();
35
- }
36
- }
37
- function APIIncreaseIdCounter() {
38
- return IdCounter++;
39
- }
40
-
41
- /**
42
- * Function getCircularReplacer() : Reduce circular references.
43
- *
44
- * @copyright https://stackoverflow.com/a/53731154
45
- */
46
- const getCircularReplacer = () => {
47
- const seen = new WeakSet();
48
- return (key, value) => {
49
- if (typeof value === "object" && value !== null) {
50
- if (seen.has(value)) {
51
- return;
52
- }
53
- seen.add(value);
54
- }
55
- return value;
56
- };
57
- };
58
-
59
- /**
60
- * Function hexColorDelta() : Return color difference in ratio decimal point.
61
- *
62
- * @copyright http://jsfiddle.net/96sME/
63
- */
64
- const hexColorDelta = function (hex1, hex2) {
65
- hex1 = hex1.replace("#", "");
66
- hex2 = hex2.replace("#", "");
67
- // Get red/green/blue int values of hex1
68
- const r1 = parseInt(hex1.substring(0, 2), 16);
69
- const g1 = parseInt(hex1.substring(2, 4), 16);
70
- const b1 = parseInt(hex1.substring(4, 6), 16);
71
- // Get red/green/blue int values of hex2
72
- const r2 = parseInt(hex2.substring(0, 2), 16);
73
- const g2 = parseInt(hex2.substring(2, 4), 16);
74
- const b2 = parseInt(hex2.substring(4, 6), 16);
75
- // Calculate differences between reds, greens and blues
76
- let r = 255 - Math.abs(r1 - r2);
77
- let g = 255 - Math.abs(g1 - g2);
78
- let b = 255 - Math.abs(b1 - b2);
79
- // Limit differences between 0 and 1
80
- r /= 255;
81
- g /= 255;
82
- b /= 255;
83
- // 0 means opposite colors, 1 means same colors
84
- return (r + g + b) / 3;
85
- };
86
-
87
- var index$6 = /*#__PURE__*/Object.freeze({
88
- __proto__: null,
89
- getCircularReplacer: getCircularReplacer,
90
- hexColorDelta: hexColorDelta
91
- });
92
-
93
- /**
94
- * @author: Leonid Vinikov <czf.leo123@gmail.com>
95
- * @description: Module for logging instances.
96
- * @TODO:
97
- * - Remove `@ts-ignore`, requires a refactor.
98
- * - Add night/white mode.
99
- */
100
- // TODO: Should by dynamic/configure-able.
101
- const MAX_WRAPPING_RECURSIVE_DEPTH = 4;
102
- class Logger {
103
- static wrappers = {};
104
- static wrapperDepth = 0;
105
- static sharedData = {};
106
- static colorsInUse = [];
107
- defaultStyle;
108
- color;
109
- outputHandler;
110
- args = {};
111
- name;
112
- state = false;
113
- static getName() {
114
- return 'Core/Modules/Logger';
115
- }
116
- /**
117
- * Function reset() : Reset logger globals.
118
- */
119
- static reset() {
120
- Logger.wrappers = {};
121
- Logger.wrapperDepth = 0;
122
- Logger.colorsInUse = [];
123
- Logger.sharedData = {};
124
- }
125
- /**
126
- * Function createCustomWrapper() : Creates custom wrapper for log entities.
127
- */
128
- static createCustomWrapper(classType, callback) {
129
- // @ts-ignore
130
- if (!Logger.wrappers[classType]) {
131
- // @ts-ignore
132
- Logger.wrappers[classType.name] = [];
133
- }
134
- // @ts-ignore
135
- Logger.wrappers[classType.name].push({
136
- classType,
137
- callback
138
- });
139
- }
140
- /**
141
- * Function getCallerName() : Return caller name.
142
- */
143
- static getCallerName() {
144
- const error = new Error(),
145
- caller = error.stack ? error.stack.split("\n")[3].trim() : '_UNKNOWN_CALLER_NAME_';
146
- if (caller.startsWith("at new")) {
147
- return "constructor";
148
- }
149
- return caller.split(".")[1].split(" ")[0];
150
- }
151
- /**
152
- * Function functionView() : Return function preview.
153
- */
154
- static getFunctionView(fn) {
155
- let fReturn = "anonymous function()";
156
- // TODO: Check if works.
157
- if (typeof fn !== "string" && fn.name.length !== 0) {
158
- fReturn = fn.name.split(" ")[1] + "()";
159
- }
160
- return fReturn;
161
- }
162
- /**
163
- * Function constructor() : Create logger class.
164
- */
165
- constructor(owner, isActive = false, args = {}) {
166
- if ('off' === globalThis.process?.env['flow_modules_logger']) {
167
- return;
168
- }
169
- this.state = isActive;
170
- this.args = args;
171
- this.name = "";
172
- if (typeof owner == "string") {
173
- this.name = owner;
174
- } else {
175
- this.name = owner.constructor.name;
176
- }
177
- if (isActive) {
178
- this.initialize();
179
- }
180
- }
181
- /**
182
- * Function initialize() : Initialize logger class.
183
- */
184
- initialize() {
185
- // @ts-ignore
186
- if (this.args.sameColor) {
187
- if (!Logger.sharedData[this.name]) {
188
- Logger.sharedData[this.name] = this.getRandomColor();
189
- }
190
- this.color = Logger.sharedData[this.name];
191
- } else {
192
- this.color = this.getRandomColor();
193
- Logger.colorsInUse.push(this.color);
194
- }
195
- this.outputHandler = console.log;
196
- 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"];
197
- }
198
- /**
199
- * Function setOutputHandler() : Set custom output handler.
200
- */
201
- setOutputHandler(outputHandler) {
202
- this.outputHandler = outputHandler;
203
- }
204
- /**
205
- * Function useWrapper() : Search for customized log view, each instance,
206
- * that typeof the instance was registered wrapper will have unique output
207
- * according to the registered callback.
208
- */
209
- useWrapper(obj, shouldHandleChildren = true) {
210
- if (!obj || 'object' !== typeof obj || Array.isArray(obj)) {
211
- return obj;
212
- }
213
- Logger.wrapperDepth++;
214
- // Result will lose classType (instanceOf will not work), now based on obj.
215
- let result = {
216
- ...obj
217
- };
218
- // @ts-ignore
219
- Object.values(Logger.wrappers).forEach(([wrapper]) => {
220
- if (obj instanceof wrapper.classType) {
221
- result = wrapper.callback(obj) || result;
222
- }
223
- });
224
- if (Logger.wrapperDepth >= MAX_WRAPPING_RECURSIVE_DEPTH) {
225
- Logger.wrapperDepth--;
226
- return result;
227
- }
228
- if (shouldHandleChildren && result) {
229
- Object.entries(result).forEach(([key, value]) => {
230
- result[key] = this.useWrapper(value, true);
231
- });
232
- }
233
- Logger.wrapperDepth--;
234
- return result;
235
- }
236
- /**
237
- * Function startEmpty() : Notify function start without args.
238
- *
239
- * @param {string} output
240
- */
241
- startEmpty(output = "") {
242
- if (!this.state) return;
243
- this.printFunctionNotify("se", Logger.getCallerName(), output);
244
- }
245
- /**
246
- * Function startWith() : Notify function start with args.
247
- *
248
- * TODO: Rename to startsWith
249
- */
250
- startWith(params) {
251
- if (!this.state) return;
252
- params = Object.assign({}, params);
253
- const type = "se";
254
- const source = Logger.getCallerName();
255
- if (typeof params == "string") {
256
- this.printInLineString(type, source, params);
257
- } else if (Object.keys(params).length === 1) {
258
- const key = Object.keys(params)[0];
259
- let value = Object.values(params)[0];
260
- // TODO: Check is repeated logic, handle it.
261
- if (typeof value === "object") {
262
- this.printNextLineObject(type, source, key, value || {});
263
- } else if (typeof value == "function") {
264
- this.printInLineFunction(type, source, key, value);
265
- } else {
266
- this.printInLineElement(type, source, key, value);
267
- }
268
- } else {
269
- this.printMultiLineObject(type, source, params);
270
- }
271
- }
272
- /**
273
- * Function object() : Prints object.
274
- **/
275
- object(params = {}, notice = "") {
276
- if (!this.state) return;
277
- const source = Logger.getCallerName();
278
- params = Object.create(params);
279
- for (let key in params) {
280
- if (typeof params[key] === "object") {
281
- params[key] = JSON.stringify(this.useWrapper(params[key]), getCircularReplacer());
282
- }
283
- this.out.apply(this, [`%c(ob)-> %c%c${this.name}%c::%c${source}%c() [${notice}] ->> ${key}: '${params[key]}'%c`].concat(this.defaultStyle));
284
- }
285
- }
286
- /**
287
- * Function debug() : Notify debug.
288
- */
289
- debug(output) {
290
- if (!this.state) return;
291
- this.printFunctionNotify("db", Logger.getCallerName(), output);
292
- }
293
- /**
294
- * Function drop : Preview as continue of log which drop ite.
295
- */
296
- drop(according, data) {
297
- if (!this.state) return;
298
- const source = Logger.getCallerName();
299
- for (let key in according) {
300
- this.out.apply(this, [`%c(dr)-> %c%c${this.name}%c::%c${source}%c() ->> corresponding ${key}: '${according[key]}' RESULT: %c↓`].concat(this.defaultStyle));
301
- }
302
- this.out(data);
303
- }
304
- /**
305
- * Function throw() : Throws logged error.
306
- */
307
- throw(output, name = 'null', params = {}) {
308
- this.printFunctionNotify("tw", Logger.getCallerName(), output);
309
- if (params) this.printNextLineObject("tw", Logger.getCallerName(), name, params);
310
- throw new Error().stack;
311
- }
312
- /**
313
- * Function clone() : Create clone instance.
314
- */
315
- clone() {
316
- return Object.assign(Object.create(Object.getPrototypeOf(this)), this);
317
- }
318
- /**
319
- * Function printFunctionNotify() : Print simple log for notify source (function).
320
- *
321
- */
322
- printFunctionNotify(type, source, output) {
323
- this.out.apply(this, [`%c(${type})-> %c%c${this.name}%c::%c${source}%c() ${output}%c`].concat(this.defaultStyle));
324
- }
325
- /**
326
- * Function printInLineElement() : Print in line element.
327
- */
328
- printInLineElement(type, source, key, value) {
329
- this.out.apply(this, [`%c(${type})-> %c%c${this.name}%c::%c${source}%c() ->> ${key}: '${value}'%c`].concat(this.defaultStyle));
330
- }
331
- /**
332
- * Function printInLineFunction() : Print in line function.
333
- */
334
- printInLineFunction(type, source, key, fn) {
335
- fn = Logger.getFunctionView(fn);
336
- this.printInLineElement(type, source, key, fn);
337
- }
338
- /**
339
- * Function printInLineString() : Print in line string.
340
- */
341
- printInLineString(type, source, string) {
342
- this.printInLineElement(type, source, "(string)", string);
343
- }
344
- /**
345
- * Function printNextLineObject() : Print object in next line.
346
- */
347
- printNextLineObject(type, source, key, obj) {
348
- obj = this.useWrapper(obj);
349
- this.out.apply(this, [`%c(${type})-> %c%c${this.name}%c::%c${source}%c() ->> ${key} %c↓`].concat(this.defaultStyle));
350
- // print in next line
351
- this.out(obj);
352
- }
353
- /**
354
- * Function printMultiLineObject() : Print object in multiline format.
355
- */
356
- printMultiLineObject(type, source, obj) {
357
- this.out.apply(this, [`%c(${type})-> %c%c${this.name}%c::%c${source}%c(${Object.keys(obj).join(", ")}) %c↓`].concat(this.defaultStyle));
358
- for (let key in obj) {
359
- let value = obj[key];
360
- if (typeof value === "object") {
361
- value = JSON.stringify(this.useWrapper(value), getCircularReplacer());
362
- } else if (typeof obj[key] == "function") {
363
- value = Logger.getFunctionView(value);
364
- }
365
- this.out.apply(this, ["%c" + key + ": `" + this.useWrapper(value) + "`", "color: #a3a3a3"]);
366
- }
367
- }
368
- /**
369
- * Function getRandomColor() : Return random color.
370
- */
371
- getRandomColor() {
372
- const letters = "0123456789ABCDEF";
373
- let color = "#";
374
- for (let i = 0; i < 6; i++) {
375
- color += letters[Math.floor(Math.random() * 16)];
376
- }
377
- let similar = Logger.colorsInUse.some(value => {
378
- // it returns the ratio of difference... closer to 1.0 is less difference.
379
- return hexColorDelta(color, value) >= 0.8;
380
- });
381
- // if the color is similar, try again.
382
- if (similar) {
383
- return this.getRandomColor();
384
- }
385
- return color;
386
- }
387
- /**
388
- * Function out() : Print console log with style
389
- */
390
- out(...args) {
391
- this.outputHandler.apply(this, args);
392
- }
393
- }
394
-
395
- /**
396
- * @author: Leonid Vinikov <czf.leo123@gmail.com>
397
- * @description: Base for all commands, they are all will be managed by the `Commands` managers.
398
- * @TODO
399
- * - Add validateArgs method or find something better.
400
- */
401
- class CommandBase extends ObjectBase {
402
- args = {};
403
- options = {};
404
- logger;
405
- constructor(args = {}, options = {}) {
406
- super();
407
- const name = this.constructor.getName();
408
- this.logger = new Logger(name, true, {
409
- sameColor: true
410
- });
411
- this.logger.startWith({
412
- args,
413
- options
414
- });
415
- this.initialize(args, options);
416
- }
417
- initialize(args, options) {
418
- this.args = args;
419
- this.options = options;
420
- }
421
- apply(args = this.args, options = this.options) {
422
- throw new ForceMethod(this, "apply");
423
- }
424
- async run() {
425
- this.onBeforeApply && this.onBeforeApply();
426
- const result = await this.apply(this.args, this.options);
427
- this.onAfterApply && this.onAfterApply();
428
- return result;
429
- }
430
- getArgs() {
431
- return this.args;
432
- }
433
- getOptions() {
434
- return this.options;
435
- }
436
- }
437
-
438
- /**
439
- * @author: Leonid Vinikov <czf.leo123@gmail.com>
440
- * @description: CommandPublic represents a USER action, every class which inherit from this class will USER action.
441
- * */
442
- class CommandPublic extends CommandBase {
443
- static getName() {
444
- return 'Core/CommandBases/CommandPublic';
445
- }
446
- }
447
-
448
- let commands = {};
449
- let controllers = {};
450
- let data = {};
451
- let internal = {};
452
-
453
- var index$5 = /*#__PURE__*/Object.freeze({
454
- __proto__: null,
455
- get commands () { return commands; },
456
- get controllers () { return controllers; },
457
- get data () { return data; },
458
- get internal () { return internal; }
459
- });
460
-
461
- /**
462
- * @author: Leonid Vinikov <czf.leo123@gmail.com>
463
- * @description: Each data command should represent a final REST endpoint.
464
- */
465
- class CommandData extends CommandBase {
466
- static getName() {
467
- return 'Core/CommandBases/CommandData';
468
- }
469
- /**
470
- * Function getEndpoint() : Override this method is required to determine endpoint and magic query params.
471
- * @example
472
- * ```
473
- * args = { query: { id: 1 } };
474
- * getEndpoint() = '/api/v1/users/{id}';
475
- * result = '/api/v1/users/1';
476
- * ```
477
- */
478
- getEndpoint() {
479
- throw new ForceMethod(this, 'getEndpoint');
480
- }
481
- apply(args = this.args, options = this.options) {
482
- const endpoint = this.applyEndpointFormat(this.getEndpoint(), args);
483
- return data.getClient().fetch(endpoint, data.currentHttpMethod, args || null);
484
- }
485
- applyEndpointFormat(endpoint, data = {}) {
486
- // Replace query with `magic` placeholders.
487
- if (endpoint.includes('{')) {
488
- endpoint = endpoint.split('/').map(endpointPart => {
489
- const match = endpointPart.match('\\{(.*?)\\}');
490
- if (match?.length && 'undefined' !== typeof data[match[1]]) {
491
- return data[match[1]];
492
- }
493
- return endpointPart;
494
- }).join('/');
495
- }
496
- return endpoint;
497
- }
498
- }
499
-
500
- /**
501
- * @author: Leonid Vinikov <czf.leo123@gmail.com>
502
- * @description: CommandInternal, is used when part of the logic needed to be in the command but not represent a user action.
503
- */
504
- class CommandInternal extends CommandBase {
505
- static getName() {
506
- return 'Core/CommandBases/CommandInternal';
507
- }
508
- }
509
-
510
- var index$4 = /*#__PURE__*/Object.freeze({
511
- __proto__: null,
512
- CommandBase: CommandBase,
513
- CommandData: CommandData,
514
- CommandInternal: CommandInternal,
515
- CommandPublic: CommandPublic
516
- });
517
-
518
- /**
519
- * @author: Leonid Vinikov <czf.leo123@gmail.com>
520
- * @description: Responsible for commands, Aka ( CommandsSpace ).
521
- */
522
- class Controller extends ObjectBase {
523
- commands;
524
- data;
525
- internal;
526
- static getName() {
527
- return 'Core/Core/Controller';
528
- }
529
- constructor() {
530
- super();
531
- this.initialize();
532
- }
533
- initialize() {
534
- this.register();
535
- this.setupHooks && this.setupHooks();
536
- }
537
- register() {
538
- this.commands = commands.register(this.getCommands(), this);
539
- this.data = data.register(this.getData(), this);
540
- this.internal = internal.register(this.getInternal(), this);
541
- }
542
- getCommands() {
543
- return {};
544
- }
545
- getData() {
546
- return {};
547
- }
548
- getInternal() {
549
- return {};
550
- }
551
- }
552
-
553
- var index$3 = /*#__PURE__*/Object.freeze({
554
- __proto__: null,
555
- Controller: Controller,
556
- ObjectBase: ObjectBase
557
- });
558
-
559
- class CommandAlreadyRegistered extends Error {
560
- constructor(command) {
561
- super(`Command: '${command.getName()}' is already registered`);
562
- }
563
- }
564
-
565
- /**
566
- * @author: Leonid Vinikov <czf.leo123@gmail.com>
567
- */
568
- class CommandNotFound extends Error {
569
- constructor(command) {
570
- super(`Command: '${command}' is not found`);
571
- }
572
- }
573
-
574
- class ControllerAlreadyRegistered extends Error {
575
- constructor(controller) {
576
- super(`Controller: '${controller.getName()}' is already registered`);
577
- }
578
- }
579
-
580
- var index$2 = /*#__PURE__*/Object.freeze({
581
- __proto__: null,
582
- CommandAlreadyRegistered: CommandAlreadyRegistered,
583
- CommandNotFound: CommandNotFound,
584
- ControllerAlreadyRegistered: ControllerAlreadyRegistered,
585
- ForceMethod: ForceMethod
586
- });
587
-
588
- var index$1 = /*#__PURE__*/Object.freeze({
589
- __proto__: null,
590
- Logger: Logger
591
- });
592
-
593
- /**
594
- * @author: Leonid Vinikov <czf.leo123@gmail.com>
595
- * @description: Responsible for manging/running/hooking commands.
596
- */
597
- class Commands extends ObjectBase {
598
- static trace = [];
599
- current = {};
600
- currentArgs = {};
601
- trace = [];
602
- commands = {};
603
- onBeforeHooks = {};
604
- onBeforeUIHooks = {};
605
- onAfterHooks = {};
606
- onAfterOnceHooks = {};
607
- onAfterUIHooks = {};
608
- onAfterAffectHooks = {};
609
- logger;
610
- static getName() {
611
- return 'Core/Managers/Commands';
612
- }
613
- static async runCallbacks(callbacks, args = {}, options = {}) {
614
- const callbacksLength = callbacks?.length || 0;
615
- for (let i = 0; i < callbacksLength; ++i) {
616
- const callback = options.pop === true ? callbacks.pop() : callbacks[i];
617
- if (!callback) {
618
- throw new Error("Callback is not defined.");
619
- }
620
- await callback(args, options);
621
- }
622
- }
623
- static hookCommand(stack, hookCommand, context) {
624
- if (!stack[hookCommand]) {
625
- stack[hookCommand] = [];
626
- }
627
- stack[hookCommand].push(context);
628
- }
629
- constructor() {
630
- super();
631
- this.logger = new Logger(this.getName(), true);
632
- this.logger.startEmpty();
633
- }
634
- async run(command, args = {}, options = {}) {
635
- if (typeof command === "string") {
636
- command = this.getCommandInstance(command, args, options);
637
- }
638
- this.attachCurrent(command, args);
639
- const result = await this.runInstance(command, args, options);
640
- this.detachCurrent(command);
641
- return result;
642
- }
643
- register(commands, controller) {
644
- const result = {};
645
- Object.values(commands).forEach(command => {
646
- const commandName = command.getName();
647
- if (this.commands[commandName]) {
648
- throw new CommandAlreadyRegistered(command);
649
- }
650
- this.commands[commandName] = command;
651
- result[commandName] = command;
652
- });
653
- return result;
654
- }
655
- getAll() {
656
- return this.commands;
657
- }
658
- getByName(name) {
659
- return this.commands[name];
660
- }
661
- getLogger() {
662
- return this.logger;
663
- }
664
- getCommandInstance(name, args = {}, options = {}) {
665
- const CommandClass = this.commands[name];
666
- if (!CommandClass) {
667
- throw new CommandNotFound(name);
668
- }
669
- // @ts-ignore
670
- return new CommandClass(args, options);
671
- }
672
- /**
673
- * Function onBefore() : Used to set hooks that effects only data and not UI.
674
- */
675
- onBefore(hookCommand, callback) {
676
- Commands.hookCommand(this.onBeforeHooks, hookCommand, callback);
677
- }
678
- /**
679
- * Function onBeforeUI() : Used to set hooks that effects only UI.
680
- */
681
- onBeforeUI(hookCommand, callback) {
682
- Commands.hookCommand(this.onBeforeUIHooks, hookCommand, callback);
683
- }
684
- /**
685
- * Function onAfter() : Used to set hooks that effects only data and not UI.
686
- */
687
- onAfter(hookCommand, callback) {
688
- Commands.hookCommand(this.onAfterHooks, hookCommand, callback);
689
- }
690
- /**
691
- * Function onAfterUI() : Used to set hooks that effects only UI.
692
- */
693
- onAfterUI(command, callback) {
694
- Commands.hookCommand(this.onAfterUIHooks, command, callback);
695
- }
696
- /**
697
- * Function onAfterOnce() : Used to set hooks that effects only data and not UI.
698
- */
699
- onAfterOnce(command, callback) {
700
- Commands.hookCommand(this.onAfterOnceHooks, command, callback);
701
- }
702
- /**
703
- * Function onAfterAffect() : Used to register a trigger that runs command after `hookCommand` run's.
704
- */
705
- onAfterAffect(hookCommand, affectCommand) {
706
- Commands.hookCommand(this.onAfterAffectHooks, hookCommand, affectCommand);
707
- }
708
- onBeforeRun(command, args = {}, options = {}) {
709
- if (this.onBeforeHooks[command.getName()]) {
710
- const callbacks = this.onBeforeHooks[command.getName()];
711
- callbacks.forEach(callback => callback(args, options));
712
- }
713
- if (this.onBeforeUIHooks[command.getName()]) {
714
- const callbacks = this.onBeforeUIHooks[command.getName()];
715
- callbacks.forEach(callback => callback(args, options));
716
- }
717
- }
718
- async runInstance(command, args = {}, options = {}) {
719
- let result = null;
720
- // TODO: Maybe a logger method to handle such cases.
721
- if (Object.keys(args).length) {
722
- this.logger.startWith({
723
- command: command.getName(),
724
- options,
725
- CommandArgs: "->"
726
- });
727
- this.logger.debug("CommandArgs:");
728
- this.logger.object(args);
729
- } else {
730
- this.logger.startWith({
731
- command: command.getName(),
732
- options,
733
- args
734
- });
735
- }
736
- this.onBeforeRun(command, args, options);
737
- result = await command.run();
738
- await this.onAfterRun(command, args, options, result);
739
- return result;
740
- }
741
- async onAfterRun(command, args, options, result) {
742
- options = Object.assign({}, options);
743
- if (this.onAfterAffectHooks[command.getName()]) {
744
- this.onAfterAffectHooks[command.getName()].forEach(command => {
745
- args.result = result;
746
- result = this.run(command.toString(), args, options);
747
- });
748
- result = await result;
749
- }
750
- if (this.onAfterHooks) {
751
- args.result = result;
752
- await Commands.runCallbacks(Object.assign([], this.onAfterHooks[command.getName()]), args, options);
753
- }
754
- if (this.onAfterOnceHooks) {
755
- await Commands.runCallbacks(this.onAfterOnceHooks[command.getName()], args, {
756
- ...options,
757
- pop: true // Delete after run.
758
- });
759
- }
760
-
761
- if (this.onAfterUIHooks) {
762
- Commands.runCallbacks(Object.assign([], this.onAfterUIHooks[command.getName()]), args, options);
763
- }
764
- return result;
765
- }
766
- attachCurrent(command, args = {}) {
767
- this.current[command.getName()] = command;
768
- this.currentArgs[command.getName()] = args;
769
- this.trace.push(command.getName());
770
- Commands.trace.push(command.getName());
771
- }
772
- detachCurrent(command) {
773
- delete this.current[command.getName()];
774
- delete this.currentArgs[command.getName()];
775
- Commands.trace.pop();
776
- this.trace.pop();
777
- }
778
- }
779
-
780
- /**
781
- * @author: Leonid Vinikov <czf.leo123@gmail.com>
782
- * @description: Responsible for manging controllers, each controller is global singleton instance.
783
- */
784
- class Controllers extends ObjectBase {
785
- controllers = {};
786
- static getName() {
787
- return 'Core/Managers/Controllers';
788
- }
789
- get(name) {
790
- return this.controllers[name];
791
- }
792
- getAll() {
793
- return this.controllers;
794
- }
795
- register(controller) {
796
- if (this.controllers[controller.getName()]) {
797
- throw new ControllerAlreadyRegistered(controller);
798
- }
799
- // Register.
800
- this.controllers[controller.getName()] = controller;
801
- return controller;
802
- }
803
- }
804
-
805
- var HTTPMethodEnum;
806
- (function (HTTPMethodEnum) {
807
- HTTPMethodEnum["DELETE"] = "DELETE";
808
- HTTPMethodEnum["GET"] = "GET";
809
- HTTPMethodEnum["OPTIONS"] = "OPTIONS";
810
- HTTPMethodEnum["PATCH"] = "PATCH";
811
- HTTPMethodEnum["POST"] = "POST";
812
- HTTPMethodEnum["PUT"] = "PUT";
813
- HTTPMethodEnum["__EMPTY__"] = "";
814
- })(HTTPMethodEnum || (HTTPMethodEnum = {}));
815
-
816
- /**
817
- * @author: Leonid Vinikov <czf.leo123@gmail.com>
818
- * @description: Providing a simple wrapper for fetch API.
819
- */
820
- class Http extends ObjectBase {
821
- logger;
822
- apiBaseUrl;
823
- static getName() {
824
- return 'Core/Clients/Http';
825
- }
826
- /**
827
- * Function constructor() : Create the http.
828
- */
829
- constructor(apiBaseUrl = 'http://localhost') {
830
- super();
831
- this.logger = new Logger(Http.getName(), true);
832
- this.logger.startWith({
833
- apiBaseUrl
834
- });
835
- this.apiBaseUrl = apiBaseUrl + '/';
836
- }
837
- /**
838
- * Function fetch() : Fetch api.
839
- */
840
- async fetch(path, method, body = null) {
841
- this.logger.startWith({
842
- path,
843
- method,
844
- body
845
- });
846
- const params = {
847
- 'credentials': 'include'
848
- },
849
- // Support cookies.
850
- headers = {};
851
- if ([HTTPMethodEnum.POST, HTTPMethodEnum.PUT, HTTPMethodEnum.PATCH].includes(method)) {
852
- Object.assign(headers, {
853
- 'Content-Type': 'application/json'
854
- });
855
- Object.assign(params, {
856
- method,
857
- headers: headers,
858
- body: JSON.stringify(body)
859
- });
860
- } else {
861
- Object.assign(params, {
862
- headers
863
- });
864
- }
865
- const response = await globalThis.fetch(this.apiBaseUrl + path, params);
866
- let data = undefined;
867
- try {
868
- data = await response.json();
869
- } catch (e) {
870
- console.error(e);
871
- return false;
872
- }
873
- // TODO: This is part should be modular and not hard coded.
874
- if (data?.error && data?.global && data?.message) {
875
- throw new Error(data.message);
876
- }
877
- this.logger.drop({
878
- path
879
- }, data);
880
- return data;
881
- }
882
- }
883
-
884
- /**
885
- * @author: Leonid Vinikov <czf.leo123@gmail.com>
886
- * @description: Responsible for manging data commands which are wrappers for HTTP requests.
887
- */
888
- class Data extends Commands {
889
- static client;
890
- currentHttpMethod;
891
- static getName() {
892
- return 'Core/Managers/Data';
893
- }
894
- constructor(Config) {
895
- super();
896
- // @ts-ignore
897
- Data.client = new Http(Config.baseURL);
898
- }
899
- getClient() {
900
- return Data.client;
901
- }
902
- get(command, args = {}, options = {}) {
903
- this.currentHttpMethod = HTTPMethodEnum.GET;
904
- return super.run(command, args, options);
905
- }
906
- update(command, args = {}, options = {}) {
907
- this.currentHttpMethod = HTTPMethodEnum.PATCH;
908
- return super.run(command, args, options);
909
- }
910
- delete(command, args = {}, options = {}) {
911
- this.currentHttpMethod = HTTPMethodEnum.DELETE;
912
- return super.run(command, args, options);
913
- }
914
- create(command, args = {}, options = {}) {
915
- this.currentHttpMethod = HTTPMethodEnum.POST;
916
- return super.run(command, args, options);
917
- }
918
- async runInstance(command, args = {}, options = {}) {
919
- if (!this.currentHttpMethod) {
920
- throw new Error('Cannot run directly use one of the http methods: "get", "update", "delete, "create');
921
- }
922
- // New args.
923
- const newArgs = {
924
- type: this.currentHttpMethod,
925
- args: {
926
- query: {},
927
- data: {}
928
- }
929
- };
930
- if (HTTPMethodEnum.GET === this.currentHttpMethod) {
931
- newArgs.args.query = args;
932
- } else {
933
- newArgs.args.data = args;
934
- }
935
- args.result = await super.runInstance(command, newArgs, options);
936
- // Clear method type.
937
- this.currentHttpMethod = HTTPMethodEnum.__EMPTY__;
938
- return args.result;
939
- }
940
- }
941
-
942
- /**
943
- * @author: Leonid Vinikov <czf.leo123@gmail.com>
944
- * @description: Responsible for manging internal commands, To serve commands that are not triggered by user.
945
- */
946
- class Internal extends Commands {
947
- static getName() {
948
- return 'Core/Managers/Internal';
949
- }
950
- }
951
-
952
- var index = /*#__PURE__*/Object.freeze({
953
- __proto__: null,
954
- Commands: Commands,
955
- Controllers: Controllers,
956
- Data: Data,
957
- Internal: Internal
958
- });
959
-
960
- var exported = /*#__PURE__*/Object.freeze({
961
- __proto__: null,
962
- commandBases: index$4,
963
- core: index$3,
964
- errors: index$2,
965
- managerBases: index,
966
- managers: index$5,
967
- modules: index$1,
968
- utils: index$6
969
- });
970
-
971
- var name = "@zenflux/core";
972
- var version = "0.0.0-dev.0";
973
- var description = "ZenFlux core";
974
- var author = "Leonid Vinikov <leonidvinikov@gmail.com> (https://github.com/iNewLegend)";
975
- var scripts = {
976
- test: "export flow_modules_logger=off && jest",
977
- build: "rollup --config rollup.config.ts --configPlugin typescript"
978
- };
979
- var repository = {
980
- type: "git",
981
- url: "git+https://github.com/zenflux/core.git"
982
- };
983
- var keywords = [
984
- "zenflux",
985
- "zen",
986
- "flux",
987
- "commands",
988
- "manager",
989
- "commands manager"
990
- ];
991
- var license = "MIT";
992
- var main = "dist/cjs/zenflux-core.js";
993
- var unpkg = "dist/umd/zenflux-core.js";
994
- var module$1 = "dist/es/zenflux-core.js";
995
- var types = "types/index.d.ts";
996
- var devDependencies = {
997
- "@babel/core": "^7.20.7",
998
- "@babel/plugin-transform-runtime": "^7.19.6",
999
- "@babel/preset-env": "^7.20.2",
1000
- "@babel/preset-typescript": "^7.18.6",
1001
- "@babel/runtime": "^7.20.7",
1002
- "@rollup/plugin-babel": "^6.0.3",
1003
- "@rollup/plugin-json": "^6.0.0",
1004
- "@rollup/plugin-node-resolve": "^15.0.1",
1005
- "@rollup/plugin-replace": "^5.0.2",
1006
- "@rollup/plugin-terser": "^0.2.1",
1007
- "@rollup/plugin-typescript": "^10.0.1",
1008
- "@types/jest": "^29.2.5",
1009
- "@typescript-eslint/eslint-plugin": "^5.48.0",
1010
- "@typescript-eslint/parser": "^5.48.0",
1011
- "@zenflux/rollup": "^0.0.0-dev.0",
1012
- "babel-jest": "^29.3.1",
1013
- rollup: "^3.9.1",
1014
- "ts-jest": "^29.0.3",
1015
- tslib: "^2.4.1"
1016
- };
1017
- var dependencies = {
1018
- "@babel/runtime": "^7.19.0"
1019
- };
1020
- var pkg = {
1021
- name: name,
1022
- version: version,
1023
- description: description,
1024
- author: author,
1025
- scripts: scripts,
1026
- repository: repository,
1027
- keywords: keywords,
1028
- license: license,
1029
- main: main,
1030
- unpkg: unpkg,
1031
- module: module$1,
1032
- types: types,
1033
- devDependencies: devDependencies,
1034
- dependencies: dependencies
1035
- };
1036
-
1037
- let isInitialized = false;
1038
- function errorInitTwice() {
1039
- if (isInitialized) {
1040
- throw new Error('ZenCore is already initialized.');
1041
- }
1042
- }
1043
- errorInitTwice();
1044
- let config = {
1045
- version: pkg.version
1046
- };
1047
- const afterInitializeCallbacks = [];
1048
- const CoreAPI = {
1049
- initialize: configuration => {
1050
- errorInitTwice();
1051
- config = configuration || config;
1052
- commands = new Commands();
1053
- controllers = new Controllers();
1054
- data = new Data(config);
1055
- internal = new Internal();
1056
- isInitialized = true;
1057
- afterInitializeCallbacks.forEach(callback => callback());
1058
- },
1059
- destroy: () => {
1060
- isInitialized = false;
1061
- commands = {};
1062
- controllers = {};
1063
- data = {};
1064
- internal = {};
1065
- },
1066
- onAfterInitialize: callback => {
1067
- afterInitializeCallbacks.push(callback);
1068
- },
1069
- config,
1070
- ...exported
1071
- };
1072
- // TODO: Make it available only for development.
1073
- if (!globalThis?.ZenCore) globalThis.ZenCore = CoreAPI;
1074
-
1075
- exports.commandBases = index$4;
1076
- exports.core = index$3;
1077
- exports.default = CoreAPI;
1078
- exports.errors = index$2;
1079
- exports.managerBases = index;
1080
- exports.managers = index$5;
1081
- exports.modules = index$1;
1082
- exports.utils = index$6;