@zenflux/core 0.0.0-development.3 → 0.0.0-devlopment.2

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