ts5deco-inject
Version:
TypeScript 5 Modern Decorator Dependency Injection Framework
4 lines (3 loc) • 15.1 kB
JavaScript
"use strict";var g=Object.defineProperty;var X=Object.getOwnPropertyDescriptor;var Q=Object.getOwnPropertyNames;var Z=Object.prototype.hasOwnProperty;var q=(t,e,n)=>e in t?g(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var ee=(t,e)=>{for(var n in e)g(t,n,{get:e[n],enumerable:!0})},te=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Q(e))!Z.call(t,r)&&r!==n&&g(t,r,{get:()=>e[r],enumerable:!(i=X(e,r))||i.enumerable});return t};var ne=t=>te(g({},"__esModule",{value:!0}),t);var l=(t,e,n)=>q(t,typeof e!="symbol"?e+"":e,n);var Ce={};ee(Ce,{CONSTANTS:()=>ve,CONTAINER_EVENTS:()=>z,CircularDependencyError:()=>v,Container:()=>c,ContainerError:()=>T,ContainerEvent:()=>B,ContainerFactory:()=>P,DECORATOR_KEYS:()=>$,DEFAULT_CONTAINER_OPTIONS:()=>N,DEFAULT_SCOPES:()=>Y,DESIGN_PARAM_TYPES:()=>Ie,DESIGN_RETURN_TYPE:()=>Ee,DESIGN_TYPE:()=>fe,ERROR_MESSAGES:()=>H,FEATURE_FLAGS:()=>J,Inject:()=>pe,Injectable:()=>de,InvalidProviderError:()=>d,PERFORMANCE_CONSTANTS:()=>W,PREDEFINED_TOKENS:()=>U,PostConstruct:()=>ye,PreDestroy:()=>ue,Provide:()=>Se,ResolutionStrategy:()=>G,STRING_TOKENS:()=>j,SYMBOL_TOKENS:()=>K,Scope:()=>Te,ServiceLifecycle:()=>k,ServiceNotFoundError:()=>f,ServiceScope:()=>D,ServiceState:()=>V,Singleton:()=>le,TypedContainerError:()=>m,clearClassMetadata:()=>ce,createMetadataKey:()=>s,getAllMethodMetadata:()=>M,getAllPropertyMetadata:()=>R,getClassMetadata:()=>h,getMethodMetadata:()=>re,getPropertyMetadata:()=>ie,hasClassMetadata:()=>oe,hasMethodMetadata:()=>ae,hasPropertyMetadata:()=>se,isClassProvider:()=>I,isExistingProvider:()=>O,isFactoryProvider:()=>C,isValueProvider:()=>_,setClassMetadata:()=>S,setMethodMetadata:()=>x,setPropertyMetadata:()=>A});module.exports=ne(Ce);var E=new WeakMap,y=new WeakMap,u=new WeakMap;function s(t){return{key:Symbol(t),description:t}}function S(t,e){let n=E.get(t)||{};E.set(t,{...n,...e})}function h(t){return E.get(t)}function A(t,e,n){let i=y.get(t);i||(i=new Map,y.set(t,i));let r=i.get(e)||{};i.set(e,{...r,...n})}function ie(t,e){return y.get(t)?.get(e)}function x(t,e,n){let i=u.get(t);i||(i=new Map,u.set(t,i));let r=i.get(e)||{};i.set(e,{...r,...n})}function re(t,e){return u.get(t)?.get(e)}function R(t){return y.get(t)}function M(t){return u.get(t)}function oe(t){return E.has(t)}function se(t,e){return y.get(t)?.has(e)??!1}function ae(t,e){return u.get(t)?.has(e)??!1}function ce(t){E.delete(t),y.delete(t.prototype),u.delete(t.prototype)}function de(t="singleton"){return function(e,n){return S(e,{injectable:!0,scope:t}),e}}function pe(t,e=!1){return function(n,i){i.addInitializer(function(){A(this.constructor.prototype,i.name,{token:t,optional:e,inject:!0})})}}function le(t,e){return S(t,{scope:"singleton"}),t}function Te(t){return function(e,n){return S(e,{scope:t}),e}}function ye(t,e){return e.addInitializer(function(){x(this.constructor.prototype,e.name,{lifecycle:"postConstruct"})}),t}function ue(t,e){return e.addInitializer(function(){x(this.constructor.prototype,e.name,{lifecycle:"preDestroy"})}),t}function Se(t,e){return function(n,i){return S(n,{providers:[{token:t,value:e}]}),n}}var fe=s("design:type"),Ie=s("design:paramtypes"),Ee=s("design:returntype");var D=(i=>(i.SINGLETON="singleton",i.PROTOTYPE="prototype",i.TRANSIENT="transient",i))(D||{}),k=(n=>(n.POST_CONSTRUCT="postConstruct",n.PRE_DESTROY="preDestroy",n))(k||{}),B=(o=>(o.SERVICE_REGISTERED="service:registered",o.SERVICE_RESOLVED="service:resolved",o.SERVICE_CREATED="service:created",o.SERVICE_DISPOSED="service:disposed",o.CONTAINER_DISPOSED="container:disposed",o))(B||{}),T=class extends Error{constructor(n,i){super(n);this.token=i;this.name="ContainerError"}},v=class extends T{constructor(n,i){super(`Circular dependency detected: ${n.map(r=>String(r)).join(" -> ")}`,i);this.dependencyChain=n;this.name="CircularDependencyError"}},f=class extends T{constructor(e){super(`Service not found: ${String(e)}`,e),this.name="ServiceNotFoundError"}},d=class extends T{constructor(e,n){super(e,n),this.name="InvalidProviderError"}};function I(t){return t.type==="class"}function _(t){return t.type==="value"}function C(t){return t.type==="factory"}function O(t){return t.type==="existing"}var G=(i=>(i.THROW_ON_MISSING="throw",i.RETURN_UNDEFINED="undefined",i.USE_DEFAULT="default",i))(G||{}),V=(r=>(r.REGISTERED="registered",r.CREATING="creating",r.CREATED="created",r.DISPOSED="disposed",r))(V||{}),m=class extends Error{constructor(n,i,r){super(n);this.token=i;this.serviceType=r;this.name="TypedContainerError"}};var U={CONTAINER:s("DI_CONTAINER"),LOGGER:s("DI_LOGGER"),CONFIG:s("DI_CONFIG"),HTTP_CLIENT:s("HTTP_CLIENT"),DATABASE:s("DATABASE"),CACHE:s("CACHE"),EVENT_BUS:s("EVENT_BUS"),METADATA_READER:s("METADATA_READER"),LIFECYCLE_MANAGER:s("LIFECYCLE_MANAGER"),DEPENDENCY_RESOLVER:s("DEPENDENCY_RESOLVER")},j={NODE_ENV:"NODE_ENV",PORT:"PORT",DATABASE_URL:"DATABASE_URL",API_KEY:"API_KEY",USER_SERVICE:"UserService",AUTH_SERVICE:"AuthService",EMAIL_SERVICE:"EmailService",REDIS_CLIENT:"RedisClient",MONGO_CLIENT:"MongoClient",MYSQL_CLIENT:"MySQLClient"},K={CONTAINER_ID:Symbol("DI_CONTAINER_ID"),PARENT_CONTAINER:Symbol("DI_PARENT_CONTAINER"),CHILD_CONTAINERS:Symbol("DI_CHILD_CONTAINERS"),INJECTABLE_METADATA:Symbol("INJECTABLE_METADATA"),DEPENDENCIES_METADATA:Symbol("DEPENDENCIES_METADATA"),SCOPE_METADATA:Symbol("SCOPE_METADATA"),POST_CONSTRUCT:Symbol("POST_CONSTRUCT"),PRE_DESTROY:Symbol("PRE_DESTROY"),SELF:Symbol("DI_SELF"),OPTIONAL:Symbol("DI_OPTIONAL"),MULTIPLE:Symbol("DI_MULTIPLE")},N={defaultScope:"singleton",autoBindInjectable:!0,skipBaseClassChecks:!1,throwOnMissingDependencies:!0,enableCaching:!0,maxCacheSize:1e3},Y={SINGLETON:"singleton",PROTOTYPE:"prototype",TRANSIENT:"transient"},z={SERVICE_REGISTERED:"service:registered",SERVICE_RESOLVED:"service:resolved",SERVICE_CREATED:"service:created",SERVICE_DISPOSED:"service:disposed",CONTAINER_DISPOSED:"container:disposed",DEPENDENCY_RESOLVED:"dependency:resolved",CIRCULAR_DEPENDENCY:"circular:dependency",MISSING_DEPENDENCY:"missing:dependency"},$={INJECTABLE:"design:injectable",INJECT:"design:inject",SCOPE:"design:scope",POST_CONSTRUCT:"design:postconstruct",PRE_DESTROY:"design:predestroy",OPTIONAL:"design:optional",SELF:"design:self",MULTIPLE:"design:multiple"},H={SERVICE_NOT_FOUND:t=>`Service not found: ${t}`,CIRCULAR_DEPENDENCY:t=>`Circular dependency detected: ${t.join(" -> ")}`,INVALID_PROVIDER:t=>`Invalid provider: ${t}`,CONTAINER_DISPOSED:"Container has been disposed",INVALID_SCOPE:t=>`Invalid scope: ${t}`,ABSTRACT_CLASS:t=>`Cannot instantiate abstract class: ${t}`,MISSING_DEPENDENCY:(t,e)=>`Missing dependency ${t} in ${e}`,INVALID_TOKEN:t=>`Invalid service token: ${t}`,REGISTRATION_FAILED:(t,e)=>`Failed to register ${t}: ${e}`,RESOLUTION_FAILED:(t,e)=>`Failed to resolve ${t}: ${e}`},W={MAX_RESOLUTION_DEPTH:100,MAX_CIRCULAR_REFERENCES:10,DEFAULT_CACHE_SIZE:1e3,DEFAULT_TIMEOUT_MS:5e3,GC_INTERVAL_MS:6e4,STATS_COLLECTION_INTERVAL_MS:3e4},J={ENABLE_ASYNC_RESOLUTION:!0,ENABLE_LAZY_LOADING:!0,ENABLE_PROXY_SERVICES:!0,ENABLE_AOP_SUPPORT:!1,ENABLE_PERFORMANCE_MONITORING:!0,ENABLE_DEBUG_LOGGING:!1,ENABLE_STRICT_MODE:!0},ve={TOKENS:{...U,...j,...K},DEFAULTS:{CONTAINER_OPTIONS:N,SCOPES:Y},EVENTS:z,DECORATORS:$,ERRORS:H,PERFORMANCE:W,FEATURES:J};var c=class t{constructor(e={},n){l(this,"registrations",new Map);l(this,"instances",new Map);l(this,"children",new Set);l(this,"options");l(this,"parent");l(this,"disposed",!1);this.options={...N,...e},this.parent=n,n&&n.children.add(this)}register(e,n={}){if(this.throwIfDisposed(),!e||!e.token)throw new d("Provider must have a valid token");this.validateProvider(e);let i={token:e.token,provider:e,options:{scope:n.scope||e.scope||this.options.defaultScope||"singleton",lazy:n.lazy??!0,tags:n.tags||[],...n.onActivation&&{onActivation:n.onActivation},...n.onDeactivation&&{onDeactivation:n.onDeactivation}},dependencies:this.extractDependencies(e),metadata:(()=>{let r=this.getSourceLocation();return{registeredAt:new Date,...r&&{sourceLocation:r}}})()};return this.registrations.set(e.token,i),this.options.autoBindInjectable&&I(e)&&this.autoBindInjectableClass(e.useClass),this}bind(e){return new w(e,this)}resolve(e){this.throwIfDisposed();let n={container:this,resolutionStack:[],cache:new Map,isOptional:!1};return this.resolveWithContext(e,n)}tryResolve(e){try{return this.resolve(e)}catch(n){if(n instanceof f)return;throw n}}has(e){return this.registrations.has(e)||(this.parent?.has(e)??!1)}unbind(e){this.throwIfDisposed();let n=this.instances.get(e);return n&&(this.disposeInstance(n,e),this.instances.delete(e)),this.registrations.delete(e)}createChild(e={}){return this.throwIfDisposed(),new t(e,this)}getParent(){return this.parent}getServices(){let e=Array.from(this.registrations.keys());return this.parent&&e.push(...this.parent.getServices()),[...new Set(e)]}clear(){this.throwIfDisposed();for(let[e,n]of this.instances)this.disposeInstance(n,e);this.instances.clear(),this.registrations.clear()}async dispose(){if(!this.disposed){this.disposed=!0;for(let e of this.children)await e.dispose();this.children.clear();for(let[e,n]of this.instances)this.disposeInstance(n,e);this.instances.clear(),this.registrations.clear(),this.parent&&this.parent.children.delete(this)}}resolveWithContext(e,n){if(n.resolutionStack.includes(e))throw new v([...n.resolutionStack,e],e);if(n.cache.has(e))return n.cache.get(e);let i=this.findRegistration(e);if(!i){if(this.options.throwOnMissingDependencies&&!n.isOptional)throw new f(e);return}let r=i.options.scope||"singleton";if(r==="singleton"){let o=this.instances.get(e);if(o)return o.lastAccessed=new Date,o.accessCount++,o.instance}n.resolutionStack.push(e);try{let o=this.createInstance(i,n);if(r==="singleton"){let p={instance:o,scope:r,createdAt:new Date,lastAccessed:new Date,accessCount:1,disposed:!1};this.instances.set(e,p)}return n.cache.set(e,o),i.options.onActivation&&i.options.onActivation(o),o}finally{n.resolutionStack.pop()}}createInstance(e,n){let{provider:i}=e;if(I(i))return this.createClassInstance(i.useClass,n);if(_(i))return i.useValue;if(C(i)){let r=this.resolveDependencies(i.deps||[],n);return i.useFactory(...r)}if(O(i))return this.resolveWithContext(i.useExisting,n);throw new d(`Unknown provider type for token: ${String(i.token)}`,i.token)}createClassInstance(e,n){let i=this.getConstructorDependencies(e),r=this.resolveDependencies(i,n),o=new e(...r);return this.injectProperties(o,n),this.callLifecycleMethods(o,"postConstruct"),o}getConstructorDependencies(e){return h(e)?.dependencies||[]}resolveDependencies(e,n){return e.map(i=>{let r={...n,isOptional:!1};return this.resolveWithContext(i,r)})}injectProperties(e,n){let i=R(e.constructor.prototype);if(i){for(let[r,o]of i)if(o.inject&&o.token)try{let p={...n,isOptional:o.optional||!1},F=this.resolveWithContext(o.token,p);F!==void 0&&(e[r]=F)}catch(p){if(!o.optional)throw p}}}callLifecycleMethods(e,n){let i=M(e.constructor.prototype);if(i){for(let[r,o]of i)if(o.lifecycle===n){let p=e[r];typeof p=="function"&&p.call(e)}}}findRegistration(e){let n=this.registrations.get(e);if(n)return n;if(this.parent)return this.parent.findRegistration(e)}validateProvider(e){if(I(e)){if(!e.useClass||typeof e.useClass!="function")throw new d("ClassProvider must have a valid useClass constructor")}else if(C(e)){if(!e.useFactory||typeof e.useFactory!="function")throw new d("FactoryProvider must have a valid useFactory function")}else if(O(e)&&!e.useExisting)throw new d("ExistingProvider must have a valid useExisting token")}extractDependencies(e){return I(e)?this.getConstructorDependencies(e.useClass):C(e)?e.deps||[]:[]}autoBindInjectableClass(e){let n=h(e);n?.injectable&&(n.dependencies||[]).forEach(r=>{typeof r=="function"&&!this.has(r)&&this.register({type:"class",token:r,useClass:r})})}disposeInstance(e,n){if(e.disposed)return;this.callLifecycleMethods(e.instance,"preDestroy");let i=this.registrations.get(n);i?.options.onDeactivation&&i.options.onDeactivation(e.instance),e.disposed=!0}getSourceLocation(){let e=new Error().stack;if(e){let n=e.split(`
`);for(let i=3;i<n.length;i++){let r=n[i];if(r&&!r.includes("Container.ts")&&!r.includes("node_modules"))return r.trim()}}}throwIfDisposed(){if(this.disposed)throw new T("Container has been disposed")}},w=class{constructor(e,n){this.token=e;this.container=n}to(e){return new b(this.token,this.container,{type:"class",token:this.token,useClass:e})}toValue(e){return this.container.register({type:"value",token:this.token,useValue:e}),new a}toFactory(e){return new L(this.token,this.container,e)}toExisting(e){return this.container.register({type:"existing",token:this.token,useExisting:e}),new a}toSelf(){if(typeof this.token!="function")throw new d("toSelf() can only be used with class tokens");return this.to(this.token)}},b=class{constructor(e,n,i){this.token=e;this.container=n;this.provider=i}inSingletonScope(){return this.container.register(this.provider,{scope:"singleton"}),new a}inPrototypeScope(){return this.container.register(this.provider,{scope:"prototype"}),new a}inTransientScope(){return this.container.register(this.provider,{scope:"transient"}),new a}inScope(e){return this.container.register(this.provider,{scope:e}),new a}withOptions(e){return this.container.register(this.provider,e),new a}},L=class{constructor(e,n,i){this.token=e;this.container=n;this.factory=i;l(this,"deps",[])}withDependencies(...e){return this.deps=e,this.container.register({type:"factory",token:this.token,useFactory:this.factory,deps:this.deps}),new a}inSingletonScope(){return this.container.register({type:"factory",token:this.token,useFactory:this.factory,deps:this.deps,scope:"singleton"}),new a}inPrototypeScope(){return this.container.register({type:"factory",token:this.token,useFactory:this.factory,deps:this.deps,scope:"prototype"}),new a}inTransientScope(){return this.container.register({type:"factory",token:this.token,useFactory:this.factory,deps:this.deps,scope:"transient"}),new a}inScope(e){return this.container.register({type:"factory",token:this.token,useFactory:this.factory,deps:this.deps,scope:e}),new a}withOptions(e){return this.container.register({type:"factory",token:this.token,useFactory:this.factory,deps:this.deps},e),new a}},a=class{};var P=class{static create(e){return new c(e)}static createSingletonContainer(){return new c({defaultScope:"singleton",enableCaching:!0,autoBindInjectable:!0,throwOnMissingDependencies:!0})}static createPrototypeContainer(){return new c({defaultScope:"prototype",enableCaching:!1,autoBindInjectable:!0,throwOnMissingDependencies:!0})}static createTestContainer(){return new c({defaultScope:"singleton",enableCaching:!0,autoBindInjectable:!1,throwOnMissingDependencies:!1,skipBaseClassChecks:!0})}static createStrictContainer(){return new c({defaultScope:"singleton",enableCaching:!0,autoBindInjectable:!0,throwOnMissingDependencies:!0,skipBaseClassChecks:!1,maxCacheSize:500})}static createHighPerformanceContainer(){return new c({defaultScope:"singleton",enableCaching:!0,autoBindInjectable:!0,throwOnMissingDependencies:!0,maxCacheSize:2e3})}};
//# sourceMappingURL=index.js.map