@chromahq/core 0.0.1

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.
@@ -0,0 +1,1559 @@
1
+ 'use strict';
2
+
3
+ function e(e){return ("object"==typeof e&&null!==e||"function"==typeof e)&&"function"==typeof e.then}function t$2(e){switch(typeof e){case "string":case "symbol":return e.toString();case "function":return e.name;default:throw new Error(`Unexpected ${typeof e} service id type`)}}const n$1=Symbol.for("@inversifyjs/common/islazyServiceIdentifier");class r{[n$1];#e;constructor(e){this.#e=e,this[n$1]=true;}static is(e){return "object"==typeof e&&null!==e&&true===e[n$1]}unwrap(){return this.#e()}}
4
+
5
+ function t$1(t,e){return Reflect.getOwnMetadata(e,t)}function n(t,e,n){Reflect.defineMetadata(e,n,t);}function a(e,n,a,f){const c=f(t$1(e,n)??a());Reflect.defineMetadata(n,c,e);}
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
+ console.error("Error in bridge handler:", error);
51
+ return {
52
+ id: context.request.id,
53
+ error: error?.message ?? "UNKNOWN_ERROR",
54
+ timestamp: Date.now()
55
+ };
56
+ }
57
+ }
58
+ class BridgeRuntimeManager {
59
+ constructor(options) {
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
+ }
67
+ /**
68
+ * Initialize the bridge runtime and start listening for connections
69
+ */
70
+ initialize() {
71
+ if (this.isInitialized) {
72
+ this.logger.warn("Bridge runtime already initialized");
73
+ return;
74
+ }
75
+ this.setupPortListener();
76
+ this.isInitialized = true;
77
+ this.logger.success(`\u{1F309} Bridge runtime initialized on port: ${this.portName}`);
78
+ }
79
+ /**
80
+ * Setup Chrome runtime port listener
81
+ */
82
+ setupPortListener() {
83
+ chrome.runtime.onConnect.addListener((port) => {
84
+ try {
85
+ if (!this.isValidPort(port)) {
86
+ return;
87
+ }
88
+ this.logger.info(`\u{1F4E1} Port connected: ${port.name}`);
89
+ this.setupMessageHandler(port);
90
+ if (chrome.runtime.lastError) {
91
+ this.logger.warn(`Runtime error during port setup: ${chrome.runtime.lastError.message}`);
92
+ chrome.runtime.lastError;
93
+ }
94
+ } catch (error) {
95
+ this.logger.error("Error setting up port listener:", error);
96
+ if (chrome.runtime.lastError) {
97
+ this.logger.warn(`Additional runtime error: ${chrome.runtime.lastError.message}`);
98
+ chrome.runtime.lastError;
99
+ }
100
+ }
101
+ });
102
+ }
103
+ /**
104
+ * Validate incoming port connection
105
+ */
106
+ isValidPort(port) {
107
+ if (port.name !== this.portName) {
108
+ this.logger.warn(`\u{1F6AB} Ignoring port "${port.name}", expected "${this.portName}"`);
109
+ return false;
110
+ }
111
+ return true;
112
+ }
113
+ /**
114
+ * Setup message handler for connected port
115
+ */
116
+ setupMessageHandler(port) {
117
+ port.onMessage.addListener(async (request) => {
118
+ const context = this.createPipelineContext(request);
119
+ try {
120
+ this.logger.debug("\u{1F4E8} Received message:", {
121
+ key: request.key,
122
+ id: request.id,
123
+ hasPayload: !!request.payload
124
+ });
125
+ const response = await this.processMessage(context);
126
+ this.sendResponse(port, response);
127
+ } catch (error) {
128
+ const errorResponse = await this.handleError(error, context);
129
+ this.sendResponse(port, errorResponse);
130
+ }
131
+ });
132
+ port.onDisconnect.addListener(() => {
133
+ if (chrome.runtime.lastError) {
134
+ this.logger.warn(`\u{1F4F4} Port disconnected with error: ${chrome.runtime.lastError.message}`);
135
+ chrome.runtime.lastError;
136
+ } else {
137
+ this.logger.info(`\u{1F4F4} Port disconnected: ${port.name}`);
138
+ }
139
+ });
140
+ }
141
+ /**
142
+ * Create pipeline context for request processing
143
+ */
144
+ createPipelineContext(request) {
145
+ return {
146
+ request,
147
+ startTime: Date.now(),
148
+ metadata: { ...request.metadata }
149
+ };
150
+ }
151
+ /**
152
+ * Process message through middleware pipeline and handler
153
+ */
154
+ async processMessage(context) {
155
+ const { request } = context;
156
+ const handler = this.resolveHandler(request.key);
157
+ const middlewares = MiddlewareRegistry.pipeline(request.key);
158
+ const data = await this.runPipeline(
159
+ middlewares,
160
+ context,
161
+ () => handler.handle(request.payload)
162
+ );
163
+ return {
164
+ id: request.id,
165
+ data,
166
+ timestamp: Date.now()
167
+ };
168
+ }
169
+ /**
170
+ * Resolve message handler from dependency injection container
171
+ */
172
+ resolveHandler(key) {
173
+ try {
174
+ const handler = this.container.get(key);
175
+ if (!handler || typeof handler.handle !== "function") {
176
+ throw new Error(`Handler "${key}" does not implement MessageHandler interface`);
177
+ }
178
+ return handler;
179
+ } catch (error) {
180
+ throw new Error(`Failed to resolve handler "${key}": ${error.message}`);
181
+ }
182
+ }
183
+ /**
184
+ * Execute middleware pipeline with proper error handling
185
+ */
186
+ async runPipeline(middlewares, context, finalHandler) {
187
+ let currentIndex = -1;
188
+ const executeNext = async () => {
189
+ currentIndex++;
190
+ if (currentIndex === middlewares.length) {
191
+ return finalHandler();
192
+ }
193
+ if (currentIndex > middlewares.length) {
194
+ throw new Error("next() called multiple times");
195
+ }
196
+ const middleware = middlewares[currentIndex];
197
+ return middleware(context, executeNext);
198
+ };
199
+ return executeNext();
200
+ }
201
+ /**
202
+ * Handle errors during message processing
203
+ */
204
+ async handleError(error, context) {
205
+ const duration = Date.now() - context.startTime;
206
+ this.logger.error(`\u{1F4A5} Message processing failed after ${duration}ms:`, {
207
+ key: context.request.key,
208
+ id: context.request.id,
209
+ error: error.message
210
+ });
211
+ return this.errorHandler.handle(error, context);
212
+ }
213
+ /**
214
+ * Send response back through the port
215
+ */
216
+ sendResponse(port, response) {
217
+ try {
218
+ if (!port) {
219
+ this.logger.warn(`Cannot send response: port is null (ID: ${response.id})`);
220
+ return;
221
+ }
222
+ port.postMessage(response);
223
+ if (chrome.runtime.lastError) {
224
+ this.logger.warn(
225
+ `Chrome runtime error during postMessage: ${chrome.runtime.lastError.message} (ID: ${response.id})`
226
+ );
227
+ chrome.runtime.lastError;
228
+ return;
229
+ }
230
+ this.logger.debug("\u{1F4E4} Response sent:", {
231
+ id: response.id,
232
+ hasData: !!response.data,
233
+ hasError: !!response.error
234
+ });
235
+ } catch (error) {
236
+ this.logger.error("Failed to send response:", error);
237
+ if (chrome.runtime.lastError) {
238
+ this.logger.warn(`Additional Chrome runtime error: ${chrome.runtime.lastError.message}`);
239
+ chrome.runtime.lastError;
240
+ }
241
+ }
242
+ }
243
+ /**
244
+ * Get runtime statistics
245
+ */
246
+ getStats() {
247
+ return {
248
+ portName: this.portName,
249
+ initialized: this.isInitialized
250
+ };
251
+ }
252
+ }
253
+ class BridgeLogger {
254
+ constructor(enabled = true) {
255
+ this.enabled = enabled;
256
+ }
257
+ info(message, context) {
258
+ if (!this.enabled) return;
259
+ console.log(`[Bridge] ${message}`);
260
+ if (context) console.log(" Context:", context);
261
+ }
262
+ success(message) {
263
+ if (!this.enabled) return;
264
+ console.log(`[Bridge] ${message}`);
265
+ }
266
+ warn(message) {
267
+ if (!this.enabled) return;
268
+ console.warn(`[Bridge] ${message}`);
269
+ }
270
+ error(message, error) {
271
+ if (!this.enabled) return;
272
+ console.error(`[Bridge] ${message}`);
273
+ if (error) console.error(" Error:", error);
274
+ }
275
+ debug(message, context) {
276
+ if (!this.enabled) return;
277
+ console.debug(`[Bridge] ${message}`);
278
+ if (context) console.debug(" Context:", context);
279
+ }
280
+ }
281
+ function bootstrap(options) {
282
+ const runtime = new BridgeRuntimeManager(options);
283
+ runtime.initialize();
284
+ }
285
+
286
+ class AlarmAdapter {
287
+ constructor() {
288
+ this.callbacks = /* @__PURE__ */ new Map();
289
+ }
290
+ onTrigger(callback) {
291
+ this.triggerCallback = callback;
292
+ }
293
+ schedule(id, when) {
294
+ const delay = Math.max(0, when - Date.now());
295
+ const timeoutId = setTimeout(() => {
296
+ this.callbacks.delete(id);
297
+ this.triggerCallback?.(id);
298
+ }, delay);
299
+ this.callbacks.set(id, () => clearTimeout(timeoutId));
300
+ return timeoutId;
301
+ }
302
+ cancel(id) {
303
+ const callback = this.callbacks.get(id);
304
+ if (callback) {
305
+ callback();
306
+ this.callbacks.delete(id);
307
+ }
308
+ }
309
+ }
310
+
311
+ class TimeoutAdapter {
312
+ constructor() {
313
+ this.callbacks = /* @__PURE__ */ new Map();
314
+ }
315
+ onTrigger(callback) {
316
+ this.triggerCallback = callback;
317
+ }
318
+ schedule(id, when) {
319
+ const delay = Math.max(0, when - Date.now());
320
+ const timeoutId = setTimeout(() => {
321
+ this.callbacks.delete(id);
322
+ this.triggerCallback?.(id);
323
+ }, delay);
324
+ this.callbacks.set(id, () => clearTimeout(timeoutId));
325
+ return timeoutId;
326
+ }
327
+ cancel(id) {
328
+ const callback = this.callbacks.get(id);
329
+ if (callback) {
330
+ callback();
331
+ this.callbacks.delete(id);
332
+ }
333
+ }
334
+ }
335
+
336
+ var JobState = /* @__PURE__ */ ((JobState2) => {
337
+ JobState2["SCHEDULED"] = "scheduled";
338
+ JobState2["RUNNING"] = "running";
339
+ JobState2["PAUSED"] = "paused";
340
+ JobState2["STOPPED"] = "stopped";
341
+ JobState2["COMPLETED"] = "completed";
342
+ JobState2["FAILED"] = "failed";
343
+ return JobState2;
344
+ })(JobState || {});
345
+
346
+ const _JobRegistry = class _JobRegistry {
347
+ constructor() {
348
+ this.jobs = /* @__PURE__ */ new Map();
349
+ }
350
+ register(id, job, options) {
351
+ const context = this.createJobContext(id, options);
352
+ this.jobs.set(id, {
353
+ job,
354
+ context,
355
+ options
356
+ });
357
+ }
358
+ resolve(id) {
359
+ const entry = this.jobs.get(id);
360
+ return entry?.job;
361
+ }
362
+ meta(id) {
363
+ const entry = this.jobs.get(id);
364
+ return entry?.options;
365
+ }
366
+ getContext(id) {
367
+ const entry = this.jobs.get(id);
368
+ return entry?.context;
369
+ }
370
+ updateState(id, state) {
371
+ const entry = this.jobs.get(id);
372
+ if (entry) {
373
+ entry.context.state = state;
374
+ entry.context.updatedAt = /* @__PURE__ */ new Date();
375
+ switch (state) {
376
+ case JobState.RUNNING:
377
+ entry.context.startedAt = /* @__PURE__ */ new Date();
378
+ break;
379
+ case JobState.PAUSED:
380
+ entry.context.pausedAt = /* @__PURE__ */ new Date();
381
+ break;
382
+ case JobState.STOPPED:
383
+ entry.context.stoppedAt = /* @__PURE__ */ new Date();
384
+ break;
385
+ case JobState.COMPLETED:
386
+ entry.context.completedAt = /* @__PURE__ */ new Date();
387
+ break;
388
+ }
389
+ }
390
+ }
391
+ setTimeoutId(id, timeoutId) {
392
+ const entry = this.jobs.get(id);
393
+ if (entry) {
394
+ entry.timeoutId = timeoutId;
395
+ }
396
+ }
397
+ setIntervalId(id, intervalId) {
398
+ const entry = this.jobs.get(id);
399
+ if (entry) {
400
+ entry.intervalId = intervalId;
401
+ }
402
+ }
403
+ clearTimers(id) {
404
+ const entry = this.jobs.get(id);
405
+ if (entry) {
406
+ if (entry.timeoutId) {
407
+ clearTimeout(entry.timeoutId);
408
+ entry.timeoutId = void 0;
409
+ }
410
+ if (entry.intervalId) {
411
+ clearInterval(entry.intervalId);
412
+ entry.intervalId = void 0;
413
+ }
414
+ }
415
+ }
416
+ pause(id) {
417
+ const entry = this.jobs.get(id);
418
+ console.log(`Pausing job ${id}`);
419
+ if (entry && entry.context.state === JobState.RUNNING) {
420
+ console.log(`paused job ${id}`);
421
+ this.updateState(id, JobState.PAUSED);
422
+ this.clearTimers(id);
423
+ entry.job.pause?.();
424
+ }
425
+ }
426
+ resume(id) {
427
+ const entry = this.jobs.get(id);
428
+ console.log(`Resuming job ${id}`);
429
+ if (entry && entry.context.state === JobState.PAUSED) {
430
+ console.log(`Resuming job ${id}`);
431
+ this.updateState(id, JobState.SCHEDULED);
432
+ entry.job.resume?.();
433
+ }
434
+ }
435
+ stop(id) {
436
+ const entry = this.jobs.get(id);
437
+ if (entry && entry.context.state !== JobState.STOPPED) {
438
+ console.log(`Stopping job ${id}`);
439
+ this.updateState(id, JobState.STOPPED);
440
+ this.clearTimers(id);
441
+ entry.job.stop?.();
442
+ }
443
+ }
444
+ createJobContext(id, options) {
445
+ const now = /* @__PURE__ */ new Date();
446
+ return {
447
+ id,
448
+ options,
449
+ state: JobState.SCHEDULED,
450
+ createdAt: now,
451
+ updatedAt: now,
452
+ retryCount: 0,
453
+ pause: () => this.pause(id),
454
+ resume: () => this.resume(id),
455
+ stop: () => this.stop(id),
456
+ complete: () => this.updateState(id, JobState.COMPLETED),
457
+ fail: (error) => {
458
+ this.updateState(id, JobState.FAILED);
459
+ const entry = this.jobs.get(id);
460
+ if (entry) entry.context.error = error;
461
+ },
462
+ retry: () => {
463
+ const entry = this.jobs.get(id);
464
+ if (entry) {
465
+ entry.context.retryCount = (entry.context.retryCount || 0) + 1;
466
+ this.updateState(id, JobState.SCHEDULED);
467
+ }
468
+ },
469
+ isRunning: () => this.getContext(id)?.state === JobState.RUNNING,
470
+ isPaused: () => this.getContext(id)?.state === JobState.PAUSED,
471
+ isStopped: () => this.getContext(id)?.state === JobState.STOPPED,
472
+ isCompleted: () => this.getContext(id)?.state === JobState.COMPLETED,
473
+ isFailed: () => this.getContext(id)?.state === JobState.FAILED,
474
+ isRetrying: () => (this.getContext(id)?.retryCount || 0) > 0,
475
+ isScheduled: () => this.getContext(id)?.state === JobState.SCHEDULED,
476
+ isDelayed: () => !!options.delay,
477
+ isRecurring: () => !!options.cron,
478
+ isCron: () => !!options.cron,
479
+ isTimeout: () => !!options.delay && !options.cron,
480
+ isAlarm: () => !!options.cron || !!options.delay && options.delay > 6e4
481
+ };
482
+ }
483
+ };
484
+ _JobRegistry.instance = new _JobRegistry();
485
+ let JobRegistry = _JobRegistry;
486
+
487
+ /* Extracts second, minute, hour, date, month and the weekday from a date. */
488
+ function extractDateElements(date) {
489
+ return {
490
+ second: date.getSeconds(),
491
+ minute: date.getMinutes(),
492
+ hour: date.getHours(),
493
+ day: date.getDate(),
494
+ month: date.getMonth(),
495
+ weekday: date.getDay(),
496
+ year: date.getFullYear(),
497
+ };
498
+ }
499
+ /* Gets the amount of days in the given month (indexed by 0) of the given year. */
500
+ function getDaysInMonth(year, month) {
501
+ return new Date(year, month + 1, 0).getDate();
502
+ }
503
+ /* Gets the amount of days from weekday1 to weekday2. */
504
+ function getDaysBetweenWeekdays(weekday1, weekday2) {
505
+ if (weekday1 <= weekday2) {
506
+ return weekday2 - weekday1;
507
+ }
508
+ return 6 - weekday1 + weekday2 + 1;
509
+ }
510
+
511
+ class Cron {
512
+ constructor({ seconds, minutes, hours, days, months, weekdays, }) {
513
+ // Validate that there are values provided.
514
+ if (!seconds || seconds.size === 0)
515
+ throw new Error('There must be at least one allowed second.');
516
+ if (!minutes || minutes.size === 0)
517
+ throw new Error('There must be at least one allowed minute.');
518
+ if (!hours || hours.size === 0)
519
+ throw new Error('There must be at least one allowed hour.');
520
+ if (!months || months.size === 0)
521
+ throw new Error('There must be at least one allowed month.');
522
+ if ((!weekdays || weekdays.size === 0) && (!days || days.size === 0))
523
+ throw new Error('There must be at least one allowed day or weekday.');
524
+ // Convert set to array and sort in ascending order.
525
+ this.seconds = Array.from(seconds).sort((a, b) => a - b);
526
+ this.minutes = Array.from(minutes).sort((a, b) => a - b);
527
+ this.hours = Array.from(hours).sort((a, b) => a - b);
528
+ this.days = Array.from(days).sort((a, b) => a - b);
529
+ this.months = Array.from(months).sort((a, b) => a - b);
530
+ this.weekdays = Array.from(weekdays).sort((a, b) => a - b);
531
+ // Validate that all values are integers within the constraint.
532
+ const validateData = (name, data, constraint) => {
533
+ if (data.some((x) => typeof x !== 'number' ||
534
+ x % 1 !== 0 ||
535
+ x < constraint.min ||
536
+ x > constraint.max)) {
537
+ throw new Error(`${name} must only consist of integers which are within the range of ${constraint.min} and ${constraint.max}`);
538
+ }
539
+ };
540
+ validateData('seconds', this.seconds, { min: 0, max: 59 });
541
+ validateData('minutes', this.minutes, { min: 0, max: 59 });
542
+ validateData('hours', this.hours, { min: 0, max: 23 });
543
+ validateData('days', this.days, { min: 1, max: 31 });
544
+ validateData('months', this.months, { min: 0, max: 11 });
545
+ validateData('weekdays', this.weekdays, { min: 0, max: 6 });
546
+ // For each element, store a reversed copy in the reversed attribute for finding prev dates.
547
+ this.reversed = {
548
+ seconds: this.seconds.map((x) => x).reverse(),
549
+ minutes: this.minutes.map((x) => x).reverse(),
550
+ hours: this.hours.map((x) => x).reverse(),
551
+ days: this.days.map((x) => x).reverse(),
552
+ months: this.months.map((x) => x).reverse(),
553
+ weekdays: this.weekdays.map((x) => x).reverse(),
554
+ };
555
+ }
556
+ /**
557
+ * Find the next or previous hour, starting from the given start hour that matches the hour constraint.
558
+ * startHour itself might also be allowed.
559
+ */
560
+ findAllowedHour(dir, startHour) {
561
+ return dir === 'next'
562
+ ? this.hours.find((x) => x >= startHour)
563
+ : this.reversed.hours.find((x) => x <= startHour);
564
+ }
565
+ /**
566
+ * Find the next or previous minute, starting from the given start minute that matches the minute constraint.
567
+ * startMinute itself might also be allowed.
568
+ */
569
+ findAllowedMinute(dir, startMinute) {
570
+ return dir === 'next'
571
+ ? this.minutes.find((x) => x >= startMinute)
572
+ : this.reversed.minutes.find((x) => x <= startMinute);
573
+ }
574
+ /**
575
+ * Find the next or previous second, starting from the given start second that matches the second constraint.
576
+ * startSecond itself IS NOT allowed.
577
+ */
578
+ findAllowedSecond(dir, startSecond) {
579
+ return dir === 'next'
580
+ ? this.seconds.find((x) => x > startSecond)
581
+ : this.reversed.seconds.find((x) => x < startSecond);
582
+ }
583
+ /**
584
+ * Find the next or previous time, starting from the given start time that matches the hour, minute
585
+ * and second constraints. startTime itself might also be allowed.
586
+ */
587
+ findAllowedTime(dir, startTime) {
588
+ // Try to find an allowed hour.
589
+ let hour = this.findAllowedHour(dir, startTime.hour);
590
+ if (hour !== undefined) {
591
+ if (hour === startTime.hour) {
592
+ // We found an hour that is the start hour. Try to find an allowed minute.
593
+ let minute = this.findAllowedMinute(dir, startTime.minute);
594
+ if (minute !== undefined) {
595
+ if (minute === startTime.minute) {
596
+ // We found a minute that is the start minute. Try to find an allowed second.
597
+ const second = this.findAllowedSecond(dir, startTime.second);
598
+ if (second !== undefined) {
599
+ // We found a second within the start hour and minute.
600
+ return { hour, minute, second };
601
+ }
602
+ // We did not find a valid second within the start minute. Try to find another minute.
603
+ minute = this.findAllowedMinute(dir, dir === 'next' ? startTime.minute + 1 : startTime.minute - 1);
604
+ if (minute !== undefined) {
605
+ // We found a minute which is not the start minute. Return that minute together with the hour and the first / last allowed second.
606
+ return {
607
+ hour,
608
+ minute,
609
+ second: dir === 'next' ? this.seconds[0] : this.reversed.seconds[0],
610
+ };
611
+ }
612
+ }
613
+ else {
614
+ // We found a minute which is not the start minute. Return that minute together with the hour and the first / last allowed second.
615
+ return {
616
+ hour,
617
+ minute,
618
+ second: dir === 'next' ? this.seconds[0] : this.reversed.seconds[0],
619
+ };
620
+ }
621
+ }
622
+ // We did not find an allowed minute / second combination inside the start hour. Try to find the next / previous allowed hour.
623
+ hour = this.findAllowedHour(dir, dir === 'next' ? startTime.hour + 1 : startTime.hour - 1);
624
+ if (hour !== undefined) {
625
+ // We found an allowed hour which is not the start hour. Return that hour together with the first / last allowed minutes / seconds.
626
+ return {
627
+ hour,
628
+ minute: dir === 'next' ? this.minutes[0] : this.reversed.minutes[0],
629
+ second: dir === 'next' ? this.seconds[0] : this.reversed.seconds[0],
630
+ };
631
+ }
632
+ }
633
+ else {
634
+ // We found an allowed hour which is not the start hour. Return that hour together with the first / last allowed minutes / seconds.
635
+ return {
636
+ hour,
637
+ minute: dir === 'next' ? this.minutes[0] : this.reversed.minutes[0],
638
+ second: dir === 'next' ? this.seconds[0] : this.reversed.seconds[0],
639
+ };
640
+ }
641
+ }
642
+ // No allowed time found.
643
+ return undefined;
644
+ }
645
+ /**
646
+ * Find the next or previous day in the given month, starting from the given startDay
647
+ * that matches either the day or the weekday constraint. startDay itself might also be allowed.
648
+ */
649
+ findAllowedDayInMonth(dir, year, month, startDay) {
650
+ var _a, _b;
651
+ if (startDay < 1)
652
+ throw new Error('startDay must not be smaller than 1.');
653
+ // If only days are restricted: allow day based on day constraint only.
654
+ // If only weekdays are restricted: allow day based on weekday constraint only.
655
+ // If both are restricted: allow day based on both day and weekday constraint. pick day that is closer to startDay.
656
+ // If none are restricted: return the day closest to startDay (respecting dir) that is allowed (or startDay itself).
657
+ const daysInMonth = getDaysInMonth(year, month);
658
+ const daysRestricted = this.days.length !== 31;
659
+ const weekdaysRestricted = this.weekdays.length !== 7;
660
+ if (!daysRestricted && !weekdaysRestricted) {
661
+ if (startDay > daysInMonth) {
662
+ return dir === 'next' ? undefined : daysInMonth;
663
+ }
664
+ return startDay;
665
+ }
666
+ // Try to find a day based on the days constraint.
667
+ let allowedDayByDays;
668
+ if (daysRestricted) {
669
+ allowedDayByDays =
670
+ dir === 'next'
671
+ ? this.days.find((x) => x >= startDay)
672
+ : this.reversed.days.find((x) => x <= startDay);
673
+ // Make sure the day does not exceed the amount of days in month.
674
+ if (allowedDayByDays !== undefined && allowedDayByDays > daysInMonth) {
675
+ allowedDayByDays = undefined;
676
+ }
677
+ }
678
+ // Try to find a day based on the weekday constraint.
679
+ let allowedDayByWeekdays;
680
+ if (weekdaysRestricted) {
681
+ const startWeekday = new Date(year, month, startDay).getDay();
682
+ const nearestAllowedWeekday = dir === 'next'
683
+ ? (_a = this.weekdays.find((x) => x >= startWeekday)) !== null && _a !== void 0 ? _a : this.weekdays[0]
684
+ : (_b = this.reversed.weekdays.find((x) => x <= startWeekday)) !== null && _b !== void 0 ? _b : this.reversed.weekdays[0];
685
+ if (nearestAllowedWeekday !== undefined) {
686
+ const daysBetweenWeekdays = dir === 'next'
687
+ ? getDaysBetweenWeekdays(startWeekday, nearestAllowedWeekday)
688
+ : getDaysBetweenWeekdays(nearestAllowedWeekday, startWeekday);
689
+ allowedDayByWeekdays =
690
+ dir === 'next'
691
+ ? startDay + daysBetweenWeekdays
692
+ : startDay - daysBetweenWeekdays;
693
+ // Make sure the day does not exceed the month boundaries.
694
+ if (allowedDayByWeekdays > daysInMonth || allowedDayByWeekdays < 1) {
695
+ allowedDayByWeekdays = undefined;
696
+ }
697
+ }
698
+ }
699
+ if (allowedDayByDays !== undefined && allowedDayByWeekdays !== undefined) {
700
+ // If a day is found both via the days and the weekdays constraint, pick the day
701
+ // that is closer to start date.
702
+ return dir === 'next'
703
+ ? Math.min(allowedDayByDays, allowedDayByWeekdays)
704
+ : Math.max(allowedDayByDays, allowedDayByWeekdays);
705
+ }
706
+ if (allowedDayByDays !== undefined) {
707
+ return allowedDayByDays;
708
+ }
709
+ if (allowedDayByWeekdays !== undefined) {
710
+ return allowedDayByWeekdays;
711
+ }
712
+ return undefined;
713
+ }
714
+ /** Gets the next date starting from the given start date or now. */
715
+ getNextDate(startDate = new Date()) {
716
+ const startDateElements = extractDateElements(startDate);
717
+ let minYear = startDateElements.year;
718
+ let startIndexMonth = this.months.findIndex((x) => x >= startDateElements.month);
719
+ if (startIndexMonth === -1) {
720
+ startIndexMonth = 0;
721
+ minYear++;
722
+ }
723
+ // We try every month within the next 5 years to make sure that we tried to
724
+ // find a matching date insidde a whole leap year.
725
+ const maxIterations = this.months.length * 5;
726
+ for (let i = 0; i < maxIterations; i++) {
727
+ // Get the next year and month.
728
+ const year = minYear + Math.floor((startIndexMonth + i) / this.months.length);
729
+ const month = this.months[(startIndexMonth + i) % this.months.length];
730
+ const isStartMonth = year === startDateElements.year && month === startDateElements.month;
731
+ // Find the next day.
732
+ let day = this.findAllowedDayInMonth('next', year, month, isStartMonth ? startDateElements.day : 1);
733
+ let isStartDay = isStartMonth && day === startDateElements.day;
734
+ // If we found a day and it is the start day, try to find a valid time beginning from the start date time.
735
+ if (day !== undefined && isStartDay) {
736
+ const nextTime = this.findAllowedTime('next', startDateElements);
737
+ if (nextTime !== undefined) {
738
+ return new Date(year, month, day, nextTime.hour, nextTime.minute, nextTime.second);
739
+ }
740
+ // If no valid time has been found for the start date, try the next day.
741
+ day = this.findAllowedDayInMonth('next', year, month, day + 1);
742
+ isStartDay = false;
743
+ }
744
+ // If we found a next day and it is not the start day, just use the next day with the first allowed values
745
+ // for hours, minutes and seconds.
746
+ if (day !== undefined && !isStartDay) {
747
+ return new Date(year, month, day, this.hours[0], this.minutes[0], this.seconds[0]);
748
+ }
749
+ // No allowed day has been found for this month. Continue to search in next month.
750
+ }
751
+ throw new Error('No valid next date was found.');
752
+ }
753
+ /** Gets the specified amount of future dates starting from the given start date or now. */
754
+ getNextDates(amount, startDate) {
755
+ const dates = [];
756
+ let nextDate;
757
+ for (let i = 0; i < amount; i++) {
758
+ nextDate = this.getNextDate(nextDate !== null && nextDate !== void 0 ? nextDate : startDate);
759
+ dates.push(nextDate);
760
+ }
761
+ return dates;
762
+ }
763
+ /**
764
+ * Get an ES6 compatible iterator which iterates over the next dates starting from startDate or now.
765
+ * The iterator runs until the optional endDate is reached or forever.
766
+ */
767
+ *getNextDatesIterator(startDate, endDate) {
768
+ let nextDate;
769
+ while (true) {
770
+ nextDate = this.getNextDate(nextDate !== null && nextDate !== void 0 ? nextDate : startDate);
771
+ if (endDate && endDate.getTime() < nextDate.getTime()) {
772
+ return;
773
+ }
774
+ yield nextDate;
775
+ }
776
+ }
777
+ /** Gets the previous date starting from the given start date or now. */
778
+ getPrevDate(startDate = new Date()) {
779
+ const startDateElements = extractDateElements(startDate);
780
+ let maxYear = startDateElements.year;
781
+ let startIndexMonth = this.reversed.months.findIndex((x) => x <= startDateElements.month);
782
+ if (startIndexMonth === -1) {
783
+ startIndexMonth = 0;
784
+ maxYear--;
785
+ }
786
+ // We try every month within the past 5 years to make sure that we tried to
787
+ // find a matching date inside a whole leap year.
788
+ const maxIterations = this.reversed.months.length * 5;
789
+ for (let i = 0; i < maxIterations; i++) {
790
+ // Get the next year and month.
791
+ const year = maxYear -
792
+ Math.floor((startIndexMonth + i) / this.reversed.months.length);
793
+ const month = this.reversed.months[(startIndexMonth + i) % this.reversed.months.length];
794
+ const isStartMonth = year === startDateElements.year && month === startDateElements.month;
795
+ // Find the previous day.
796
+ let day = this.findAllowedDayInMonth('prev', year, month, isStartMonth
797
+ ? startDateElements.day
798
+ : // Start searching from the last day of the month.
799
+ getDaysInMonth(year, month));
800
+ let isStartDay = isStartMonth && day === startDateElements.day;
801
+ // If we found a day and it is the start day, try to find a valid time beginning from the start date time.
802
+ if (day !== undefined && isStartDay) {
803
+ const prevTime = this.findAllowedTime('prev', startDateElements);
804
+ if (prevTime !== undefined) {
805
+ return new Date(year, month, day, prevTime.hour, prevTime.minute, prevTime.second);
806
+ }
807
+ // If no valid time has been found for the start date, try the previous day.
808
+ if (day > 1) {
809
+ day = this.findAllowedDayInMonth('prev', year, month, day - 1);
810
+ isStartDay = false;
811
+ }
812
+ }
813
+ // If we found a previous day and it is not the start day, just use the previous day with the first allowed values
814
+ // for hours, minutes and seconds (which will be the latest time due to using the reversed array).
815
+ if (day !== undefined && !isStartDay) {
816
+ return new Date(year, month, day, this.reversed.hours[0], this.reversed.minutes[0], this.reversed.seconds[0]);
817
+ }
818
+ // No allowed day has been found for this month. Continue to search in previous month.
819
+ }
820
+ throw new Error('No valid previous date was found.');
821
+ }
822
+ /** Gets the specified amount of previous dates starting from the given start date or now. */
823
+ getPrevDates(amount, startDate) {
824
+ const dates = [];
825
+ let prevDate;
826
+ for (let i = 0; i < amount; i++) {
827
+ prevDate = this.getPrevDate(prevDate !== null && prevDate !== void 0 ? prevDate : startDate);
828
+ dates.push(prevDate);
829
+ }
830
+ return dates;
831
+ }
832
+ /**
833
+ * Get an ES6 compatible iterator which iterates over the previous dates starting from startDate or now.
834
+ * The iterator runs until the optional endDate is reached or forever.
835
+ */
836
+ *getPrevDatesIterator(startDate, endDate) {
837
+ let prevDate;
838
+ while (true) {
839
+ prevDate = this.getPrevDate(prevDate !== null && prevDate !== void 0 ? prevDate : startDate);
840
+ if (endDate && endDate.getTime() > prevDate.getTime()) {
841
+ return;
842
+ }
843
+ yield prevDate;
844
+ }
845
+ }
846
+ /** Returns true when there is a cron date at the given date. */
847
+ matchDate(date) {
848
+ const { second, minute, hour, day, month, weekday } = extractDateElements(date);
849
+ if (this.seconds.indexOf(second) === -1 ||
850
+ this.minutes.indexOf(minute) === -1 ||
851
+ this.hours.indexOf(hour) === -1 ||
852
+ this.months.indexOf(month) === -1) {
853
+ return false;
854
+ }
855
+ if (this.days.length !== 31 && this.weekdays.length !== 7) {
856
+ return (this.days.indexOf(day) !== -1 || this.weekdays.indexOf(weekday) !== -1);
857
+ }
858
+ return (this.days.indexOf(day) !== -1 && this.weekdays.indexOf(weekday) !== -1);
859
+ }
860
+ }
861
+
862
+ const secondConstraint = {
863
+ min: 0,
864
+ max: 59,
865
+ };
866
+ const minuteConstraint = {
867
+ min: 0,
868
+ max: 59,
869
+ };
870
+ const hourConstraint = {
871
+ min: 0,
872
+ max: 23,
873
+ };
874
+ const dayConstraint = {
875
+ min: 1,
876
+ max: 31,
877
+ };
878
+ const monthConstraint = {
879
+ min: 1,
880
+ max: 12,
881
+ aliases: {
882
+ jan: '1',
883
+ feb: '2',
884
+ mar: '3',
885
+ apr: '4',
886
+ may: '5',
887
+ jun: '6',
888
+ jul: '7',
889
+ aug: '8',
890
+ sep: '9',
891
+ oct: '10',
892
+ nov: '11',
893
+ dec: '12',
894
+ },
895
+ };
896
+ const weekdayConstraint = {
897
+ min: 0,
898
+ max: 7,
899
+ aliases: {
900
+ mon: '1',
901
+ tue: '2',
902
+ wed: '3',
903
+ thu: '4',
904
+ fri: '5',
905
+ sat: '6',
906
+ sun: '7',
907
+ },
908
+ };
909
+ const timeNicknames = {
910
+ '@yearly': '0 0 1 1 *',
911
+ '@annually': '0 0 1 1 *',
912
+ '@monthly': '0 0 1 * *',
913
+ '@weekly': '0 0 * * 0',
914
+ '@daily': '0 0 * * *',
915
+ '@hourly': '0 * * * *',
916
+ '@minutely': '* * * * *',
917
+ };
918
+ function parseElement(element, constraint) {
919
+ const result = new Set();
920
+ // If returned set of numbers is empty, the scheduler class interpretes the emtpy set of numbers as all valid values of the constraint
921
+ if (element === '*') {
922
+ for (let i = constraint.min; i <= constraint.max; i = i + 1) {
923
+ result.add(i);
924
+ }
925
+ return result;
926
+ }
927
+ // If the element is a list, parse each element in the list.
928
+ const listElements = element.split(',');
929
+ if (listElements.length > 1) {
930
+ for (const listElement of listElements) {
931
+ const parsedListElement = parseElement(listElement, constraint);
932
+ for (const x of parsedListElement) {
933
+ result.add(x);
934
+ }
935
+ }
936
+ return result;
937
+ }
938
+ // Helper function to parse a single element, which includes checking for alias, valid number and constraint min and max.
939
+ const parseSingleElement = (singleElement) => {
940
+ var _a, _b;
941
+ // biome-ignore lint/style/noParameterAssign: adding another variable with a new name is more confusing
942
+ singleElement =
943
+ (_b = (_a = constraint.aliases) === null || _a === void 0 ? void 0 : _a[singleElement.toLowerCase()]) !== null && _b !== void 0 ? _b : singleElement;
944
+ const parsedElement = Number.parseInt(singleElement, 10);
945
+ if (Number.isNaN(parsedElement)) {
946
+ throw new Error(`Failed to parse ${element}: ${singleElement} is NaN.`);
947
+ }
948
+ if (parsedElement < constraint.min || parsedElement > constraint.max) {
949
+ throw new Error(`Failed to parse ${element}: ${singleElement} is outside of constraint range of ${constraint.min} - ${constraint.max}.`);
950
+ }
951
+ return parsedElement;
952
+ };
953
+ // Detect if the element is a range.
954
+ // Possible range formats: 'start-end', 'start-end/step', '*', '*/step'.
955
+ // Where start and end can be numbers or aliases.
956
+ // Capture groups: 1: start-end, 2: start, 3: end, 4: /step, 5: step.
957
+ const rangeSegments = /^(([0-9a-zA-Z]+)-([0-9a-zA-Z]+)|\*)(\/([0-9]+))?$/.exec(element);
958
+ // If not, it must be a single element.
959
+ if (rangeSegments === null) {
960
+ result.add(parseSingleElement(element));
961
+ return result;
962
+ }
963
+ // If it is a range, get start and end of the range.
964
+ let parsedStart = rangeSegments[1] === '*'
965
+ ? constraint.min
966
+ : parseSingleElement(rangeSegments[2]);
967
+ const parsedEnd = rangeSegments[1] === '*'
968
+ ? constraint.max
969
+ : parseSingleElement(rangeSegments[3]);
970
+ // 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
971
+ if (constraint === weekdayConstraint &&
972
+ parsedStart === 7 &&
973
+ // this check ensures that sun-sun is not incorrectly parsed as [0,1,2,3,4,5,6]
974
+ parsedEnd !== 7) {
975
+ parsedStart = 0;
976
+ }
977
+ if (parsedStart > parsedEnd) {
978
+ throw new Error(`Failed to parse ${element}: Invalid range (start: ${parsedStart}, end: ${parsedEnd}).`);
979
+ }
980
+ // Check whether there is a custom step defined for the range, defaulting to 1.
981
+ const step = rangeSegments[5];
982
+ let parsedStep = 1;
983
+ if (step !== undefined) {
984
+ parsedStep = Number.parseInt(step, 10);
985
+ if (Number.isNaN(parsedStep)) {
986
+ throw new Error(`Failed to parse step: ${step} is NaN.`);
987
+ }
988
+ if (parsedStep < 1) {
989
+ throw new Error(`Failed to parse step: Expected ${step} to be greater than 0.`);
990
+ }
991
+ }
992
+ // Go from start to end of the range by the given steps.
993
+ for (let i = parsedStart; i <= parsedEnd; i = i + parsedStep) {
994
+ result.add(i);
995
+ }
996
+ return result;
997
+ }
998
+ /** Parses a cron expression into a Cron instance. */
999
+ function parseCronExpression(cronExpression) {
1000
+ var _a;
1001
+ if (typeof cronExpression !== 'string') {
1002
+ throw new TypeError('Invalid cron expression: must be of type string.');
1003
+ }
1004
+ // Convert time nicknames.
1005
+ // biome-ignore lint/style/noParameterAssign: adding another variable with a new name is more confusing
1006
+ cronExpression = (_a = timeNicknames[cronExpression.toLowerCase()]) !== null && _a !== void 0 ? _a : cronExpression;
1007
+ // Split the cron expression into its elements, removing empty elements (extra whitespaces).
1008
+ const elements = cronExpression.split(' ').filter((elem) => elem.length > 0);
1009
+ if (elements.length < 5 || elements.length > 6) {
1010
+ throw new Error('Invalid cron expression: expected 5 or 6 elements.');
1011
+ }
1012
+ const rawSeconds = elements.length === 6 ? elements[0] : '0';
1013
+ const rawMinutes = elements.length === 6 ? elements[1] : elements[0];
1014
+ const rawHours = elements.length === 6 ? elements[2] : elements[1];
1015
+ const rawDays = elements.length === 6 ? elements[3] : elements[2];
1016
+ const rawMonths = elements.length === 6 ? elements[4] : elements[3];
1017
+ const rawWeekdays = elements.length === 6 ? elements[5] : elements[4];
1018
+ return new Cron({
1019
+ seconds: parseElement(rawSeconds, secondConstraint),
1020
+ minutes: parseElement(rawMinutes, minuteConstraint),
1021
+ hours: parseElement(rawHours, hourConstraint),
1022
+ days: parseElement(rawDays, dayConstraint),
1023
+ // months in cron are indexed by 1, but Cron expects indexes by 0, so we need to reduce all set values by one.
1024
+ months: new Set(Array.from(parseElement(rawMonths, monthConstraint)).map((x) => x - 1)),
1025
+ weekdays: new Set(Array.from(parseElement(rawWeekdays, weekdayConstraint)).map((x) => x % 7)),
1026
+ });
1027
+ }
1028
+
1029
+ function getNextCronDate(expr) {
1030
+ try {
1031
+ const interval = parseCronExpression(expr);
1032
+ return interval.getNextDate();
1033
+ } catch (error) {
1034
+ console.error("Invalid cron expression:", expr, error);
1035
+ throw new Error("Invalid cron expression");
1036
+ }
1037
+ }
1038
+
1039
+ class Scheduler {
1040
+ constructor() {
1041
+ this.registry = JobRegistry.instance;
1042
+ this.alarm = new AlarmAdapter();
1043
+ this.timeout = new TimeoutAdapter();
1044
+ console.log("Scheduler initialized");
1045
+ this.alarm.onTrigger((id) => this.execute(id));
1046
+ this.timeout.onTrigger((id) => this.execute(id));
1047
+ }
1048
+ schedule(id, options) {
1049
+ const context = this.registry.getContext(id);
1050
+ if (!context || context.isStopped()) {
1051
+ console.log(`Job ${id} is stopped, skipping schedule`);
1052
+ return;
1053
+ }
1054
+ console.log(`Scheduling job ${id} with options:`, options);
1055
+ const when = this.getScheduleTime(options);
1056
+ console.log(`Job ${id} will execute at:`, new Date(when).toISOString());
1057
+ const adapter = when - Date.now() < 6e4 ? this.timeout : this.alarm;
1058
+ const timerId = adapter.schedule(id, when);
1059
+ if (adapter === this.timeout) {
1060
+ this.registry.setTimeoutId(id, timerId);
1061
+ }
1062
+ }
1063
+ pause(id) {
1064
+ console.log(`Pausing job ${id}`);
1065
+ this.registry.pause(id);
1066
+ }
1067
+ resume(id) {
1068
+ console.log(`Resuming job ${id}`);
1069
+ this.registry.resume(id);
1070
+ const options = this.registry.meta(id);
1071
+ if (options) {
1072
+ this.schedule(id, options);
1073
+ }
1074
+ }
1075
+ stop(id) {
1076
+ console.log(`Stopping job ${id}`);
1077
+ this.registry.stop(id);
1078
+ }
1079
+ async execute(id) {
1080
+ const job = this.registry.resolve(id);
1081
+ const context = this.registry.getContext(id);
1082
+ if (!job || !context) {
1083
+ console.log(`Job ${id} not found or no context`);
1084
+ return;
1085
+ }
1086
+ if (context.isPaused() || context.isStopped()) {
1087
+ console.log(`Job ${id} is paused or stopped, skipping execution`);
1088
+ return;
1089
+ }
1090
+ try {
1091
+ this.registry.updateState(id, JobState.RUNNING);
1092
+ console.log(`Executing job ${id}`);
1093
+ await job.handle(context);
1094
+ if (!context.isStopped() && !context.isPaused()) {
1095
+ this.registry.updateState(id, JobState.COMPLETED);
1096
+ const options = this.registry.meta(id);
1097
+ if (options?.cron) {
1098
+ this.registry.updateState(id, JobState.SCHEDULED);
1099
+ this.schedule(id, options);
1100
+ }
1101
+ }
1102
+ } catch (error) {
1103
+ console.error(`Job ${id} execution failed:`, error);
1104
+ context.fail(error);
1105
+ }
1106
+ }
1107
+ getScheduleTime(options) {
1108
+ if (options.delay) return Date.now() + options.delay;
1109
+ if (options.cron) {
1110
+ const date = getNextCronDate(options.cron);
1111
+ if (!date) {
1112
+ throw new Error("Invalid cron expression");
1113
+ }
1114
+ return date.getTime();
1115
+ }
1116
+ return Date.now();
1117
+ }
1118
+ // Public API for job control
1119
+ getJobState(id) {
1120
+ return this.registry.getContext(id)?.state;
1121
+ }
1122
+ listJobs() {
1123
+ const jobs = [];
1124
+ return jobs;
1125
+ }
1126
+ }
1127
+
1128
+ class ApplicationBootstrap {
1129
+ constructor() {
1130
+ this.serviceDependencies = /* @__PURE__ */ new Map();
1131
+ this.serviceRegistry = /* @__PURE__ */ new Map();
1132
+ this.logger = new BootstrapLogger();
1133
+ }
1134
+ /**
1135
+ * Create and initialize a new Chroma application instance
1136
+ */
1137
+ async create() {
1138
+ try {
1139
+ this.logger.info("\u{1F680} Starting Chroma application bootstrap...");
1140
+ await this.discoverServices();
1141
+ await this.validateDependencies();
1142
+ await this.registerServices();
1143
+ await this.registerMessages();
1144
+ await this.registerJobs();
1145
+ await this.bootMessages();
1146
+ this.logger.success("\u{1F389} Chroma application initialization complete!");
1147
+ bootstrap({ container });
1148
+ } catch (error) {
1149
+ this.logger.error("\u{1F4A5} Application bootstrap failed:", error);
1150
+ throw error;
1151
+ }
1152
+ }
1153
+ /**
1154
+ * Discover all services in the application directory
1155
+ */
1156
+ async discoverServices() {
1157
+ this.logger.info("\u{1F50D} Discovering services...");
1158
+ const serviceModules = undefined(
1159
+ "/src/app/services/*.service.{ts,js}",
1160
+ { eager: true }
1161
+ );
1162
+ for (const module of Object.values(serviceModules)) {
1163
+ const ServiceClass = module?.default;
1164
+ if (!ServiceClass) continue;
1165
+ this.serviceRegistry.set(ServiceClass.name, ServiceClass);
1166
+ }
1167
+ for (const module of Object.values(serviceModules)) {
1168
+ const ServiceClass = module?.default;
1169
+ if (!ServiceClass) continue;
1170
+ const dependencies = this.resolveDependencies(ServiceClass);
1171
+ this.serviceDependencies.set(ServiceClass.name, {
1172
+ service: ServiceClass,
1173
+ dependencies,
1174
+ registered: false
1175
+ });
1176
+ this.logger.debug(`\u{1F4E6} Discovered ${ServiceClass.name}`, {
1177
+ dependencies: dependencies.map((dep) => dep.name)
1178
+ });
1179
+ }
1180
+ this.logger.success(`\u2705 Discovered ${this.serviceDependencies.size} services`);
1181
+ }
1182
+ /**
1183
+ * Resolve service dependencies using reflection and fallback parsing
1184
+ */
1185
+ resolveDependencies(ServiceClass) {
1186
+ const paramTypes = Reflect.getMetadata("design:paramtypes", ServiceClass) || [];
1187
+ if (paramTypes.length > 0) {
1188
+ return paramTypes.filter((type) => type && type !== Object);
1189
+ }
1190
+ if (ServiceClass.length > 0) {
1191
+ return this.parseConstructorDependencies(ServiceClass);
1192
+ }
1193
+ return [];
1194
+ }
1195
+ /**
1196
+ * Parse constructor dependencies from class string representation
1197
+ */
1198
+ parseConstructorDependencies(ServiceClass) {
1199
+ const constructorString = ServiceClass.toString();
1200
+ const constructorMatch = constructorString.match(/constructor\s*\(([^)]*)\)/);
1201
+ if (!constructorMatch) return [];
1202
+ const parameters = constructorMatch[1].split(",").map((param) => param.trim().toLowerCase()).filter((param) => param.length > 0);
1203
+ const dependencies = [];
1204
+ for (const param of parameters) {
1205
+ const matchingService = Array.from(this.serviceRegistry.entries()).find(
1206
+ ([name]) => name.toLowerCase() === param
1207
+ );
1208
+ if (matchingService) {
1209
+ dependencies.push(matchingService[1]);
1210
+ } else {
1211
+ this.logger.warn(`\u26A0\uFE0F No service found for parameter "${param}" in ${ServiceClass.name}`);
1212
+ }
1213
+ }
1214
+ return dependencies;
1215
+ }
1216
+ /**
1217
+ * Validate service dependencies and detect circular references
1218
+ */
1219
+ async validateDependencies() {
1220
+ this.logger.info("\u{1F50D} Validating dependencies...");
1221
+ const circularDependencies = this.detectCircularDependencies();
1222
+ if (circularDependencies.length > 0) {
1223
+ this.handleCircularDependencies(circularDependencies);
1224
+ } else {
1225
+ this.logger.success("\u2705 No circular dependencies detected");
1226
+ }
1227
+ }
1228
+ /**
1229
+ * Detect circular dependencies using depth-first search
1230
+ */
1231
+ detectCircularDependencies() {
1232
+ const visited = /* @__PURE__ */ new Set();
1233
+ const recursionStack = /* @__PURE__ */ new Set();
1234
+ const circularDeps = [];
1235
+ const dfs = (serviceName, path) => {
1236
+ if (recursionStack.has(serviceName)) {
1237
+ const cycleStart = path.indexOf(serviceName);
1238
+ const cycle = path.slice(cycleStart).concat([serviceName]);
1239
+ circularDeps.push({
1240
+ cycle: Object.freeze(cycle),
1241
+ services: Object.freeze(Array.from(new Set(cycle)))
1242
+ });
1243
+ return;
1244
+ }
1245
+ if (visited.has(serviceName)) return;
1246
+ visited.add(serviceName);
1247
+ recursionStack.add(serviceName);
1248
+ const serviceMetadata = this.serviceDependencies.get(serviceName);
1249
+ if (serviceMetadata) {
1250
+ for (const dependency of serviceMetadata.dependencies) {
1251
+ if (this.serviceDependencies.has(dependency.name)) {
1252
+ dfs(dependency.name, [...path, serviceName]);
1253
+ }
1254
+ }
1255
+ }
1256
+ recursionStack.delete(serviceName);
1257
+ };
1258
+ for (const serviceName of this.serviceDependencies.keys()) {
1259
+ if (!visited.has(serviceName)) {
1260
+ dfs(serviceName, []);
1261
+ }
1262
+ }
1263
+ return circularDeps;
1264
+ }
1265
+ /**
1266
+ * Handle circular dependencies with detailed reporting
1267
+ */
1268
+ handleCircularDependencies(circularDeps) {
1269
+ this.logger.error("\u{1F534} CIRCULAR DEPENDENCIES DETECTED");
1270
+ this.logger.divider();
1271
+ circularDeps.forEach((circular, index) => {
1272
+ this.logger.error(`\u{1F4CD} Circular Dependency #${index + 1}:`);
1273
+ this.logger.error(` Cycle: ${circular.cycle.join(" \u2192 ")}`);
1274
+ this.logger.error(` Affected Services: ${circular.services.join(", ")}`);
1275
+ this.logger.info(" \u{1F4A1} Resolution Suggestions:");
1276
+ this.logger.info(" \u2022 Extract shared functionality into a separate service");
1277
+ this.logger.info(" \u2022 Use interfaces or abstractions to break the cycle");
1278
+ this.logger.info(" \u2022 Consider Factory or Provider patterns");
1279
+ this.logger.info(" \u2022 Move shared logic to utility classes");
1280
+ });
1281
+ this.logger.divider();
1282
+ this.logger.warn("\u26A0\uFE0F Application will continue but some services may fail to resolve");
1283
+ this.logger.warn(" Please address these circular dependencies for optimal functionality");
1284
+ }
1285
+ /**
1286
+ * Register all services with the dependency injection container
1287
+ */
1288
+ async registerServices() {
1289
+ this.logger.info("\u{1F527} Registering services...");
1290
+ for (const serviceName of this.serviceDependencies.keys()) {
1291
+ await this.registerService(serviceName);
1292
+ }
1293
+ const results = this.getRegistrationResults();
1294
+ this.reportRegistrationResults(results);
1295
+ }
1296
+ /**
1297
+ * Register a single service with dependency resolution
1298
+ */
1299
+ async registerService(serviceName, visitedServices = /* @__PURE__ */ new Set(), registrationPath = []) {
1300
+ const serviceMetadata = this.serviceDependencies.get(serviceName);
1301
+ if (!serviceMetadata) {
1302
+ return { success: false, message: `Service ${serviceName} not found` };
1303
+ }
1304
+ if (serviceMetadata.registered) {
1305
+ return { success: true, message: `Service ${serviceName} already registered` };
1306
+ }
1307
+ if (visitedServices.has(serviceName)) {
1308
+ const cycle = [...registrationPath, serviceName];
1309
+ this.logger.warn(`\u{1F504} Circular dependency in registration: ${cycle.join(" \u2192 ")}`);
1310
+ return { success: false, message: "Circular dependency detected" };
1311
+ }
1312
+ const newVisited = new Set(visitedServices).add(serviceName);
1313
+ const newPath = [...registrationPath, serviceName];
1314
+ for (const dependency of serviceMetadata.dependencies) {
1315
+ if (this.serviceDependencies.has(dependency.name)) {
1316
+ await this.registerService(dependency.name, newVisited, newPath);
1317
+ }
1318
+ }
1319
+ try {
1320
+ const ServiceClass = serviceMetadata.service;
1321
+ b(L$1(), ServiceClass);
1322
+ serviceMetadata.dependencies.forEach((dependency, index) => {
1323
+ b(_$1(dependency), ServiceClass, index);
1324
+ });
1325
+ container.bind(ServiceClass).toSelf().inSingletonScope();
1326
+ serviceMetadata.registered = true;
1327
+ this.logger.success(`\u2705 Registered service: ${ServiceClass.name}`);
1328
+ return { success: true, message: `Successfully registered ${ServiceClass.name}` };
1329
+ } catch (error) {
1330
+ const errorMessage = `Failed to register ${serviceName}`;
1331
+ this.logger.error(`\u274C ${errorMessage}:`, error);
1332
+ return { success: false, message: errorMessage, error };
1333
+ }
1334
+ }
1335
+ /**
1336
+ * Get registration results summary
1337
+ */
1338
+ getRegistrationResults() {
1339
+ const successful = [];
1340
+ const failed = [];
1341
+ for (const [name, metadata] of this.serviceDependencies.entries()) {
1342
+ if (metadata.registered) {
1343
+ successful.push(name);
1344
+ } else {
1345
+ failed.push(name);
1346
+ }
1347
+ }
1348
+ return { successful, failed };
1349
+ }
1350
+ /**
1351
+ * Report service registration results
1352
+ */
1353
+ reportRegistrationResults({
1354
+ successful,
1355
+ failed
1356
+ }) {
1357
+ if (failed.length > 0) {
1358
+ this.logger.error("\u26A0\uFE0F Some services could not be registered:");
1359
+ failed.forEach((serviceName) => {
1360
+ const metadata = this.serviceDependencies.get(serviceName);
1361
+ const deps = metadata?.dependencies.map((d) => d.name).join(", ") || "none";
1362
+ this.logger.error(` \u2022 ${serviceName} (dependencies: ${deps})`);
1363
+ });
1364
+ } else {
1365
+ this.logger.success(`\u2705 All ${successful.length} services registered successfully`);
1366
+ }
1367
+ }
1368
+ /**
1369
+ * Register message handlers
1370
+ */
1371
+ async registerMessages() {
1372
+ this.logger.info("\u{1F4E8} Registering messages...");
1373
+ const messageModules = undefined(
1374
+ "/src/app/messages/*.message.{ts,js}",
1375
+ { eager: true }
1376
+ );
1377
+ for (const module of Object.values(messageModules)) {
1378
+ const MessageClass = module?.default;
1379
+ if (!MessageClass) continue;
1380
+ try {
1381
+ const dependencies = this.resolveDependencies(MessageClass);
1382
+ b(L$1(), MessageClass);
1383
+ dependencies.forEach((dependency, index) => {
1384
+ b(_$1(dependency), MessageClass, index);
1385
+ });
1386
+ const messageMetadata = Reflect.getMetadata("name", MessageClass);
1387
+ const messageName = messageMetadata || MessageClass.name;
1388
+ container.bind(messageName).to(MessageClass).inSingletonScope();
1389
+ this.logger.success(`\u2705 Registered message: ${messageName}`);
1390
+ } catch (error) {
1391
+ this.logger.error(`\u274C Failed to register message ${MessageClass.name}:`, error);
1392
+ }
1393
+ }
1394
+ }
1395
+ /**
1396
+ * Boot all registered messages
1397
+ */
1398
+ async bootMessages() {
1399
+ this.logger.info("\u{1F680} Booting messages...");
1400
+ const messageModules = undefined(
1401
+ "/src/app/messages/*.message.{ts,js}",
1402
+ { eager: true }
1403
+ );
1404
+ for (const module of Object.values(messageModules)) {
1405
+ const MessageClass = module?.default;
1406
+ if (!MessageClass || typeof MessageClass.prototype.boot !== "function") continue;
1407
+ try {
1408
+ const messageMetadata = Reflect.getMetadata("name", MessageClass);
1409
+ const messageName = messageMetadata || MessageClass.name;
1410
+ const messageInstance = container.get(messageName);
1411
+ await messageInstance.boot();
1412
+ this.logger.success(`\u2705 Booted message: ${messageName}`);
1413
+ } catch (error) {
1414
+ this.logger.error(`\u274C Failed to boot message ${MessageClass.name}:`, error);
1415
+ }
1416
+ }
1417
+ }
1418
+ /**
1419
+ * Register jobs for scheduled execution
1420
+ */
1421
+ async registerJobs() {
1422
+ this.logger.info("\u{1F552} Registering jobs...");
1423
+ const jobModules = undefined("/src/app/jobs/*.job.{ts,js}", {
1424
+ eager: true
1425
+ });
1426
+ for (const module of Object.values(jobModules)) {
1427
+ const JobClass = module?.default;
1428
+ if (!JobClass) continue;
1429
+ try {
1430
+ const dependencies = this.resolveDependencies(JobClass);
1431
+ b(L$1(), JobClass);
1432
+ dependencies.forEach((dependency, index) => {
1433
+ b(_$1(dependency), JobClass, index);
1434
+ });
1435
+ const jobMetadata = Reflect.getMetadata("name", JobClass);
1436
+ const jobName = jobMetadata || JobClass.name;
1437
+ container.bind(JobClass).toSelf().inSingletonScope();
1438
+ const id = "12";
1439
+ const options = Reflect.getMetadata("job:options", JobClass) || {};
1440
+ const instance = container.get(JobClass);
1441
+ this.scheduler = new Scheduler();
1442
+ JobRegistry.instance.register(id, instance, options);
1443
+ this.scheduler.schedule(id, options);
1444
+ this.logger.success(`\u2705 Registered job: ${jobName}`);
1445
+ } catch (error) {
1446
+ this.logger.error(`\u274C Failed to register job ${JobClass.name}:`, error);
1447
+ }
1448
+ }
1449
+ }
1450
+ }
1451
+ class BootstrapLogger {
1452
+ info(message, context) {
1453
+ console.log(message);
1454
+ if (context) console.log(" ", context);
1455
+ }
1456
+ success(message) {
1457
+ console.log(message);
1458
+ }
1459
+ warn(message) {
1460
+ console.warn(message);
1461
+ }
1462
+ error(message, error) {
1463
+ console.error(message);
1464
+ if (error) console.error(" ", error);
1465
+ }
1466
+ debug(message, context) {
1467
+ console.debug(message);
1468
+ if (context) console.debug(" ", context);
1469
+ }
1470
+ divider() {
1471
+ console.log("=".repeat(50));
1472
+ }
1473
+ }
1474
+ async function create() {
1475
+ const bootstrap2 = new ApplicationBootstrap();
1476
+ await bootstrap2.create();
1477
+ }
1478
+
1479
+ class IMessage {
1480
+ handle(...args) {
1481
+ throw new Error("Method not implemented.");
1482
+ }
1483
+ }
1484
+ function Message(name) {
1485
+ return function(constructor) {
1486
+ Reflect.defineMetadata("name", name, constructor);
1487
+ return constructor;
1488
+ };
1489
+ }
1490
+
1491
+ function Injectable() {
1492
+ return function(constructor) {
1493
+ L$1()(constructor);
1494
+ };
1495
+ }
1496
+
1497
+ class Booteable {
1498
+ /**
1499
+ * Optional destroy method to be called when the service is being destroyed.
1500
+ * This can be used to clean up resources or perform any necessary teardown logic.
1501
+ */
1502
+ destroy() {
1503
+ }
1504
+ }
1505
+ function isBooteable(obj) {
1506
+ return typeof obj.boot === "function";
1507
+ }
1508
+ function isDestroyable(obj) {
1509
+ return typeof obj.destroy === "function";
1510
+ }
1511
+
1512
+ class Job {
1513
+ constructor(data) {
1514
+ this.data = data;
1515
+ }
1516
+ pause() {
1517
+ console.log(`Job ${this.constructor.name} paused`);
1518
+ }
1519
+ resume() {
1520
+ console.log(`Job ${this.constructor.name} resumed`);
1521
+ }
1522
+ stop() {
1523
+ console.log(`Job ${this.constructor.name} stopped`);
1524
+ }
1525
+ }
1526
+
1527
+ function JobConfig(options = {}) {
1528
+ return function(constructor) {
1529
+ Reflect.defineMetadata("job:options", { options }, constructor);
1530
+ return constructor;
1531
+ };
1532
+ }
1533
+
1534
+ const Delay = (ms) => JobConfig({ delay: ms });
1535
+
1536
+ function Every(cron) {
1537
+ return function(constructor) {
1538
+ Reflect.defineMetadata("job:options", { cron }, constructor);
1539
+ return constructor;
1540
+ };
1541
+ }
1542
+
1543
+ exports.Booteable = Booteable;
1544
+ exports.Delay = Delay;
1545
+ exports.Every = Every;
1546
+ exports.IMessage = IMessage;
1547
+ exports.Inject = _$1;
1548
+ exports.Injectable = Injectable;
1549
+ exports.Job = Job;
1550
+ exports.JobState = JobState;
1551
+ exports.METADATA_KEY = METADATA_KEY;
1552
+ exports.Message = Message;
1553
+ exports.bind = bind;
1554
+ exports.container = container;
1555
+ exports.create = create;
1556
+ exports.isBooteable = isBooteable;
1557
+ exports.isDestroyable = isDestroyable;
1558
+ exports.isInjectable = isInjectable;
1559
+ exports.resolve = resolve;