@zenflux/core 0.0.0-abc.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.
- package/LICENSE +21 -0
- package/README.md +2 -0
- package/dist/cjs/zenflux-core.js +1102 -0
- package/dist/es/rollup.config.d.ts +23 -0
- package/dist/es/src/clients/http.d.ts +20 -0
- package/dist/es/src/command-bases/command-base.d.ts +22 -0
- package/dist/es/src/command-bases/command-data.d.ts +17 -0
- package/dist/es/src/command-bases/command-internal.d.ts +9 -0
- package/dist/es/src/command-bases/command-public.d.ts +9 -0
- package/dist/es/src/command-bases/index.d.ts +7 -0
- package/dist/es/src/core/controller.d.ts +35 -0
- package/dist/es/src/core/index.d.ts +2 -0
- package/dist/es/src/core/object-base.d.ts +14 -0
- package/dist/es/src/enums/http.d.ts +12 -0
- package/dist/es/src/errors/command-already-registered.d.ts +8 -0
- package/dist/es/src/errors/command-not-found.d.ts +7 -0
- package/dist/es/src/errors/controller-already-registered.d.ts +8 -0
- package/dist/es/src/errors/force-method.d.ts +11 -0
- package/dist/es/src/errors/index.d.ts +4 -0
- package/dist/es/src/exports.d.ts +10 -0
- package/dist/es/src/index.d.ts +5 -0
- package/dist/es/src/initializer.d.ts +19 -0
- package/dist/es/src/interfaces/commands.d.ts +13 -0
- package/dist/es/src/interfaces/config.d.ts +10 -0
- package/dist/es/src/interfaces/object-base.d.ts +10 -0
- package/dist/es/src/manager-bases/commands.d.ts +74 -0
- package/dist/es/src/manager-bases/controllers.d.ts +17 -0
- package/dist/es/src/manager-bases/data.d.ts +23 -0
- package/dist/es/src/manager-bases/index.d.ts +7 -0
- package/dist/es/src/manager-bases/internal.d.ts +9 -0
- package/dist/es/src/managers/index.d.ts +8 -0
- package/dist/es/src/modules/index.d.ts +1 -0
- package/dist/es/src/modules/logger.d.ts +117 -0
- package/dist/es/src/utils/index.d.ts +2 -0
- package/dist/es/src/utils/object.d.ts +6 -0
- package/dist/es/src/utils/rgb.d.ts +6 -0
- package/dist/es/zenflux-core.js +1091 -0
- package/dist/es/zenflux-core.mjs +12 -0
- package/dist/umd/zenflux-core.js +12 -0
- package/package.json +55 -0
- package/src/clients/http.ts +81 -0
- package/src/command-bases/command-base.ts +67 -0
- package/src/command-bases/command-data.ts +54 -0
- package/src/command-bases/command-internal.ts +13 -0
- package/src/command-bases/command-public.ts +13 -0
- package/src/command-bases/index.ts +7 -0
- package/src/core/controller.ts +61 -0
- package/src/core/index.ts +2 -0
- package/src/core/object-base.ts +46 -0
- package/src/enums/http.ts +12 -0
- package/src/errors/command-already-registered.ts +12 -0
- package/src/errors/command-not-found.ts +10 -0
- package/src/errors/controller-already-registered.ts +12 -0
- package/src/errors/force-method.ts +22 -0
- package/src/errors/index.ts +4 -0
- package/src/exports.ts +11 -0
- package/src/index.ts +7 -0
- package/src/initializer.ts +63 -0
- package/src/interfaces/commands.ts +17 -0
- package/src/interfaces/config.ts +11 -0
- package/src/interfaces/object-base.ts +12 -0
- package/src/manager-bases/commands.ts +272 -0
- package/src/manager-bases/controllers.ts +36 -0
- package/src/manager-bases/data.ts +89 -0
- package/src/manager-bases/index.ts +7 -0
- package/src/manager-bases/internal.ts +13 -0
- package/src/managers/index.ts +9 -0
- package/src/modules/index.ts +1 -0
- package/src/modules/logger.ts +413 -0
- package/src/utils/index.ts +2 -0
- package/src/utils/object.ts +18 -0
- package/src/utils/rgb.ts +33 -0
- package/types/index.d.ts +2 -0
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
class t extends Error{constructor(t,e){super(`ForeMethod implementation: at '${t}' method: '${e}'`)}}class e extends Error{constructor(t,e){super(`ForeMethod implementation: at '${t.getName()}' method: '${e}'`)}}let r=0;class s{virtualId=0;static getName(){throw new t("ObjectBase","getName")}constructor(){this.virtualId=r,r++}getName(){return this.constructor.getName()}}
|
|
2
|
+
/**
|
|
3
|
+
* Function getCircularReplacer() : Reduce circular references.
|
|
4
|
+
*
|
|
5
|
+
* @copyright https://stackoverflow.com/a/53731154
|
|
6
|
+
*/
|
|
7
|
+
const n=()=>{const t=new WeakSet;return(e,r)=>{if("object"==typeof r&&null!==r){if(t.has(r))return;t.add(r)}return r}},o=function(t,e){t=t.replace("#",""),e=e.replace("#","");const r=parseInt(t.substring(0,2),16),s=parseInt(t.substring(2,4),16),n=parseInt(t.substring(4,6),16),o=parseInt(e.substring(0,2),16),a=parseInt(e.substring(2,4),16),i=parseInt(e.substring(4,6),16);let c=255-Math.abs(r-o),l=255-Math.abs(s-a),h=255-Math.abs(n-i);return c/=255,l/=255,h/=255,(c+l+h)/3};
|
|
8
|
+
/**
|
|
9
|
+
* Function hexColorDelta() : Return color difference in ratio decimal point.
|
|
10
|
+
*
|
|
11
|
+
* @copyright http://jsfiddle.net/96sME/
|
|
12
|
+
*/var a=Object.freeze({__proto__:null,getCircularReplacer:n,hexColorDelta:o});class i{static wrappers={};static wrapperDepth=0;static sharedData={};static colorsInUse=[];defaultStyle;color;outputHandler;args={};name;state=!1;static getName(){return"Core/Modules/Logger"}static reset(){i.wrappers={},i.wrapperDepth=0,i.colorsInUse=[],i.sharedData={}}static createCustomWrapper(t,e){i.wrappers[t]||(i.wrappers[t.name]=[]),i.wrappers[t.name].push({classType:t,callback:e})}static getCallerName(){const t=Error(),e=t.stack?t.stack.split("\n")[3].trim():"_UNKNOWN_CALLER_NAME_";return e.startsWith("at new")?"constructor":e.split(".")[1].split(" ")[0]}static getFunctionView(t){let e="anonymous function()";return"string"!=typeof t&&0!==t.name.length&&(e=t.name.split(" ")[1]+"()"),e}constructor(t,e=!1,r={}){"off"!==globalThis.process?.env.flow_modules_logger&&(this.state=e,this.args=r,this.name="",this.name="string"==typeof t?t:t.constructor.name,e&&this.initialize())}initialize(){this.args.sameColor?(i.sharedData[this.name]||(i.sharedData[this.name]=this.getRandomColor()),this.color=i.sharedData[this.name]):(this.color=this.getRandomColor(),i.colorsInUse.push(this.color)),this.outputHandler=console.log,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"]}setOutputHandler(t){this.outputHandler=t}useWrapper(t,e=!0){if(!t||"object"!=typeof t||Array.isArray(t))return t;i.wrapperDepth++;let r={...t};return Object.values(i.wrappers).forEach((([e])=>{t instanceof e.classType&&(r=e.callback(t)||r)})),4>i.wrapperDepth?(e&&r&&Object.entries(r).forEach((([t,e])=>{r[t]=this.useWrapper(e,!0)})),i.wrapperDepth--,r):(i.wrapperDepth--,r)}startEmpty(t=""){this.state&&this.printFunctionNotify("se",i.getCallerName(),t)}startWith(t){if(!this.state)return;t=Object.assign({},t);const e="se",r=i.getCallerName();if("string"==typeof t)this.printInLineString(e,r,t);else if(1===Object.keys(t).length){const s=Object.keys(t)[0];let n=Object.values(t)[0];"object"==typeof n?this.printNextLineObject(e,r,s,n||{}):"function"==typeof n?this.printInLineFunction(e,r,s,n):this.printInLineElement(e,r,s,n)}else this.printMultiLineObject(e,r,t)}object(t={},e=""){if(!this.state)return;const r=i.getCallerName();t=Object.create(t);for(let s in t)"object"==typeof t[s]&&(t[s]=JSON.stringify(this.useWrapper(t[s]),n())),this.out.apply(this,[`%c(ob)-> %c%c${this.name}%c::%c${r}%c() [${e}] ->> ${s}: '${t[s]}'%c`].concat(this.defaultStyle))}debug(t){this.state&&this.printFunctionNotify("db",i.getCallerName(),t)}drop(t,e){if(!this.state)return;const r=i.getCallerName();for(let e in t)this.out.apply(this,[`%c(dr)-> %c%c${this.name}%c::%c${r}%c() ->> corresponding ${e}: '${t[e]}' RESULT: %c↓`].concat(this.defaultStyle));this.out(e)}throw(t,e="null",r={}){throw this.printFunctionNotify("tw",i.getCallerName(),t),r&&this.printNextLineObject("tw",i.getCallerName(),e,r),Error().stack}clone(){return Object.assign(Object.create(Object.getPrototypeOf(this)),this)}printFunctionNotify(t,e,r){this.out.apply(this,[`%c(${t})-> %c%c${this.name}%c::%c${e}%c() ${r}%c`].concat(this.defaultStyle))}printInLineElement(t,e,r,s){this.out.apply(this,[`%c(${t})-> %c%c${this.name}%c::%c${e}%c() ->> ${r}: '${s}'%c`].concat(this.defaultStyle))}printInLineFunction(t,e,r,s){s=i.getFunctionView(s),this.printInLineElement(t,e,r,s)}printInLineString(t,e,r){this.printInLineElement(t,e,"(string)",r)}printNextLineObject(t,e,r,s){s=this.useWrapper(s),this.out.apply(this,[`%c(${t})-> %c%c${this.name}%c::%c${e}%c() ->> ${r} %c↓`].concat(this.defaultStyle)),this.out(s)}printMultiLineObject(t,e,r){this.out.apply(this,[`%c(${t})-> %c%c${this.name}%c::%c${e}%c(${Object.keys(r).join(", ")}) %c↓`].concat(this.defaultStyle));for(let t in r){let e=r[t];"object"==typeof e?e=JSON.stringify(this.useWrapper(e),n()):"function"==typeof r[t]&&(e=i.getFunctionView(e)),this.out.call(this,"%c"+t+": `"+this.useWrapper(e)+"`","color: #a3a3a3")}}getRandomColor(){let t="#";for(let e=0;6>e;e++)t+="0123456789ABCDEF"[Math.floor(16*Math.random())];return i.colorsInUse.some((e=>o(t,e)>=.8))?this.getRandomColor():t}out(...t){this.outputHandler.apply(this,t)}}class c extends s{args={};options={};logger;constructor(t={},e={}){super();const r=this.constructor.getName();this.logger=new i(r,!0,{sameColor:!0}),this.logger.startWith({args:t,options:e}),this.initialize(t,e)}initialize(t,e){this.args=t,this.options=e}apply(t=this.args,r=this.options){throw new e(this,"apply")}async run(){this.onBeforeApply&&this.onBeforeApply();const t=await this.apply(this.args,this.options);return this.onAfterApply&&this.onAfterApply(),t}getArgs(){return this.args}getOptions(){return this.options}}let l={},h={},u={},p={};var g=Object.freeze({__proto__:null,get commands(){return l},get controllers(){return h},get data(){return u},get internal(){return p}});var m=Object.freeze({__proto__:null,CommandBase:c,CommandData:class extends c{static getName(){return"Core/CommandBases/CommandData"}getEndpoint(){throw new e(this,"getEndpoint")}apply(t=this.args,e=this.options){const r=this.applyEndpointFormat(this.getEndpoint(),t);return u.getClient().fetch(r,u.currentHttpMethod,t||null)}applyEndpointFormat(t,e={}){return t.includes("{")&&(t=t.split("/").map((t=>{const r=t.match("\\{(.*?)\\}");return r?.length&&void 0!==e[r[1]]?e[r[1]]:t})).join("/")),t}},CommandInternal:class extends c{static getName(){return"Core/CommandBases/CommandInternal"}},CommandPublic:class extends c{static getName(){return"Core/CommandBases/CommandPublic"}}});var d=Object.freeze({__proto__:null,Controller:class extends s{commands;data;internal;static getName(){return"Core/Core/Controller"}constructor(){super(),this.initialize()}initialize(){this.register(),this.setupHooks&&this.setupHooks()}register(){this.commands=l.register(this.getCommands(),this),this.data=u.register(this.getData(),this),this.internal=p.register(this.getInternal(),this)}getCommands(){return{}}getData(){return{}}getInternal(){return{}}},ObjectBase:s});class f extends Error{constructor(t){super(`Command: '${t.getName()}' is already registered`)}}class C extends Error{constructor(t){super(`Command: '${t}' is not found`)}}class y extends Error{constructor(t){super(`Controller: '${t.getName()}' is already registered`)}}var b,N=Object.freeze({__proto__:null,CommandAlreadyRegistered:f,CommandNotFound:C,ControllerAlreadyRegistered:y,ForceMethod:e}),w=Object.freeze({__proto__:null,Logger:i});class O extends s{static trace=[];current={};currentArgs={};trace=[];commands={};onBeforeHooks={};onBeforeUIHooks={};onAfterHooks={};onAfterOnceHooks={};onAfterUIHooks={};onAfterAffectHooks={};logger;static getName(){return"Core/Managers/Commands"}static async runCallbacks(t,e={},r={}){const s=t?.length||0;for(let n=0;s>n;++n){const s=!0===r.pop?t.pop():t[n];if(!s)throw Error("Callback is not defined.");await s(e,r)}}static hookCommand(t,e,r){t[e]||(t[e]=[]),t[e].push(r)}constructor(){super(),this.logger=new i(this.getName(),!0),this.logger.startEmpty()}async run(t,e={},r={}){"string"==typeof t&&(t=this.getCommandInstance(t,e,r)),this.attachCurrent(t,e);const s=await this.runInstance(t,e,r);return this.detachCurrent(t),s}register(t,e){const r={};return Object.values(t).forEach((t=>{const e=t.getName();if(this.commands[e])throw new f(t);this.commands[e]=t,r[e]=t})),r}getAll(){return this.commands}getByName(t){return this.commands[t]}getLogger(){return this.logger}getCommandInstance(t,e={},r={}){const s=this.commands[t];if(!s)throw new C(t);return new s(e,r)}onBefore(t,e){O.hookCommand(this.onBeforeHooks,t,e)}onBeforeUI(t,e){O.hookCommand(this.onBeforeUIHooks,t,e)}onAfter(t,e){O.hookCommand(this.onAfterHooks,t,e)}onAfterUI(t,e){O.hookCommand(this.onAfterUIHooks,t,e)}onAfterOnce(t,e){O.hookCommand(this.onAfterOnceHooks,t,e)}onAfterAffect(t,e){O.hookCommand(this.onAfterAffectHooks,t,e)}onBeforeRun(t,e={},r={}){if(this.onBeforeHooks[t.getName()]){this.onBeforeHooks[t.getName()].forEach((t=>t(e,r)))}if(this.onBeforeUIHooks[t.getName()]){this.onBeforeUIHooks[t.getName()].forEach((t=>t(e,r)))}}async runInstance(t,e={},r={}){let s=null;return Object.keys(e).length?(this.logger.startWith({command:t.getName(),options:r,CommandArgs:"->"}),this.logger.debug("CommandArgs:"),this.logger.object(e)):this.logger.startWith({command:t.getName(),options:r,args:e}),this.onBeforeRun(t,e,r),s=await t.run(),await this.onAfterRun(t,e,r,s),s}async onAfterRun(t,e,r,s){return r=Object.assign({},r),this.onAfterAffectHooks[t.getName()]&&(this.onAfterAffectHooks[t.getName()].forEach((t=>{e.result=s,s=this.run(""+t,e,r)})),s=await s),this.onAfterHooks&&(e.result=s,await O.runCallbacks(Object.assign([],this.onAfterHooks[t.getName()]),e,r)),this.onAfterOnceHooks&&await O.runCallbacks(this.onAfterOnceHooks[t.getName()],e,{...r,pop:!0}),this.onAfterUIHooks&&O.runCallbacks(Object.assign([],this.onAfterUIHooks[t.getName()]),e,r),s}attachCurrent(t,e={}){this.current[t.getName()]=t,this.currentArgs[t.getName()]=e,this.trace.push(t.getName()),O.trace.push(t.getName())}detachCurrent(t){delete this.current[t.getName()],delete this.currentArgs[t.getName()],O.trace.pop(),this.trace.pop()}}class A extends s{controllers={};static getName(){return"Core/Managers/Controllers"}get(t){return this.controllers[t]}getAll(){return this.controllers}register(t){if(this.controllers[t.getName()])throw new y(t);return this.controllers[t.getName()]=t,t}}!function(t){t.DELETE="DELETE",t.GET="GET",t.OPTIONS="OPTIONS",t.PATCH="PATCH",t.POST="POST",t.PUT="PUT",t.__EMPTY__=""}(b||(b={}));class k extends s{logger;apiBaseUrl;static getName(){return"Core/Clients/Http"}constructor(t="http://localhost"){super(),this.logger=new i(k.getName(),!0),this.logger.startWith({apiBaseUrl:t}),this.apiBaseUrl=t+"/"}async fetch(t,e,r=null){this.logger.startWith({path:t,method:e,body:r});const s={credentials:"include"},n={};[b.POST,b.PUT,b.PATCH].includes(e)?(Object.assign(n,{"Content-Type":"application/json"}),Object.assign(s,{method:e,headers:n,body:JSON.stringify(r)})):Object.assign(s,{headers:n});const o=await globalThis.fetch(this.apiBaseUrl+t,s);let a;try{a=await o.json()}catch(t){return console.error(t),!1}if(a?.error&&a?.global&&a?.message)throw Error(a.message);return this.logger.drop({path:t},a),a}}class E extends O{static client;currentHttpMethod;static getName(){return"Core/Managers/Data"}constructor(t){super(),E.client=new k(t.baseURL)}getClient(){return E.client}get(t,e={},r={}){return this.currentHttpMethod=b.GET,super.run(t,e,r)}update(t,e={},r={}){return this.currentHttpMethod=b.PATCH,super.run(t,e,r)}delete(t,e={},r={}){return this.currentHttpMethod=b.DELETE,super.run(t,e,r)}create(t,e={},r={}){return this.currentHttpMethod=b.POST,super.run(t,e,r)}async runInstance(t,e={},r={}){if(!this.currentHttpMethod)throw Error('Cannot run directly use one of the http methods: "get", "update", "delete, "create');const s={type:this.currentHttpMethod,args:{query:{},data:{}}};return b.GET===this.currentHttpMethod?s.args.query=e:s.args.data=e,e.result=await super.runInstance(t,s,r),this.currentHttpMethod=b.__EMPTY__,e.result}}class H extends O{static getName(){return"Core/Managers/Internal"}}var _=Object.freeze({__proto__:null,Commands:O,Controllers:A,Data:E,Internal:H}),j=Object.freeze({__proto__:null,commandBases:m,core:d,errors:N,managerBases:_,managers:g,modules:w,utils:a}),I="0.0.0-abc.0";let $=!1;function B(){if($)throw Error("ZenCore is already initialized.")}B();let M={version:I};const T=[],U={initialize:t=>{B(),M=t||M,l=new O,h=new A,u=new E(M),p=new H,$=!0,T.forEach((t=>t()))},destroy:()=>{$=!1,l={},h={},u={},p={}},onAfterInitialize:t=>{T.push(t)},config:M,...j};export{m as commandBases,d as core,U as default,N as errors,_ as managerBases,g as managers,w as modules,a as utils};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self)["@zenflux/core"]={})}(this,(function(t){"use strict";class e extends Error{constructor(t,e){super(`ForeMethod implementation: at '${t}' method: '${e}'`)}}class r extends Error{constructor(t,e){super(`ForeMethod implementation: at '${t.getName()}' method: '${e}'`)}}let s=0;class o{virtualId=0;static getName(){throw new e("ObjectBase","getName")}constructor(){this.virtualId=s,s++}getName(){return this.constructor.getName()}}
|
|
2
|
+
/**
|
|
3
|
+
* Function getCircularReplacer() : Reduce circular references.
|
|
4
|
+
*
|
|
5
|
+
* @copyright https://stackoverflow.com/a/53731154
|
|
6
|
+
*/
|
|
7
|
+
const n=()=>{const t=new WeakSet;return(e,r)=>{if("object"==typeof r&&null!==r){if(t.has(r))return;t.add(r)}return r}},a=function(t,e){t=t.replace("#",""),e=e.replace("#","");const r=parseInt(t.substring(0,2),16),s=parseInt(t.substring(2,4),16),o=parseInt(t.substring(4,6),16),n=parseInt(e.substring(0,2),16),a=parseInt(e.substring(2,4),16),i=parseInt(e.substring(4,6),16);let c=255-Math.abs(r-n),l=255-Math.abs(s-a),h=255-Math.abs(o-i);return c/=255,l/=255,h/=255,(c+l+h)/3};
|
|
8
|
+
/**
|
|
9
|
+
* Function hexColorDelta() : Return color difference in ratio decimal point.
|
|
10
|
+
*
|
|
11
|
+
* @copyright http://jsfiddle.net/96sME/
|
|
12
|
+
*/var i=Object.freeze({__proto__:null,getCircularReplacer:n,hexColorDelta:a});class c{static wrappers={};static wrapperDepth=0;static sharedData={};static colorsInUse=[];defaultStyle;color;outputHandler;args={};name;state=!1;static getName(){return"Core/Modules/Logger"}static reset(){c.wrappers={},c.wrapperDepth=0,c.colorsInUse=[],c.sharedData={}}static createCustomWrapper(t,e){c.wrappers[t]||(c.wrappers[t.name]=[]),c.wrappers[t.name].push({classType:t,callback:e})}static getCallerName(){const t=Error(),e=t.stack?t.stack.split("\n")[3].trim():"_UNKNOWN_CALLER_NAME_";return e.startsWith("at new")?"constructor":e.split(".")[1].split(" ")[0]}static getFunctionView(t){let e="anonymous function()";return"string"!=typeof t&&0!==t.name.length&&(e=t.name.split(" ")[1]+"()"),e}constructor(t,e=!1,r={}){"off"!==globalThis.process?.env.flow_modules_logger&&(this.state=e,this.args=r,this.name="",this.name="string"==typeof t?t:t.constructor.name,e&&this.initialize())}initialize(){this.args.sameColor?(c.sharedData[this.name]||(c.sharedData[this.name]=this.getRandomColor()),this.color=c.sharedData[this.name]):(this.color=this.getRandomColor(),c.colorsInUse.push(this.color)),this.outputHandler=console.log,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"]}setOutputHandler(t){this.outputHandler=t}useWrapper(t,e=!0){if(!t||"object"!=typeof t||Array.isArray(t))return t;c.wrapperDepth++;let r={...t};return Object.values(c.wrappers).forEach((([e])=>{t instanceof e.classType&&(r=e.callback(t)||r)})),4>c.wrapperDepth?(e&&r&&Object.entries(r).forEach((([t,e])=>{r[t]=this.useWrapper(e,!0)})),c.wrapperDepth--,r):(c.wrapperDepth--,r)}startEmpty(t=""){this.state&&this.printFunctionNotify("se",c.getCallerName(),t)}startWith(t){if(!this.state)return;t=Object.assign({},t);const e="se",r=c.getCallerName();if("string"==typeof t)this.printInLineString(e,r,t);else if(1===Object.keys(t).length){const s=Object.keys(t)[0];let o=Object.values(t)[0];"object"==typeof o?this.printNextLineObject(e,r,s,o||{}):"function"==typeof o?this.printInLineFunction(e,r,s,o):this.printInLineElement(e,r,s,o)}else this.printMultiLineObject(e,r,t)}object(t={},e=""){if(!this.state)return;const r=c.getCallerName();t=Object.create(t);for(let s in t)"object"==typeof t[s]&&(t[s]=JSON.stringify(this.useWrapper(t[s]),n())),this.out.apply(this,[`%c(ob)-> %c%c${this.name}%c::%c${r}%c() [${e}] ->> ${s}: '${t[s]}'%c`].concat(this.defaultStyle))}debug(t){this.state&&this.printFunctionNotify("db",c.getCallerName(),t)}drop(t,e){if(!this.state)return;const r=c.getCallerName();for(let e in t)this.out.apply(this,[`%c(dr)-> %c%c${this.name}%c::%c${r}%c() ->> corresponding ${e}: '${t[e]}' RESULT: %c↓`].concat(this.defaultStyle));this.out(e)}throw(t,e="null",r={}){throw this.printFunctionNotify("tw",c.getCallerName(),t),r&&this.printNextLineObject("tw",c.getCallerName(),e,r),Error().stack}clone(){return Object.assign(Object.create(Object.getPrototypeOf(this)),this)}printFunctionNotify(t,e,r){this.out.apply(this,[`%c(${t})-> %c%c${this.name}%c::%c${e}%c() ${r}%c`].concat(this.defaultStyle))}printInLineElement(t,e,r,s){this.out.apply(this,[`%c(${t})-> %c%c${this.name}%c::%c${e}%c() ->> ${r}: '${s}'%c`].concat(this.defaultStyle))}printInLineFunction(t,e,r,s){s=c.getFunctionView(s),this.printInLineElement(t,e,r,s)}printInLineString(t,e,r){this.printInLineElement(t,e,"(string)",r)}printNextLineObject(t,e,r,s){s=this.useWrapper(s),this.out.apply(this,[`%c(${t})-> %c%c${this.name}%c::%c${e}%c() ->> ${r} %c↓`].concat(this.defaultStyle)),this.out(s)}printMultiLineObject(t,e,r){this.out.apply(this,[`%c(${t})-> %c%c${this.name}%c::%c${e}%c(${Object.keys(r).join(", ")}) %c↓`].concat(this.defaultStyle));for(let t in r){let e=r[t];"object"==typeof e?e=JSON.stringify(this.useWrapper(e),n()):"function"==typeof r[t]&&(e=c.getFunctionView(e)),this.out.call(this,"%c"+t+": `"+this.useWrapper(e)+"`","color: #a3a3a3")}}getRandomColor(){let t="#";for(let e=0;6>e;e++)t+="0123456789ABCDEF"[Math.floor(16*Math.random())];return c.colorsInUse.some((e=>a(t,e)>=.8))?this.getRandomColor():t}out(...t){this.outputHandler.apply(this,t)}}class l extends o{args={};options={};logger;constructor(t={},e={}){super();const r=this.constructor.getName();this.logger=new c(r,!0,{sameColor:!0}),this.logger.startWith({args:t,options:e}),this.initialize(t,e)}initialize(t,e){this.args=t,this.options=e}apply(t=this.args,e=this.options){throw new r(this,"apply")}async run(){this.onBeforeApply&&this.onBeforeApply();const t=await this.apply(this.args,this.options);return this.onAfterApply&&this.onAfterApply(),t}getArgs(){return this.args}getOptions(){return this.options}}let h={},u={},p={},g={};var m=Object.freeze({__proto__:null,get commands(){return h},get controllers(){return u},get data(){return p},get internal(){return g}});var d=Object.freeze({__proto__:null,CommandBase:l,CommandData:class extends l{static getName(){return"Core/CommandBases/CommandData"}getEndpoint(){throw new r(this,"getEndpoint")}apply(t=this.args,e=this.options){const r=this.applyEndpointFormat(this.getEndpoint(),t);return p.getClient().fetch(r,p.currentHttpMethod,t||null)}applyEndpointFormat(t,e={}){return t.includes("{")&&(t=t.split("/").map((t=>{const r=t.match("\\{(.*?)\\}");return r?.length&&void 0!==e[r[1]]?e[r[1]]:t})).join("/")),t}},CommandInternal:class extends l{static getName(){return"Core/CommandBases/CommandInternal"}},CommandPublic:class extends l{static getName(){return"Core/CommandBases/CommandPublic"}}});var f=Object.freeze({__proto__:null,Controller:class extends o{commands;data;internal;static getName(){return"Core/Core/Controller"}constructor(){super(),this.initialize()}initialize(){this.register(),this.setupHooks&&this.setupHooks()}register(){this.commands=h.register(this.getCommands(),this),this.data=p.register(this.getData(),this),this.internal=g.register(this.getInternal(),this)}getCommands(){return{}}getData(){return{}}getInternal(){return{}}},ObjectBase:o});class y extends Error{constructor(t){super(`Command: '${t.getName()}' is already registered`)}}class C extends Error{constructor(t){super(`Command: '${t}' is not found`)}}class b extends Error{constructor(t){super(`Controller: '${t.getName()}' is already registered`)}}var N,w=Object.freeze({__proto__:null,CommandAlreadyRegistered:y,CommandNotFound:C,ControllerAlreadyRegistered:b,ForceMethod:r}),O=Object.freeze({__proto__:null,Logger:c});class A extends o{static trace=[];current={};currentArgs={};trace=[];commands={};onBeforeHooks={};onBeforeUIHooks={};onAfterHooks={};onAfterOnceHooks={};onAfterUIHooks={};onAfterAffectHooks={};logger;static getName(){return"Core/Managers/Commands"}static async runCallbacks(t,e={},r={}){const s=t?.length||0;for(let o=0;s>o;++o){const s=!0===r.pop?t.pop():t[o];if(!s)throw Error("Callback is not defined.");await s(e,r)}}static hookCommand(t,e,r){t[e]||(t[e]=[]),t[e].push(r)}constructor(){super(),this.logger=new c(this.getName(),!0),this.logger.startEmpty()}async run(t,e={},r={}){"string"==typeof t&&(t=this.getCommandInstance(t,e,r)),this.attachCurrent(t,e);const s=await this.runInstance(t,e,r);return this.detachCurrent(t),s}register(t,e){const r={};return Object.values(t).forEach((t=>{const e=t.getName();if(this.commands[e])throw new y(t);this.commands[e]=t,r[e]=t})),r}getAll(){return this.commands}getByName(t){return this.commands[t]}getLogger(){return this.logger}getCommandInstance(t,e={},r={}){const s=this.commands[t];if(!s)throw new C(t);return new s(e,r)}onBefore(t,e){A.hookCommand(this.onBeforeHooks,t,e)}onBeforeUI(t,e){A.hookCommand(this.onBeforeUIHooks,t,e)}onAfter(t,e){A.hookCommand(this.onAfterHooks,t,e)}onAfterUI(t,e){A.hookCommand(this.onAfterUIHooks,t,e)}onAfterOnce(t,e){A.hookCommand(this.onAfterOnceHooks,t,e)}onAfterAffect(t,e){A.hookCommand(this.onAfterAffectHooks,t,e)}onBeforeRun(t,e={},r={}){if(this.onBeforeHooks[t.getName()]){this.onBeforeHooks[t.getName()].forEach((t=>t(e,r)))}if(this.onBeforeUIHooks[t.getName()]){this.onBeforeUIHooks[t.getName()].forEach((t=>t(e,r)))}}async runInstance(t,e={},r={}){let s=null;return Object.keys(e).length?(this.logger.startWith({command:t.getName(),options:r,CommandArgs:"->"}),this.logger.debug("CommandArgs:"),this.logger.object(e)):this.logger.startWith({command:t.getName(),options:r,args:e}),this.onBeforeRun(t,e,r),s=await t.run(),await this.onAfterRun(t,e,r,s),s}async onAfterRun(t,e,r,s){return r=Object.assign({},r),this.onAfterAffectHooks[t.getName()]&&(this.onAfterAffectHooks[t.getName()].forEach((t=>{e.result=s,s=this.run(""+t,e,r)})),s=await s),this.onAfterHooks&&(e.result=s,await A.runCallbacks(Object.assign([],this.onAfterHooks[t.getName()]),e,r)),this.onAfterOnceHooks&&await A.runCallbacks(this.onAfterOnceHooks[t.getName()],e,{...r,pop:!0}),this.onAfterUIHooks&&A.runCallbacks(Object.assign([],this.onAfterUIHooks[t.getName()]),e,r),s}attachCurrent(t,e={}){this.current[t.getName()]=t,this.currentArgs[t.getName()]=e,this.trace.push(t.getName()),A.trace.push(t.getName())}detachCurrent(t){delete this.current[t.getName()],delete this.currentArgs[t.getName()],A.trace.pop(),this.trace.pop()}}class k extends o{controllers={};static getName(){return"Core/Managers/Controllers"}get(t){return this.controllers[t]}getAll(){return this.controllers}register(t){if(this.controllers[t.getName()])throw new b(t);return this.controllers[t.getName()]=t,t}}!function(t){t.DELETE="DELETE",t.GET="GET",t.OPTIONS="OPTIONS",t.PATCH="PATCH",t.POST="POST",t.PUT="PUT",t.__EMPTY__=""}(N||(N={}));class E extends o{logger;apiBaseUrl;static getName(){return"Core/Clients/Http"}constructor(t="http://localhost"){super(),this.logger=new c(E.getName(),!0),this.logger.startWith({apiBaseUrl:t}),this.apiBaseUrl=t+"/"}async fetch(t,e,r=null){this.logger.startWith({path:t,method:e,body:r});const s={credentials:"include"},o={};[N.POST,N.PUT,N.PATCH].includes(e)?(Object.assign(o,{"Content-Type":"application/json"}),Object.assign(s,{method:e,headers:o,body:JSON.stringify(r)})):Object.assign(s,{headers:o});const n=await globalThis.fetch(this.apiBaseUrl+t,s);let a;try{a=await n.json()}catch(t){return console.error(t),!1}if(a?.error&&a?.global&&a?.message)throw Error(a.message);return this.logger.drop({path:t},a),a}}class _ extends A{static client;currentHttpMethod;static getName(){return"Core/Managers/Data"}constructor(t){super(),_.client=new E(t.baseURL)}getClient(){return _.client}get(t,e={},r={}){return this.currentHttpMethod=N.GET,super.run(t,e,r)}update(t,e={},r={}){return this.currentHttpMethod=N.PATCH,super.run(t,e,r)}delete(t,e={},r={}){return this.currentHttpMethod=N.DELETE,super.run(t,e,r)}create(t,e={},r={}){return this.currentHttpMethod=N.POST,super.run(t,e,r)}async runInstance(t,e={},r={}){if(!this.currentHttpMethod)throw Error('Cannot run directly use one of the http methods: "get", "update", "delete, "create');const s={type:this.currentHttpMethod,args:{query:{},data:{}}};return N.GET===this.currentHttpMethod?s.args.query=e:s.args.data=e,e.result=await super.runInstance(t,s,r),this.currentHttpMethod=N.__EMPTY__,e.result}}class j extends A{static getName(){return"Core/Managers/Internal"}}var H=Object.freeze({__proto__:null,Commands:A,Controllers:k,Data:_,Internal:j}),I=Object.freeze({__proto__:null,commandBases:d,core:f,errors:w,managerBases:H,managers:m,modules:O,utils:i}),$="0.0.0-abc.0";let B=!1;function T(){if(B)throw Error("ZenCore is already initialized.")}T();let M={version:$};const x=[],U={initialize:t=>{T(),M=t||M,h=new A,u=new k,p=new _(M),g=new j,B=!0,x.forEach((t=>t()))},destroy:()=>{B=!1,h={},u={},p={},g={}},onAfterInitialize:t=>{x.push(t)},config:M,...I};t.commandBases=d,t.core=f,t.default=U,t.errors=w,t.managerBases=H,t.managers=m,t.modules=O,t.utils=i,Object.defineProperty(t,"__esModule",{value:!0})}));
|
package/package.json
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@zenflux/core",
|
|
3
|
+
"version": "0.0.0-abc.0",
|
|
4
|
+
"description": "ZenFlux core",
|
|
5
|
+
"author": "Leonid Vinikov <leonidvinikov@gmail.com> (https://github.com/iNewLegend)",
|
|
6
|
+
"scripts": {
|
|
7
|
+
"test": "export flow_modules_logger=off && jest",
|
|
8
|
+
"build": "rollup --config rollup.config.ts --configPlugin typescript"
|
|
9
|
+
},
|
|
10
|
+
"repository": {
|
|
11
|
+
"type": "git",
|
|
12
|
+
"url": "git+https://github.com/zenflux/core.git"
|
|
13
|
+
},
|
|
14
|
+
"keywords": [
|
|
15
|
+
"zenflux",
|
|
16
|
+
"zen",
|
|
17
|
+
"flux",
|
|
18
|
+
"commands",
|
|
19
|
+
"manager",
|
|
20
|
+
"commands manager"
|
|
21
|
+
],
|
|
22
|
+
"files": [
|
|
23
|
+
"dist",
|
|
24
|
+
"src",
|
|
25
|
+
"types"
|
|
26
|
+
],
|
|
27
|
+
"license": "MIT",
|
|
28
|
+
"main": "dist/cjs/zenflux-core.js",
|
|
29
|
+
"unpkg": "dist/umd/zenflux-core.js",
|
|
30
|
+
"module": "dist/es/zenflux-core.js",
|
|
31
|
+
"types": "types/index.d.ts",
|
|
32
|
+
"devDependencies": {
|
|
33
|
+
"@babel/core": "^7.20.7",
|
|
34
|
+
"@babel/plugin-transform-runtime": "^7.19.6",
|
|
35
|
+
"@babel/preset-env": "^7.20.2",
|
|
36
|
+
"@babel/preset-typescript": "^7.18.6",
|
|
37
|
+
"@babel/runtime": "^7.20.7",
|
|
38
|
+
"@rollup/plugin-babel": "^6.0.3",
|
|
39
|
+
"@rollup/plugin-json": "^6.0.0",
|
|
40
|
+
"@rollup/plugin-node-resolve": "^15.0.1",
|
|
41
|
+
"@rollup/plugin-replace": "^5.0.2",
|
|
42
|
+
"@rollup/plugin-terser": "^0.2.1",
|
|
43
|
+
"@rollup/plugin-typescript": "^10.0.1",
|
|
44
|
+
"@types/jest": "^29.2.5",
|
|
45
|
+
"@typescript-eslint/eslint-plugin": "^5.48.0",
|
|
46
|
+
"@typescript-eslint/parser": "^5.48.0",
|
|
47
|
+
"babel-jest": "^29.3.1",
|
|
48
|
+
"rollup": "^3.9.1",
|
|
49
|
+
"ts-jest": "^29.0.3",
|
|
50
|
+
"tslib": "^2.4.1"
|
|
51
|
+
},
|
|
52
|
+
"dependencies": {
|
|
53
|
+
"@babel/runtime": "^7.19.0"
|
|
54
|
+
}
|
|
55
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @author: Leonid Vinikov <leonidvinikov@gmail.com>
|
|
3
|
+
* @description: Providing a simple wrapper for fetch API.
|
|
4
|
+
*/
|
|
5
|
+
import ObjectBase from "../core/object-base";
|
|
6
|
+
|
|
7
|
+
import Logger from '../modules/logger';
|
|
8
|
+
|
|
9
|
+
import { HTTPMethodEnum } from "../enums/http";
|
|
10
|
+
|
|
11
|
+
export class Http extends ObjectBase {
|
|
12
|
+
private readonly logger: Logger;
|
|
13
|
+
|
|
14
|
+
private readonly apiBaseUrl: string;
|
|
15
|
+
|
|
16
|
+
static getName() {
|
|
17
|
+
return 'Core/Clients/Http';
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Function constructor() : Create the http.
|
|
22
|
+
*/
|
|
23
|
+
constructor( apiBaseUrl = 'http://localhost' ) {
|
|
24
|
+
super();
|
|
25
|
+
|
|
26
|
+
this.logger = new Logger( Http.getName(), true );
|
|
27
|
+
|
|
28
|
+
this.logger.startWith( { apiBaseUrl } );
|
|
29
|
+
|
|
30
|
+
this.apiBaseUrl = apiBaseUrl + '/';
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Function fetch() : Fetch api.
|
|
35
|
+
*/
|
|
36
|
+
async fetch( path: string, method: HTTPMethodEnum, body: {} | null = null ) {
|
|
37
|
+
this.logger.startWith( { path, method, body } );
|
|
38
|
+
|
|
39
|
+
const params: RequestInit = { 'credentials': 'include' }, // Support cookies.
|
|
40
|
+
headers = {};
|
|
41
|
+
|
|
42
|
+
if ( [
|
|
43
|
+
HTTPMethodEnum.POST,
|
|
44
|
+
HTTPMethodEnum.PUT,
|
|
45
|
+
HTTPMethodEnum.PATCH,
|
|
46
|
+
].includes( method ) ) {
|
|
47
|
+
Object.assign( headers, { 'Content-Type': 'application/json' } );
|
|
48
|
+
Object.assign( params, {
|
|
49
|
+
method,
|
|
50
|
+
headers: headers,
|
|
51
|
+
body: JSON.stringify( body )
|
|
52
|
+
} );
|
|
53
|
+
|
|
54
|
+
} else {
|
|
55
|
+
Object.assign( params, { headers } );
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const response = await globalThis.fetch( this.apiBaseUrl + path, params );
|
|
59
|
+
|
|
60
|
+
let data = undefined;
|
|
61
|
+
|
|
62
|
+
try {
|
|
63
|
+
data = await response.json();
|
|
64
|
+
} catch ( e ) {
|
|
65
|
+
console.error( e );
|
|
66
|
+
|
|
67
|
+
return false;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// TODO: This is part should be modular and not hard coded.
|
|
71
|
+
if ( data?.error && data?.global && data?.message ) {
|
|
72
|
+
throw new Error( data.message );
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
this.logger.drop( { path }, data );
|
|
76
|
+
|
|
77
|
+
return data;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export default Http;
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @author: Leonid Vinikov <leonidvinikov@gmail.com>
|
|
3
|
+
* @description: Base for all commands, they are all will be managed by the `Commands` managers.
|
|
4
|
+
* @TODO
|
|
5
|
+
* - Add validateArgs method or find something better.
|
|
6
|
+
*/
|
|
7
|
+
import ObjectBase from "../core/object-base";
|
|
8
|
+
|
|
9
|
+
import ForceMethod from "../errors/force-method";
|
|
10
|
+
|
|
11
|
+
import Logger from "../modules/logger";
|
|
12
|
+
|
|
13
|
+
import { ICommandArgsInterface, ICommandOptionsInterface } from "../interfaces/commands";
|
|
14
|
+
|
|
15
|
+
export abstract class CommandBase extends ObjectBase {
|
|
16
|
+
protected args: ICommandArgsInterface = {};
|
|
17
|
+
protected options: ICommandOptionsInterface = {};
|
|
18
|
+
|
|
19
|
+
private readonly logger: Logger;
|
|
20
|
+
|
|
21
|
+
constructor( args: ICommandArgsInterface = {}, options = {} ) {
|
|
22
|
+
super();
|
|
23
|
+
|
|
24
|
+
const name = ( this.constructor as typeof CommandBase ).getName();
|
|
25
|
+
|
|
26
|
+
this.logger = new Logger( name, true, {
|
|
27
|
+
sameColor: true,
|
|
28
|
+
} );
|
|
29
|
+
|
|
30
|
+
this.logger.startWith( { args, options } );
|
|
31
|
+
|
|
32
|
+
this.initialize( args, options );
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
initialize( args: ICommandArgsInterface, options: ICommandOptionsInterface ) {
|
|
36
|
+
this.args = args;
|
|
37
|
+
this.options = options;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
apply( args = this.args, options = this.options ): any {// eslint-disable-line @typescript-eslint/no-unused-vars
|
|
41
|
+
throw new ForceMethod( this, "apply" );
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async run() {
|
|
45
|
+
this.onBeforeApply && this.onBeforeApply();
|
|
46
|
+
|
|
47
|
+
const result = await this.apply( this.args, this.options );
|
|
48
|
+
|
|
49
|
+
this.onAfterApply && this.onAfterApply();
|
|
50
|
+
|
|
51
|
+
return result;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
getArgs() {
|
|
55
|
+
return this.args;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
getOptions() {
|
|
59
|
+
return this.options;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
onBeforeApply?():void;
|
|
63
|
+
|
|
64
|
+
onAfterApply?():void;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export default CommandBase;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @author: Leonid Vinikov <leonidvinikov@gmail.com>
|
|
3
|
+
* @description: Each data command should represent a final REST endpoint.
|
|
4
|
+
*/
|
|
5
|
+
import { ForceMethod } from '../errors/force-method';
|
|
6
|
+
import { CommandBase } from './command-base';
|
|
7
|
+
|
|
8
|
+
import { data } from '../managers/';
|
|
9
|
+
|
|
10
|
+
export abstract class CommandData extends CommandBase {
|
|
11
|
+
static getName() {
|
|
12
|
+
return 'Core/CommandBases/CommandData';
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Function getEndpoint() : Override this method is required to determine endpoint and magic query params.
|
|
17
|
+
* @example
|
|
18
|
+
* ```
|
|
19
|
+
* args = { query: { id: 1 } };
|
|
20
|
+
* getEndpoint() = '/api/v1/users/{id}';
|
|
21
|
+
* result = '/api/v1/users/1';
|
|
22
|
+
* ```
|
|
23
|
+
*/
|
|
24
|
+
getEndpoint(): string {
|
|
25
|
+
throw new ForceMethod( this, 'getEndpoint' );
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
apply( args = this.args, options = this.options ) {// eslint-disable-line @typescript-eslint/no-unused-vars
|
|
29
|
+
const endpoint = this.applyEndpointFormat( this.getEndpoint(), args );
|
|
30
|
+
|
|
31
|
+
return data.getClient().fetch(
|
|
32
|
+
endpoint, data.currentHttpMethod, args || null
|
|
33
|
+
);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
private applyEndpointFormat( endpoint: string, data: any = {} ): string {
|
|
37
|
+
// Replace query with `magic` placeholders.
|
|
38
|
+
if ( endpoint.includes( '{' ) ) {
|
|
39
|
+
endpoint = endpoint.split( '/' ).map( ( endpointPart ) => {
|
|
40
|
+
const match = endpointPart.match( '\\{(.*?)\\}' );
|
|
41
|
+
|
|
42
|
+
if ( match?.length && 'undefined' !== typeof data[ match[ 1 ] ] ) {
|
|
43
|
+
return data[ match[ 1 ] ];
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
return endpointPart;
|
|
47
|
+
} ).join( '/' );
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
return endpoint;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export default CommandData;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @author: Leonid Vinikov <leonidvinikov@gmail.com>
|
|
3
|
+
* @description: CommandInternal, is used when part of the logic needed to be in the command but not represent a user action.
|
|
4
|
+
*/
|
|
5
|
+
import CommandBase from "./command-base";
|
|
6
|
+
|
|
7
|
+
export class CommandInternal extends CommandBase {
|
|
8
|
+
static getName() {
|
|
9
|
+
return 'Core/CommandBases/CommandInternal';
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export default CommandInternal;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @author: Leonid Vinikov <leonidvinikov@gmail.com>
|
|
3
|
+
* @description: CommandPublic represents a USER action, every class which inherit from this class will USER action.
|
|
4
|
+
* */
|
|
5
|
+
import CommandBase from "./command-base";
|
|
6
|
+
|
|
7
|
+
export class CommandPublic extends CommandBase {
|
|
8
|
+
static getName() {
|
|
9
|
+
return 'Core/CommandBases/CommandPublic';
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export default CommandPublic;
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @author: Leonid Vinikov <leonidvinikov@gmail.com>
|
|
3
|
+
* @description: Responsible for commands, Aka ( CommandsSpace ).
|
|
4
|
+
*/
|
|
5
|
+
import ObjectBase from "./object-base";
|
|
6
|
+
|
|
7
|
+
import { CommandData, CommandInternal, CommandPublic } from "../command-bases";
|
|
8
|
+
|
|
9
|
+
import * as managers from "../managers/";
|
|
10
|
+
|
|
11
|
+
export abstract class Controller extends ObjectBase {
|
|
12
|
+
commands: { [ key: string ]: typeof CommandPublic };
|
|
13
|
+
data: { [ key: string ]: typeof CommandData };
|
|
14
|
+
internal: { [ key: string ]: typeof CommandInternal };
|
|
15
|
+
|
|
16
|
+
static getName() {
|
|
17
|
+
return 'Core/Core/Controller';
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
public constructor() {
|
|
21
|
+
super();
|
|
22
|
+
|
|
23
|
+
this.initialize();
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
initialize() {
|
|
27
|
+
this.register();
|
|
28
|
+
|
|
29
|
+
this.setupHooks && this.setupHooks();
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
register() {
|
|
33
|
+
this.commands = managers.commands.register( this.getCommands(), this ) as
|
|
34
|
+
{ [ key: string ]: typeof CommandPublic };
|
|
35
|
+
|
|
36
|
+
this.data = managers.data.register( this.getData(), this ) as
|
|
37
|
+
{ [ key: string ]: typeof CommandData };
|
|
38
|
+
|
|
39
|
+
this.internal = managers.internal.register( this.getInternal(), this ) as
|
|
40
|
+
{ [ key: string ]: typeof CommandInternal };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
getCommands(): { [ key: string ]: typeof CommandPublic } {
|
|
44
|
+
return {};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
getData(): { [ key: string ]: typeof CommandData } {
|
|
48
|
+
return {};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
getInternal(): { [ key: string ]: typeof CommandInternal } {
|
|
52
|
+
return {};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Function setupHooks() : Override this method to setup hooks.
|
|
57
|
+
*/
|
|
58
|
+
setupHooks?():void
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export default Controller;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @author: Leonid Vinikov <leonidvinikov@gmail.com>
|
|
3
|
+
* @description: is base class/object for all classes, responsible for: 'getName', implementation.
|
|
4
|
+
*/
|
|
5
|
+
import { ForceMethodBase } from "../errors/force-method";
|
|
6
|
+
|
|
7
|
+
import { IObjectBaseInterface } from "../interfaces/object-base";
|
|
8
|
+
|
|
9
|
+
let IdCounter = 0;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Base class 4 *
|
|
13
|
+
*/
|
|
14
|
+
export abstract class ObjectBase implements IObjectBaseInterface {
|
|
15
|
+
public virtualId: number = 0;
|
|
16
|
+
|
|
17
|
+
static getName(): string {
|
|
18
|
+
throw new ForceMethodBase( "ObjectBase", "getName" );
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
constructor() {
|
|
22
|
+
this.virtualId = IdCounter;
|
|
23
|
+
|
|
24
|
+
APIIncreaseIdCounter();
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
getName(): string {
|
|
28
|
+
return ( this.constructor as typeof ObjectBase ).getName();
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function APIResetIdCounter() {
|
|
33
|
+
IdCounter = 0;
|
|
34
|
+
|
|
35
|
+
return 0;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function APIIncreaseIdCounter(): number {
|
|
39
|
+
return IdCounter++;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function APIGetIdCounter(): number {
|
|
43
|
+
return IdCounter;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export default ObjectBase;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @author: Leonid Vinikov <leonidvinikov@gmail.com>
|
|
3
|
+
*/
|
|
4
|
+
export enum HTTPMethodEnum {
|
|
5
|
+
DELETE = 'DELETE', // Delete.
|
|
6
|
+
GET = 'GET', // Read.
|
|
7
|
+
OPTIONS = 'OPTIONS',// Options about the request
|
|
8
|
+
PATCH = 'PATCH', // Update/Modify.
|
|
9
|
+
POST = 'POST', // Create.
|
|
10
|
+
PUT = 'PUT', // Update/Replace.
|
|
11
|
+
'__EMPTY__' = ''
|
|
12
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @author: Leonid Vinikov <leonidvinikov@gmail.com>
|
|
3
|
+
*/
|
|
4
|
+
import CommandBase from "../command-bases/command-base";
|
|
5
|
+
|
|
6
|
+
export class CommandAlreadyRegistered extends Error {
|
|
7
|
+
constructor( command: typeof CommandBase ) {
|
|
8
|
+
super( `Command: '${ command.getName() }' is already registered` );
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export default CommandAlreadyRegistered;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @author: Leonid Vinikov <leonidvinikov@gmail.com>
|
|
3
|
+
*/
|
|
4
|
+
import Controller from "../core/controller";
|
|
5
|
+
|
|
6
|
+
export class ControllerAlreadyRegistered extends Error {
|
|
7
|
+
constructor( controller: Controller ) {
|
|
8
|
+
super( `Controller: '${ controller.getName() }' is already registered` );
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export default ControllerAlreadyRegistered;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @author: Leonid Vinikov <leonidvinikov@gmail.com>
|
|
3
|
+
*/
|
|
4
|
+
import ObjectBase from "../core/object-base";
|
|
5
|
+
|
|
6
|
+
export class ForceMethodBase extends Error {
|
|
7
|
+
constructor( className: string, methodName: string ) {
|
|
8
|
+
super(
|
|
9
|
+
`ForeMethod implementation: at '${ className }' method: '${ methodName }'`
|
|
10
|
+
);
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export class ForceMethod extends Error {
|
|
15
|
+
constructor( context: ObjectBase | typeof ObjectBase, methodName: string ) {
|
|
16
|
+
super(
|
|
17
|
+
`ForeMethod implementation: at '${ context.getName() }' method: '${ methodName }'`
|
|
18
|
+
);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export default ForceMethod;
|
package/src/exports.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @author: Leonid Vinikov <leonidvinikov@gmail.com>
|
|
3
|
+
*/
|
|
4
|
+
export * as commandBases from "./command-bases";
|
|
5
|
+
export * as core from "./core";
|
|
6
|
+
export * as errors from "./errors";
|
|
7
|
+
export * as managers from "./managers";
|
|
8
|
+
export * as managerBases from "./manager-bases";
|
|
9
|
+
export * as modules from "./modules";
|
|
10
|
+
export * as utils from "./utils";
|
|
11
|
+
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import pkg from "../package.json";
|
|
2
|
+
|
|
3
|
+
import * as exported from './exports';
|
|
4
|
+
|
|
5
|
+
import { IAPIConfig } from "./interfaces/config";
|
|
6
|
+
|
|
7
|
+
declare global {
|
|
8
|
+
var ZenCore: any;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
let isInitialized = false;
|
|
12
|
+
|
|
13
|
+
function errorInitTwice() {
|
|
14
|
+
if ( isInitialized ) {
|
|
15
|
+
throw new Error( 'ZenCore is already initialized.' );
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
errorInitTwice();
|
|
20
|
+
|
|
21
|
+
export let config: IAPIConfig = {
|
|
22
|
+
version: pkg.version,
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const afterInitializeCallbacks: ( () => void )[] = [];
|
|
26
|
+
|
|
27
|
+
export const CoreAPI = {
|
|
28
|
+
initialize: ( configuration?: IAPIConfig ) => {
|
|
29
|
+
errorInitTwice();
|
|
30
|
+
|
|
31
|
+
config = configuration || config;
|
|
32
|
+
|
|
33
|
+
exported.managers.commands = new exported.managerBases.Commands();
|
|
34
|
+
exported.managers.controllers = new exported.managerBases.Controllers();
|
|
35
|
+
exported.managers.data = new exported.managerBases.Data( config );
|
|
36
|
+
exported.managers.internal = new exported.managerBases.Internal();
|
|
37
|
+
|
|
38
|
+
isInitialized = true;
|
|
39
|
+
|
|
40
|
+
afterInitializeCallbacks.forEach( ( callback ) => callback() );
|
|
41
|
+
},
|
|
42
|
+
|
|
43
|
+
destroy: () => {
|
|
44
|
+
isInitialized = false;
|
|
45
|
+
|
|
46
|
+
exported.managers.commands = {} as exported.managerBases.Commands;
|
|
47
|
+
exported.managers.controllers = {} as exported.managerBases.Controllers
|
|
48
|
+
exported.managers.data = {} as exported.managerBases.Data;
|
|
49
|
+
exported.managers.internal = {} as exported.managerBases.Internal;
|
|
50
|
+
},
|
|
51
|
+
|
|
52
|
+
onAfterInitialize: ( callback: () => void ) => {
|
|
53
|
+
afterInitializeCallbacks.push( callback );
|
|
54
|
+
},
|
|
55
|
+
|
|
56
|
+
config,
|
|
57
|
+
|
|
58
|
+
...exported,
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// TODO: Make it available only for development.
|
|
62
|
+
// if ( ! globalThis?.ZenCore ) globalThis.ZenCore = CoreAPI;
|
|
63
|
+
|