ts5deco-inject
Version:
TypeScript 5 Modern Decorator Dependency Injection Framework
4 lines (3 loc) • 14.6 kB
JavaScript
var F=Object.defineProperty;var k=(n,e,t)=>e in n?F(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var l=(n,e,t)=>k(n,typeof e!="symbol"?e+"":e,t);var S=new WeakMap,y=new WeakMap,u=new WeakMap;function s(n){return{key:Symbol(n),description:n}}function f(n,e){let t=S.get(n)||{};S.set(n,{...t,...e})}function g(n){return S.get(n)}function _(n,e,t){let i=y.get(n);i||(i=new Map,y.set(n,i));let r=i.get(e)||{};i.set(e,{...r,...t})}function Z(n,e){return y.get(n)?.get(e)}function h(n,e,t){let i=u.get(n);i||(i=new Map,u.set(n,i));let r=i.get(e)||{};i.set(e,{...r,...t})}function q(n,e){return u.get(n)?.get(e)}function m(n){return y.get(n)}function w(n){return u.get(n)}function ee(n){return S.has(n)}function te(n,e){return y.get(n)?.has(e)??!1}function ne(n,e){return u.get(n)?.has(e)??!1}function ie(n){S.delete(n),y.delete(n.prototype),u.delete(n.prototype)}function se(n="singleton"){return function(e,t){return f(e,{injectable:!0,scope:n}),e}}function ae(n,e=!1){return function(t,i){i.addInitializer(function(){_(this.constructor.prototype,i.name,{token:n,optional:e,inject:!0})})}}function ce(n,e){return f(n,{scope:"singleton"}),n}function de(n){return function(e,t){return f(e,{scope:n}),e}}function pe(n,e){return e.addInitializer(function(){h(this.constructor.prototype,e.name,{lifecycle:"postConstruct"})}),n}function le(n,e){return e.addInitializer(function(){h(this.constructor.prototype,e.name,{lifecycle:"preDestroy"})}),n}function Te(n,e){return function(t,i){return f(t,{providers:[{token:n,value:e}]}),t}}var ye=s("design:type"),ue=s("design:paramtypes"),Se=s("design:returntype");var x=(i=>(i.SINGLETON="singleton",i.PROTOTYPE="prototype",i.TRANSIENT="transient",i))(x||{}),B=(t=>(t.POST_CONSTRUCT="postConstruct",t.PRE_DESTROY="preDestroy",t))(B||{}),G=(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))(G||{}),T=class extends Error{constructor(t,i){super(t);this.token=i;this.name="ContainerError"}},v=class extends T{constructor(t,i){super(`Circular dependency detected: ${t.map(r=>String(r)).join(" -> ")}`,i);this.dependencyChain=t;this.name="CircularDependencyError"}},I=class extends T{constructor(e){super(`Service not found: ${String(e)}`,e),this.name="ServiceNotFoundError"}},d=class extends T{constructor(e,t){super(e,t),this.name="InvalidProviderError"}};function E(n){return n.type==="class"}function b(n){return n.type==="value"}function C(n){return n.type==="factory"}function D(n){return n.type==="existing"}var V=(i=>(i.THROW_ON_MISSING="throw",i.RETURN_UNDEFINED="undefined",i.USE_DEFAULT="default",i))(V||{}),U=(r=>(r.REGISTERED="registered",r.CREATING="creating",r.CREATED="created",r.DISPOSED="disposed",r))(U||{}),L=class extends Error{constructor(t,i,r){super(t);this.token=i;this.serviceType=r;this.name="TypedContainerError"}};var j={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")},K={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"},Y={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")},O={defaultScope:"singleton",autoBindInjectable:!0,skipBaseClassChecks:!1,throwOnMissingDependencies:!0,enableCaching:!0,maxCacheSize:1e3},z={SINGLETON:"singleton",PROTOTYPE:"prototype",TRANSIENT:"transient"},$={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"},H={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"},W={SERVICE_NOT_FOUND:n=>`Service not found: ${n}`,CIRCULAR_DEPENDENCY:n=>`Circular dependency detected: ${n.join(" -> ")}`,INVALID_PROVIDER:n=>`Invalid provider: ${n}`,CONTAINER_DISPOSED:"Container has been disposed",INVALID_SCOPE:n=>`Invalid scope: ${n}`,ABSTRACT_CLASS:n=>`Cannot instantiate abstract class: ${n}`,MISSING_DEPENDENCY:(n,e)=>`Missing dependency ${n} in ${e}`,INVALID_TOKEN:n=>`Invalid service token: ${n}`,REGISTRATION_FAILED:(n,e)=>`Failed to register ${n}: ${e}`,RESOLUTION_FAILED:(n,e)=>`Failed to resolve ${n}: ${e}`},J={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},X={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},Ce={TOKENS:{...j,...K,...Y},DEFAULTS:{CONTAINER_OPTIONS:O,SCOPES:z},EVENTS:$,DECORATORS:H,ERRORS:W,PERFORMANCE:J,FEATURES:X};var c=class n{constructor(e={},t){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={...O,...e},this.parent=t,t&&t.children.add(this)}register(e,t={}){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:t.scope||e.scope||this.options.defaultScope||"singleton",lazy:t.lazy??!0,tags:t.tags||[],...t.onActivation&&{onActivation:t.onActivation},...t.onDeactivation&&{onDeactivation:t.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&&E(e)&&this.autoBindInjectableClass(e.useClass),this}bind(e){return new N(e,this)}resolve(e){this.throwIfDisposed();let t={container:this,resolutionStack:[],cache:new Map,isOptional:!1};return this.resolveWithContext(e,t)}tryResolve(e){try{return this.resolve(e)}catch(t){if(t instanceof I)return;throw t}}has(e){return this.registrations.has(e)||(this.parent?.has(e)??!1)}unbind(e){this.throwIfDisposed();let t=this.instances.get(e);return t&&(this.disposeInstance(t,e),this.instances.delete(e)),this.registrations.delete(e)}createChild(e={}){return this.throwIfDisposed(),new n(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,t]of this.instances)this.disposeInstance(t,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,t]of this.instances)this.disposeInstance(t,e);this.instances.clear(),this.registrations.clear(),this.parent&&this.parent.children.delete(this)}}resolveWithContext(e,t){if(t.resolutionStack.includes(e))throw new v([...t.resolutionStack,e],e);if(t.cache.has(e))return t.cache.get(e);let i=this.findRegistration(e);if(!i){if(this.options.throwOnMissingDependencies&&!t.isOptional)throw new I(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}t.resolutionStack.push(e);try{let o=this.createInstance(i,t);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 t.cache.set(e,o),i.options.onActivation&&i.options.onActivation(o),o}finally{t.resolutionStack.pop()}}createInstance(e,t){let{provider:i}=e;if(E(i))return this.createClassInstance(i.useClass,t);if(b(i))return i.useValue;if(C(i)){let r=this.resolveDependencies(i.deps||[],t);return i.useFactory(...r)}if(D(i))return this.resolveWithContext(i.useExisting,t);throw new d(`Unknown provider type for token: ${String(i.token)}`,i.token)}createClassInstance(e,t){let i=this.getConstructorDependencies(e),r=this.resolveDependencies(i,t),o=new e(...r);return this.injectProperties(o,t),this.callLifecycleMethods(o,"postConstruct"),o}getConstructorDependencies(e){return g(e)?.dependencies||[]}resolveDependencies(e,t){return e.map(i=>{let r={...t,isOptional:!1};return this.resolveWithContext(i,r)})}injectProperties(e,t){let i=m(e.constructor.prototype);if(i){for(let[r,o]of i)if(o.inject&&o.token)try{let p={...t,isOptional:o.optional||!1},M=this.resolveWithContext(o.token,p);M!==void 0&&(e[r]=M)}catch(p){if(!o.optional)throw p}}}callLifecycleMethods(e,t){let i=w(e.constructor.prototype);if(i){for(let[r,o]of i)if(o.lifecycle===t){let p=e[r];typeof p=="function"&&p.call(e)}}}findRegistration(e){let t=this.registrations.get(e);if(t)return t;if(this.parent)return this.parent.findRegistration(e)}validateProvider(e){if(E(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(D(e)&&!e.useExisting)throw new d("ExistingProvider must have a valid useExisting token")}extractDependencies(e){return E(e)?this.getConstructorDependencies(e.useClass):C(e)?e.deps||[]:[]}autoBindInjectableClass(e){let t=g(e);t?.injectable&&(t.dependencies||[]).forEach(r=>{typeof r=="function"&&!this.has(r)&&this.register({type:"class",token:r,useClass:r})})}disposeInstance(e,t){if(e.disposed)return;this.callLifecycleMethods(e.instance,"preDestroy");let i=this.registrations.get(t);i?.options.onDeactivation&&i.options.onDeactivation(e.instance),e.disposed=!0}getSourceLocation(){let e=new Error().stack;if(e){let t=e.split(`
`);for(let i=3;i<t.length;i++){let r=t[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")}},N=class{constructor(e,t){this.token=e;this.container=t}to(e){return new P(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 A(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)}},P=class{constructor(e,t,i){this.token=e;this.container=t;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}},A=class{constructor(e,t,i){this.token=e;this.container=t;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 R=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})}};export{Ce as CONSTANTS,$ as CONTAINER_EVENTS,v as CircularDependencyError,c as Container,T as ContainerError,G as ContainerEvent,R as ContainerFactory,H as DECORATOR_KEYS,O as DEFAULT_CONTAINER_OPTIONS,z as DEFAULT_SCOPES,ue as DESIGN_PARAM_TYPES,Se as DESIGN_RETURN_TYPE,ye as DESIGN_TYPE,W as ERROR_MESSAGES,X as FEATURE_FLAGS,ae as Inject,se as Injectable,d as InvalidProviderError,J as PERFORMANCE_CONSTANTS,j as PREDEFINED_TOKENS,pe as PostConstruct,le as PreDestroy,Te as Provide,V as ResolutionStrategy,K as STRING_TOKENS,Y as SYMBOL_TOKENS,de as Scope,B as ServiceLifecycle,I as ServiceNotFoundError,x as ServiceScope,U as ServiceState,ce as Singleton,L as TypedContainerError,ie as clearClassMetadata,s as createMetadataKey,w as getAllMethodMetadata,m as getAllPropertyMetadata,g as getClassMetadata,q as getMethodMetadata,Z as getPropertyMetadata,ee as hasClassMetadata,ne as hasMethodMetadata,te as hasPropertyMetadata,E as isClassProvider,D as isExistingProvider,C as isFactoryProvider,b as isValueProvider,f as setClassMetadata,h as setMethodMetadata,_ as setPropertyMetadata};
//# sourceMappingURL=index.mjs.map