@chromahq/core 0.1.10 → 0.1.12
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/dist/IJob-Bds0eWrM.js +17 -0
- package/dist/IJob-Bds0eWrM.js.map +1 -0
- package/dist/IJob-aWBqI3FC.js +14 -0
- package/dist/IJob-aWBqI3FC.js.map +1 -0
- package/dist/boot.cjs.js +1557 -0
- package/dist/boot.cjs.js.map +1 -0
- package/dist/boot.d.ts +21 -0
- package/dist/boot.es.js +1555 -0
- package/dist/boot.es.js.map +1 -0
- package/dist/index.cjs.js +29 -1689
- package/dist/index.cjs.js.map +1 -0
- package/dist/index.d.ts +19 -53
- package/dist/index.es.js +27 -1680
- package/dist/index.es.js.map +1 -0
- package/package.json +20 -5
package/dist/index.cjs.js
CHANGED
|
@@ -1,1671 +1,13 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
var core = require('@inversifyjs/core');
|
|
4
|
+
var IJob = require('./IJob-Bds0eWrM.js');
|
|
4
5
|
|
|
5
|
-
function
|
|
6
|
-
|
|
7
|
-
const s="@inversifyjs/container/bindingId";function c(){const i=t$1(Object,s)??0;return i===Number.MAX_SAFE_INTEGER?n(Object,s,Number.MIN_SAFE_INTEGER):a(Object,s,(()=>i),(e=>e+1)),i}const u={Request:"Request",Singleton:"Singleton",Transient:"Transient"},d={ConstantValue:"ConstantValue",DynamicValue:"DynamicValue",Factory:"Factory",Instance:"Instance",Provider:"Provider",ResolvedValue:"ResolvedValue",ServiceRedirection:"ServiceRedirection"};function*l(...e){for(const t of e)yield*t;}class p{#e;#t;#n;constructor(e){this.#e=new Map,this.#t={};for(const t of Reflect.ownKeys(e))this.#t[t]=new Map;this.#n=e;}add(e,t){this.#i(e).push(t);for(const n of Reflect.ownKeys(t))this.#o(n,t[n]).push(e);}clone(){const e=this.#r(),t=this.#a(),n=Reflect.ownKeys(this.#n),i=this._buildNewInstance(this.#n);this.#s(this.#e,i.#e,e,t);for(const t of n)this.#c(this.#t[t],i.#t[t],e);return i}get(e,t){return this.#t[e].get(t)}getAllKeys(e){return this.#t[e].keys()}removeByRelation(e,t){const n=this.get(e,t);if(void 0===n)return;const i=new Set(n);for(const n of i){const i=this.#e.get(n);if(void 0===i)throw new Error("Expecting model relation, none found");for(const o of i)o[e]===t&&this.#u(n,o);this.#e.delete(n);}}_buildNewInstance(e){return new p(e)}_cloneModel(e){return e}_cloneRelation(e){return e}#r(){const e=new Map;for(const t of this.#e.keys()){const n=this._cloneModel(t);e.set(t,n);}return e}#a(){const e=new Map;for(const t of this.#e.values())for(const n of t){const t=this._cloneRelation(n);e.set(n,t);}return e}#i(e){let t=this.#e.get(e);return void 0===t&&(t=[],this.#e.set(e,t)),t}#o(e,t){let n=this.#t[e].get(t);return void 0===n&&(n=[],this.#t[e].set(t,n)),n}#d(e,t){const n=t.get(e);if(void 0===n)throw new Error("Expecting model to be cloned, none found");return n}#l(e,t){const n=t.get(e);if(void 0===n)throw new Error("Expecting relation to be cloned, none found");return n}#c(e,t,n){for(const[i,o]of e){const e=new Array;for(const t of o)e.push(this.#d(t,n));t.set(i,e);}}#s(e,t,n,i){for(const[o,r]of e){const e=new Array;for(const t of r)e.push(this.#l(t,i));t.set(this.#d(o,n),e);}}#u(e,t){for(const n of Reflect.ownKeys(t))this.#p(e,n,t[n]);}#p(e,t,n){const i=this.#t[t].get(n);if(void 0!==i){const o=i.indexOf(e);-1!==o&&i.splice(o,1),0===i.length&&this.#t[t].delete(n);}}}var f,g,h;!function(e){e.moduleId="moduleId",e.serviceId="serviceId";}(f||(f={}));let m$1 = class m{#f;#g;constructor(e,t){this.#f=t??new p({moduleId:{isOptional:true},serviceId:{isOptional:false}}),this.#g=e;}static build(e){return new m(e)}add(e,t){this.#f.add(e,t);}clone(){return new m(this.#g,this.#f.clone())}get(e){const t=[],n=this.#f.get(f.serviceId,e);void 0!==n&&t.push(n);const i=this.#g?.get(e);if(void 0!==i&&t.push(i),0!==t.length)return l(...t)}removeAllByModuleId(e){this.#f.removeByRelation(f.moduleId,e);}removeAllByServiceId(e){this.#f.removeByRelation(f.serviceId,e);}};function v(e){return e.isRight?{isRight:true,value:e.value}:e}function y(e){switch(e.type){case d.ConstantValue:case d.DynamicValue:return function(e){return {cache:v(e.cache),id:e.id,isSatisfiedBy:e.isSatisfiedBy,moduleId:e.moduleId,onActivation:e.onActivation,onDeactivation:e.onDeactivation,scope:e.scope,serviceIdentifier:e.serviceIdentifier,type:e.type,value:e.value}}(e);case d.Factory:return function(e){return {cache:v(e.cache),factory:e.factory,id:e.id,isSatisfiedBy:e.isSatisfiedBy,moduleId:e.moduleId,onActivation:e.onActivation,onDeactivation:e.onDeactivation,scope:e.scope,serviceIdentifier:e.serviceIdentifier,type:e.type}}(e);case d.Instance:return function(e){return {cache:v(e.cache),id:e.id,implementationType:e.implementationType,isSatisfiedBy:e.isSatisfiedBy,moduleId:e.moduleId,onActivation:e.onActivation,onDeactivation:e.onDeactivation,scope:e.scope,serviceIdentifier:e.serviceIdentifier,type:e.type}}(e);case d.Provider:return function(e){return {cache:v(e.cache),id:e.id,isSatisfiedBy:e.isSatisfiedBy,moduleId:e.moduleId,onActivation:e.onActivation,onDeactivation:e.onDeactivation,provider:e.provider,scope:e.scope,serviceIdentifier:e.serviceIdentifier,type:e.type}}(e);case d.ResolvedValue:return function(e){return {cache:v(e.cache),factory:e.factory,id:e.id,isSatisfiedBy:e.isSatisfiedBy,metadata:e.metadata,moduleId:e.moduleId,onActivation:e.onActivation,onDeactivation:e.onDeactivation,scope:e.scope,serviceIdentifier:e.serviceIdentifier,type:e.type}}(e);case d.ServiceRedirection:return function(e){return {id:e.id,isSatisfiedBy:e.isSatisfiedBy,moduleId:e.moduleId,serviceIdentifier:e.serviceIdentifier,targetServiceIdentifier:e.targetServiceIdentifier,type:e.type}}(e)}}!function(e){e.id="id",e.moduleId="moduleId",e.serviceId="serviceId";}(g||(g={}));class M extends p{_buildNewInstance(e){return new M(e)}_cloneModel(e){return y(e)}}let I$1 = class I{#h;#g;constructor(e,t){this.#h=t??new M({id:{isOptional:false},moduleId:{isOptional:true},serviceId:{isOptional:false}}),this.#g=e;}static build(e){return new I(e)}clone(){return new I(this.#g,this.#h.clone())}get(e){return this.getNonParentBindings(e)??this.#g?.get(e)}getBoundServices(){const e=new Set(this.#h.getAllKeys(g.serviceId));if(void 0!==this.#g)for(const t of this.#g.getBoundServices())e.add(t);return e}getById(e){return this.#h.get(g.id,e)??this.#g?.getById(e)}getByModuleId(e){return this.#h.get(g.moduleId,e)??this.#g?.getByModuleId(e)}getNonParentBindings(e){return this.#h.get(g.serviceId,e)}getNonParentBoundServices(){return this.#h.getAllKeys(g.serviceId)}removeById(e){this.#h.removeByRelation(g.id,e);}removeAllByModuleId(e){this.#h.removeByRelation(g.moduleId,e);}removeAllByServiceId(e){this.#h.removeByRelation(g.serviceId,e);}set(e){const t={[g.id]:e.id,[g.serviceId]:e.serviceIdentifier};void 0!==e.moduleId&&(t[g.moduleId]=e.moduleId),this.#h.add(e,t);}};!function(e){e.moduleId="moduleId",e.serviceId="serviceId";}(h||(h={}));class w{#m;#g;constructor(e,t){this.#m=t??new p({moduleId:{isOptional:true},serviceId:{isOptional:false}}),this.#g=e;}static build(e){return new w(e)}add(e,t){this.#m.add(e,t);}clone(){return new w(this.#g,this.#m.clone())}get(e){const t=[],n=this.#m.get(h.serviceId,e);void 0!==n&&t.push(n);const i=this.#g?.get(e);if(void 0!==i&&t.push(i),0!==t.length)return l(...t)}removeAllByModuleId(e){this.#m.removeByRelation(h.moduleId,e);}removeAllByServiceId(e){this.#m.removeByRelation(h.serviceId,e);}}function b(e,t,n){const i=Array.isArray(e)?e:[e];if(void 0!==n)if("number"!=typeof n)Reflect.decorate(i,t.prototype,n);else for(const e of i)e(t,void 0,n);else Reflect.decorate(i,t);}const S="@inversifyjs/core/classMetadataReflectKey";function j$1(){return {constructorArguments:[],lifecycle:{postConstructMethodName:void 0,preDestroyMethodName:void 0},properties:new Map,scope:void 0}}const R="@inversifyjs/core/pendingClassMetadataCountReflectKey";const T$1=Symbol.for("@inversifyjs/core/InversifyCoreError");let A$1 = class A extends Error{[T$1];kind;constructor(e,t,n){super(t,n),this[T$1]=true,this.kind=e;}static is(e){return "object"==typeof e&&null!==e&&true===e[T$1]}static isErrorOfKind(e,t){return A.is(e)&&e.kind===t}};var C$1,B$1,$$1;function x$1(t){const n=t$1(t,S)??j$1();if(!function(t){const n=t$1(t,R);return void 0!==n&&0!==n}(t))return function(e,t){const n=[];if(t.length<e.length)throw new A$1(C$1.missingInjectionDecorator,`Found unexpected missing metadata on type "${e.name}". "${e.name}" constructor requires at least ${e.length.toString()} arguments, found ${t.length.toString()} instead.\nAre you using @inject, @multiInject or @unmanaged decorators in every non optional constructor argument?\n\nIf you're using typescript and want to rely on auto injection, set "emitDecoratorMetadata" compiler option to true`);for(let e=0;e<t.length;++e) void 0===t[e]&&n.push(e);if(n.length>0)throw new A$1(C$1.missingInjectionDecorator,`Found unexpected missing metadata on type "${e.name}" at constructor indexes "${n.join('", "')}".\n\nAre you using @inject, @multiInject or @unmanaged decorators at those indexes?\n\nIf you're using typescript and want to rely on auto injection, set "emitDecoratorMetadata" compiler option to true`)}(t,n.constructorArguments),n;!function(e,t){const n=[];for(let i=0;i<t.constructorArguments.length;++i){const o=t.constructorArguments[i];void 0!==o&&o.kind!==B$1.unknown||n.push(` - Missing or incomplete metadata for type "${e.name}" at constructor argument with index ${i.toString()}.\nEvery constructor parameter must be decorated either with @inject, @multiInject or @unmanaged decorator.`);}for(const[i,o]of t.properties)o.kind===B$1.unknown&&n.push(` - Missing or incomplete metadata for type "${e.name}" at property "${i.toString()}".\nThis property must be decorated either with @inject or @multiInject decorator.`);if(0===n.length)throw new A$1(C$1.unknown,`Unexpected class metadata for type "${e.name}" with uncompletion traces.\nThis might be caused by one of the following reasons:\n\n1. A third party library is targeting inversify reflection metadata.\n2. A bug is causing the issue. Consider submiting an issue to fix it.`);throw new A$1(C$1.missingInjectionDecorator,`Invalid class metadata at type ${e.name}:\n\n${n.join("\n\n")}`)}(t,n);}function D$1(){return 0}function k$1(e){return t=>{ void 0!==t&&t.kind===B$1.unknown&&a(e,R,D$1,(e=>e-1));}}function P$1(e,t){return (...n)=>i=>{if(void 0===i)return e(...n);if(i.kind===$$1.unmanaged)throw new A$1(C$1.injectionDecoratorConflict,"Unexpected injection found. Multiple @inject, @multiInject or @unmanaged decorators found");return t(i,...n)}}function O$1(e){if(e.kind!==B$1.unknown&&true!==e.isFromTypescriptParamType)throw new A$1(C$1.injectionDecoratorConflict,"Unexpected injection found. Multiple @inject, @multiInject or @unmanaged decorators found")}!function(e){e[e.injectionDecoratorConflict=0]="injectionDecoratorConflict",e[e.missingInjectionDecorator=1]="missingInjectionDecorator",e[e.planning=2]="planning",e[e.resolution=3]="resolution",e[e.unknown=4]="unknown";}(C$1||(C$1={})),function(e){e[e.unknown=32]="unknown";}(B$1||(B$1={})),function(e){e[e.multipleInjection=0]="multipleInjection",e[e.singleInjection=1]="singleInjection",e[e.unmanaged=2]="unmanaged";}($$1||($$1={}));const V$1=P$1((function(e,t){return {kind:e,name:void 0,optional:false,tags:new Map,value:t}}),(function(e,t,n){return O$1(e),{...e,kind:t,value:n}}));function F$1(e,t){return n=>{const i=n.properties.get(t);return n.properties.set(t,e(i)),n}}var E$1;function N$1(e,t,n,i){if(A$1.isErrorOfKind(i,C$1.injectionDecoratorConflict)){const o=function(e,t,n){if(void 0===n){if(void 0===t)throw new A$1(C$1.unknown,"Unexpected undefined property and index values");return {kind:E$1.property,property:t,targetClass:e.constructor}}return "number"==typeof n?{index:n,kind:E$1.parameter,targetClass:e}:{kind:E$1.method,method:t,targetClass:e}}(e,t,n);throw new A$1(C$1.injectionDecoratorConflict,`Unexpected injection error.\n\nCause:\n\n${i.message}\n\nDetails\n\n${function(e){switch(e.kind){case E$1.method:return `[class: "${e.targetClass.name}", method: "${e.method.toString()}"]`;case E$1.parameter:return `[class: "${e.targetClass.name}", index: "${e.index.toString()}"]`;case E$1.property:return `[class: "${e.targetClass.name}", property: "${e.property.toString()}"]`}}(o)}`,{cause:i})}throw i}function U$1(e,t){return (i,o,r)=>{try{void 0===r?function(e,t){const i=K$1(e,t);return (e,t)=>{a(e.constructor,S,j$1,F$1(i(e),t));}}(e,t)(i,o):"number"==typeof r?function(e,t){const i=K$1(e,t);return (e,t,o)=>{if(!function(e,t){return "function"==typeof e&&void 0===t}(e,t))throw new A$1(C$1.injectionDecoratorConflict,`Found an @inject decorator in a non constructor parameter.\nFound @inject decorator at method "${t?.toString()??""}" at class "${e.constructor.name}"`);a(e,S,j$1,function(e,t){return n=>{const i=n.constructorArguments[t];return n.constructorArguments[t]=e(i),n}}(i(e),o));}}(e,t)(i,o,r):function(e,t){const i=K$1(e,t);return (e,t,o)=>{if(!function(e){return void 0!==e.set}(o))throw new A$1(C$1.injectionDecoratorConflict,`Found an @inject decorator in a non setter property method.\nFound @inject decorator at method "${t.toString()}" at class "${e.constructor.name}"`);a(e.constructor,S,j$1,F$1(i(e),t));}}(e,t)(i,o,r);}catch(e){N$1(i,o,r,e);}}}function K$1(e,t){return n=>{const i=t(n);return t=>(i(t),e(t))}}function _$1(e){return U$1(V$1($$1.singleInjection,e),k$1)}!function(e){e[e.method=0]="method",e[e.parameter=1]="parameter",e[e.property=2]="property";}(E$1||(E$1={}));const q$1="@inversifyjs/core/classIsInjectableFlagReflectKey";const z$1=[Array,BigInt,Boolean,Function,Number,Object,String];function G$1(t){const i=t$1(t,"design:paramtypes");void 0!==i&&a(t,S,j$1,function(e){return t=>(e.forEach(((e,n)=>{var i;void 0!==t.constructorArguments[n]||(i=e,z$1.includes(i))||(t.constructorArguments[n]=function(e){return {isFromTypescriptParamType:true,kind:$$1.singleInjection,name:void 0,optional:false,tags:new Map,value:e}}(e));})),t)}(i));}function L$1(i){return o=>{!function(n$1){if(void 0!==t$1(n$1,q$1))throw new A$1(C$1.injectionDecoratorConflict,`Cannot apply @injectable decorator multiple times at class "${n$1.name}"`);n(n$1,q$1,true);}(o),G$1(o);}}var ue;!function(e){e[e.multipleInjection=0]="multipleInjection",e[e.singleInjection=1]="singleInjection";}(ue||(ue={}));class de{#v;constructor(e){this.#v=e;}get name(){return this.#v.elem.name}get serviceIdentifier(){return this.#v.elem.serviceIdentifier}get tags(){return this.#v.elem.tags}getAncestor(){if(void 0!==this.#v.previous)return new de(this.#v.previous)}}class le{last;constructor(e){this.last=e;}concat(e){return new le({elem:e,previous:this.last})}[Symbol.iterator](){let e=this.last;return {next:()=>{if(void 0===e)return {done:true,value:void 0};const t=e.elem;return e=e.previous,{done:false,value:t}}}}}function pe(e,t,n){const i=n?.customServiceIdentifier??t.serviceIdentifier,o=[...e.getBindings(i)??[]].filter((e=>e.isSatisfiedBy(t)));if(0===o.length&&void 0!==e.autobindOptions&&"function"==typeof i){const t=function(e,t){const n=x$1(t),i=n.scope??e.scope;return {cache:{isRight:false,value:void 0},id:c(),implementationType:t,isSatisfiedBy:()=>true,moduleId:void 0,onActivation:void 0,onDeactivation:void 0,scope:i,serviceIdentifier:t,type:d.Instance}}(e.autobindOptions,i);e.setBinding(t),o.push(t);}return o}function fe(e){return void 0!==e.redirections}function ge(e,t,n,i){let r,a;fe(n)?(r=n.binding.targetServiceIdentifier,a=n.binding.serviceIdentifier):(r=n.serviceIdentifier,a=n.parent?.binding.serviceIdentifier),Array.isArray(e)?function(e,t,n,i,r){if(0!==e.length){const t=`Ambiguous bindings found for service: "${t$2(n)}".\n\nRegistered bindings:\n\n${e.map((e=>function(e){switch(e.type){case d.Instance:return `[ type: "${e.type}", serviceIdentifier: "${t$2(e.serviceIdentifier)}", scope: "${e.scope}", implementationType: "${e.implementationType.name}" ]`;case d.ServiceRedirection:return `[ type: "${e.type}", serviceIdentifier: "${t$2(e.serviceIdentifier)}", redirection: "${t$2(e.targetServiceIdentifier)}" ]`;default:return `[ type: "${e.type}", serviceIdentifier: "${t$2(e.serviceIdentifier)}", scope: "${e.scope}" ]`}}(e.binding))).join("\n")}\n\nTrying to resolve bindings for "${me(n,i)}".\n\n${ve(r)}`;throw new A$1(C$1.planning,t)}t||he(n,i,r);}(e,t,r,a,i):function(e,t,n,i,o){if(void 0!==e||t)return;he(n,i,o);}(e,t,r,a,i);}function he(e,t,n){const i=`No bindings found for service: "${t$2(e)}".\n\nTrying to resolve bindings for "${me(e,t)}".\n\n${ve(n)}`;throw new A$1(C$1.planning,i)}function me(e,t){return void 0===t?`${t$2(e)} (Root service)`:t$2(t)}function ve(e){const t=0===e.tags.size?"":`\n- tags:\n - ${[...e.tags.keys()].map((e=>e.toString())).join("\n - ")}`;return `Binding constraints:\n- service identifier: ${t$2(e.serviceIdentifier)}\n- name: ${e.name?.toString()??"-"}${t}`}function ye(e,t,n){if(1!==e.redirections.length)ge(e.redirections,t,e,n);else {const[i]=e.redirections;fe(i)&&ye(i,t,n);}}function Me(e,t,n){if(Array.isArray(e.bindings)&&1===e.bindings.length){const[i]=e.bindings;fe(i)&&ye(i,t,n);}else ge(e.bindings,t,e,n);}function Ie(e,t){if(function(e){return e instanceof Error&&(e instanceof RangeError&&/stack space|call stack|too much recursion/i.test(e.message)||"InternalError"===e.name&&/too much recursion/.test(e.message))}(t)){const n=function(e){const t=[...e];if(0===t.length)return "(No dependency trace)";return t.map(t$2).join(" -> ")}(function(e){const t=new Set;for(const n of e.servicesBranch){if(t.has(n))return [...t,n];t.add(n);}return [...t]}(e));throw new A$1(C$1.planning,`Circular dependency found: ${n}`,{cause:t})}throw t}function we(e){try{const t=new Map;void 0!==e.rootConstraints.tag&&t.set(e.rootConstraints.tag.key,e.rootConstraints.tag.value);const n=new le({elem:{name:e.rootConstraints.name,serviceIdentifier:e.rootConstraints.serviceIdentifier,tags:t},previous:void 0}),i=new de(n.last),o=pe(e,i),r=[],a={bindings:r,parent:void 0,serviceIdentifier:e.rootConstraints.serviceIdentifier};if(r.push(...Te(e,n,o,a)),!e.rootConstraints.isMultiple){Me(a,e.rootConstraints.isOptional??!1,i);const[t]=r;a.bindings=t;}return {tree:{root:a}}}catch(t){Ie(e,t);}}function be(e,t,n,i){const o={binding:t,classMetadata:e.getClassMetadata(t.implementationType),constructorParams:[],parent:i,propertyParams:new Map};return Ce({autobindOptions:e.autobindOptions,getBindings:e.getBindings,getClassMetadata:e.getClassMetadata,node:o,servicesBranch:e.servicesBranch,setBinding:e.setBinding},n)}function Se(e,t,n){if(n.kind===$$1.unmanaged)return;const i=r.is(n.value)?n.value.unwrap():n.value,o=t.concat({name:n.name,serviceIdentifier:i,tags:n.tags}),a=new de(o.last),s=pe(e,a),c=[],u={bindings:c,parent:e.node,serviceIdentifier:i};if(c.push(...Te(e,o,s,u)),n.kind===$$1.singleInjection){Me(u,n.optional,a);const[e]=c;u.bindings=e;}return u}function je(e,t,n){const i=r.is(n.value)?n.value.unwrap():n.value,o=t.concat({name:n.name,serviceIdentifier:i,tags:n.tags}),a=new de(o.last),s=pe(e,a),c=[],u={bindings:c,parent:e.node,serviceIdentifier:i};if(c.push(...Te(e,o,s,u)),n.kind===ue.singleInjection){Me(u,n.optional,a);const[e]=c;u.bindings=e;}return u}function Re(e,t,n,i){const o={binding:t,params:[],parent:i};return Ce({autobindOptions:e.autobindOptions,getBindings:e.getBindings,getClassMetadata:e.getClassMetadata,node:o,servicesBranch:e.servicesBranch,setBinding:e.setBinding},n)}function Te(e,t,n,i){const o=fe(i)?i.binding.targetServiceIdentifier:i.serviceIdentifier;e.servicesBranch.push(o);const r=[];for(const o of n)switch(o.type){case d.Instance:r.push(be(e,o,t,i));break;case d.ResolvedValue:r.push(Re(e,o,t,i));break;case d.ServiceRedirection:{const n=Ae(e,t,o,i);r.push(n);break}default:r.push({binding:o,parent:i});}return e.servicesBranch.pop(),r}function Ae(e,t,n,i){const o={binding:n,parent:i,redirections:[]},r=pe(e,new de(t.last),{customServiceIdentifier:n.targetServiceIdentifier});return o.redirections.push(...Te(e,t,r,o)),o}function Ce(e,t){return e.node.binding.type===d.Instance?function(e,t,n){const i=t.classMetadata;for(const[o,r]of i.constructorArguments.entries())t.constructorParams[o]=Se(e,n,r);for(const[o,r]of i.properties){const i=Se(e,n,r);void 0!==i&&t.propertyParams.set(o,i);}return e.node}(e,e.node,t):function(e,t,n){const i=t.binding.metadata;for(const[o,r]of i.arguments.entries())t.params[o]=je(e,n,r);return e.node}(e,e.node,t)}class Be{#y;#M;#I;constructor(){this.#y=[],this.#M=8,this.#I=1024;}*[Symbol.iterator](){let e=0;for(const t of this.#y){const n=t.deref();void 0===n?++e:yield n;}this.#y.length>=this.#M&&this.#w(e)&&this.#b(e);}push(e){const t=new WeakRef(e);if(this.#y.push(t),this.#y.length>=this.#M&&this.#y.length%this.#I===0){let e=0;for(const t of this.#y) void 0===t.deref()&&++e;this.#w(e)&&this.#b(e);}}#b(e){const t=new Array(this.#y.length-e);let n=0;for(const e of this.#y)e.deref()&&(t[n++]=e);this.#y=t;}#w(e){return e>=.5*this.#y.length}}var $e;!function(e){e[e.singleMandatory=0]="singleMandatory",e[e.singleOptional=1]="singleOptional",e[e.multipleMandatory=2]="multipleMandatory",e[e.multipleOptional=3]="multipleOptional",e[e.length=4]="length";}($e||($e={}));class xe{#S;#j;#R;#T;#A;constructor(){this.#S=this.#C(),this.#j=this.#C(),this.#R=this.#C(),this.#T=this.#C(),this.#A=new Be;}clearCache(){for(const e of this.#B())e.clear();for(const e of this.#A)e.clearCache();}get(e){return void 0===e.name?void 0===e.tag?this.#$(this.#S,e).get(e.serviceIdentifier):this.#$(this.#T,e).get(e.serviceIdentifier)?.get(e.tag.key)?.get(e.tag.value):void 0===e.tag?this.#$(this.#j,e).get(e.serviceIdentifier)?.get(e.name):this.#$(this.#R,e).get(e.serviceIdentifier)?.get(e.name)?.get(e.tag.key)?.get(e.tag.value)}set(e,t){ void 0===e.name?void 0===e.tag?this.#$(this.#S,e).set(e.serviceIdentifier,t):this.#x(this.#x(this.#$(this.#T,e),e.serviceIdentifier),e.tag.key).set(e.tag.value,t):void 0===e.tag?this.#x(this.#$(this.#j,e),e.serviceIdentifier).set(e.name,t):this.#x(this.#x(this.#x(this.#$(this.#R,e),e.serviceIdentifier),e.name),e.tag.key).set(e.tag.value,t);}subscribe(e){this.#A.push(e);}#C(){const e=new Array($e.length);for(let t=0;t<e.length;++t)e[t]=new Map;return e}#x(e,t){let n=e.get(t);return void 0===n&&(n=new Map,e.set(t,n)),n}#$(e,t){return e[this.#D(t)]}#B(){return [...this.#S,...this.#j,...this.#R,...this.#T]}#D(e){return e.isMultiple?true===e.optional?$e.multipleOptional:$e.multipleMandatory:true===e.optional?$e.singleOptional:$e.singleMandatory}}function De(e$1,t){return e(t)?(e$1.cache={isRight:true,value:t},t.then((t=>ke(e$1,t)))):ke(e$1,t)}function ke(e,t){return e.cache={isRight:true,value:t},t}function Pe(e$1,t,n){const i=e$1.getActivations(t);return void 0===i?n:e(n)?Oe(e$1,n,i[Symbol.iterator]()):function(e$1,t,n){let i=t,o=n.next();for(;true!==o.done;){const t=o.value(e$1.context,i);if(e(t))return Oe(e$1,t,n);i=t,o=n.next();}return i}(e$1,n,i[Symbol.iterator]())}async function Oe(e,t,n){let i=await t,o=n.next();for(;true!==o.done;)i=await o.value(e.context,i),o=n.next();return i}function Ve(e$1,t,n){let i=n;if(void 0!==t.onActivation){const n=t.onActivation;i=e(i)?i.then((t=>n(e$1.context,t))):n(e$1.context,i);}return Pe(e$1,t.serviceIdentifier,i)}function Fe(e){return (t,n)=>{if(n.cache.isRight)return n.cache.value;return De(n,Ve(t,n,e(t,n)))}}const Ee=Fe((function(e,t){return t.value}));function Ne(e){return e}function Ue(e,t){return (n,i)=>{const o=e(i);switch(o.scope){case u.Singleton:if(o.cache.isRight)return o.cache.value;return De(o,Ve(n,o,t(n,i)));case u.Request:{if(n.requestScopeCache.has(o.id))return n.requestScopeCache.get(o.id);const e=Ve(n,o,t(n,i));return n.requestScopeCache.set(o.id,e),e}case u.Transient:return Ve(n,o,t(n,i))}}}const Ke=(e=>Ue(Ne,e))((function(e,t){return t.value(e.context)}));const _e=Fe((function(e,t){return t.factory(e.context)}));function qe(e$1,t,n){const i=function(e$1,t,n){if(void 0===n)return;if(!(n in e$1))throw new A$1(C$1.resolution,`Expecting a "${n.toString()}" property when resolving "${t.implementationType.name}" class @postConstruct decorated method, none found.`);if("function"!=typeof e$1[n])throw new A$1(C$1.resolution,`Expecting a "${n.toString()}" method when resolving "${t.implementationType.name}" class @postConstruct decorated method, a non function property was found instead.`);{let i;try{i=e$1[n]();}catch(e){throw new A$1(C$1.resolution,`Unexpected error found when calling "${n.toString()}" @postConstruct decorated method on class "${t.implementationType.name}"`,{cause:e})}if(e(i))return async function(e,t,n){try{await n;}catch(n){throw new A$1(C$1.resolution,`Unexpected error found when calling "${t.toString()}" @postConstruct decorated method on class "${e.implementationType.name}"`,{cause:n})}}(t,n,i)}}(e$1,t,n);return e(i)?i.then((()=>e$1)):e$1}function ze(e$1){return (t,n,i)=>{const o=new i.binding.implementationType(...t),r=e$1(n,o,i);return e(r)?r.then((()=>qe(o,i.binding,i.classMetadata.lifecycle.postConstructMethodName))):qe(o,i.binding,i.classMetadata.lifecycle.postConstructMethodName)}}const Ge=Fe((function(e,t){return t.provider(e.context)}));function Le(e){return e.binding}function We(e){return e.binding}const Xe=function(e$1){return (t,n,i)=>{const o=[];for(const[r,s]of i.propertyParams){const c=i.classMetadata.properties.get(r);if(void 0===c)throw new A$1(C$1.resolution,`Expecting metadata at property "${r.toString()}", none found`);c.kind!==$$1.unmanaged&&void 0!==s.bindings&&(n[r]=e$1(t,s),e(n[r])&&o.push((async()=>{n[r]=await n[r];})()));}if(o.length>0)return Promise.all(o).then((()=>{}))}}(nt),He=function(e){return function t(n,i){const o=[];for(const r of i.redirections)fe(r)?o.push(...t(n,r)):o.push(e(n,r));return o}}(tt),Je=function(e$1,t,n){return (i,o)=>{const r=e$1(i,o);return e(r)?t(r,i,o):n(r,i,o)}}(function(e$1){return (t,n)=>{const i=[];for(const o of n.constructorParams) void 0===o?i.push(void 0):i.push(e$1(t,o));return i.some(e)?Promise.all(i):i}}(nt),function(e){return async(t,n,i)=>{const o=await t;return e(o,n,i)}}(ze(Xe)),ze(Xe)),Qe=function(e$1){return (t,n)=>{const i=e$1(t,n);return e(i)?i.then((e=>n.binding.factory(...e))):n.binding.factory(...i)}}(function(e$1){return (t,n)=>{const i=[];for(const o of n.params)i.push(e$1(t,o));return i.some(e)?Promise.all(i):i}}(nt)),Ye=(e=>Ue(Le,e))(Je),Ze=(e=>Ue(We,e))(Qe);function et(e){return nt(e,e.planResult.tree.root)}function tt(e,t){switch(t.binding.type){case d.ConstantValue:return Ee(e,t.binding);case d.DynamicValue:return Ke(e,t.binding);case d.Factory:return _e(e,t.binding);case d.Instance:return Ye(e,t);case d.Provider:return Ge(e,t.binding);case d.ResolvedValue:return Ze(e,t)}}function nt(e$1,t){if(void 0!==t.bindings)return Array.isArray(t.bindings)?function(e$1,t){const n=[];for(const i of t)fe(i)?n.push(...He(e$1,i)):n.push(tt(e$1,i));if(n.some(e))return Promise.all(n);return n}(e$1,t.bindings):function(e,t){if(fe(t)){const n=He(e,t);if(1===n.length)return n[0];throw new A$1(C$1.resolution,"Unexpected multiple resolved values on single injection")}return tt(e,t)}(e$1,t.bindings)}function it(e){return void 0!==e.scope}function ot(e,t){if(void 0!==e.lifecycle.preDestroyMethodName&&"function"==typeof t[e.lifecycle.preDestroyMethodName])return t[e.lifecycle.preDestroyMethodName]()}function rt(e$1,t,n){const i=e$1.getDeactivations(t);if(void 0!==i)return e(n)?at(n,i[Symbol.iterator]()):function(e$1,t){let n=t.next();for(;true!==n.done;){const i=n.value(e$1);if(e(i))return at(e$1,t);n=t.next();}}(n,i[Symbol.iterator]())}async function at(e,t){const n=await e;let i=t.next();for(;true!==i.done;)await i.value(n),i=t.next();}function st(e$1,t){const n=function(e$1,t){if(t.type===d.Instance){const n=e$1.getClassMetadata(t.implementationType),i=t.cache.value;return e(i)?i.then((e=>ot(n,e))):ot(n,i)}}(e$1,t);return void 0===n?ct(e$1,t):n.then((()=>ct(e$1,t)))}function ct(e$1,t){const n=t.cache;return e(n.value)?n.value.then((n=>ut(e$1,t,n))):ut(e$1,t,n.value)}function ut(e,t,n){let i;if(void 0!==t.onDeactivation){i=(0, t.onDeactivation)(n);}return void 0===i?rt(e,t.serviceIdentifier,n):i.then((()=>rt(e,t.serviceIdentifier,n)))}function dt(e,t){if(void 0===t)return;const n=function(e){const t=[];for(const n of e)it(n)&&n.scope===u.Singleton&&n.cache.isRight&&t.push(n);return t}(t),i=[];for(const t of n){const n=st(e,t);void 0!==n&&i.push(n);}return i.length>0?Promise.all(i).then((()=>{})):void 0}function lt(e,t){const n=e.getBindingsFromModule(t);return dt(e,n)}function pt(e,t){const n=e.getBindings(t);return dt(e,n)}
|
|
8
|
-
|
|
9
|
-
const t=Symbol.for("@inversifyjs/plugin/isPlugin");
|
|
10
|
-
|
|
11
|
-
const m=Symbol.for("@inversifyjs/container/bindingIdentifier");function I(e){return "object"==typeof e&&null!==e&&true===e[m]}class A{static always=e=>true}function P(e){return {[m]:true,id:e.id}}function C(e){return n=>{for(let i=n.getAncestor();void 0!==i;i=i.getAncestor())if(e(i))return true;return false}}function B(e){return n=>n.name===e}function x(e){return n=>n.serviceIdentifier===e}function O(e,n){return i=>i.tags.has(e)&&i.tags.get(e)===n}function N(e){return void 0===e.name&&0===e.tags.size}function U(e){const n=C(e);return e=>!n(e)}function F(e){return n=>{const i=n.getAncestor();return void 0===i||!e(i)}}function k(e){return n=>{const i=n.getAncestor();return void 0!==i&&e(i)}}class j{#i;constructor(e){this.#i=e;}getIdentifier(){return P(this.#i)}inRequestScope(){return this.#i.scope=u.Request,new E(this.#i)}inSingletonScope(){return this.#i.scope=u.Singleton,new E(this.#i)}inTransientScope(){return this.#i.scope=u.Transient,new E(this.#i)}}class D{#t;#r;#a;#s;constructor(e,n,i,t){this.#t=e,this.#r=n,this.#a=i,this.#s=t;}to(e){const n=x$1(e),i={cache:{isRight:false,value:void 0},id:c(),implementationType:e,isSatisfiedBy:A.always,moduleId:this.#r,onActivation:void 0,onDeactivation:void 0,scope:n.scope??this.#a,serviceIdentifier:this.#s,type:d.Instance};return this.#t(i),new L(i)}toSelf(){if("function"!=typeof this.#s)throw new Error('"toSelf" function can only be applied when a newable function is used as service identifier');return this.to(this.#s)}toConstantValue(e){const n={cache:{isRight:false,value:void 0},id:c(),isSatisfiedBy:A.always,moduleId:this.#r,onActivation:void 0,onDeactivation:void 0,scope:u.Singleton,serviceIdentifier:this.#s,type:d.ConstantValue,value:e};return this.#t(n),new E(n)}toDynamicValue(e){const n={cache:{isRight:false,value:void 0},id:c(),isSatisfiedBy:A.always,moduleId:this.#r,onActivation:void 0,onDeactivation:void 0,scope:this.#a,serviceIdentifier:this.#s,type:d.DynamicValue,value:e};return this.#t(n),new L(n)}toResolvedValue(e,n){const i={cache:{isRight:false,value:void 0},factory:e,id:c(),isSatisfiedBy:A.always,metadata:this.#o(n),moduleId:this.#r,onActivation:void 0,onDeactivation:void 0,scope:this.#a,serviceIdentifier:this.#s,type:d.ResolvedValue};return this.#t(i),new L(i)}toFactory(e){const n={cache:{isRight:false,value:void 0},factory:e,id:c(),isSatisfiedBy:A.always,moduleId:this.#r,onActivation:void 0,onDeactivation:void 0,scope:u.Singleton,serviceIdentifier:this.#s,type:d.Factory};return this.#t(n),new E(n)}toProvider(e){const n={cache:{isRight:false,value:void 0},id:c(),isSatisfiedBy:A.always,moduleId:this.#r,onActivation:void 0,onDeactivation:void 0,provider:e,scope:u.Singleton,serviceIdentifier:this.#s,type:d.Provider};return this.#t(n),new E(n)}toService(e){const n={id:c(),isSatisfiedBy:A.always,moduleId:this.#r,serviceIdentifier:this.#s,targetServiceIdentifier:e,type:d.ServiceRedirection};this.#t(n);}#o(e){return {arguments:(e??[]).map((e=>function(e){return "object"==typeof e&&!r.is(e)}(e)?{kind:true===e.isMultiple?ue.multipleInjection:ue.singleInjection,name:e.name,optional:e.optional??false,tags:new Map((e.tags??[]).map((e=>[e.key,e.value]))),value:e.serviceIdentifier}:{kind:ue.singleInjection,name:void 0,optional:false,tags:new Map,value:e}))}}}class T{#i;constructor(e){this.#i=e;}getIdentifier(){return P(this.#i)}onActivation(e){return this.#i.onActivation=e,new V(this.#i)}onDeactivation(e){return this.#i.onDeactivation=e,new V(this.#i)}}class V{#i;constructor(e){this.#i=e;}getIdentifier(){return P(this.#i)}when(e){return this.#i.isSatisfiedBy=e,new T(this.#i)}whenAnyAncestor(e){return this.when(C(e))}whenAnyAncestorIs(e){return this.when(C(x(e)))}whenAnyAncestorNamed(e){return this.when(function(e){return C(B(e))}(e))}whenAnyAncestorTagged(e,n){return this.when(function(e,n){return C(O(e,n))}(e,n))}whenDefault(){return this.when(N)}whenNamed(e){return this.when(B(e))}whenNoParent(e){return this.when(F(e))}whenNoParentIs(e){return this.when(F(x(e)))}whenNoParentNamed(e){return this.when(function(e){return F(B(e))}(e))}whenNoParentTagged(e,n){return this.when(function(e,n){return F(O(e,n))}(e,n))}whenParent(e){return this.when(k(e))}whenParentIs(e){return this.when(k(x(e)))}whenParentNamed(e){return this.when(function(e){return k(B(e))}(e))}whenParentTagged(e,n){return this.when(function(e,n){return k(O(e,n))}(e,n))}whenTagged(e,n){return this.when(O(e,n))}whenNoAncestor(e){return this.when(U(e))}whenNoAncestorIs(e){return this.when(U(x(e)))}whenNoAncestorNamed(e){return this.when(function(e){return U(B(e))}(e))}whenNoAncestorTagged(e,n){return this.when(function(e,n){return U(O(e,n))}(e,n))}}class E extends V{#c;constructor(e){super(e),this.#c=new T(e);}onActivation(e){return this.#c.onActivation(e)}onDeactivation(e){return this.#c.onDeactivation(e)}}class L extends E{#d;constructor(e){super(e),this.#d=new j(e);}inRequestScope(){return this.#d.inRequestScope()}inSingletonScope(){return this.#d.inSingletonScope()}inTransientScope(){return this.#d.inTransientScope()}}const q=Symbol.for("@inversifyjs/container/InversifyContainerError");class $ extends Error{[q];kind;constructor(e,n,i){super(n,i),this[q]=true,this.kind=e;}static is(e){return "object"==typeof e&&null!==e&&true===e[q]}static isErrorOfKind(e,n){return $.is(e)&&e.kind===n}}var G;!function(e){e[e.invalidOperation=0]="invalidOperation";}(G||(G={}));class H{#l;#a;#u;constructor(e,n,i){this.#l=e,this.#a=n,this.#u=i;}bind(e){return new D((e=>{this.#h(e);}),void 0,this.#a,e)}isBound(e,n){const i=this.#u.bindingService.get(e);return this.#v(e,i,n)}isCurrentBound(e,n){const i=this.#u.bindingService.getNonParentBindings(e);return this.#v(e,i,n)}async rebind(e){return await this.unbind(e),this.bind(e)}rebindSync(e){return this.unbindSync(e),this.bind(e)}async unbind(e){await this.#g(e);}async unbindAll(){const e=[...this.#u.bindingService.getNonParentBoundServices()];await Promise.all(e.map((async e=>pt(this.#l,e))));for(const n of e)this.#u.activationService.removeAllByServiceId(n),this.#u.bindingService.removeAllByServiceId(n),this.#u.deactivationService.removeAllByServiceId(n);this.#u.planResultCacheService.clearCache();}unbindSync(e){ void 0!==this.#g(e)&&this.#f(e);}#h(e){this.#u.bindingService.set(e),this.#u.planResultCacheService.clearCache();}#f(e){let n;if(I(e)){const t=this.#u.bindingService.getById(e.id),r=(i=t,function(e){if(void 0===e)return;const n=e.next();return true!==n.done?n.value:void 0}(i?.[Symbol.iterator]()))?.serviceIdentifier;n=void 0===r?"Unexpected asynchronous deactivation when unbinding binding identifier. Consider using Container.unbind() instead.":`Unexpected asynchronous deactivation when unbinding "${t$2(r)}" binding. Consider using Container.unbind() instead.`;}else n=`Unexpected asynchronous deactivation when unbinding "${t$2(e)}" service. Consider using Container.unbind() instead.`;var i;throw new $(G.invalidOperation,n)}#g(e){return I(e)?this.#b(e):this.#p(e)}#b(e){const n=this.#u.bindingService.getById(e.id),i=dt(this.#l,n);if(void 0!==i)return i.then((()=>{this.#S(e);}));this.#S(e);}#S(e){this.#u.bindingService.removeById(e.id),this.#u.planResultCacheService.clearCache();}#p(e){const n=pt(this.#l,e);if(void 0!==n)return n.then((()=>{this.#M(e);}));this.#M(e);}#M(e){this.#u.activationService.removeAllByServiceId(e),this.#u.bindingService.removeAllByServiceId(e),this.#u.deactivationService.removeAllByServiceId(e),this.#u.planResultCacheService.clearCache();}#v(e,n,i){if(void 0===n)return false;const t={getAncestor:()=>{},name:i?.name,serviceIdentifier:e,tags:new Map};void 0!==i?.tag&&t.tags.set(i.tag.key,i.tag.value);for(const e of n)if(e.isSatisfiedBy(t))return true;return false}}class _{#y;#l;#a;#u;constructor(e,n,i,t){this.#y=e,this.#l=n,this.#a=i,this.#u=t;}async load(...e){await Promise.all(this.#n(...e));}loadSync(...e){const n=this.#n(...e);for(const e of n)if(void 0!==e)throw new $(G.invalidOperation,"Unexpected asynchronous module load. Consider using Container.load() instead.")}async unload(...e){await Promise.all(this.#R(...e)),this.#w(e);}unloadSync(...e){const n=this.#R(...e);for(const e of n)if(void 0!==e)throw new $(G.invalidOperation,"Unexpected asynchronous module unload. Consider using Container.unload() instead.");this.#w(e);}#m(e){return {bind:n=>new D((e=>{this.#h(e);}),e,this.#a,n),isBound:this.#y.isBound.bind(this.#y),onActivation:(n,i)=>{this.#u.activationService.add(i,{moduleId:e,serviceId:n});},onDeactivation:(n,i)=>{this.#u.deactivationService.add(i,{moduleId:e,serviceId:n});},rebind:this.#y.rebind.bind(this.#y),rebindSync:this.#y.rebindSync.bind(this.#y),unbind:this.#y.unbind.bind(this.#y),unbindSync:this.#y.unbindSync.bind(this.#y)}}#w(e){for(const n of e)this.#u.activationService.removeAllByModuleId(n.id),this.#u.bindingService.removeAllByModuleId(n.id),this.#u.deactivationService.removeAllByModuleId(n.id);this.#u.planResultCacheService.clearCache();}#n(...e){return e.map((e=>e.load(this.#m(e.id))))}#h(e){this.#u.bindingService.set(e),this.#u.planResultCacheService.clearCache();}#R(...e){return e.map((e=>lt(this.#l,e.id)))}}class z{#I;#A;#P;#u;constructor(e,n,i){this.#u=n,this.#P=i,this.#I=this.#C(e),this.#A=this.#B();}register(e,n){const i=new n(e,this.#A);if(true!==i[t])throw new $(G.invalidOperation,"Invalid plugin. The plugin must extend the Plugin class");i.load(this.#I);}#C(e){return {define:(n,i)=>{if(Object.prototype.hasOwnProperty.call(e,n))throw new $(G.invalidOperation,`Container already has a method named "${String(n)}"`);e[n]=i;},onPlan:this.#P.onPlan.bind(this.#P)}}#B(){const e=this.#u;return {get activationService(){return e.activationService},get bindingService(){return e.bindingService},get deactivationService(){return e.deactivationService},get planResultCacheService(){return e.planResultCacheService}}}}class K{activationService;bindingService;deactivationService;planResultCacheService;#x;constructor(e,n,i,t){this.activationService=e,this.bindingService=n,this.deactivationService=i,this.planResultCacheService=t,this.#x=[];}reset(e,n,i){this.activationService=e,this.bindingService=n,this.deactivationService=i,this.planResultCacheService.clearCache();for(const e of this.#x)e();}onReset(e){this.#x.push(e);}}class X{#O;#a;#N;#U;#F;#k;#u;#j;constructor(e,n,i){this.#u=e,this.#F=this.#D(),this.#O=n,this.#a=i,this.#N=e=>this.#u.activationService.get(e),this.#U=this.#u.bindingService.get.bind(this.#u.bindingService),this.#k=[],this.#j=this.#h.bind(this),this.#u.onReset((()=>{this.#T();}));}get(e$1,n){const i=this.#V(false,e$1,n),t=this.#E(i);if(e(t))throw new $(G.invalidOperation,`Unexpected asynchronous service when resolving service "${t$2(e$1)}"`);return t}getAll(e$1,n){const i=this.#V(true,e$1,n),t=this.#E(i);if(e(t))throw new $(G.invalidOperation,`Unexpected asynchronous service when resolving service "${t$2(e$1)}"`);return t}async getAllAsync(e,n){const i=this.#V(true,e,n);return this.#E(i)}async getAsync(e,n){const i=this.#V(false,e,n);return this.#E(i)}onPlan(e){this.#k.push(e);}#T(){this.#U=this.#u.bindingService.get.bind(this.#u.bindingService),this.#j=this.#h.bind(this),this.#F=this.#D();}#L(e,n,i){return {isMultiple:e,name:i?.name,optional:i?.optional,serviceIdentifier:n,tag:i?.tag}}#q(e,n,i){const r={autobindOptions:i?.autobind??this.#O?{scope:this.#a}:void 0,getBindings:this.#U,getClassMetadata:x$1,rootConstraints:{isMultiple:n,serviceIdentifier:e},servicesBranch:[],setBinding:this.#j};return this.#$(r,i),r}#V(e,n,i){const t=this.#L(e,n,i),r=this.#u.planResultCacheService.get(t);if(void 0!==r)return r;const a=we(this.#q(n,e,i));this.#u.planResultCacheService.set(t,a);for(const e of this.#k)e(t,a);return a}#D(){return {get:this.get.bind(this),getAll:this.getAll.bind(this),getAllAsync:this.getAllAsync.bind(this),getAsync:this.getAsync.bind(this)}}#E(e){return et({context:this.#F,getActivations:this.#N,planResult:e,requestScopeCache:new Map})}#$(e,n){ void 0!==n&&(void 0!==n.name&&(e.rootConstraints.name=n.name),true===n.optional&&(e.rootConstraints.isOptional=true),void 0!==n.tag&&(e.rootConstraints.tag={key:n.tag.key,value:n.tag.value}));}#h(e){this.#u.bindingService.set(e),this.#u.planResultCacheService.clearCache();}}class J{#u;#G;constructor(e){this.#u=e,this.#G=[];}restore(){const e=this.#G.pop();if(void 0===e)throw new $(G.invalidOperation,"No snapshot available to restore");this.#u.reset(e.activationService,e.bindingService,e.deactivationService);}snapshot(){this.#G.push({activationService:this.#u.activationService.clone(),bindingService:this.#u.bindingService.clone(),deactivationService:this.#u.deactivationService.clone()});}}const Q=u.Transient;class W{#y;#H;#_;#u;#P;#z;constructor(e){this.#u=this.#K(e);const n=e?.autobind??false,i=e?.defaultScope??Q,r={getBindings:(a=this.#u).bindingService.get.bind(a.bindingService),getBindingsFromModule:a.bindingService.getByModuleId.bind(a.bindingService),getClassMetadata:x$1,getDeactivations:a.deactivationService.get.bind(a.deactivationService)};var a;this.#y=new H(r,i,this.#u),this.#H=new _(this.#y,r,i,this.#u),this.#P=new X(this.#u,n,i),this.#_=new z(this,this.#u,this.#P),this.#z=new J(this.#u);}bind(e){return this.#y.bind(e)}get(e,n){return this.#P.get(e,n)}getAll(e,n){return this.#P.getAll(e,n)}async getAllAsync(e,n){return this.#P.getAllAsync(e,n)}async getAsync(e,n){return this.#P.getAsync(e,n)}isBound(e,n){return this.#y.isBound(e,n)}isCurrentBound(e,n){return this.#y.isCurrentBound(e,n)}async load(...e){return this.#H.load(...e)}loadSync(...e){this.#H.loadSync(...e);}onActivation(e,n){this.#u.activationService.add(n,{serviceId:e});}onDeactivation(e,n){this.#u.deactivationService.add(n,{serviceId:e});}register(e){this.#_.register(this,e);}restore(){this.#z.restore();}async rebind(e){return this.#y.rebind(e)}rebindSync(e){return this.#y.rebindSync(e)}snapshot(){this.#z.snapshot();}async unbind(e){await this.#y.unbind(e);}async unbindAll(){return this.#y.unbindAll()}unbindSync(e){this.#y.unbindSync(e);}async unload(...e){return this.#H.unload(...e)}unloadSync(...e){this.#H.unloadSync(...e);}#K(e){if(void 0===e?.parent)return new K(m$1.build(void 0),I$1.build(void 0),w.build(void 0),new xe);const n=new xe;return e.parent.#u.planResultCacheService.subscribe(n),new K(m$1.build(e.parent.#u.activationService),I$1.build(e.parent.#u.bindingService),w.build(e.parent.#u.deactivationService),n)}}
|
|
12
|
-
|
|
13
|
-
const METADATA_KEY = {
|
|
14
|
-
PARAM_TYPES: "design:paramtypes",
|
|
15
|
-
TYPE: "design:type",
|
|
16
|
-
RETURN_TYPE: "design:returntype"
|
|
17
|
-
};
|
|
18
|
-
const container = new W({
|
|
19
|
-
defaultScope: "Singleton"
|
|
20
|
-
});
|
|
21
|
-
const bind = (id, cls) => container.bind(id).to(cls).inSingletonScope();
|
|
22
|
-
const resolve = (id) => container.get(id);
|
|
23
|
-
function isInjectable(target) {
|
|
24
|
-
return !!Reflect.getMetadata(METADATA_KEY.PARAM_TYPES, target);
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
class MiddlewareRegistryClass {
|
|
28
|
-
constructor() {
|
|
29
|
-
this.global = [];
|
|
30
|
-
this.perHandler = /* @__PURE__ */ new Map();
|
|
31
|
-
}
|
|
32
|
-
registerGlobal(fn) {
|
|
33
|
-
this.global.push(fn);
|
|
34
|
-
}
|
|
35
|
-
registerForKey(key, fn) {
|
|
36
|
-
const arr = this.perHandler.get(key) ?? [];
|
|
37
|
-
arr.push(fn);
|
|
38
|
-
this.perHandler.set(key, arr);
|
|
39
|
-
}
|
|
40
|
-
pipeline(key) {
|
|
41
|
-
return [...this.global, ...this.perHandler.get(key) ?? []];
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
const MiddlewareRegistry = new MiddlewareRegistryClass();
|
|
45
|
-
|
|
46
|
-
const DEFAULT_PORT_NAME = "chroma-bridge";
|
|
47
|
-
|
|
48
|
-
class DefaultErrorHandler {
|
|
49
|
-
handle(error, context) {
|
|
50
|
-
return {
|
|
51
|
-
id: context.request.id,
|
|
52
|
-
error: error?.message ?? "UNKNOWN_ERROR",
|
|
53
|
-
timestamp: Date.now()
|
|
54
|
-
};
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
const _BridgeRuntimeManager = class _BridgeRuntimeManager {
|
|
58
|
-
constructor(options) {
|
|
59
|
-
this.keepAliveTimer = null;
|
|
60
|
-
this.isInitialized = false;
|
|
61
|
-
this.container = options.container;
|
|
62
|
-
this.portName = options.portName ?? DEFAULT_PORT_NAME;
|
|
63
|
-
this.enableLogging = options.enableLogging ?? true;
|
|
64
|
-
this.errorHandler = options.errorHandler ?? new DefaultErrorHandler();
|
|
65
|
-
this.logger = new BridgeLogger(this.enableLogging);
|
|
66
|
-
this.keepAlive = options.keepAlive ?? false;
|
|
67
|
-
}
|
|
68
|
-
/**
|
|
69
|
-
* Initialize the bridge runtime and start listening for connections
|
|
70
|
-
*/
|
|
71
|
-
initialize() {
|
|
72
|
-
if (this.isInitialized) {
|
|
73
|
-
this.logger.warn("Bridge runtime already initialized");
|
|
74
|
-
return;
|
|
75
|
-
}
|
|
76
|
-
this.setupPortListener();
|
|
77
|
-
if (this.keepAlive) {
|
|
78
|
-
this.startKeepAlive();
|
|
79
|
-
}
|
|
80
|
-
this.isInitialized = true;
|
|
81
|
-
this.logger.success(`\u{1F309} Bridge runtime initialized on port: ${this.portName}`);
|
|
82
|
-
}
|
|
83
|
-
/**
|
|
84
|
-
* Setup Chrome runtime port listener
|
|
85
|
-
*/
|
|
86
|
-
setupPortListener() {
|
|
87
|
-
chrome.runtime.onConnect.addListener((port) => {
|
|
88
|
-
try {
|
|
89
|
-
if (!this.isValidPort(port)) {
|
|
90
|
-
return;
|
|
91
|
-
}
|
|
92
|
-
this.logger.info(`\u{1F4E1} Port connected: ${port.name}`);
|
|
93
|
-
this.setupMessageHandler(port);
|
|
94
|
-
if (chrome.runtime.lastError) {
|
|
95
|
-
this.logger.warn(`Runtime error during port setup: ${chrome.runtime.lastError.message}`);
|
|
96
|
-
chrome.runtime.lastError;
|
|
97
|
-
}
|
|
98
|
-
} catch (error) {
|
|
99
|
-
this.logger.error("Error setting up port listener:", error);
|
|
100
|
-
if (chrome.runtime.lastError) {
|
|
101
|
-
this.logger.warn(`Additional runtime error: ${chrome.runtime.lastError.message}`);
|
|
102
|
-
chrome.runtime.lastError;
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
});
|
|
106
|
-
}
|
|
107
|
-
/**
|
|
108
|
-
* Validate incoming port connection
|
|
109
|
-
*/
|
|
110
|
-
isValidPort(port) {
|
|
111
|
-
if (port.name !== this.portName) {
|
|
112
|
-
this.logger.warn(`Ignoring port "${port.name}", expected "${this.portName}"`);
|
|
113
|
-
return false;
|
|
114
|
-
}
|
|
115
|
-
const senderId = port.sender?.id;
|
|
116
|
-
if (senderId !== chrome.runtime.id) {
|
|
117
|
-
this.logger.warn(
|
|
118
|
-
`Ignoring port from different extension (senderId: ${senderId}, expected: ${chrome.runtime.id})`
|
|
119
|
-
);
|
|
120
|
-
return false;
|
|
121
|
-
}
|
|
122
|
-
return true;
|
|
123
|
-
}
|
|
124
|
-
/**
|
|
125
|
-
* Setup message handler for connected port
|
|
126
|
-
*/
|
|
127
|
-
setupMessageHandler(port) {
|
|
128
|
-
port.onMessage.addListener(async (request) => {
|
|
129
|
-
const context = this.createPipelineContext(request);
|
|
130
|
-
try {
|
|
131
|
-
this.logger.debug("\u{1F4E8} Received message:", {
|
|
132
|
-
key: request.key,
|
|
133
|
-
id: request.id,
|
|
134
|
-
hasPayload: !!request.payload
|
|
135
|
-
});
|
|
136
|
-
const response = await this.processMessage(context);
|
|
137
|
-
this.sendResponse(port, response);
|
|
138
|
-
} catch (error) {
|
|
139
|
-
const errorResponse = await this.handleError(error, context);
|
|
140
|
-
this.sendResponse(port, errorResponse);
|
|
141
|
-
}
|
|
142
|
-
});
|
|
143
|
-
port.onDisconnect.addListener(() => {
|
|
144
|
-
if (chrome.runtime.lastError) {
|
|
145
|
-
this.logger.warn(`\u{1F4F4} Port disconnected with error: ${chrome.runtime.lastError.message}`);
|
|
146
|
-
chrome.runtime.lastError;
|
|
147
|
-
} else {
|
|
148
|
-
this.logger.info(`\u{1F4F4} Port disconnected: ${port.name}`);
|
|
149
|
-
}
|
|
150
|
-
});
|
|
151
|
-
}
|
|
152
|
-
/**
|
|
153
|
-
* Create pipeline context for request processing
|
|
154
|
-
*/
|
|
155
|
-
createPipelineContext(request) {
|
|
156
|
-
return {
|
|
157
|
-
request,
|
|
158
|
-
startTime: Date.now(),
|
|
159
|
-
metadata: { ...request.metadata }
|
|
160
|
-
};
|
|
161
|
-
}
|
|
162
|
-
/**
|
|
163
|
-
* Process message through middleware pipeline and handler
|
|
164
|
-
*/
|
|
165
|
-
async processMessage(context) {
|
|
166
|
-
const { request } = context;
|
|
167
|
-
const handler = this.resolveHandler(request.key);
|
|
168
|
-
const middlewares = MiddlewareRegistry.pipeline(request.key);
|
|
169
|
-
const data = await this.runPipeline(
|
|
170
|
-
middlewares,
|
|
171
|
-
context,
|
|
172
|
-
() => handler.handle(request.payload)
|
|
173
|
-
);
|
|
174
|
-
return {
|
|
175
|
-
id: request.id,
|
|
176
|
-
data,
|
|
177
|
-
timestamp: Date.now()
|
|
178
|
-
};
|
|
179
|
-
}
|
|
180
|
-
/**
|
|
181
|
-
* Resolve message handler from dependency injection container
|
|
182
|
-
*/
|
|
183
|
-
resolveHandler(key) {
|
|
184
|
-
try {
|
|
185
|
-
const handler = this.container.get(key);
|
|
186
|
-
if (!handler || typeof handler.handle !== "function") {
|
|
187
|
-
throw new Error(`Handler "${key}" does not implement MessageHandler interface`);
|
|
188
|
-
}
|
|
189
|
-
return handler;
|
|
190
|
-
} catch (error) {
|
|
191
|
-
throw new Error(`Failed to resolve handler "${key}": ${error.message}`);
|
|
192
|
-
}
|
|
193
|
-
}
|
|
194
|
-
/**
|
|
195
|
-
* Execute middleware pipeline with proper error handling
|
|
196
|
-
*/
|
|
197
|
-
async runPipeline(middlewares, context, finalHandler) {
|
|
198
|
-
let currentIndex = -1;
|
|
199
|
-
const executeNext = async () => {
|
|
200
|
-
currentIndex++;
|
|
201
|
-
if (currentIndex === middlewares.length) {
|
|
202
|
-
return finalHandler();
|
|
203
|
-
}
|
|
204
|
-
if (currentIndex > middlewares.length) {
|
|
205
|
-
throw new Error("next() called multiple times");
|
|
206
|
-
}
|
|
207
|
-
const middleware = middlewares[currentIndex];
|
|
208
|
-
return middleware(context, executeNext);
|
|
209
|
-
};
|
|
210
|
-
return executeNext();
|
|
211
|
-
}
|
|
212
|
-
/**
|
|
213
|
-
* Handle errors during message processing
|
|
214
|
-
*/
|
|
215
|
-
async handleError(error, context) {
|
|
216
|
-
const duration = Date.now() - context.startTime;
|
|
217
|
-
this.logger.error(`\u{1F4A5} Message processing failed after ${duration}ms:`, {
|
|
218
|
-
key: context.request.key,
|
|
219
|
-
id: context.request.id,
|
|
220
|
-
error: error.message
|
|
221
|
-
});
|
|
222
|
-
return this.errorHandler.handle(error, context);
|
|
223
|
-
}
|
|
224
|
-
/**
|
|
225
|
-
* Send response back through the port
|
|
226
|
-
*/
|
|
227
|
-
sendResponse(port, response) {
|
|
228
|
-
try {
|
|
229
|
-
if (!port) {
|
|
230
|
-
this.logger.warn(`Cannot send response: port is null (ID: ${response.id})`);
|
|
231
|
-
return;
|
|
232
|
-
}
|
|
233
|
-
port.postMessage(response);
|
|
234
|
-
if (chrome.runtime.lastError) {
|
|
235
|
-
this.logger.warn(
|
|
236
|
-
`Chrome runtime error during postMessage: ${chrome.runtime.lastError.message} (ID: ${response.id})`
|
|
237
|
-
);
|
|
238
|
-
chrome.runtime.lastError;
|
|
239
|
-
return;
|
|
240
|
-
}
|
|
241
|
-
this.logger.debug("\u{1F4E4} Response sent:", {
|
|
242
|
-
id: response.id,
|
|
243
|
-
hasData: !!response.data,
|
|
244
|
-
hasError: !!response.error,
|
|
245
|
-
data: response.data
|
|
246
|
-
});
|
|
247
|
-
} catch (error) {
|
|
248
|
-
this.logger.error("Failed to send response:", error);
|
|
249
|
-
if (chrome.runtime.lastError) {
|
|
250
|
-
this.logger.warn(`Additional Chrome runtime error: ${chrome.runtime.lastError.message}`);
|
|
251
|
-
chrome.runtime.lastError;
|
|
252
|
-
}
|
|
253
|
-
}
|
|
254
|
-
}
|
|
255
|
-
/**
|
|
256
|
-
* Get runtime statistics
|
|
257
|
-
*/
|
|
258
|
-
getStats() {
|
|
259
|
-
return {
|
|
260
|
-
portName: this.portName,
|
|
261
|
-
initialized: this.isInitialized
|
|
262
|
-
};
|
|
263
|
-
}
|
|
264
|
-
/**
|
|
265
|
-
* Start keep-alive timer to keep service worker alive
|
|
266
|
-
*/
|
|
267
|
-
startKeepAlive() {
|
|
268
|
-
if (this.keepAliveTimer) return;
|
|
269
|
-
this.logger.info("Starting keep-alive timer to keep service worker alive");
|
|
270
|
-
this.keepAliveTimer = setInterval(() => {
|
|
271
|
-
chrome.runtime.getPlatformInfo(() => {
|
|
272
|
-
});
|
|
273
|
-
}, _BridgeRuntimeManager.KEEP_ALIVE_INTERVAL_MS);
|
|
274
|
-
}
|
|
275
|
-
/**
|
|
276
|
-
* Stop keep-alive timer
|
|
277
|
-
*/
|
|
278
|
-
stopKeepAlive() {
|
|
279
|
-
if (this.keepAliveTimer) {
|
|
280
|
-
clearInterval(this.keepAliveTimer);
|
|
281
|
-
this.keepAliveTimer = null;
|
|
282
|
-
this.logger.info("Stopped keep-alive timer");
|
|
283
|
-
}
|
|
284
|
-
}
|
|
285
|
-
};
|
|
286
|
-
_BridgeRuntimeManager.KEEP_ALIVE_INTERVAL_MS = 25e3;
|
|
287
|
-
let BridgeRuntimeManager = _BridgeRuntimeManager;
|
|
288
|
-
class BridgeLogger {
|
|
289
|
-
constructor(enabled = true) {
|
|
290
|
-
this.enabled = enabled;
|
|
291
|
-
}
|
|
292
|
-
info(message, context) {
|
|
293
|
-
if (!this.enabled) return;
|
|
294
|
-
console.log(`[Bridge] ${message}`);
|
|
295
|
-
if (context) console.log(" Context:", context);
|
|
296
|
-
}
|
|
297
|
-
success(message) {
|
|
298
|
-
if (!this.enabled) return;
|
|
299
|
-
console.log(`[Bridge] ${message}`);
|
|
300
|
-
}
|
|
301
|
-
warn(message) {
|
|
302
|
-
if (!this.enabled) return;
|
|
303
|
-
console.warn(`[Bridge] ${message}`);
|
|
304
|
-
}
|
|
305
|
-
error(message, error) {
|
|
306
|
-
if (!this.enabled) return;
|
|
307
|
-
console.error(`[Bridge] ${message}`);
|
|
308
|
-
if (error) console.error(" Error:", error);
|
|
309
|
-
}
|
|
310
|
-
debug(message, context) {
|
|
311
|
-
if (!this.enabled) return;
|
|
312
|
-
console.debug(`[Bridge] ${message}`);
|
|
313
|
-
if (context) console.debug(" Context:", context);
|
|
314
|
-
}
|
|
315
|
-
}
|
|
316
|
-
function bootstrap$1(options) {
|
|
317
|
-
const runtime = new BridgeRuntimeManager(options);
|
|
318
|
-
console.debug("\u{1F309} Initializing Bridge Runtime with options:", options);
|
|
319
|
-
runtime.initialize();
|
|
320
|
-
}
|
|
321
|
-
|
|
322
|
-
class AlarmAdapter {
|
|
323
|
-
constructor() {
|
|
324
|
-
this.callbacks = /* @__PURE__ */ new Map();
|
|
325
|
-
}
|
|
326
|
-
onTrigger(callback) {
|
|
327
|
-
this.triggerCallback = callback;
|
|
328
|
-
}
|
|
329
|
-
schedule(id, when) {
|
|
330
|
-
const delay = Math.max(0, when - Date.now());
|
|
331
|
-
const timeoutId = setTimeout(() => {
|
|
332
|
-
this.callbacks.delete(id);
|
|
333
|
-
this.triggerCallback?.(id);
|
|
334
|
-
}, delay);
|
|
335
|
-
this.callbacks.set(id, () => clearTimeout(timeoutId));
|
|
336
|
-
return timeoutId;
|
|
337
|
-
}
|
|
338
|
-
cancel(id) {
|
|
339
|
-
const callback = this.callbacks.get(id);
|
|
340
|
-
if (callback) {
|
|
341
|
-
callback();
|
|
342
|
-
this.callbacks.delete(id);
|
|
343
|
-
}
|
|
344
|
-
}
|
|
345
|
-
}
|
|
346
|
-
|
|
347
|
-
class TimeoutAdapter {
|
|
348
|
-
constructor() {
|
|
349
|
-
this.callbacks = /* @__PURE__ */ new Map();
|
|
350
|
-
}
|
|
351
|
-
onTrigger(callback) {
|
|
352
|
-
this.triggerCallback = callback;
|
|
353
|
-
}
|
|
354
|
-
schedule(id, when) {
|
|
355
|
-
const delay = Math.max(0, when - Date.now());
|
|
356
|
-
const timeoutId = setTimeout(() => {
|
|
357
|
-
this.callbacks.delete(id);
|
|
358
|
-
this.triggerCallback?.(id);
|
|
359
|
-
}, delay);
|
|
360
|
-
this.callbacks.set(id, () => clearTimeout(timeoutId));
|
|
361
|
-
return timeoutId;
|
|
362
|
-
}
|
|
363
|
-
cancel(id) {
|
|
364
|
-
const callback = this.callbacks.get(id);
|
|
365
|
-
if (callback) {
|
|
366
|
-
callback();
|
|
367
|
-
this.callbacks.delete(id);
|
|
368
|
-
}
|
|
369
|
-
}
|
|
370
|
-
}
|
|
371
|
-
|
|
372
|
-
var JobState = /* @__PURE__ */ ((JobState2) => {
|
|
373
|
-
JobState2["SCHEDULED"] = "scheduled";
|
|
374
|
-
JobState2["RUNNING"] = "running";
|
|
375
|
-
JobState2["PAUSED"] = "paused";
|
|
376
|
-
JobState2["STOPPED"] = "stopped";
|
|
377
|
-
JobState2["COMPLETED"] = "completed";
|
|
378
|
-
JobState2["FAILED"] = "failed";
|
|
379
|
-
return JobState2;
|
|
380
|
-
})(JobState || {});
|
|
381
|
-
|
|
382
|
-
const _JobRegistry = class _JobRegistry {
|
|
383
|
-
constructor() {
|
|
384
|
-
this.jobs = /* @__PURE__ */ new Map();
|
|
385
|
-
}
|
|
386
|
-
register(id, job, options) {
|
|
387
|
-
const context = this.createJobContext(id, options);
|
|
388
|
-
this.jobs.set(id, {
|
|
389
|
-
job,
|
|
390
|
-
context,
|
|
391
|
-
options
|
|
392
|
-
});
|
|
393
|
-
}
|
|
394
|
-
resolve(id) {
|
|
395
|
-
const entry = this.jobs.get(id);
|
|
396
|
-
return entry?.job;
|
|
397
|
-
}
|
|
398
|
-
meta(id) {
|
|
399
|
-
const entry = this.jobs.get(id);
|
|
400
|
-
return entry?.options;
|
|
401
|
-
}
|
|
402
|
-
getContext(id) {
|
|
403
|
-
const entry = this.jobs.get(id);
|
|
404
|
-
return entry?.context;
|
|
405
|
-
}
|
|
406
|
-
updateState(id, state) {
|
|
407
|
-
const entry = this.jobs.get(id);
|
|
408
|
-
if (entry) {
|
|
409
|
-
entry.context.state = state;
|
|
410
|
-
entry.context.updatedAt = /* @__PURE__ */ new Date();
|
|
411
|
-
switch (state) {
|
|
412
|
-
case JobState.RUNNING:
|
|
413
|
-
entry.context.startedAt = /* @__PURE__ */ new Date();
|
|
414
|
-
break;
|
|
415
|
-
case JobState.PAUSED:
|
|
416
|
-
entry.context.pausedAt = /* @__PURE__ */ new Date();
|
|
417
|
-
break;
|
|
418
|
-
case JobState.STOPPED:
|
|
419
|
-
entry.context.stoppedAt = /* @__PURE__ */ new Date();
|
|
420
|
-
break;
|
|
421
|
-
case JobState.COMPLETED:
|
|
422
|
-
entry.context.completedAt = /* @__PURE__ */ new Date();
|
|
423
|
-
break;
|
|
424
|
-
}
|
|
425
|
-
}
|
|
426
|
-
}
|
|
427
|
-
setTimeoutId(id, timeoutId) {
|
|
428
|
-
const entry = this.jobs.get(id);
|
|
429
|
-
if (entry) {
|
|
430
|
-
entry.timeoutId = timeoutId;
|
|
431
|
-
}
|
|
432
|
-
}
|
|
433
|
-
setIntervalId(id, intervalId) {
|
|
434
|
-
const entry = this.jobs.get(id);
|
|
435
|
-
if (entry) {
|
|
436
|
-
entry.intervalId = intervalId;
|
|
437
|
-
}
|
|
438
|
-
}
|
|
439
|
-
clearTimers(id) {
|
|
440
|
-
const entry = this.jobs.get(id);
|
|
441
|
-
if (entry) {
|
|
442
|
-
if (entry.timeoutId) {
|
|
443
|
-
clearTimeout(entry.timeoutId);
|
|
444
|
-
entry.timeoutId = void 0;
|
|
445
|
-
}
|
|
446
|
-
if (entry.intervalId) {
|
|
447
|
-
clearInterval(entry.intervalId);
|
|
448
|
-
entry.intervalId = void 0;
|
|
449
|
-
}
|
|
450
|
-
}
|
|
451
|
-
}
|
|
452
|
-
pause(id) {
|
|
453
|
-
const entry = this.jobs.get(id);
|
|
454
|
-
console.log(`Pausing job ${id}`);
|
|
455
|
-
if (entry && entry.context.state === JobState.RUNNING) {
|
|
456
|
-
console.log(`paused job ${id}`);
|
|
457
|
-
this.updateState(id, JobState.PAUSED);
|
|
458
|
-
this.clearTimers(id);
|
|
459
|
-
entry.job.pause?.();
|
|
460
|
-
}
|
|
461
|
-
}
|
|
462
|
-
resume(id) {
|
|
463
|
-
const entry = this.jobs.get(id);
|
|
464
|
-
console.log(`Resuming job ${id}`);
|
|
465
|
-
if (entry && entry.context.state === JobState.PAUSED) {
|
|
466
|
-
console.log(`Resuming job ${id}`);
|
|
467
|
-
this.updateState(id, JobState.SCHEDULED);
|
|
468
|
-
entry.job.resume?.();
|
|
469
|
-
}
|
|
470
|
-
}
|
|
471
|
-
stop(id) {
|
|
472
|
-
const entry = this.jobs.get(id);
|
|
473
|
-
if (entry && entry.context.state !== JobState.STOPPED) {
|
|
474
|
-
console.log(`Stopping job ${id}`);
|
|
475
|
-
this.updateState(id, JobState.STOPPED);
|
|
476
|
-
this.clearTimers(id);
|
|
477
|
-
entry.job.stop?.();
|
|
478
|
-
}
|
|
479
|
-
}
|
|
480
|
-
createJobContext(id, options) {
|
|
481
|
-
const now = /* @__PURE__ */ new Date();
|
|
482
|
-
return {
|
|
483
|
-
id,
|
|
484
|
-
options,
|
|
485
|
-
state: JobState.SCHEDULED,
|
|
486
|
-
createdAt: now,
|
|
487
|
-
updatedAt: now,
|
|
488
|
-
retryCount: 0,
|
|
489
|
-
pause: () => this.pause(id),
|
|
490
|
-
resume: () => this.resume(id),
|
|
491
|
-
stop: () => this.stop(id),
|
|
492
|
-
complete: () => this.updateState(id, JobState.COMPLETED),
|
|
493
|
-
fail: (error) => {
|
|
494
|
-
this.updateState(id, JobState.FAILED);
|
|
495
|
-
const entry = this.jobs.get(id);
|
|
496
|
-
if (entry) entry.context.error = error;
|
|
497
|
-
},
|
|
498
|
-
retry: () => {
|
|
499
|
-
const entry = this.jobs.get(id);
|
|
500
|
-
if (entry) {
|
|
501
|
-
entry.context.retryCount = (entry.context.retryCount || 0) + 1;
|
|
502
|
-
this.updateState(id, JobState.SCHEDULED);
|
|
503
|
-
}
|
|
504
|
-
},
|
|
505
|
-
isRunning: () => this.getContext(id)?.state === JobState.RUNNING,
|
|
506
|
-
isPaused: () => this.getContext(id)?.state === JobState.PAUSED,
|
|
507
|
-
isStopped: () => this.getContext(id)?.state === JobState.STOPPED,
|
|
508
|
-
isCompleted: () => this.getContext(id)?.state === JobState.COMPLETED,
|
|
509
|
-
isFailed: () => this.getContext(id)?.state === JobState.FAILED,
|
|
510
|
-
isRetrying: () => (this.getContext(id)?.retryCount || 0) > 0,
|
|
511
|
-
isScheduled: () => this.getContext(id)?.state === JobState.SCHEDULED,
|
|
512
|
-
isDelayed: () => !!options.delay,
|
|
513
|
-
isRecurring: () => !!options.cron,
|
|
514
|
-
isCron: () => !!options.cron,
|
|
515
|
-
isTimeout: () => !!options.delay && !options.cron,
|
|
516
|
-
isAlarm: () => !!options.cron || !!options.delay && options.delay > 6e4
|
|
517
|
-
};
|
|
518
|
-
}
|
|
519
|
-
};
|
|
520
|
-
_JobRegistry.instance = new _JobRegistry();
|
|
521
|
-
let JobRegistry = _JobRegistry;
|
|
522
|
-
|
|
523
|
-
/* Extracts second, minute, hour, date, month and the weekday from a date. */
|
|
524
|
-
function extractDateElements(date) {
|
|
525
|
-
return {
|
|
526
|
-
second: date.getSeconds(),
|
|
527
|
-
minute: date.getMinutes(),
|
|
528
|
-
hour: date.getHours(),
|
|
529
|
-
day: date.getDate(),
|
|
530
|
-
month: date.getMonth(),
|
|
531
|
-
weekday: date.getDay(),
|
|
532
|
-
year: date.getFullYear(),
|
|
533
|
-
};
|
|
534
|
-
}
|
|
535
|
-
/* Gets the amount of days in the given month (indexed by 0) of the given year. */
|
|
536
|
-
function getDaysInMonth(year, month) {
|
|
537
|
-
return new Date(year, month + 1, 0).getDate();
|
|
538
|
-
}
|
|
539
|
-
/* Gets the amount of days from weekday1 to weekday2. */
|
|
540
|
-
function getDaysBetweenWeekdays(weekday1, weekday2) {
|
|
541
|
-
if (weekday1 <= weekday2) {
|
|
542
|
-
return weekday2 - weekday1;
|
|
543
|
-
}
|
|
544
|
-
return 6 - weekday1 + weekday2 + 1;
|
|
545
|
-
}
|
|
546
|
-
|
|
547
|
-
class Cron {
|
|
548
|
-
constructor({ seconds, minutes, hours, days, months, weekdays, }) {
|
|
549
|
-
// Validate that there are values provided.
|
|
550
|
-
if (!seconds || seconds.size === 0)
|
|
551
|
-
throw new Error('There must be at least one allowed second.');
|
|
552
|
-
if (!minutes || minutes.size === 0)
|
|
553
|
-
throw new Error('There must be at least one allowed minute.');
|
|
554
|
-
if (!hours || hours.size === 0)
|
|
555
|
-
throw new Error('There must be at least one allowed hour.');
|
|
556
|
-
if (!months || months.size === 0)
|
|
557
|
-
throw new Error('There must be at least one allowed month.');
|
|
558
|
-
if ((!weekdays || weekdays.size === 0) && (!days || days.size === 0))
|
|
559
|
-
throw new Error('There must be at least one allowed day or weekday.');
|
|
560
|
-
// Convert set to array and sort in ascending order.
|
|
561
|
-
this.seconds = Array.from(seconds).sort((a, b) => a - b);
|
|
562
|
-
this.minutes = Array.from(minutes).sort((a, b) => a - b);
|
|
563
|
-
this.hours = Array.from(hours).sort((a, b) => a - b);
|
|
564
|
-
this.days = Array.from(days).sort((a, b) => a - b);
|
|
565
|
-
this.months = Array.from(months).sort((a, b) => a - b);
|
|
566
|
-
this.weekdays = Array.from(weekdays).sort((a, b) => a - b);
|
|
567
|
-
// Validate that all values are integers within the constraint.
|
|
568
|
-
const validateData = (name, data, constraint) => {
|
|
569
|
-
if (data.some((x) => typeof x !== 'number' ||
|
|
570
|
-
x % 1 !== 0 ||
|
|
571
|
-
x < constraint.min ||
|
|
572
|
-
x > constraint.max)) {
|
|
573
|
-
throw new Error(`${name} must only consist of integers which are within the range of ${constraint.min} and ${constraint.max}`);
|
|
574
|
-
}
|
|
575
|
-
};
|
|
576
|
-
validateData('seconds', this.seconds, { min: 0, max: 59 });
|
|
577
|
-
validateData('minutes', this.minutes, { min: 0, max: 59 });
|
|
578
|
-
validateData('hours', this.hours, { min: 0, max: 23 });
|
|
579
|
-
validateData('days', this.days, { min: 1, max: 31 });
|
|
580
|
-
validateData('months', this.months, { min: 0, max: 11 });
|
|
581
|
-
validateData('weekdays', this.weekdays, { min: 0, max: 6 });
|
|
582
|
-
// For each element, store a reversed copy in the reversed attribute for finding prev dates.
|
|
583
|
-
this.reversed = {
|
|
584
|
-
seconds: this.seconds.map((x) => x).reverse(),
|
|
585
|
-
minutes: this.minutes.map((x) => x).reverse(),
|
|
586
|
-
hours: this.hours.map((x) => x).reverse(),
|
|
587
|
-
days: this.days.map((x) => x).reverse(),
|
|
588
|
-
months: this.months.map((x) => x).reverse(),
|
|
589
|
-
weekdays: this.weekdays.map((x) => x).reverse(),
|
|
590
|
-
};
|
|
591
|
-
}
|
|
592
|
-
/**
|
|
593
|
-
* Find the next or previous hour, starting from the given start hour that matches the hour constraint.
|
|
594
|
-
* startHour itself might also be allowed.
|
|
595
|
-
*/
|
|
596
|
-
findAllowedHour(dir, startHour) {
|
|
597
|
-
return dir === 'next'
|
|
598
|
-
? this.hours.find((x) => x >= startHour)
|
|
599
|
-
: this.reversed.hours.find((x) => x <= startHour);
|
|
600
|
-
}
|
|
601
|
-
/**
|
|
602
|
-
* Find the next or previous minute, starting from the given start minute that matches the minute constraint.
|
|
603
|
-
* startMinute itself might also be allowed.
|
|
604
|
-
*/
|
|
605
|
-
findAllowedMinute(dir, startMinute) {
|
|
606
|
-
return dir === 'next'
|
|
607
|
-
? this.minutes.find((x) => x >= startMinute)
|
|
608
|
-
: this.reversed.minutes.find((x) => x <= startMinute);
|
|
609
|
-
}
|
|
610
|
-
/**
|
|
611
|
-
* Find the next or previous second, starting from the given start second that matches the second constraint.
|
|
612
|
-
* startSecond itself IS NOT allowed.
|
|
613
|
-
*/
|
|
614
|
-
findAllowedSecond(dir, startSecond) {
|
|
615
|
-
return dir === 'next'
|
|
616
|
-
? this.seconds.find((x) => x > startSecond)
|
|
617
|
-
: this.reversed.seconds.find((x) => x < startSecond);
|
|
618
|
-
}
|
|
619
|
-
/**
|
|
620
|
-
* Find the next or previous time, starting from the given start time that matches the hour, minute
|
|
621
|
-
* and second constraints. startTime itself might also be allowed.
|
|
622
|
-
*/
|
|
623
|
-
findAllowedTime(dir, startTime) {
|
|
624
|
-
// Try to find an allowed hour.
|
|
625
|
-
let hour = this.findAllowedHour(dir, startTime.hour);
|
|
626
|
-
if (hour !== undefined) {
|
|
627
|
-
if (hour === startTime.hour) {
|
|
628
|
-
// We found an hour that is the start hour. Try to find an allowed minute.
|
|
629
|
-
let minute = this.findAllowedMinute(dir, startTime.minute);
|
|
630
|
-
if (minute !== undefined) {
|
|
631
|
-
if (minute === startTime.minute) {
|
|
632
|
-
// We found a minute that is the start minute. Try to find an allowed second.
|
|
633
|
-
const second = this.findAllowedSecond(dir, startTime.second);
|
|
634
|
-
if (second !== undefined) {
|
|
635
|
-
// We found a second within the start hour and minute.
|
|
636
|
-
return { hour, minute, second };
|
|
637
|
-
}
|
|
638
|
-
// We did not find a valid second within the start minute. Try to find another minute.
|
|
639
|
-
minute = this.findAllowedMinute(dir, dir === 'next' ? startTime.minute + 1 : startTime.minute - 1);
|
|
640
|
-
if (minute !== undefined) {
|
|
641
|
-
// We found a minute which is not the start minute. Return that minute together with the hour and the first / last allowed second.
|
|
642
|
-
return {
|
|
643
|
-
hour,
|
|
644
|
-
minute,
|
|
645
|
-
second: dir === 'next' ? this.seconds[0] : this.reversed.seconds[0],
|
|
646
|
-
};
|
|
647
|
-
}
|
|
648
|
-
}
|
|
649
|
-
else {
|
|
650
|
-
// We found a minute which is not the start minute. Return that minute together with the hour and the first / last allowed second.
|
|
651
|
-
return {
|
|
652
|
-
hour,
|
|
653
|
-
minute,
|
|
654
|
-
second: dir === 'next' ? this.seconds[0] : this.reversed.seconds[0],
|
|
655
|
-
};
|
|
656
|
-
}
|
|
657
|
-
}
|
|
658
|
-
// We did not find an allowed minute / second combination inside the start hour. Try to find the next / previous allowed hour.
|
|
659
|
-
hour = this.findAllowedHour(dir, dir === 'next' ? startTime.hour + 1 : startTime.hour - 1);
|
|
660
|
-
if (hour !== undefined) {
|
|
661
|
-
// We found an allowed hour which is not the start hour. Return that hour together with the first / last allowed minutes / seconds.
|
|
662
|
-
return {
|
|
663
|
-
hour,
|
|
664
|
-
minute: dir === 'next' ? this.minutes[0] : this.reversed.minutes[0],
|
|
665
|
-
second: dir === 'next' ? this.seconds[0] : this.reversed.seconds[0],
|
|
666
|
-
};
|
|
667
|
-
}
|
|
668
|
-
}
|
|
669
|
-
else {
|
|
670
|
-
// We found an allowed hour which is not the start hour. Return that hour together with the first / last allowed minutes / seconds.
|
|
671
|
-
return {
|
|
672
|
-
hour,
|
|
673
|
-
minute: dir === 'next' ? this.minutes[0] : this.reversed.minutes[0],
|
|
674
|
-
second: dir === 'next' ? this.seconds[0] : this.reversed.seconds[0],
|
|
675
|
-
};
|
|
676
|
-
}
|
|
677
|
-
}
|
|
678
|
-
// No allowed time found.
|
|
679
|
-
return undefined;
|
|
680
|
-
}
|
|
681
|
-
/**
|
|
682
|
-
* Find the next or previous day in the given month, starting from the given startDay
|
|
683
|
-
* that matches either the day or the weekday constraint. startDay itself might also be allowed.
|
|
684
|
-
*/
|
|
685
|
-
findAllowedDayInMonth(dir, year, month, startDay) {
|
|
686
|
-
var _a, _b;
|
|
687
|
-
if (startDay < 1)
|
|
688
|
-
throw new Error('startDay must not be smaller than 1.');
|
|
689
|
-
// If only days are restricted: allow day based on day constraint only.
|
|
690
|
-
// If only weekdays are restricted: allow day based on weekday constraint only.
|
|
691
|
-
// If both are restricted: allow day based on both day and weekday constraint. pick day that is closer to startDay.
|
|
692
|
-
// If none are restricted: return the day closest to startDay (respecting dir) that is allowed (or startDay itself).
|
|
693
|
-
const daysInMonth = getDaysInMonth(year, month);
|
|
694
|
-
const daysRestricted = this.days.length !== 31;
|
|
695
|
-
const weekdaysRestricted = this.weekdays.length !== 7;
|
|
696
|
-
if (!daysRestricted && !weekdaysRestricted) {
|
|
697
|
-
if (startDay > daysInMonth) {
|
|
698
|
-
return dir === 'next' ? undefined : daysInMonth;
|
|
699
|
-
}
|
|
700
|
-
return startDay;
|
|
701
|
-
}
|
|
702
|
-
// Try to find a day based on the days constraint.
|
|
703
|
-
let allowedDayByDays;
|
|
704
|
-
if (daysRestricted) {
|
|
705
|
-
allowedDayByDays =
|
|
706
|
-
dir === 'next'
|
|
707
|
-
? this.days.find((x) => x >= startDay)
|
|
708
|
-
: this.reversed.days.find((x) => x <= startDay);
|
|
709
|
-
// Make sure the day does not exceed the amount of days in month.
|
|
710
|
-
if (allowedDayByDays !== undefined && allowedDayByDays > daysInMonth) {
|
|
711
|
-
allowedDayByDays = undefined;
|
|
712
|
-
}
|
|
713
|
-
}
|
|
714
|
-
// Try to find a day based on the weekday constraint.
|
|
715
|
-
let allowedDayByWeekdays;
|
|
716
|
-
if (weekdaysRestricted) {
|
|
717
|
-
const startWeekday = new Date(year, month, startDay).getDay();
|
|
718
|
-
const nearestAllowedWeekday = dir === 'next'
|
|
719
|
-
? (_a = this.weekdays.find((x) => x >= startWeekday)) !== null && _a !== void 0 ? _a : this.weekdays[0]
|
|
720
|
-
: (_b = this.reversed.weekdays.find((x) => x <= startWeekday)) !== null && _b !== void 0 ? _b : this.reversed.weekdays[0];
|
|
721
|
-
if (nearestAllowedWeekday !== undefined) {
|
|
722
|
-
const daysBetweenWeekdays = dir === 'next'
|
|
723
|
-
? getDaysBetweenWeekdays(startWeekday, nearestAllowedWeekday)
|
|
724
|
-
: getDaysBetweenWeekdays(nearestAllowedWeekday, startWeekday);
|
|
725
|
-
allowedDayByWeekdays =
|
|
726
|
-
dir === 'next'
|
|
727
|
-
? startDay + daysBetweenWeekdays
|
|
728
|
-
: startDay - daysBetweenWeekdays;
|
|
729
|
-
// Make sure the day does not exceed the month boundaries.
|
|
730
|
-
if (allowedDayByWeekdays > daysInMonth || allowedDayByWeekdays < 1) {
|
|
731
|
-
allowedDayByWeekdays = undefined;
|
|
732
|
-
}
|
|
733
|
-
}
|
|
734
|
-
}
|
|
735
|
-
if (allowedDayByDays !== undefined && allowedDayByWeekdays !== undefined) {
|
|
736
|
-
// If a day is found both via the days and the weekdays constraint, pick the day
|
|
737
|
-
// that is closer to start date.
|
|
738
|
-
return dir === 'next'
|
|
739
|
-
? Math.min(allowedDayByDays, allowedDayByWeekdays)
|
|
740
|
-
: Math.max(allowedDayByDays, allowedDayByWeekdays);
|
|
741
|
-
}
|
|
742
|
-
if (allowedDayByDays !== undefined) {
|
|
743
|
-
return allowedDayByDays;
|
|
744
|
-
}
|
|
745
|
-
if (allowedDayByWeekdays !== undefined) {
|
|
746
|
-
return allowedDayByWeekdays;
|
|
747
|
-
}
|
|
748
|
-
return undefined;
|
|
749
|
-
}
|
|
750
|
-
/** Gets the next date starting from the given start date or now. */
|
|
751
|
-
getNextDate(startDate = new Date()) {
|
|
752
|
-
const startDateElements = extractDateElements(startDate);
|
|
753
|
-
let minYear = startDateElements.year;
|
|
754
|
-
let startIndexMonth = this.months.findIndex((x) => x >= startDateElements.month);
|
|
755
|
-
if (startIndexMonth === -1) {
|
|
756
|
-
startIndexMonth = 0;
|
|
757
|
-
minYear++;
|
|
758
|
-
}
|
|
759
|
-
// We try every month within the next 5 years to make sure that we tried to
|
|
760
|
-
// find a matching date insidde a whole leap year.
|
|
761
|
-
const maxIterations = this.months.length * 5;
|
|
762
|
-
for (let i = 0; i < maxIterations; i++) {
|
|
763
|
-
// Get the next year and month.
|
|
764
|
-
const year = minYear + Math.floor((startIndexMonth + i) / this.months.length);
|
|
765
|
-
const month = this.months[(startIndexMonth + i) % this.months.length];
|
|
766
|
-
const isStartMonth = year === startDateElements.year && month === startDateElements.month;
|
|
767
|
-
// Find the next day.
|
|
768
|
-
let day = this.findAllowedDayInMonth('next', year, month, isStartMonth ? startDateElements.day : 1);
|
|
769
|
-
let isStartDay = isStartMonth && day === startDateElements.day;
|
|
770
|
-
// If we found a day and it is the start day, try to find a valid time beginning from the start date time.
|
|
771
|
-
if (day !== undefined && isStartDay) {
|
|
772
|
-
const nextTime = this.findAllowedTime('next', startDateElements);
|
|
773
|
-
if (nextTime !== undefined) {
|
|
774
|
-
return new Date(year, month, day, nextTime.hour, nextTime.minute, nextTime.second);
|
|
775
|
-
}
|
|
776
|
-
// If no valid time has been found for the start date, try the next day.
|
|
777
|
-
day = this.findAllowedDayInMonth('next', year, month, day + 1);
|
|
778
|
-
isStartDay = false;
|
|
779
|
-
}
|
|
780
|
-
// If we found a next day and it is not the start day, just use the next day with the first allowed values
|
|
781
|
-
// for hours, minutes and seconds.
|
|
782
|
-
if (day !== undefined && !isStartDay) {
|
|
783
|
-
return new Date(year, month, day, this.hours[0], this.minutes[0], this.seconds[0]);
|
|
784
|
-
}
|
|
785
|
-
// No allowed day has been found for this month. Continue to search in next month.
|
|
786
|
-
}
|
|
787
|
-
throw new Error('No valid next date was found.');
|
|
788
|
-
}
|
|
789
|
-
/** Gets the specified amount of future dates starting from the given start date or now. */
|
|
790
|
-
getNextDates(amount, startDate) {
|
|
791
|
-
const dates = [];
|
|
792
|
-
let nextDate;
|
|
793
|
-
for (let i = 0; i < amount; i++) {
|
|
794
|
-
nextDate = this.getNextDate(nextDate !== null && nextDate !== void 0 ? nextDate : startDate);
|
|
795
|
-
dates.push(nextDate);
|
|
796
|
-
}
|
|
797
|
-
return dates;
|
|
798
|
-
}
|
|
799
|
-
/**
|
|
800
|
-
* Get an ES6 compatible iterator which iterates over the next dates starting from startDate or now.
|
|
801
|
-
* The iterator runs until the optional endDate is reached or forever.
|
|
802
|
-
*/
|
|
803
|
-
*getNextDatesIterator(startDate, endDate) {
|
|
804
|
-
let nextDate;
|
|
805
|
-
while (true) {
|
|
806
|
-
nextDate = this.getNextDate(nextDate !== null && nextDate !== void 0 ? nextDate : startDate);
|
|
807
|
-
if (endDate && endDate.getTime() < nextDate.getTime()) {
|
|
808
|
-
return;
|
|
809
|
-
}
|
|
810
|
-
yield nextDate;
|
|
811
|
-
}
|
|
812
|
-
}
|
|
813
|
-
/** Gets the previous date starting from the given start date or now. */
|
|
814
|
-
getPrevDate(startDate = new Date()) {
|
|
815
|
-
const startDateElements = extractDateElements(startDate);
|
|
816
|
-
let maxYear = startDateElements.year;
|
|
817
|
-
let startIndexMonth = this.reversed.months.findIndex((x) => x <= startDateElements.month);
|
|
818
|
-
if (startIndexMonth === -1) {
|
|
819
|
-
startIndexMonth = 0;
|
|
820
|
-
maxYear--;
|
|
821
|
-
}
|
|
822
|
-
// We try every month within the past 5 years to make sure that we tried to
|
|
823
|
-
// find a matching date inside a whole leap year.
|
|
824
|
-
const maxIterations = this.reversed.months.length * 5;
|
|
825
|
-
for (let i = 0; i < maxIterations; i++) {
|
|
826
|
-
// Get the next year and month.
|
|
827
|
-
const year = maxYear -
|
|
828
|
-
Math.floor((startIndexMonth + i) / this.reversed.months.length);
|
|
829
|
-
const month = this.reversed.months[(startIndexMonth + i) % this.reversed.months.length];
|
|
830
|
-
const isStartMonth = year === startDateElements.year && month === startDateElements.month;
|
|
831
|
-
// Find the previous day.
|
|
832
|
-
let day = this.findAllowedDayInMonth('prev', year, month, isStartMonth
|
|
833
|
-
? startDateElements.day
|
|
834
|
-
: // Start searching from the last day of the month.
|
|
835
|
-
getDaysInMonth(year, month));
|
|
836
|
-
let isStartDay = isStartMonth && day === startDateElements.day;
|
|
837
|
-
// If we found a day and it is the start day, try to find a valid time beginning from the start date time.
|
|
838
|
-
if (day !== undefined && isStartDay) {
|
|
839
|
-
const prevTime = this.findAllowedTime('prev', startDateElements);
|
|
840
|
-
if (prevTime !== undefined) {
|
|
841
|
-
return new Date(year, month, day, prevTime.hour, prevTime.minute, prevTime.second);
|
|
842
|
-
}
|
|
843
|
-
// If no valid time has been found for the start date, try the previous day.
|
|
844
|
-
if (day > 1) {
|
|
845
|
-
day = this.findAllowedDayInMonth('prev', year, month, day - 1);
|
|
846
|
-
isStartDay = false;
|
|
847
|
-
}
|
|
848
|
-
}
|
|
849
|
-
// If we found a previous day and it is not the start day, just use the previous day with the first allowed values
|
|
850
|
-
// for hours, minutes and seconds (which will be the latest time due to using the reversed array).
|
|
851
|
-
if (day !== undefined && !isStartDay) {
|
|
852
|
-
return new Date(year, month, day, this.reversed.hours[0], this.reversed.minutes[0], this.reversed.seconds[0]);
|
|
853
|
-
}
|
|
854
|
-
// No allowed day has been found for this month. Continue to search in previous month.
|
|
855
|
-
}
|
|
856
|
-
throw new Error('No valid previous date was found.');
|
|
857
|
-
}
|
|
858
|
-
/** Gets the specified amount of previous dates starting from the given start date or now. */
|
|
859
|
-
getPrevDates(amount, startDate) {
|
|
860
|
-
const dates = [];
|
|
861
|
-
let prevDate;
|
|
862
|
-
for (let i = 0; i < amount; i++) {
|
|
863
|
-
prevDate = this.getPrevDate(prevDate !== null && prevDate !== void 0 ? prevDate : startDate);
|
|
864
|
-
dates.push(prevDate);
|
|
865
|
-
}
|
|
866
|
-
return dates;
|
|
867
|
-
}
|
|
868
|
-
/**
|
|
869
|
-
* Get an ES6 compatible iterator which iterates over the previous dates starting from startDate or now.
|
|
870
|
-
* The iterator runs until the optional endDate is reached or forever.
|
|
871
|
-
*/
|
|
872
|
-
*getPrevDatesIterator(startDate, endDate) {
|
|
873
|
-
let prevDate;
|
|
874
|
-
while (true) {
|
|
875
|
-
prevDate = this.getPrevDate(prevDate !== null && prevDate !== void 0 ? prevDate : startDate);
|
|
876
|
-
if (endDate && endDate.getTime() > prevDate.getTime()) {
|
|
877
|
-
return;
|
|
878
|
-
}
|
|
879
|
-
yield prevDate;
|
|
880
|
-
}
|
|
881
|
-
}
|
|
882
|
-
/** Returns true when there is a cron date at the given date. */
|
|
883
|
-
matchDate(date) {
|
|
884
|
-
const { second, minute, hour, day, month, weekday } = extractDateElements(date);
|
|
885
|
-
if (this.seconds.indexOf(second) === -1 ||
|
|
886
|
-
this.minutes.indexOf(minute) === -1 ||
|
|
887
|
-
this.hours.indexOf(hour) === -1 ||
|
|
888
|
-
this.months.indexOf(month) === -1) {
|
|
889
|
-
return false;
|
|
890
|
-
}
|
|
891
|
-
if (this.days.length !== 31 && this.weekdays.length !== 7) {
|
|
892
|
-
return (this.days.indexOf(day) !== -1 || this.weekdays.indexOf(weekday) !== -1);
|
|
893
|
-
}
|
|
894
|
-
return (this.days.indexOf(day) !== -1 && this.weekdays.indexOf(weekday) !== -1);
|
|
895
|
-
}
|
|
896
|
-
}
|
|
897
|
-
|
|
898
|
-
const secondConstraint = {
|
|
899
|
-
min: 0,
|
|
900
|
-
max: 59,
|
|
901
|
-
};
|
|
902
|
-
const minuteConstraint = {
|
|
903
|
-
min: 0,
|
|
904
|
-
max: 59,
|
|
905
|
-
};
|
|
906
|
-
const hourConstraint = {
|
|
907
|
-
min: 0,
|
|
908
|
-
max: 23,
|
|
909
|
-
};
|
|
910
|
-
const dayConstraint = {
|
|
911
|
-
min: 1,
|
|
912
|
-
max: 31,
|
|
913
|
-
};
|
|
914
|
-
const monthConstraint = {
|
|
915
|
-
min: 1,
|
|
916
|
-
max: 12,
|
|
917
|
-
aliases: {
|
|
918
|
-
jan: '1',
|
|
919
|
-
feb: '2',
|
|
920
|
-
mar: '3',
|
|
921
|
-
apr: '4',
|
|
922
|
-
may: '5',
|
|
923
|
-
jun: '6',
|
|
924
|
-
jul: '7',
|
|
925
|
-
aug: '8',
|
|
926
|
-
sep: '9',
|
|
927
|
-
oct: '10',
|
|
928
|
-
nov: '11',
|
|
929
|
-
dec: '12',
|
|
930
|
-
},
|
|
931
|
-
};
|
|
932
|
-
const weekdayConstraint = {
|
|
933
|
-
min: 0,
|
|
934
|
-
max: 7,
|
|
935
|
-
aliases: {
|
|
936
|
-
mon: '1',
|
|
937
|
-
tue: '2',
|
|
938
|
-
wed: '3',
|
|
939
|
-
thu: '4',
|
|
940
|
-
fri: '5',
|
|
941
|
-
sat: '6',
|
|
942
|
-
sun: '7',
|
|
943
|
-
},
|
|
944
|
-
};
|
|
945
|
-
const timeNicknames = {
|
|
946
|
-
'@yearly': '0 0 1 1 *',
|
|
947
|
-
'@annually': '0 0 1 1 *',
|
|
948
|
-
'@monthly': '0 0 1 * *',
|
|
949
|
-
'@weekly': '0 0 * * 0',
|
|
950
|
-
'@daily': '0 0 * * *',
|
|
951
|
-
'@hourly': '0 * * * *',
|
|
952
|
-
'@minutely': '* * * * *',
|
|
953
|
-
};
|
|
954
|
-
function parseElement(element, constraint) {
|
|
955
|
-
const result = new Set();
|
|
956
|
-
// If returned set of numbers is empty, the scheduler class interpretes the emtpy set of numbers as all valid values of the constraint
|
|
957
|
-
if (element === '*') {
|
|
958
|
-
for (let i = constraint.min; i <= constraint.max; i = i + 1) {
|
|
959
|
-
result.add(i);
|
|
960
|
-
}
|
|
961
|
-
return result;
|
|
962
|
-
}
|
|
963
|
-
// If the element is a list, parse each element in the list.
|
|
964
|
-
const listElements = element.split(',');
|
|
965
|
-
if (listElements.length > 1) {
|
|
966
|
-
for (const listElement of listElements) {
|
|
967
|
-
const parsedListElement = parseElement(listElement, constraint);
|
|
968
|
-
for (const x of parsedListElement) {
|
|
969
|
-
result.add(x);
|
|
970
|
-
}
|
|
971
|
-
}
|
|
972
|
-
return result;
|
|
973
|
-
}
|
|
974
|
-
// Helper function to parse a single element, which includes checking for alias, valid number and constraint min and max.
|
|
975
|
-
const parseSingleElement = (singleElement) => {
|
|
976
|
-
var _a, _b;
|
|
977
|
-
// biome-ignore lint/style/noParameterAssign: adding another variable with a new name is more confusing
|
|
978
|
-
singleElement =
|
|
979
|
-
(_b = (_a = constraint.aliases) === null || _a === void 0 ? void 0 : _a[singleElement.toLowerCase()]) !== null && _b !== void 0 ? _b : singleElement;
|
|
980
|
-
const parsedElement = Number.parseInt(singleElement, 10);
|
|
981
|
-
if (Number.isNaN(parsedElement)) {
|
|
982
|
-
throw new Error(`Failed to parse ${element}: ${singleElement} is NaN.`);
|
|
983
|
-
}
|
|
984
|
-
if (parsedElement < constraint.min || parsedElement > constraint.max) {
|
|
985
|
-
throw new Error(`Failed to parse ${element}: ${singleElement} is outside of constraint range of ${constraint.min} - ${constraint.max}.`);
|
|
986
|
-
}
|
|
987
|
-
return parsedElement;
|
|
988
|
-
};
|
|
989
|
-
// Detect if the element is a range.
|
|
990
|
-
// Possible range formats: 'start-end', 'start-end/step', '*', '*/step'.
|
|
991
|
-
// Where start and end can be numbers or aliases.
|
|
992
|
-
// Capture groups: 1: start-end, 2: start, 3: end, 4: /step, 5: step.
|
|
993
|
-
const rangeSegments = /^(([0-9a-zA-Z]+)-([0-9a-zA-Z]+)|\*)(\/([0-9]+))?$/.exec(element);
|
|
994
|
-
// If not, it must be a single element.
|
|
995
|
-
if (rangeSegments === null) {
|
|
996
|
-
result.add(parseSingleElement(element));
|
|
997
|
-
return result;
|
|
998
|
-
}
|
|
999
|
-
// If it is a range, get start and end of the range.
|
|
1000
|
-
let parsedStart = rangeSegments[1] === '*'
|
|
1001
|
-
? constraint.min
|
|
1002
|
-
: parseSingleElement(rangeSegments[2]);
|
|
1003
|
-
const parsedEnd = rangeSegments[1] === '*'
|
|
1004
|
-
? constraint.max
|
|
1005
|
-
: parseSingleElement(rangeSegments[3]);
|
|
1006
|
-
// need to catch Sunday, which gets parsed here as 7, but is also legitimate at the start of a range as 0, to avoid the out of order error
|
|
1007
|
-
if (constraint === weekdayConstraint &&
|
|
1008
|
-
parsedStart === 7 &&
|
|
1009
|
-
// this check ensures that sun-sun is not incorrectly parsed as [0,1,2,3,4,5,6]
|
|
1010
|
-
parsedEnd !== 7) {
|
|
1011
|
-
parsedStart = 0;
|
|
1012
|
-
}
|
|
1013
|
-
if (parsedStart > parsedEnd) {
|
|
1014
|
-
throw new Error(`Failed to parse ${element}: Invalid range (start: ${parsedStart}, end: ${parsedEnd}).`);
|
|
1015
|
-
}
|
|
1016
|
-
// Check whether there is a custom step defined for the range, defaulting to 1.
|
|
1017
|
-
const step = rangeSegments[5];
|
|
1018
|
-
let parsedStep = 1;
|
|
1019
|
-
if (step !== undefined) {
|
|
1020
|
-
parsedStep = Number.parseInt(step, 10);
|
|
1021
|
-
if (Number.isNaN(parsedStep)) {
|
|
1022
|
-
throw new Error(`Failed to parse step: ${step} is NaN.`);
|
|
1023
|
-
}
|
|
1024
|
-
if (parsedStep < 1) {
|
|
1025
|
-
throw new Error(`Failed to parse step: Expected ${step} to be greater than 0.`);
|
|
1026
|
-
}
|
|
1027
|
-
}
|
|
1028
|
-
// Go from start to end of the range by the given steps.
|
|
1029
|
-
for (let i = parsedStart; i <= parsedEnd; i = i + parsedStep) {
|
|
1030
|
-
result.add(i);
|
|
1031
|
-
}
|
|
1032
|
-
return result;
|
|
1033
|
-
}
|
|
1034
|
-
/** Parses a cron expression into a Cron instance. */
|
|
1035
|
-
function parseCronExpression(cronExpression) {
|
|
1036
|
-
var _a;
|
|
1037
|
-
if (typeof cronExpression !== 'string') {
|
|
1038
|
-
throw new TypeError('Invalid cron expression: must be of type string.');
|
|
1039
|
-
}
|
|
1040
|
-
// Convert time nicknames.
|
|
1041
|
-
// biome-ignore lint/style/noParameterAssign: adding another variable with a new name is more confusing
|
|
1042
|
-
cronExpression = (_a = timeNicknames[cronExpression.toLowerCase()]) !== null && _a !== void 0 ? _a : cronExpression;
|
|
1043
|
-
// Split the cron expression into its elements, removing empty elements (extra whitespaces).
|
|
1044
|
-
const elements = cronExpression.split(' ').filter((elem) => elem.length > 0);
|
|
1045
|
-
if (elements.length < 5 || elements.length > 6) {
|
|
1046
|
-
throw new Error('Invalid cron expression: expected 5 or 6 elements.');
|
|
1047
|
-
}
|
|
1048
|
-
const rawSeconds = elements.length === 6 ? elements[0] : '0';
|
|
1049
|
-
const rawMinutes = elements.length === 6 ? elements[1] : elements[0];
|
|
1050
|
-
const rawHours = elements.length === 6 ? elements[2] : elements[1];
|
|
1051
|
-
const rawDays = elements.length === 6 ? elements[3] : elements[2];
|
|
1052
|
-
const rawMonths = elements.length === 6 ? elements[4] : elements[3];
|
|
1053
|
-
const rawWeekdays = elements.length === 6 ? elements[5] : elements[4];
|
|
1054
|
-
return new Cron({
|
|
1055
|
-
seconds: parseElement(rawSeconds, secondConstraint),
|
|
1056
|
-
minutes: parseElement(rawMinutes, minuteConstraint),
|
|
1057
|
-
hours: parseElement(rawHours, hourConstraint),
|
|
1058
|
-
days: parseElement(rawDays, dayConstraint),
|
|
1059
|
-
// months in cron are indexed by 1, but Cron expects indexes by 0, so we need to reduce all set values by one.
|
|
1060
|
-
months: new Set(Array.from(parseElement(rawMonths, monthConstraint)).map((x) => x - 1)),
|
|
1061
|
-
weekdays: new Set(Array.from(parseElement(rawWeekdays, weekdayConstraint)).map((x) => x % 7)),
|
|
1062
|
-
});
|
|
1063
|
-
}
|
|
1064
|
-
|
|
1065
|
-
function getNextCronDate(expr) {
|
|
1066
|
-
try {
|
|
1067
|
-
const interval = parseCronExpression(expr);
|
|
1068
|
-
return interval.getNextDate();
|
|
1069
|
-
} catch (error) {
|
|
1070
|
-
console.error("Invalid cron expression:", expr, error);
|
|
1071
|
-
throw new Error("Invalid cron expression");
|
|
1072
|
-
}
|
|
1073
|
-
}
|
|
1074
|
-
|
|
1075
|
-
function Injectable() {
|
|
1076
|
-
return function(constructor) {
|
|
1077
|
-
L$1()(constructor);
|
|
1078
|
-
};
|
|
1079
|
-
}
|
|
1080
|
-
|
|
1081
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
1082
|
-
var __decorateClass = (decorators, target, key, kind) => {
|
|
1083
|
-
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
|
|
1084
|
-
for (var i = decorators.length - 1, decorator; i >= 0; i--)
|
|
1085
|
-
if (decorator = decorators[i])
|
|
1086
|
-
result = (decorator(result)) || result;
|
|
1087
|
-
return result;
|
|
1088
|
-
};
|
|
1089
|
-
let Scheduler = class {
|
|
1090
|
-
constructor() {
|
|
1091
|
-
this.registry = JobRegistry.instance;
|
|
1092
|
-
this.alarm = new AlarmAdapter();
|
|
1093
|
-
this.timeout = new TimeoutAdapter();
|
|
1094
|
-
console.log("Scheduler initialized");
|
|
1095
|
-
this.alarm.onTrigger(this.execute.bind(this));
|
|
1096
|
-
this.timeout.onTrigger(this.execute.bind(this));
|
|
1097
|
-
}
|
|
1098
|
-
schedule(id, options) {
|
|
1099
|
-
const context = this.registry.getContext(id);
|
|
1100
|
-
if (!context || context.isStopped()) {
|
|
1101
|
-
console.log(`Job ${id} is stopped, skipping schedule`);
|
|
1102
|
-
return;
|
|
1103
|
-
}
|
|
1104
|
-
console.log(`Scheduling job ${id} with options:`, options);
|
|
1105
|
-
const when = this.getScheduleTime(options);
|
|
1106
|
-
const adapter = when - Date.now() < 6e4 ? this.timeout : this.alarm;
|
|
1107
|
-
const timerId = adapter.schedule(id, when);
|
|
1108
|
-
if (adapter === this.timeout) {
|
|
1109
|
-
this.registry.setTimeoutId(id, timerId);
|
|
1110
|
-
}
|
|
1111
|
-
}
|
|
1112
|
-
pause(id) {
|
|
1113
|
-
console.log(`Pausing job ${id}`);
|
|
1114
|
-
this.registry.pause(id);
|
|
1115
|
-
}
|
|
1116
|
-
resume(id) {
|
|
1117
|
-
console.log(`Resuming job ${id}`);
|
|
1118
|
-
this.registry.resume(id);
|
|
1119
|
-
const options = this.registry.meta(id);
|
|
1120
|
-
if (options) {
|
|
1121
|
-
this.schedule(id, options);
|
|
1122
|
-
}
|
|
1123
|
-
}
|
|
1124
|
-
stop(id) {
|
|
1125
|
-
console.log(`Stopping job ${id}`);
|
|
1126
|
-
this.registry.stop(id);
|
|
1127
|
-
}
|
|
1128
|
-
async execute(id) {
|
|
1129
|
-
const job = this.registry.resolve(id);
|
|
1130
|
-
const context = this.registry.getContext(id);
|
|
1131
|
-
if (!job || !context) {
|
|
1132
|
-
console.log(`Job ${id} not found or no context`);
|
|
1133
|
-
return;
|
|
1134
|
-
}
|
|
1135
|
-
if (context.isPaused() || context.isStopped()) {
|
|
1136
|
-
console.log(`Job ${id} is paused or stopped, skipping execution`);
|
|
1137
|
-
return;
|
|
1138
|
-
}
|
|
1139
|
-
try {
|
|
1140
|
-
this.registry.updateState(id, JobState.RUNNING);
|
|
1141
|
-
console.log(`Executing job ${id}`);
|
|
1142
|
-
const jobInstance = container.get(id);
|
|
1143
|
-
console.log(jobInstance);
|
|
1144
|
-
await jobInstance.handle.bind(jobInstance).call(jobInstance, context);
|
|
1145
|
-
if (!context.isStopped() && !context.isPaused()) {
|
|
1146
|
-
this.registry.updateState(id, JobState.COMPLETED);
|
|
1147
|
-
const options = this.registry.meta(id);
|
|
1148
|
-
if (options?.cron) {
|
|
1149
|
-
this.registry.updateState(id, JobState.SCHEDULED);
|
|
1150
|
-
this.schedule(id, options);
|
|
1151
|
-
}
|
|
1152
|
-
}
|
|
1153
|
-
} catch (error) {
|
|
1154
|
-
console.error(`Job ${id} execution failed:`, error);
|
|
1155
|
-
context.fail(error);
|
|
1156
|
-
}
|
|
1157
|
-
}
|
|
1158
|
-
getScheduleTime(options) {
|
|
1159
|
-
if (options.delay) return Date.now() + options.delay;
|
|
1160
|
-
if (options.cron) {
|
|
1161
|
-
const date = getNextCronDate(options.cron);
|
|
1162
|
-
if (!date) {
|
|
1163
|
-
throw new Error("Invalid cron expression");
|
|
1164
|
-
}
|
|
1165
|
-
return date.getTime();
|
|
1166
|
-
}
|
|
1167
|
-
return Date.now();
|
|
1168
|
-
}
|
|
1169
|
-
// Public API for job control
|
|
1170
|
-
getJobState(id) {
|
|
1171
|
-
return this.registry.getContext(id)?.state;
|
|
1172
|
-
}
|
|
1173
|
-
listJobs() {
|
|
1174
|
-
const jobs = [];
|
|
1175
|
-
return jobs;
|
|
1176
|
-
}
|
|
1177
|
-
};
|
|
1178
|
-
Scheduler = __decorateClass([
|
|
1179
|
-
Injectable()
|
|
1180
|
-
], Scheduler);
|
|
1181
|
-
|
|
1182
|
-
class ApplicationBootstrap {
|
|
1183
|
-
constructor() {
|
|
1184
|
-
this.serviceDependencies = /* @__PURE__ */ new Map();
|
|
1185
|
-
this.serviceRegistry = /* @__PURE__ */ new Map();
|
|
1186
|
-
this.logger = new BootstrapLogger();
|
|
1187
|
-
this.storeDefinitions = [];
|
|
1188
|
-
}
|
|
1189
|
-
/**
|
|
1190
|
-
* Add a store definition to be initialized
|
|
1191
|
-
*/
|
|
1192
|
-
withStore(storeDefinition) {
|
|
1193
|
-
if (storeDefinition && storeDefinition.name) {
|
|
1194
|
-
this.storeDefinitions.push(storeDefinition);
|
|
1195
|
-
this.logger.debug(`\u{1F4E6} Added store definition: ${storeDefinition.name}`);
|
|
1196
|
-
}
|
|
1197
|
-
return this;
|
|
1198
|
-
}
|
|
1199
|
-
/**
|
|
1200
|
-
* Add multiple store definitions to be initialized
|
|
1201
|
-
*/
|
|
1202
|
-
withStores(storeDefinitions) {
|
|
1203
|
-
for (const store of storeDefinitions) {
|
|
1204
|
-
this.withStore(store);
|
|
1205
|
-
}
|
|
1206
|
-
return this;
|
|
1207
|
-
}
|
|
1208
|
-
/**
|
|
1209
|
-
* Create and initialize a new Chroma application instance
|
|
1210
|
-
*/
|
|
1211
|
-
async create({
|
|
1212
|
-
keepPortAlive = false,
|
|
1213
|
-
portName
|
|
1214
|
-
}) {
|
|
1215
|
-
try {
|
|
1216
|
-
this.logger.info("\u{1F680} Starting Chroma application bootstrap...");
|
|
1217
|
-
await this.discoverAndInitializeStores();
|
|
1218
|
-
await this.discoverServices();
|
|
1219
|
-
await this.validateDependencies();
|
|
1220
|
-
await this.registerServices();
|
|
1221
|
-
await this.registerMessages();
|
|
1222
|
-
await this.registerJobs();
|
|
1223
|
-
await this.bootMessages();
|
|
1224
|
-
await this.bootServices();
|
|
1225
|
-
this.logger.success("\u{1F389} Chroma application initialization complete!");
|
|
1226
|
-
bootstrap$1({ container, keepAlive: keepPortAlive, portName });
|
|
1227
|
-
} catch (error) {
|
|
1228
|
-
this.logger.error("\u{1F4A5} Application bootstrap failed:", error);
|
|
1229
|
-
throw error;
|
|
1230
|
-
}
|
|
1231
|
-
}
|
|
1232
|
-
/**
|
|
1233
|
-
* Boot all registered services by calling their onBoot method if present
|
|
1234
|
-
*/
|
|
1235
|
-
async bootServices() {
|
|
1236
|
-
this.logger.info("\u{1F680} Booting services...");
|
|
1237
|
-
console.log("services", this.serviceRegistry.entries());
|
|
1238
|
-
for (const [serviceName, ServiceClass] of this.serviceRegistry.entries()) {
|
|
1239
|
-
try {
|
|
1240
|
-
const instance = container.get(ServiceClass);
|
|
1241
|
-
if (typeof instance.onBoot === "function") {
|
|
1242
|
-
await instance.onBoot();
|
|
1243
|
-
this.logger.success(`Booted service: ${serviceName}`);
|
|
1244
|
-
}
|
|
1245
|
-
} catch (error) {
|
|
1246
|
-
this.logger.error(`Failed to boot service ${serviceName}:`, error);
|
|
1247
|
-
}
|
|
1248
|
-
}
|
|
1249
|
-
}
|
|
1250
|
-
/**
|
|
1251
|
-
* Discover all services in the application directory
|
|
1252
|
-
*/
|
|
1253
|
-
async discoverServices() {
|
|
1254
|
-
this.logger.info("\u{1F50D} Discovering services...");
|
|
1255
|
-
const serviceModules = undefined(
|
|
1256
|
-
"/src/app/services/**/*.service.{ts,js}",
|
|
1257
|
-
{ eager: true }
|
|
1258
|
-
);
|
|
1259
|
-
for (const module of Object.values(serviceModules)) {
|
|
1260
|
-
const ServiceClass = module?.default;
|
|
1261
|
-
if (!ServiceClass) continue;
|
|
1262
|
-
this.serviceRegistry.set(ServiceClass.name, ServiceClass);
|
|
1263
|
-
}
|
|
1264
|
-
for (const module of Object.values(serviceModules)) {
|
|
1265
|
-
const ServiceClass = module?.default;
|
|
1266
|
-
if (!ServiceClass) continue;
|
|
1267
|
-
const dependencies = this.resolveDependencies(ServiceClass);
|
|
1268
|
-
this.serviceDependencies.set(ServiceClass.name, {
|
|
1269
|
-
service: ServiceClass,
|
|
1270
|
-
dependencies,
|
|
1271
|
-
registered: false
|
|
1272
|
-
});
|
|
1273
|
-
this.logger.debug(`\u{1F4E6} Discovered ${ServiceClass.name}`, {
|
|
1274
|
-
dependencies: dependencies.map((dep) => dep.name)
|
|
1275
|
-
});
|
|
1276
|
-
}
|
|
1277
|
-
this.logger.success(`\u2705 Discovered ${this.serviceDependencies.size} services`);
|
|
1278
|
-
}
|
|
1279
|
-
/**
|
|
1280
|
-
* Initialize stores from provided definitions
|
|
1281
|
-
*/
|
|
1282
|
-
async discoverAndInitializeStores() {
|
|
1283
|
-
try {
|
|
1284
|
-
if (this.storeDefinitions.length === 0) {
|
|
1285
|
-
this.logger.debug("\u{1F4ED} No store definitions provided");
|
|
1286
|
-
return;
|
|
1287
|
-
}
|
|
1288
|
-
this.logger.info(`Initializing ${this.storeDefinitions.length} store(s)...`);
|
|
1289
|
-
const chromaGlobal = globalThis.__CHROMA__;
|
|
1290
|
-
if (chromaGlobal?.initStores && typeof chromaGlobal.initStores === "function") {
|
|
1291
|
-
let isFirstStore = true;
|
|
1292
|
-
for (const store of this.storeDefinitions) {
|
|
1293
|
-
const { classes, store: storeInstance } = await chromaGlobal.initStores(store);
|
|
1294
|
-
const diKey = `CentralStore:${store.name}`;
|
|
1295
|
-
container.bind(diKey).toConstantValue(storeInstance);
|
|
1296
|
-
if (isFirstStore) {
|
|
1297
|
-
container.bind("appStore").toConstantValue(storeInstance);
|
|
1298
|
-
isFirstStore = false;
|
|
1299
|
-
}
|
|
1300
|
-
this.registerMessageClass(classes.GetStoreStateMessage, `store:${store.name}:getState`);
|
|
1301
|
-
this.registerMessageClass(classes.SetStoreStateMessage, `store:${store.name}:setState`);
|
|
1302
|
-
this.registerMessageClass(
|
|
1303
|
-
classes.SubscribeToStoreMessage,
|
|
1304
|
-
`store:${store.name}:subscribe`
|
|
1305
|
-
);
|
|
1306
|
-
this.logger.debug(`\u2705 Initialized store: ${store.name}`);
|
|
1307
|
-
}
|
|
1308
|
-
}
|
|
1309
|
-
this.logger.success(`\u2705 Initialized ${this.storeDefinitions.length} store(s)`);
|
|
1310
|
-
} catch (error) {
|
|
1311
|
-
this.logger.error("\u274C Failed to initialize stores:", error);
|
|
1312
|
-
}
|
|
1313
|
-
}
|
|
1314
|
-
/**
|
|
1315
|
-
* Resolve service dependencies using reflection and fallback parsing
|
|
1316
|
-
*/
|
|
1317
|
-
resolveDependencies(ServiceClass) {
|
|
1318
|
-
const paramTypes = Reflect.getMetadata("design:paramtypes", ServiceClass) || [];
|
|
1319
|
-
if (paramTypes.length > 0) {
|
|
1320
|
-
return paramTypes.filter((type) => type && type !== Object);
|
|
1321
|
-
}
|
|
1322
|
-
if (ServiceClass.length > 0) {
|
|
1323
|
-
return this.parseConstructorDependencies(ServiceClass);
|
|
1324
|
-
}
|
|
1325
|
-
return [];
|
|
1326
|
-
}
|
|
1327
|
-
/**
|
|
1328
|
-
* Parse constructor dependencies from class string representation
|
|
1329
|
-
*/
|
|
1330
|
-
parseConstructorDependencies(ServiceClass) {
|
|
1331
|
-
const constructorString = ServiceClass.toString();
|
|
1332
|
-
const constructorMatch = constructorString.match(/constructor\s*\(([^)]*)\)/);
|
|
1333
|
-
if (!constructorMatch) return [];
|
|
1334
|
-
const parameters = constructorMatch[1].split(",").map((param) => param.trim()).filter((param) => param.length > 0);
|
|
1335
|
-
const dependencies = [];
|
|
1336
|
-
for (const param of parameters) {
|
|
1337
|
-
const paramName = param.toLowerCase();
|
|
1338
|
-
if (paramName === "appstore") {
|
|
1339
|
-
let storeInstance;
|
|
1340
|
-
storeInstance = container.get("appStore");
|
|
1341
|
-
if (!storeInstance) {
|
|
1342
|
-
throw new Error(`No store found for parameter "${param}" in ${ServiceClass.name}`);
|
|
1343
|
-
}
|
|
1344
|
-
dependencies.push("appStore");
|
|
1345
|
-
continue;
|
|
1346
|
-
}
|
|
1347
|
-
const matchingService = Array.from(this.serviceRegistry.entries()).find(
|
|
1348
|
-
([name]) => name.toLowerCase() === paramName
|
|
1349
|
-
);
|
|
1350
|
-
if (matchingService) {
|
|
1351
|
-
dependencies.push(matchingService[1]);
|
|
1352
|
-
} else {
|
|
1353
|
-
this.logger.warn(`\u26A0\uFE0F No service found for parameter "${param}" in ${ServiceClass.name}`);
|
|
1354
|
-
dependencies.push(void 0);
|
|
1355
|
-
}
|
|
1356
|
-
}
|
|
1357
|
-
return dependencies;
|
|
1358
|
-
}
|
|
1359
|
-
/**
|
|
1360
|
-
* Validate service dependencies and detect circular references
|
|
1361
|
-
*/
|
|
1362
|
-
async validateDependencies() {
|
|
1363
|
-
this.logger.info("\u{1F50D} Validating dependencies...");
|
|
1364
|
-
const circularDependencies = this.detectCircularDependencies();
|
|
1365
|
-
if (circularDependencies.length > 0) {
|
|
1366
|
-
this.handleCircularDependencies(circularDependencies);
|
|
1367
|
-
} else {
|
|
1368
|
-
this.logger.success("\u2705 No circular dependencies detected");
|
|
1369
|
-
}
|
|
1370
|
-
}
|
|
1371
|
-
/**
|
|
1372
|
-
* Detect circular dependencies using depth-first search
|
|
1373
|
-
*/
|
|
1374
|
-
detectCircularDependencies() {
|
|
1375
|
-
const visited = /* @__PURE__ */ new Set();
|
|
1376
|
-
const recursionStack = /* @__PURE__ */ new Set();
|
|
1377
|
-
const circularDeps = [];
|
|
1378
|
-
const dfs = (serviceName, path) => {
|
|
1379
|
-
if (recursionStack.has(serviceName)) {
|
|
1380
|
-
const cycleStart = path.indexOf(serviceName);
|
|
1381
|
-
const cycle = path.slice(cycleStart).concat([serviceName]);
|
|
1382
|
-
circularDeps.push({
|
|
1383
|
-
cycle: Object.freeze(cycle),
|
|
1384
|
-
services: Object.freeze(Array.from(new Set(cycle)))
|
|
1385
|
-
});
|
|
1386
|
-
return;
|
|
1387
|
-
}
|
|
1388
|
-
if (visited.has(serviceName)) return;
|
|
1389
|
-
visited.add(serviceName);
|
|
1390
|
-
recursionStack.add(serviceName);
|
|
1391
|
-
const serviceMetadata = this.serviceDependencies.get(serviceName);
|
|
1392
|
-
if (serviceMetadata) {
|
|
1393
|
-
for (const dependency of serviceMetadata.dependencies) {
|
|
1394
|
-
if (this.serviceDependencies.has(dependency.name)) {
|
|
1395
|
-
dfs(dependency.name, [...path, serviceName]);
|
|
1396
|
-
}
|
|
1397
|
-
}
|
|
1398
|
-
}
|
|
1399
|
-
recursionStack.delete(serviceName);
|
|
1400
|
-
};
|
|
1401
|
-
for (const serviceName of this.serviceDependencies.keys()) {
|
|
1402
|
-
if (!visited.has(serviceName)) {
|
|
1403
|
-
dfs(serviceName, []);
|
|
1404
|
-
}
|
|
1405
|
-
}
|
|
1406
|
-
return circularDeps;
|
|
1407
|
-
}
|
|
1408
|
-
/**
|
|
1409
|
-
* Handle circular dependencies with detailed reporting
|
|
1410
|
-
*/
|
|
1411
|
-
handleCircularDependencies(circularDeps) {
|
|
1412
|
-
this.logger.error("\u{1F534} CIRCULAR DEPENDENCIES DETECTED");
|
|
1413
|
-
this.logger.divider();
|
|
1414
|
-
circularDeps.forEach((circular, index) => {
|
|
1415
|
-
this.logger.error(`\u{1F4CD} Circular Dependency #${index + 1}:`);
|
|
1416
|
-
this.logger.error(` Cycle: ${circular.cycle.join(" \u2192 ")}`);
|
|
1417
|
-
this.logger.error(` Affected Services: ${circular.services.join(", ")}`);
|
|
1418
|
-
this.logger.info(" \u{1F4A1} Resolution Suggestions:");
|
|
1419
|
-
this.logger.info(" \u2022 Extract shared functionality into a separate service");
|
|
1420
|
-
this.logger.info(" \u2022 Use interfaces or abstractions to break the cycle");
|
|
1421
|
-
this.logger.info(" \u2022 Consider Factory or Provider patterns");
|
|
1422
|
-
this.logger.info(" \u2022 Move shared logic to utility classes");
|
|
1423
|
-
});
|
|
1424
|
-
this.logger.divider();
|
|
1425
|
-
this.logger.warn("\u26A0\uFE0F Application will continue but some services may fail to resolve");
|
|
1426
|
-
this.logger.warn(" Please address these circular dependencies for optimal functionality");
|
|
1427
|
-
}
|
|
1428
|
-
/**
|
|
1429
|
-
* Register all services with the dependency injection container
|
|
1430
|
-
*/
|
|
1431
|
-
async registerServices() {
|
|
1432
|
-
this.logger.info("\u{1F527} Registering services...");
|
|
1433
|
-
for (const serviceName of this.serviceDependencies.keys()) {
|
|
1434
|
-
await this.registerService(serviceName);
|
|
1435
|
-
}
|
|
1436
|
-
const results = this.getRegistrationResults();
|
|
1437
|
-
this.reportRegistrationResults(results);
|
|
1438
|
-
}
|
|
1439
|
-
/**
|
|
1440
|
-
* Register a single service with dependency resolution
|
|
1441
|
-
*/
|
|
1442
|
-
async registerService(serviceName, visitedServices = /* @__PURE__ */ new Set(), registrationPath = []) {
|
|
1443
|
-
const serviceMetadata = this.serviceDependencies.get(serviceName);
|
|
1444
|
-
if (!serviceMetadata) {
|
|
1445
|
-
return { success: false, message: `Service ${serviceName} not found` };
|
|
1446
|
-
}
|
|
1447
|
-
if (serviceMetadata.registered) {
|
|
1448
|
-
return { success: true, message: `Service ${serviceName} already registered` };
|
|
1449
|
-
}
|
|
1450
|
-
if (visitedServices.has(serviceName)) {
|
|
1451
|
-
const cycle = [...registrationPath, serviceName];
|
|
1452
|
-
this.logger.warn(`\u{1F504} Circular dependency in registration: ${cycle.join(" \u2192 ")}`);
|
|
1453
|
-
return { success: false, message: "Circular dependency detected" };
|
|
1454
|
-
}
|
|
1455
|
-
const newVisited = new Set(visitedServices).add(serviceName);
|
|
1456
|
-
const newPath = [...registrationPath, serviceName];
|
|
1457
|
-
for (const dependency of serviceMetadata.dependencies) {
|
|
1458
|
-
if (this.serviceDependencies.has(dependency.name)) {
|
|
1459
|
-
await this.registerService(dependency.name, newVisited, newPath);
|
|
1460
|
-
}
|
|
1461
|
-
}
|
|
1462
|
-
try {
|
|
1463
|
-
const ServiceClass = serviceMetadata.service;
|
|
1464
|
-
b(L$1(), ServiceClass);
|
|
1465
|
-
serviceMetadata.dependencies.forEach((dependency, index) => {
|
|
1466
|
-
b(_$1(dependency), ServiceClass, index);
|
|
1467
|
-
});
|
|
1468
|
-
container.bind(ServiceClass).toSelf().inSingletonScope();
|
|
1469
|
-
serviceMetadata.registered = true;
|
|
1470
|
-
this.logger.success(`\u2705 Registered service: ${ServiceClass.name}`);
|
|
1471
|
-
return { success: true, message: `Successfully registered ${ServiceClass.name}` };
|
|
1472
|
-
} catch (error) {
|
|
1473
|
-
const errorMessage = `Failed to register ${serviceName}`;
|
|
1474
|
-
this.logger.error(`\u274C ${errorMessage}:`, error);
|
|
1475
|
-
return { success: false, message: errorMessage, error };
|
|
1476
|
-
}
|
|
1477
|
-
}
|
|
1478
|
-
/**
|
|
1479
|
-
* Get registration results summary
|
|
1480
|
-
*/
|
|
1481
|
-
getRegistrationResults() {
|
|
1482
|
-
const successful = [];
|
|
1483
|
-
const failed = [];
|
|
1484
|
-
for (const [name, metadata] of this.serviceDependencies.entries()) {
|
|
1485
|
-
if (metadata.registered) {
|
|
1486
|
-
successful.push(name);
|
|
1487
|
-
} else {
|
|
1488
|
-
failed.push(name);
|
|
1489
|
-
}
|
|
1490
|
-
}
|
|
1491
|
-
return { successful, failed };
|
|
1492
|
-
}
|
|
1493
|
-
/**
|
|
1494
|
-
* Report service registration results
|
|
1495
|
-
*/
|
|
1496
|
-
reportRegistrationResults({
|
|
1497
|
-
successful,
|
|
1498
|
-
failed
|
|
1499
|
-
}) {
|
|
1500
|
-
if (failed.length > 0) {
|
|
1501
|
-
this.logger.error("\u26A0\uFE0F Some services could not be registered:");
|
|
1502
|
-
failed.forEach((serviceName) => {
|
|
1503
|
-
const metadata = this.serviceDependencies.get(serviceName);
|
|
1504
|
-
const deps = metadata?.dependencies.map((d) => d.name).join(", ") || "none";
|
|
1505
|
-
this.logger.error(` \u2022 ${serviceName} (dependencies: ${deps})`);
|
|
1506
|
-
});
|
|
1507
|
-
} else {
|
|
1508
|
-
this.logger.success(`\u2705 All ${successful.length} services registered successfully`);
|
|
1509
|
-
}
|
|
1510
|
-
}
|
|
1511
|
-
/**
|
|
1512
|
-
* Register message handlers
|
|
1513
|
-
*/
|
|
1514
|
-
async registerMessages() {
|
|
1515
|
-
this.logger.info("\u{1F4E8} Registering messages...");
|
|
1516
|
-
const messageModules = undefined(
|
|
1517
|
-
"/src/app/messages/**/*.message.{ts,js}",
|
|
1518
|
-
{ eager: true }
|
|
1519
|
-
);
|
|
1520
|
-
for (const module of Object.values(messageModules)) {
|
|
1521
|
-
const MessageClass = module?.default;
|
|
1522
|
-
if (!MessageClass) continue;
|
|
1523
|
-
try {
|
|
1524
|
-
const dependencies = this.resolveDependencies(MessageClass);
|
|
1525
|
-
b(L$1(), MessageClass);
|
|
1526
|
-
dependencies.forEach((dependency, index) => {
|
|
1527
|
-
b(_$1(dependency), MessageClass, index);
|
|
1528
|
-
});
|
|
1529
|
-
const messageMetadata = Reflect.getMetadata("name", MessageClass);
|
|
1530
|
-
const messageName = messageMetadata || MessageClass.name;
|
|
1531
|
-
container.bind(messageName).to(MessageClass).inSingletonScope();
|
|
1532
|
-
this.logger.success(`\u2705 Registered message: ${messageName}`);
|
|
1533
|
-
} catch (error) {
|
|
1534
|
-
this.logger.error(`\u274C Failed to register message ${MessageClass.name}:`, error);
|
|
1535
|
-
}
|
|
1536
|
-
}
|
|
1537
|
-
}
|
|
1538
|
-
async registerMessageClass(MessageClass, name) {
|
|
1539
|
-
const dependencies = this.resolveDependencies(MessageClass);
|
|
1540
|
-
b(L$1(), MessageClass);
|
|
1541
|
-
dependencies.forEach((dependency, index) => {
|
|
1542
|
-
b(_$1(dependency), MessageClass, index);
|
|
1543
|
-
});
|
|
1544
|
-
container.bind(name).to(MessageClass).inSingletonScope();
|
|
1545
|
-
this.logger.success(`\u2705 Registered message: ${name}`);
|
|
1546
|
-
}
|
|
1547
|
-
/**
|
|
1548
|
-
* Boot all registered messages
|
|
1549
|
-
*/
|
|
1550
|
-
async bootMessages() {
|
|
1551
|
-
this.logger.info("\u{1F680} Booting messages...");
|
|
1552
|
-
const messageModules = undefined(
|
|
1553
|
-
"/src/app/messages/**/*.message.{ts,js}",
|
|
1554
|
-
{ eager: true }
|
|
1555
|
-
);
|
|
1556
|
-
for (const module of Object.values(messageModules)) {
|
|
1557
|
-
const MessageClass = module?.default;
|
|
1558
|
-
if (!MessageClass || typeof MessageClass.prototype.boot !== "function") continue;
|
|
1559
|
-
try {
|
|
1560
|
-
const messageMetadata = Reflect.getMetadata("name", MessageClass);
|
|
1561
|
-
const messageName = messageMetadata || MessageClass.name;
|
|
1562
|
-
const messageInstance = container.get(messageName);
|
|
1563
|
-
await messageInstance.boot();
|
|
1564
|
-
this.logger.success(`\u2705 Booted message: ${messageName}`);
|
|
1565
|
-
} catch (error) {
|
|
1566
|
-
this.logger.error(`\u274C Failed to boot message ${MessageClass.name}:`, error);
|
|
1567
|
-
}
|
|
1568
|
-
}
|
|
1569
|
-
}
|
|
1570
|
-
/**
|
|
1571
|
-
* Register jobs for scheduled execution
|
|
1572
|
-
*/
|
|
1573
|
-
async registerJobs() {
|
|
1574
|
-
this.logger.info("\u{1F552} Registering jobs...");
|
|
1575
|
-
const jobModules = undefined(
|
|
1576
|
-
"/src/app/jobs/**/*.job.{ts,js}",
|
|
1577
|
-
{ eager: true }
|
|
1578
|
-
);
|
|
1579
|
-
this.scheduler = new Scheduler();
|
|
1580
|
-
for (const module of Object.values(jobModules)) {
|
|
1581
|
-
const JobClass = module?.default;
|
|
1582
|
-
if (!JobClass) continue;
|
|
1583
|
-
try {
|
|
1584
|
-
const dependencies = this.resolveDependencies(JobClass);
|
|
1585
|
-
b(L$1(), JobClass);
|
|
1586
|
-
dependencies.forEach((dependency, index) => {
|
|
1587
|
-
b(_$1(dependency), JobClass, index);
|
|
1588
|
-
});
|
|
1589
|
-
const jobMetadata = Reflect.getMetadata("name", JobClass);
|
|
1590
|
-
const jobName = jobMetadata || JobClass.name;
|
|
1591
|
-
container.bind(JobClass).toSelf().inSingletonScope();
|
|
1592
|
-
const id = `${jobName.toLowerCase()}:${JobClass.name.toLowerCase()} ${Math.random().toString(36).substring(2, 15)}`;
|
|
1593
|
-
container.bind(id).to(JobClass).inSingletonScope();
|
|
1594
|
-
const options = Reflect.getMetadata("job:options", JobClass) || {};
|
|
1595
|
-
const instance = container.get(JobClass);
|
|
1596
|
-
JobRegistry.instance.register(id, instance, options);
|
|
1597
|
-
this.scheduler.schedule(id, options);
|
|
1598
|
-
this.logger.success(`\u2705 Registered job: ${jobName}`);
|
|
1599
|
-
} catch (error) {
|
|
1600
|
-
this.logger.error(`\u274C Failed to register job ${JobClass.name}:`, error);
|
|
1601
|
-
}
|
|
1602
|
-
}
|
|
1603
|
-
}
|
|
1604
|
-
}
|
|
1605
|
-
class BootstrapLogger {
|
|
1606
|
-
info(message, context) {
|
|
1607
|
-
console.log(message);
|
|
1608
|
-
if (context) console.log(" ", context);
|
|
1609
|
-
}
|
|
1610
|
-
success(message) {
|
|
1611
|
-
console.log(message);
|
|
1612
|
-
}
|
|
1613
|
-
warn(message) {
|
|
1614
|
-
console.warn(message);
|
|
1615
|
-
}
|
|
1616
|
-
error(message, error) {
|
|
1617
|
-
console.error(message);
|
|
1618
|
-
if (error) console.error(" ", error);
|
|
1619
|
-
}
|
|
1620
|
-
debug(message, context) {
|
|
1621
|
-
console.debug(message);
|
|
1622
|
-
if (context) console.debug(" ", context);
|
|
1623
|
-
}
|
|
1624
|
-
divider() {
|
|
1625
|
-
console.log("=".repeat(50));
|
|
1626
|
-
}
|
|
1627
|
-
}
|
|
1628
|
-
async function create({
|
|
1629
|
-
keepPortAlive = false,
|
|
1630
|
-
portName
|
|
1631
|
-
} = {}) {
|
|
1632
|
-
const bootstrap2 = new ApplicationBootstrap();
|
|
1633
|
-
await bootstrap2.create({
|
|
1634
|
-
keepPortAlive,
|
|
1635
|
-
portName
|
|
1636
|
-
});
|
|
1637
|
-
}
|
|
1638
|
-
function bootstrap() {
|
|
1639
|
-
return new BootstrapBuilder();
|
|
1640
|
-
}
|
|
1641
|
-
class BootstrapBuilder {
|
|
1642
|
-
constructor() {
|
|
1643
|
-
this.app = new ApplicationBootstrap();
|
|
1644
|
-
}
|
|
1645
|
-
/**
|
|
1646
|
-
* Add a store definition to be initialized
|
|
1647
|
-
*/
|
|
1648
|
-
withStore(storeDefinition) {
|
|
1649
|
-
this.app.withStore(storeDefinition);
|
|
1650
|
-
return this;
|
|
1651
|
-
}
|
|
1652
|
-
/**
|
|
1653
|
-
* Add multiple store definitions to be initialized
|
|
1654
|
-
*/
|
|
1655
|
-
withStores(storeDefinitions) {
|
|
1656
|
-
this.app.withStores(storeDefinitions);
|
|
1657
|
-
return this;
|
|
1658
|
-
}
|
|
1659
|
-
/**
|
|
1660
|
-
* Create and start the application
|
|
1661
|
-
*/
|
|
1662
|
-
async create({
|
|
1663
|
-
keepPortAlive = false,
|
|
1664
|
-
portName
|
|
1665
|
-
} = {}) {
|
|
1666
|
-
await this.app.create({ keepPortAlive, portName });
|
|
1667
|
-
}
|
|
6
|
+
function Service() {
|
|
7
|
+
return core.injectable();
|
|
1668
8
|
}
|
|
9
|
+
const Use = (id) => core.inject(id);
|
|
10
|
+
const Store = () => Use(IJob.TOKENS.Store);
|
|
1669
11
|
|
|
1670
12
|
class IMessage {
|
|
1671
13
|
handle(...args) {
|
|
@@ -1674,26 +16,12 @@ class IMessage {
|
|
|
1674
16
|
}
|
|
1675
17
|
function Message(name) {
|
|
1676
18
|
return function(constructor) {
|
|
19
|
+
core.injectable()(constructor);
|
|
1677
20
|
Reflect.defineMetadata("name", name, constructor);
|
|
1678
21
|
return constructor;
|
|
1679
22
|
};
|
|
1680
23
|
}
|
|
1681
24
|
|
|
1682
|
-
class Booteable {
|
|
1683
|
-
/**
|
|
1684
|
-
* Optional destroy method to be called when the service is being destroyed.
|
|
1685
|
-
* This can be used to clean up resources or perform any necessary teardown logic.
|
|
1686
|
-
*/
|
|
1687
|
-
destroy() {
|
|
1688
|
-
}
|
|
1689
|
-
}
|
|
1690
|
-
function isBooteable(obj) {
|
|
1691
|
-
return typeof obj.boot === "function";
|
|
1692
|
-
}
|
|
1693
|
-
function isDestroyable(obj) {
|
|
1694
|
-
return typeof obj.destroy === "function";
|
|
1695
|
-
}
|
|
1696
|
-
|
|
1697
25
|
class Job {
|
|
1698
26
|
constructor(data) {
|
|
1699
27
|
this.data = data;
|
|
@@ -1711,6 +39,7 @@ class Job {
|
|
|
1711
39
|
|
|
1712
40
|
function JobConfig(options = {}) {
|
|
1713
41
|
return function(constructor) {
|
|
42
|
+
core.injectable()(constructor);
|
|
1714
43
|
Reflect.defineMetadata("job:options", { options }, constructor);
|
|
1715
44
|
return constructor;
|
|
1716
45
|
};
|
|
@@ -1720,26 +49,37 @@ const Delay = (ms) => JobConfig({ delay: ms });
|
|
|
1720
49
|
|
|
1721
50
|
function Every(cron) {
|
|
1722
51
|
return function(constructor) {
|
|
52
|
+
core.injectable()(constructor);
|
|
1723
53
|
Reflect.defineMetadata("job:options", { cron }, constructor);
|
|
1724
54
|
return constructor;
|
|
1725
55
|
};
|
|
1726
56
|
}
|
|
1727
57
|
|
|
58
|
+
class Booteable {
|
|
59
|
+
/**
|
|
60
|
+
* Optional destroy method to be called when the service is being destroyed.
|
|
61
|
+
* This can be used to clean up resources or perform any necessary teardown logic.
|
|
62
|
+
*/
|
|
63
|
+
destroy() {
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
function isBooteable(obj) {
|
|
67
|
+
return typeof obj.boot === "function";
|
|
68
|
+
}
|
|
69
|
+
function isDestroyable(obj) {
|
|
70
|
+
return typeof obj.destroy === "function";
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
exports.JobState = IJob.JobState;
|
|
1728
74
|
exports.Booteable = Booteable;
|
|
1729
75
|
exports.Delay = Delay;
|
|
1730
76
|
exports.Every = Every;
|
|
1731
77
|
exports.IMessage = IMessage;
|
|
1732
|
-
exports.Inject = _$1;
|
|
1733
|
-
exports.Injectable = Injectable;
|
|
1734
78
|
exports.Job = Job;
|
|
1735
|
-
exports.JobState = JobState;
|
|
1736
|
-
exports.METADATA_KEY = METADATA_KEY;
|
|
1737
79
|
exports.Message = Message;
|
|
1738
|
-
exports.
|
|
1739
|
-
exports.
|
|
1740
|
-
exports.
|
|
1741
|
-
exports.create = create;
|
|
80
|
+
exports.Service = Service;
|
|
81
|
+
exports.Store = Store;
|
|
82
|
+
exports.Use = Use;
|
|
1742
83
|
exports.isBooteable = isBooteable;
|
|
1743
84
|
exports.isDestroyable = isDestroyable;
|
|
1744
|
-
|
|
1745
|
-
exports.resolve = resolve;
|
|
85
|
+
//# sourceMappingURL=index.cjs.js.map
|