@kaokei/di 5.0.3 → 5.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -14,12 +14,11 @@
14
14
 
15
15
  本库主要特点是参考借鉴了`InversifyJS`和`Angular`的优秀 API 设计,不依赖`reflect-metadata`,支持属性注入的循环依赖。
16
16
 
17
- - [入门指南](./docs/guide/index.md)
17
+ - [快速开始](./docs/guide/index.md)
18
18
  - [API 文档](./docs/api/index.md)
19
- - [博客文章](./docs/note/01.什么是Token.md)
20
- - [CodeSandbox 在线示例](./docs/guide/EXAMPLES.md)
19
+ - [示例代码](./docs/examples/index.md)
20
+ - [笔记文章](./docs/note/01.什么是Token.md)
21
21
 
22
22
  ## Todo List
23
23
 
24
24
  1. 改成tsdown来打包代码
25
- 2. 源码-->单元测试-->文档-->示例代码
@@ -6,9 +6,9 @@ export interface InjectPropertiesResult {
6
6
  bindings: Binding[];
7
7
  }
8
8
  export declare class Binding<T = unknown> {
9
- static _resolvers: Record<string, string>;
10
- container: Container;
11
- context: Context;
9
+ static _resolvers: Map<string, (this: Binding, options: Options) => unknown>;
10
+ container?: Container;
11
+ context?: Context;
12
12
  token: CommonToken<T>;
13
13
  type: BindingType;
14
14
  status: StatusType;
@@ -31,7 +31,7 @@ export declare class Binding<T = unknown> {
31
31
  toDynamicValue(func: DynamicValue<T>): this;
32
32
  inTransientScope(): this;
33
33
  toService(token: CommonToken<T>): this;
34
- get(options: Options<T>): any;
34
+ get(options: Options<T>): unknown;
35
35
  _getAwaitBindings(bindings: Binding[], filter: PostConstructParam): Binding[];
36
36
  /**
37
37
  * PostConstruct 生命周期处理
package/dist/binding.d.ts CHANGED
@@ -6,9 +6,9 @@ export interface InjectPropertiesResult {
6
6
  bindings: Binding[];
7
7
  }
8
8
  export declare class Binding<T = unknown> {
9
- static _resolvers: Record<string, string>;
10
- container: Container;
11
- context: Context;
9
+ static _resolvers: Map<string, (this: Binding, options: Options) => unknown>;
10
+ container?: Container;
11
+ context?: Context;
12
12
  token: CommonToken<T>;
13
13
  type: BindingType;
14
14
  status: StatusType;
@@ -31,7 +31,7 @@ export declare class Binding<T = unknown> {
31
31
  toDynamicValue(func: DynamicValue<T>): this;
32
32
  inTransientScope(): this;
33
33
  toService(token: CommonToken<T>): this;
34
- get(options: Options<T>): any;
34
+ get(options: Options<T>): unknown;
35
35
  _getAwaitBindings(bindings: Binding[], filter: PostConstructParam): Binding[];
36
36
  /**
37
37
  * PostConstruct 生命周期处理
@@ -1,34 +1,38 @@
1
1
  import { Binding } from './binding';
2
- import { Options, CommonToken, ActivationHandler, DeactivationHandler } from './interfaces';
2
+ import { GetOptions, Options, CommonToken, ActivationHandler, DeactivationHandler } from './interfaces';
3
3
  export declare class Container {
4
4
  static _instanceContainerMap: WeakMap<object, Container>;
5
5
  static getContainerOf(instance: object): Container | undefined;
6
6
  parent?: Container;
7
7
  children?: Set<Container>;
8
8
  _bindings: Map<CommonToken, Binding>;
9
+ _destroyed: boolean;
9
10
  _onActivationHandler?: ActivationHandler;
10
11
  _onDeactivationHandler?: DeactivationHandler;
11
12
  bind<T>(token: CommonToken<T>): Binding<T>;
12
13
  unbind<T>(token: CommonToken<T>): void;
14
+ tryGet<T>(token: CommonToken<T>): T | undefined;
15
+ rebind<T>(token: CommonToken<T>): Binding<T>;
13
16
  unbindAll(): void;
14
17
  isCurrentBound<T>(token: CommonToken<T>): boolean;
15
18
  isBound<T>(token: CommonToken<T>): boolean;
16
19
  createChild(): Container;
17
20
  destroy(): void;
18
- get<T>(token: CommonToken<T>, options: Options<T> & {
21
+ get<T>(token: CommonToken<T>, options: GetOptions & {
19
22
  optional: true;
20
23
  }): T | void;
21
- get<T>(token: CommonToken<T>, options?: Options<T> & {
24
+ get<T>(token: CommonToken<T>, options?: GetOptions & {
22
25
  optional?: false;
23
26
  }): T;
24
- get<T>(token: CommonToken<T>, options?: Options<T>): T | void;
25
- getAsync<T>(token: CommonToken<T>, options: Options<T> & {
27
+ get<T>(token: CommonToken<T>, options?: GetOptions): T | void;
28
+ getAsync<T>(token: CommonToken<T>, options: GetOptions & {
26
29
  optional: true;
27
30
  }): Promise<T | void>;
28
- getAsync<T>(token: CommonToken<T>, options?: Options<T> & {
31
+ getAsync<T>(token: CommonToken<T>, options?: GetOptions & {
29
32
  optional?: false;
30
33
  }): Promise<T>;
31
- getAsync<T>(token: CommonToken<T>, options?: Options<T>): Promise<T | void>;
34
+ getAsync<T>(token: CommonToken<T>, options?: GetOptions): Promise<T | void>;
35
+ _resolveWithInternalOpts<T>(token: CommonToken<T>, options: Options<T>): T | void;
32
36
  _resolveSkipSelf<T>(token: CommonToken<T>, options: Options<T>): T | void;
33
37
  _resolveSelf<T>(token: CommonToken<T>, options: Options<T>): T | void;
34
38
  _resolveDefault<T>(token: CommonToken<T>, options: Options<T>): T | void;
@@ -1,34 +1,38 @@
1
1
  import { Binding } from './binding';
2
- import { Options, CommonToken, ActivationHandler, DeactivationHandler } from './interfaces';
2
+ import { GetOptions, Options, CommonToken, ActivationHandler, DeactivationHandler } from './interfaces';
3
3
  export declare class Container {
4
4
  static _instanceContainerMap: WeakMap<object, Container>;
5
5
  static getContainerOf(instance: object): Container | undefined;
6
6
  parent?: Container;
7
7
  children?: Set<Container>;
8
8
  _bindings: Map<CommonToken, Binding>;
9
+ _destroyed: boolean;
9
10
  _onActivationHandler?: ActivationHandler;
10
11
  _onDeactivationHandler?: DeactivationHandler;
11
12
  bind<T>(token: CommonToken<T>): Binding<T>;
12
13
  unbind<T>(token: CommonToken<T>): void;
14
+ tryGet<T>(token: CommonToken<T>): T | undefined;
15
+ rebind<T>(token: CommonToken<T>): Binding<T>;
13
16
  unbindAll(): void;
14
17
  isCurrentBound<T>(token: CommonToken<T>): boolean;
15
18
  isBound<T>(token: CommonToken<T>): boolean;
16
19
  createChild(): Container;
17
20
  destroy(): void;
18
- get<T>(token: CommonToken<T>, options: Options<T> & {
21
+ get<T>(token: CommonToken<T>, options: GetOptions & {
19
22
  optional: true;
20
23
  }): T | void;
21
- get<T>(token: CommonToken<T>, options?: Options<T> & {
24
+ get<T>(token: CommonToken<T>, options?: GetOptions & {
22
25
  optional?: false;
23
26
  }): T;
24
- get<T>(token: CommonToken<T>, options?: Options<T>): T | void;
25
- getAsync<T>(token: CommonToken<T>, options: Options<T> & {
27
+ get<T>(token: CommonToken<T>, options?: GetOptions): T | void;
28
+ getAsync<T>(token: CommonToken<T>, options: GetOptions & {
26
29
  optional: true;
27
30
  }): Promise<T | void>;
28
- getAsync<T>(token: CommonToken<T>, options?: Options<T> & {
31
+ getAsync<T>(token: CommonToken<T>, options?: GetOptions & {
29
32
  optional?: false;
30
33
  }): Promise<T>;
31
- getAsync<T>(token: CommonToken<T>, options?: Options<T>): Promise<T | void>;
34
+ getAsync<T>(token: CommonToken<T>, options?: GetOptions): Promise<T | void>;
35
+ _resolveWithInternalOpts<T>(token: CommonToken<T>, options: Options<T>): T | void;
32
36
  _resolveSkipSelf<T>(token: CommonToken<T>, options: Options<T>): T | void;
33
37
  _resolveSelf<T>(token: CommonToken<T>, options: Options<T>): T | void;
34
38
  _resolveDefault<T>(token: CommonToken<T>, options: Options<T>): T | void;
@@ -1,5 +1,5 @@
1
1
  import { BaseError } from './BaseError';
2
- import { CommonToken } from '../interfaces';
2
+ import { CommonToken, Options } from '../interfaces';
3
3
  export declare class BindingNotFoundError extends BaseError {
4
- constructor(token: CommonToken);
4
+ constructor(token: CommonToken, options?: Options);
5
5
  }
@@ -1,5 +1,5 @@
1
1
  import { BaseError } from './BaseError';
2
- import { CommonToken } from '../interfaces';
2
+ import { CommonToken, Options } from '../interfaces';
3
3
  export declare class BindingNotFoundError extends BaseError {
4
- constructor(token: CommonToken);
4
+ constructor(token: CommonToken, options?: Options);
5
5
  }
@@ -0,0 +1,5 @@
1
+ import { BaseError } from './BaseError';
2
+ import { CommonToken } from '../interfaces';
3
+ export declare class ContainerDestroyedError extends BaseError {
4
+ constructor(token: CommonToken);
5
+ }
@@ -0,0 +1,5 @@
1
+ import { BaseError } from './BaseError';
2
+ import { CommonToken } from '../interfaces';
3
+ export declare class ContainerDestroyedError extends BaseError {
4
+ constructor(token: CommonToken);
5
+ }
package/dist/index.cjs CHANGED
@@ -1 +1,3 @@
1
- "use strict";var z=Object.defineProperty;var U=(n,t,e)=>t in n?z(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var o=(n,t,e)=>U(n,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u={INJECTED_PROPS:"injected:props",INJECT:"inject",SELF:"self",SKIP_SELF:"skipSelf",OPTIONAL:"optional",POST_CONSTRUCT:"postConstruct",PRE_DESTROY:"preDestroy"},f={DEFAULT:"default",INITING:"initing",ACTIVATED:"activated"},p={INVALID:"Invalid",INSTANCE:"Instance",CONSTANT:"ConstantValue",DYNAMIC:"DynamicValue"},N={POST_CONSTRUCT:"Multiple @PostConstruct decorators are not allowed in a single class.",PRE_DESTROY:"Multiple @PreDestroy decorators are not allowed in a single class.",INVALID_TOKEN:"@Inject or @LazyInject requires a valid token, but received null or undefined.",LAZY_INJECT_INVALID_TOKEN:"@LazyInject requires a valid token, but received null or undefined."},D=Symbol("UNINITIALIZED");function _(n,t){return Object.prototype.hasOwnProperty.call(n,t)}function Y(n){return n!==null&&typeof n=="object"}const y=new WeakMap;function O(n){return typeof n=="function"&&Object.getPrototypeOf(n)!==Function.prototype}function P(n,t){y.set(n,t)}function V(n){const t=y.get(n);if(t)return t[u.POST_CONSTRUCT];if(O(n))return V(Object.getPrototypeOf(n))}function j(n){const t=y.get(n);if(t)return t[u.PRE_DESTROY];if(O(n))return j(Object.getPrototypeOf(n))}function w(n){const t=y.get(n),e=t&&_(t,u.INJECTED_PROPS)?t[u.INJECTED_PROPS]:void 0;if(!O(n))return e;const i=w(Object.getPrototypeOf(n));if(i||e)return Object.assign({},i,e)}class J{constructor(t){o(this,"name");this.name=t}}class R{constructor(t){o(this,"_callback");this._callback=t}resolve(){return this._callback()}}function b(n){if(!n)throw new Error(N.INVALID_TOKEN);return n instanceof R?n.resolve():n}class v extends Error{constructor(e,i){const s=(i==null?void 0:i.name)||"<unknown token>";super(`${e}${s}`);o(this,"token");this.name=this.constructor.name,this.token=i}}class m extends v{constructor(t){super("");const e=[];let i=t;for(;i&&i.token;)e.push(i.token),i=i.parent;const s=e.reverse().map(r=>r.name||"<anonymous>").join(" --> ");this.message=`Circular dependency found: ${s}`}}class L extends v{constructor(t){super("Invalid binding: ",t)}}class k extends m{constructor(t){super(t),this.name="CircularDependencyError inside @PostConstruct"}}const E=class E{constructor(t,e){o(this,"container");o(this,"context");o(this,"token");o(this,"type",p.INVALID);o(this,"status",f.DEFAULT);o(this,"classValue");o(this,"constantValue");o(this,"dynamicValue");o(this,"cache");o(this,"postConstructResult",D);o(this,"transient",!1);o(this,"onActivationHandler");o(this,"onDeactivationHandler");this.container=e,this.context={container:this.container},this.token=t}onActivation(t){this.onActivationHandler=t}onDeactivation(t){this.onDeactivationHandler=t}activate(t){const e=this.onActivationHandler?this.onActivationHandler(this.context,t):t;return this.container.activate(e,this.token)}deactivate(){this.onDeactivationHandler&&this.onDeactivationHandler(this.cache)}to(t){return this.type=p.INSTANCE,this.classValue=t,this}toSelf(){return this.to(this.token)}toConstantValue(t){return this.type=p.CONSTANT,this.constantValue=t,this}toDynamicValue(t){return this.type=p.DYNAMIC,this.dynamicValue=t,this}inTransientScope(){return this.transient=!0,this}toService(t){return this.toDynamicValue(e=>e.container.get(t,{parent:{token:this.token}}))}get(t){if(f.INITING===this.status)throw new m(t);if(f.ACTIVATED===this.status)if(this.transient)this.status=f.DEFAULT;else return this.cache;const e=E._resolvers[this.type];if(e)return this[e](t);throw new L(this.token)}_getAwaitBindings(t,e){return e===!0?t:Array.isArray(e)?t.filter(i=>e.includes(i.token)):typeof e=="function"?t.filter(e):[]}_postConstruct(t,e){if(p.INSTANCE===this.type){const{key:i,value:s}=V(this.classValue)||{};if(i)if(s){const r=e.filter(c=>p.INSTANCE===(c==null?void 0:c.type)),a=this._getAwaitBindings(r,s);for(const c of a)if(c&&c.postConstructResult===D)throw new k({token:c.token,parent:t});const l=a.map(c=>c.postConstructResult);this.postConstructResult=Promise.all(l).then(()=>this._execute(i))}else this.postConstructResult=this._execute(i);else this.postConstructResult=void 0}}preDestroy(){if(p.INSTANCE===this.type){const{key:t}=j(this.classValue)||{};t&&this._execute(t)}I._instanceContainerMap.delete(this.cache),this.container=null,this.context=null,this.classValue=void 0,this.constantValue=void 0,this.dynamicValue=void 0,this.cache=void 0,this.postConstructResult=D,this.onActivationHandler=void 0,this.onDeactivationHandler=void 0}_execute(t){const e=this.cache[t];return e==null?void 0:e.call(this.cache)}_resolveInstanceValue(t){this.status=f.INITING;const e=this._createInstance();this.cache=this.activate(e),this.status=f.ACTIVATED,this._registerInstance();const{properties:i,bindings:s}=this._getInjectProperties(t);return this._injectProperties(i),this._postConstruct(t,s),this.cache}_createInstance(){const t=this.classValue;return new t}_registerInstance(){I._instanceContainerMap.set(this.cache,this.container)}_injectProperties(t){Object.assign(this.cache,t)}_resolveConstantValue(){return this.status=f.INITING,this.cache=this.activate(this.constantValue),this.status=f.ACTIVATED,this.cache}_resolveDynamicValue(){this.status=f.INITING;const t=this.dynamicValue(this.context);return this.cache=this.activate(t),this.status=f.ACTIVATED,this.cache}_getInjectProperties(t){const e=w(this.classValue)||{},i=Object.keys(e),s=Object.create(null),r=[];for(let a=0;a<i.length;a++){const l=i[a],c=e[l],h=Object.assign({},c);h.parent=t;const d=this.container.get(b(h.inject),h);d===void 0&&h.optional||(s[l]=d),r.push(h.binding)}return{properties:s,bindings:r}}};o(E,"_resolvers",{[p.INSTANCE]:"_resolveInstanceValue",[p.CONSTANT]:"_resolveConstantValue",[p.DYNAMIC]:"_resolveDynamicValue"});let C=E;class B extends v{constructor(t){super("No matching binding found for token: ",t)}}class H extends v{constructor(t){super("Cannot bind token multiple times: ",t)}}const T=class T{constructor(){o(this,"parent");o(this,"children");o(this,"_bindings",new Map);o(this,"_onActivationHandler");o(this,"_onDeactivationHandler")}static getContainerOf(t){return T._instanceContainerMap.get(t)}bind(t){if(this._bindings.has(t))throw new H(t);const e=this._buildBinding(t);return this._bindings.set(t,e),e}unbind(t){if(this._bindings.has(t)){const e=this._getBinding(t);this.deactivate(e),e.deactivate(),e.preDestroy(),this._bindings.delete(t)}}unbindAll(){const t=Array.from(this._bindings.keys());for(const e of t)this.unbind(e)}isCurrentBound(t){return this._bindings.has(t)}isBound(t){return this.isCurrentBound(t)||!!this.parent&&this.parent.isBound(t)}createChild(){const t=new T;return t.parent=this,this.children||(this.children=new Set),this.children.add(t),t}destroy(){var t,e;if(this.children){const i=Array.from(this.children);for(const s of i)s.destroy()}this.unbindAll(),this._bindings.clear(),(e=(t=this.parent)==null?void 0:t.children)==null||e.delete(this),this.parent=void 0,this.children=void 0,this._onActivationHandler=void 0,this._onDeactivationHandler=void 0}get(t,e={}){return e.skipSelf?this._resolveSkipSelf(t,e):e.self?this._resolveSelf(t,e):this._resolveDefault(t,e)}getAsync(t,e={}){let i;try{i=this.get(t,e)}catch(r){return Promise.reject(r)}const s=e.binding;return(s==null?void 0:s.postConstructResult)instanceof Promise?s.postConstructResult.then(()=>i):Promise.resolve(i)}_resolveSkipSelf(t,e){return this.parent?(e.skipSelf=!1,this.parent.get(t,e)):this._checkBindingNotFoundError(t,e)}_resolveSelf(t,e){const i=this._getBinding(t);return i?(e.token=t,e.binding=i,i.get(e)):this._checkBindingNotFoundError(t,e)}_resolveDefault(t,e){const i=this._getBinding(t);return i?(e.token=t,e.binding=i,i.get(e)):this.parent?this.parent.get(t,e):this._checkBindingNotFoundError(t,e)}onActivation(t){this._onActivationHandler=t}onDeactivation(t){this._onDeactivationHandler=t}activate(t,e){return this._onActivationHandler?this._onActivationHandler({container:this},t,e):t}deactivate(t){this._onDeactivationHandler&&this._onDeactivationHandler(t.cache,t.token)}_buildBinding(t){return new C(t,this)}_getBinding(t){return this._bindings.get(t)}_checkBindingNotFoundError(t,e){if(!e.optional)throw new B(t)}};o(T,"_instanceContainerMap",new WeakMap);let I=T;class M extends v{constructor(t,e){super(`@LazyInject(${t==null?void 0:t.name}) in class ${e.name} requires a registered container but none was found. Token: `,t)}}function A(n,t){return function(e){return function(i,s){const r=s.name,a=s.metadata;_(a,u.INJECTED_PROPS)||(a[u.INJECTED_PROPS]={});const l=a[u.INJECTED_PROPS];l[r]||(l[r]={}),l[r][n]=e===void 0?t:e}}}function F(n,t){return e=>(i,s)=>{const r=s.name,a=s.metadata;if(_(a,n))throw new Error(t);a[n]={key:r,value:e}}}const K=A(u.INJECT),G=A(u.SELF,!0),$=A(u.SKIP_SELF,!0),Z=A(u.OPTIONAL,!0),q=F(u.POST_CONSTRUCT,N.POST_CONSTRUCT),W=F(u.PRE_DESTROY,N.PRE_DESTROY);function Q(){return function(n,t){const e=t.metadata;P(n,e)}}function X(n,t,e,i){if(e==null)throw new Error(N.LAZY_INJECT_INVALID_TOKEN);const s=Symbol.for(t);Object.defineProperty(n,t,{configurable:!0,enumerable:!0,get(){if(!_(n,s)){const r=i||I.getContainerOf(n),a=n.constructor;if(!r)throw new M(b(e),a);n[s]=r.get(b(e),{parent:{token:a}})}return n[s]},set(r){n[s]=r}})}function x(n,t){return function(e,i){const s=i.name;i.addInitializer(function(){X(this,s,n,t)})}}function tt(n){return function(t){return x(t,n)}}function et(n,t){const e=t.name;t.addInitializer(function(){this[e]=n.bind(this)})}const S=Symbol("decorate.metadata");function nt(n,t,e){const i=Array.isArray(n)?n:[n],s=t.prototype,r=typeof s[e]=="function",a=[];_(t,S)||(t[S]={});const l=t[S],c={kind:r?"method":"field",name:e,static:!1,private:!1,addInitializer(d){a.push(d)},metadata:l};let h=r?s[e]:void 0;for(let d=i.length-1;d>=0;d--){const g=i[d](h,c);r&&typeof g=="function"&&(h=g)}if(r&&h!==s[e]&&(s[e]=h),P(t,l),a.length>0){const d=Object.create(s);for(const g of a)g.call(d)}}exports.BaseError=v;exports.Binding=C;exports.BindingNotFoundError=B;exports.BindingNotValidError=L;exports.CircularDependencyError=m;exports.Container=I;exports.ContainerNotFoundError=M;exports.DuplicateBindingError=H;exports.ERRORS=N;exports.Inject=K;exports.Injectable=Q;exports.LazyInject=x;exports.LazyToken=R;exports.Optional=Z;exports.PostConstruct=q;exports.PostConstructError=k;exports.PreDestroy=W;exports.Self=G;exports.SkipSelf=$;exports.Token=J;exports.autobind=et;exports.createLazyInject=tt;exports.decorate=nt;exports.hasOwn=_;exports.isObject=Y;
1
+ "use strict";var Y=Object.defineProperty;var J=(n,t,e)=>t in n?Y(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var r=(n,t,e)=>J(n,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const l={INJECTED_PROPS:"injected:props",INJECT:"inject",SELF:"self",SKIP_SELF:"skipSelf",OPTIONAL:"optional",POST_CONSTRUCT:"postConstruct",PRE_DESTROY:"preDestroy"},f={DEFAULT:"default",INITING:"initing",ACTIVATED:"activated"},p={INVALID:"Invalid",INSTANCE:"Instance",CONSTANT:"ConstantValue",DYNAMIC:"DynamicValue"},C={POST_CONSTRUCT:"Multiple @PostConstruct decorators are not allowed in a single class.",PRE_DESTROY:"Multiple @PreDestroy decorators are not allowed in a single class.",INVALID_TOKEN:"@Inject or @LazyInject requires a valid token, but received null or undefined.",LAZY_INJECT_INVALID_TOKEN:"@LazyInject requires a valid token, but received null or undefined."},D=Symbol("UNINITIALIZED");function E(n,t){return Object.prototype.hasOwnProperty.call(n,t)}function G(n){return n!==null&&typeof n=="object"}const O=new WeakMap,y=new WeakMap;function m(n){return typeof n=="function"&&Object.getPrototypeOf(n)!==Function.prototype}function j(n,t){O.set(n,t),y.delete(n)}function V(n){const t=O.get(n);if(t)return t[l.POST_CONSTRUCT];if(m(n))return V(Object.getPrototypeOf(n))}function w(n){const t=O.get(n);if(t)return t[l.PRE_DESTROY];if(m(n))return w(Object.getPrototypeOf(n))}function R(n){if(y.has(n)){const e=y.get(n);return e&&Object.assign({},e)}const t=K(n);return y.set(n,t),t&&Object.assign({},t)}function K(n){const t=O.get(n),e=t&&E(t,l.INJECTED_PROPS)?t[l.INJECTED_PROPS]:void 0;if(!m(n))return e;const i=R(Object.getPrototypeOf(n));if(i||e)return Object.assign({},i,e)}class q{constructor(t){r(this,"name");this.name=t}}class L{constructor(t){r(this,"_callback");this._callback=t}resolve(){return this._callback()}}function A(n){if(!n)throw new Error(C.INVALID_TOKEN);return n instanceof L?n.resolve():n}class _ extends Error{constructor(e,i){const s=(i==null?void 0:i.name)||"<unknown token>";super(`${e}${s}`);r(this,"token");this.name=this.constructor.name,this.token=i}}function B(n){const t=[];let e=n;for(;e&&e.token;)t.push(e.token.name||"<anonymous>"),e=e.parent;return t.reverse()}class P extends _{constructor(t){super(""),this.message="Circular dependency found: "+B(t).join(" --> ")}}class k extends _{constructor(t){super("Binding is not configured (missing .to() / .toSelf() / .toConstantValue() / .toDynamicValue()): ",t)}}class M extends P{constructor(t){super(t),this.name="CircularDependencyError inside @PostConstruct"}}const T=class T{constructor(t,e){r(this,"container");r(this,"context");r(this,"token");r(this,"type",p.INVALID);r(this,"status",f.DEFAULT);r(this,"classValue");r(this,"constantValue");r(this,"dynamicValue");r(this,"cache");r(this,"postConstructResult",D);r(this,"transient",!1);r(this,"onActivationHandler");r(this,"onDeactivationHandler");this.container=e,this.context={container:this.container},this.token=t}onActivation(t){this.onActivationHandler=t}onDeactivation(t){this.onDeactivationHandler=t}activate(t){const e=this.onActivationHandler?this.onActivationHandler(this.context,t):t;return this.container.activate(e,this.token)}deactivate(){this.onDeactivationHandler&&this.onDeactivationHandler(this.cache)}to(t){return this.type=p.INSTANCE,this.classValue=t,this}toSelf(){return this.to(this.token)}toConstantValue(t){return this.type=p.CONSTANT,this.constantValue=t,this}toDynamicValue(t){return this.type=p.DYNAMIC,this.dynamicValue=t,this}inTransientScope(){return this.transient=!0,this}toService(t){return this.toDynamicValue(e=>e.container._resolveWithInternalOpts(t,{parent:{token:this.token}}))}get(t){if(f.INITING===this.status)throw new P(t);if(f.ACTIVATED===this.status)if(this.transient)this.status=f.DEFAULT;else return this.cache;const e=T._resolvers.get(this.type);if(e)return e.call(this,t);throw new k(this.token)}_getAwaitBindings(t,e){return e===!0?t:Array.isArray(e)?t.filter(i=>e.includes(i.token)):typeof e=="function"?t.filter(e):[]}_postConstruct(t,e){if(p.INSTANCE===this.type){const{key:i,value:s}=V(this.classValue)||{};if(i)if(s){const o=e.filter(u=>p.INSTANCE===(u==null?void 0:u.type)),a=this._getAwaitBindings(o,s);for(const u of a)if(u&&u.postConstructResult===D)throw new M({token:u.token,parent:t});const c=a.map(u=>u.postConstructResult);this.postConstructResult=Promise.all(c).then(()=>this._execute(i))}else this.postConstructResult=this._execute(i);else this.postConstructResult=void 0}}preDestroy(){if(p.INSTANCE===this.type&&this.cache!==void 0){const{key:t}=w(this.classValue)||{};t&&this._execute(t)}this.container&&!this.container._destroyed&&I._instanceContainerMap.delete(this.cache),this.container=void 0,this.context=void 0,this.classValue=void 0,this.constantValue=void 0,this.dynamicValue=void 0,this.cache=void 0,this.postConstructResult=D,this.onActivationHandler=void 0,this.onDeactivationHandler=void 0}_execute(t){const e=this.cache[t];return e==null?void 0:e.call(this.cache)}_resolveInstanceValue(t){this.status=f.INITING;const e=this._createInstance();this.cache=this.activate(e),this.status=f.ACTIVATED,this._registerInstance();const{properties:i,bindings:s}=this._getInjectProperties(t);return this._injectProperties(i),this._postConstruct(t,s),this.cache}_createInstance(){const t=this.classValue;return new t}_registerInstance(){I._instanceContainerMap.set(this.cache,this.container)}_injectProperties(t){Object.assign(this.cache,t)}_resolveConstantValue(){return this.status=f.INITING,this.cache=this.activate(this.constantValue),this.status=f.ACTIVATED,this.cache}_resolveDynamicValue(){this.status=f.INITING;const t=this.dynamicValue(this.context);return this.cache=this.activate(t),this.status=f.ACTIVATED,this.cache}_getInjectProperties(t){const e=R(this.classValue)||{},i=Object.keys(e),s=Object.create(null),o=[];for(let a=0;a<i.length;a++){const c=i[a],u=e[c],h=Object.assign({},u);h.parent=t;const d=this.container._resolveWithInternalOpts(A(h.inject),h);d===void 0&&h.optional||(s[c]=d),o.push(h.binding)}return{properties:s,bindings:o}}};r(T,"_resolvers",new Map([[p.INSTANCE,function(t){return this._resolveInstanceValue(t)}],[p.CONSTANT,function(t){return this._resolveConstantValue()}],[p.DYNAMIC,function(t){return this._resolveDynamicValue()}]]));let N=T;class H extends _{constructor(t,e){if(super("No matching binding found for token: ",t),e!=null&&e.parent){const i=B(e.parent);i.length>0&&(this.message+=`
2
+ `+i.map(s=>" required by: "+s).join(`
3
+ `))}}}class F extends _{constructor(t){super("Cannot bind token multiple times: ",t)}}class x extends _{constructor(t){super("Container has been destroyed. Cannot call get() for token: ",t)}}const v=class v{constructor(){r(this,"parent");r(this,"children");r(this,"_bindings",new Map);r(this,"_destroyed",!1);r(this,"_onActivationHandler");r(this,"_onDeactivationHandler")}static getContainerOf(t){return v._instanceContainerMap.get(t)}bind(t){if(this._bindings.has(t))throw new F(t);const e=this._buildBinding(t);return this._bindings.set(t,e),e}unbind(t){if(this._bindings.has(t)){const e=this._getBinding(t);this.deactivate(e),e.deactivate(),e.preDestroy(),this._bindings.delete(t)}}tryGet(t){return this.get(t,{optional:!0})}rebind(t){return this._bindings.has(t)&&this.unbind(t),this.bind(t)}unbindAll(){const t=Array.from(this._bindings.keys());for(const e of t)this.unbind(e)}isCurrentBound(t){return this._bindings.has(t)}isBound(t){return this.isCurrentBound(t)||!!this.parent&&this.parent.isBound(t)}createChild(){const t=new v;return t.parent=this,this.children||(this.children=new Set),this.children.add(t),t}destroy(){var t,e;if(this._destroyed=!0,this.children){const i=Array.from(this.children);for(const s of i)s.destroy()}this.unbindAll(),this._bindings.clear(),(e=(t=this.parent)==null?void 0:t.children)==null||e.delete(this),this.parent=void 0,this.children=void 0,this._onActivationHandler=void 0,this._onDeactivationHandler=void 0}get(t,e={}){const i=Object.assign({},e);return this._resolveWithInternalOpts(t,i)}getAsync(t,e={}){const i=Object.assign({},e);let s;try{s=this._resolveWithInternalOpts(t,i)}catch(a){return Promise.reject(a)}const o=i.binding;return(o==null?void 0:o.postConstructResult)instanceof Promise?o.postConstructResult.then(()=>s):Promise.resolve(s)}_resolveWithInternalOpts(t,e){if(this._destroyed)throw new x(t);return e.skipSelf?this._resolveSkipSelf(t,e):e.self?this._resolveSelf(t,e):this._resolveDefault(t,e)}_resolveSkipSelf(t,e){if(this.parent){const i=Object.assign({},e,{skipSelf:!1});return this.parent._resolveWithInternalOpts(t,i)}return this._checkBindingNotFoundError(t,e)}_resolveSelf(t,e){const i=this._getBinding(t);return i?(e.token=t,e.binding=i,i.get(e)):this._checkBindingNotFoundError(t,e)}_resolveDefault(t,e){const i=this._getBinding(t);return i?(e.token=t,e.binding=i,i.get(e)):this.parent?this.parent._resolveWithInternalOpts(t,e):this._checkBindingNotFoundError(t,e)}onActivation(t){this._onActivationHandler=t}onDeactivation(t){this._onDeactivationHandler=t}activate(t,e){return this._onActivationHandler?this._onActivationHandler({container:this},t,e):t}deactivate(t){this._onDeactivationHandler&&this._onDeactivationHandler(t.cache,t.token)}_buildBinding(t){return new N(t,this)}_getBinding(t){return this._bindings.get(t)}_checkBindingNotFoundError(t,e){if(!e.optional)throw new H(t,e)}};r(v,"_instanceContainerMap",new WeakMap);let I=v;class z extends _{constructor(t,e){super(`@LazyInject(${t==null?void 0:t.name}) in class ${e.name} requires a registered container but none was found. Token: `,t)}}function b(n,t){return function(e){return function(i,s){const o=s.name,a=s.metadata;E(a,l.INJECTED_PROPS)||(a[l.INJECTED_PROPS]={});const c=a[l.INJECTED_PROPS];c[o]||(c[o]={}),c[o][n]=e===void 0?t:e}}}function W(n,t){return e=>(i,s)=>{const o=s.name,a=s.metadata;if(E(a,n))throw new Error(t);a[n]={key:o,value:e}}}const Z=b(l.INJECT),$=b(l.SELF,!0),Q=b(l.SKIP_SELF,!0),X=b(l.OPTIONAL,!0),tt=W(l.POST_CONSTRUCT,C.POST_CONSTRUCT),et=W(l.PRE_DESTROY,C.PRE_DESTROY);function nt(){return function(n,t){const e=t.metadata;j(n,e)}}function it(n,t,e,i){if(e==null)throw new Error(C.LAZY_INJECT_INVALID_TOKEN);let s,o=!1;Object.defineProperty(n,t,{configurable:!0,enumerable:!0,get(){if(!o){const a=i||I.getContainerOf(n),c=n.constructor;if(!a)throw new z(A(e),c);s=a._resolveWithInternalOpts(A(e),{parent:{token:c}}),o=!0}return s},set(a){s=a,o=!0}})}function U(n,t){return function(e,i){const s=i.name;i.addInitializer(function(){it(this,s,n,t)})}}function st(n){return function(t){return U(t,n)}}function rt(n,t){const e=t.name;t.addInitializer(function(){this[e]=n.bind(this)})}const S=new WeakMap;function ot(n,t,e){const i=Array.isArray(n)?n:[n],s=t.prototype,o=typeof s[e]=="function",a=[];S.has(t)||S.set(t,{});const c=S.get(t),u={kind:o?"method":"field",name:e,static:!1,private:!1,addInitializer(d){a.push(d)},metadata:c};let h=o?s[e]:void 0;for(let d=i.length-1;d>=0;d--){const g=i[d](h,u);o&&typeof g=="function"&&(h=g)}if(o&&h!==s[e]&&(s[e]=h),j(t,c),a.length>0){const d=Object.create(s);for(const g of a)g.call(d)}}exports.BaseError=_;exports.Binding=N;exports.BindingNotFoundError=H;exports.BindingNotValidError=k;exports.CircularDependencyError=P;exports.Container=I;exports.ContainerDestroyedError=x;exports.ContainerNotFoundError=z;exports.DuplicateBindingError=F;exports.ERRORS=C;exports.Inject=Z;exports.Injectable=nt;exports.LazyInject=U;exports.LazyToken=L;exports.Optional=X;exports.PostConstruct=tt;exports.PostConstructError=M;exports.PreDestroy=et;exports.Self=$;exports.SkipSelf=Q;exports.Token=q;exports.autobind=rt;exports.createLazyInject=st;exports.decorate=ot;exports.hasOwn=E;exports.isObject=G;
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- export type { Newable, InjectFunction, CommonToken, TokenType, GenericToken, LazyTokenCallback, Context, DynamicValue, RecordObject, Options, ActivationHandler, DeactivationHandler, PostConstructParam, } from './interfaces';
1
+ export type { Newable, InjectFunction, CommonToken, TokenType, GenericToken, LazyTokenCallback, Context, DynamicValue, RecordObject, GetOptions, Options, ActivationHandler, DeactivationHandler, PostConstructParam, } from './interfaces';
2
2
  export { Container } from './container';
3
3
  export { Binding } from './binding';
4
4
  export { Token, LazyToken } from './token';
@@ -10,4 +10,5 @@ export { CircularDependencyError } from './errors/CircularDependencyError';
10
10
  export { DuplicateBindingError } from './errors/DuplicateBindingError';
11
11
  export { PostConstructError } from './errors/PostConstructError';
12
12
  export { ContainerNotFoundError } from './errors/ContainerNotFoundError';
13
+ export { ContainerDestroyedError } from './errors/ContainerDestroyedError';
13
14
  export { hasOwn, isObject, ERRORS } from './constants';
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export type { Newable, InjectFunction, CommonToken, TokenType, GenericToken, LazyTokenCallback, Context, DynamicValue, RecordObject, Options, ActivationHandler, DeactivationHandler, PostConstructParam, } from './interfaces';
1
+ export type { Newable, InjectFunction, CommonToken, TokenType, GenericToken, LazyTokenCallback, Context, DynamicValue, RecordObject, GetOptions, Options, ActivationHandler, DeactivationHandler, PostConstructParam, } from './interfaces';
2
2
  export { Container } from './container';
3
3
  export { Binding } from './binding';
4
4
  export { Token, LazyToken } from './token';
@@ -10,4 +10,5 @@ export { CircularDependencyError } from './errors/CircularDependencyError';
10
10
  export { DuplicateBindingError } from './errors/DuplicateBindingError';
11
11
  export { PostConstructError } from './errors/PostConstructError';
12
12
  export { ContainerNotFoundError } from './errors/ContainerNotFoundError';
13
+ export { ContainerDestroyedError } from './errors/ContainerDestroyedError';
13
14
  export { hasOwn, isObject, ERRORS } from './constants';
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
- var L = Object.defineProperty;
2
- var k = (n, t, e) => t in n ? L(n, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : n[t] = e;
3
- var o = (n, t, e) => k(n, typeof t != "symbol" ? t + "" : t, e);
4
- const u = {
1
+ var B = Object.defineProperty;
2
+ var M = (n, t, e) => t in n ? B(n, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : n[t] = e;
3
+ var r = (n, t, e) => M(n, typeof t != "symbol" ? t + "" : t, e);
4
+ const l = {
5
5
  // 记录实例属性装饰器对应的数据的键
6
6
  INJECTED_PROPS: "injected:props",
7
7
  // Inject 装饰器的键
@@ -25,7 +25,7 @@ const u = {
25
25
  INSTANCE: "Instance",
26
26
  CONSTANT: "ConstantValue",
27
27
  DYNAMIC: "DynamicValue"
28
- }, g = {
28
+ }, T = {
29
29
  // 用于 decorator.ts 的 createMetaDecorator —— 重复装饰器检测
30
30
  POST_CONSTRUCT: "Multiple @PostConstruct decorators are not allowed in a single class.",
31
31
  PRE_DESTROY: "Multiple @PreDestroy decorators are not allowed in a single class.",
@@ -33,108 +33,120 @@ const u = {
33
33
  INVALID_TOKEN: "@Inject or @LazyInject requires a valid token, but received null or undefined.",
34
34
  // 用于 decorator.ts 的 defineLazyProperty —— 无效 token
35
35
  LAZY_INJECT_INVALID_TOKEN: "@LazyInject requires a valid token, but received null or undefined."
36
- }, A = Symbol("UNINITIALIZED");
37
- function v(n, t) {
36
+ }, E = Symbol("UNINITIALIZED");
37
+ function m(n, t) {
38
38
  return Object.prototype.hasOwnProperty.call(n, t);
39
39
  }
40
- function K(n) {
40
+ function Z(n) {
41
41
  return n !== null && typeof n == "object";
42
42
  }
43
- const E = /* @__PURE__ */ new WeakMap();
44
- function b(n) {
43
+ const y = /* @__PURE__ */ new WeakMap(), g = /* @__PURE__ */ new WeakMap();
44
+ function S(n) {
45
45
  return typeof n == "function" && Object.getPrototypeOf(n) !== Function.prototype;
46
46
  }
47
- function O(n, t) {
48
- E.set(n, t);
49
- }
50
- function P(n) {
51
- const t = E.get(n);
52
- if (t)
53
- return t[u.POST_CONSTRUCT];
54
- if (b(n))
55
- return P(Object.getPrototypeOf(n));
47
+ function P(n, t) {
48
+ y.set(n, t), g.delete(n);
56
49
  }
57
50
  function V(n) {
58
- const t = E.get(n);
51
+ const t = y.get(n);
59
52
  if (t)
60
- return t[u.PRE_DESTROY];
61
- if (b(n))
53
+ return t[l.POST_CONSTRUCT];
54
+ if (S(n))
62
55
  return V(Object.getPrototypeOf(n));
63
56
  }
64
57
  function w(n) {
65
- const t = E.get(n), e = t && v(t, u.INJECTED_PROPS) ? t[u.INJECTED_PROPS] : void 0;
66
- if (!b(n))
58
+ const t = y.get(n);
59
+ if (t)
60
+ return t[l.PRE_DESTROY];
61
+ if (S(n))
62
+ return w(Object.getPrototypeOf(n));
63
+ }
64
+ function j(n) {
65
+ if (g.has(n)) {
66
+ const e = g.get(n);
67
+ return e && Object.assign({}, e);
68
+ }
69
+ const t = H(n);
70
+ return g.set(n, t), t && Object.assign({}, t);
71
+ }
72
+ function H(n) {
73
+ const t = y.get(n), e = t && m(t, l.INJECTED_PROPS) ? t[l.INJECTED_PROPS] : void 0;
74
+ if (!S(n))
67
75
  return e;
68
- const i = w(Object.getPrototypeOf(n));
76
+ const i = j(Object.getPrototypeOf(n));
69
77
  if (i || e)
70
78
  return Object.assign({}, i, e);
71
79
  }
72
- class G {
80
+ class $ {
73
81
  constructor(t) {
74
82
  // 仅类型层面存在,无运行时开销
75
- o(this, "name");
83
+ r(this, "name");
76
84
  this.name = t;
77
85
  }
78
86
  }
79
- class B {
87
+ class x {
80
88
  constructor(t) {
81
- o(this, "_callback");
89
+ r(this, "_callback");
82
90
  this._callback = t;
83
91
  }
84
92
  resolve() {
85
93
  return this._callback();
86
94
  }
87
95
  }
88
- function S(n) {
96
+ function D(n) {
89
97
  if (!n)
90
- throw new Error(g.INVALID_TOKEN);
91
- return n instanceof B ? n.resolve() : n;
98
+ throw new Error(T.INVALID_TOKEN);
99
+ return n instanceof x ? n.resolve() : n;
92
100
  }
93
- class T extends Error {
101
+ class _ extends Error {
94
102
  constructor(e, i) {
95
103
  const s = (i == null ? void 0 : i.name) || "<unknown token>";
96
104
  super(`${e}${s}`);
97
- o(this, "token");
105
+ r(this, "token");
98
106
  this.name = this.constructor.name, this.token = i;
99
107
  }
100
108
  }
101
- class R extends T {
109
+ function R(n) {
110
+ const t = [];
111
+ let e = n;
112
+ for (; e && e.token; )
113
+ t.push(e.token.name || "<anonymous>"), e = e.parent;
114
+ return t.reverse();
115
+ }
116
+ class L extends _ {
102
117
  constructor(t) {
103
- super("");
104
- const e = [];
105
- let i = t;
106
- for (; i && i.token; )
107
- e.push(i.token), i = i.parent;
108
- const s = e.reverse().map((r) => r.name || "<anonymous>").join(" --> ");
109
- this.message = `Circular dependency found: ${s}`;
118
+ super(""), this.message = "Circular dependency found: " + R(t).join(" --> ");
110
119
  }
111
120
  }
112
- class H extends T {
121
+ class F extends _ {
113
122
  constructor(t) {
114
- super("Invalid binding: ", t);
123
+ super(
124
+ "Binding is not configured (missing .to() / .toSelf() / .toConstantValue() / .toDynamicValue()): ",
125
+ t
126
+ );
115
127
  }
116
128
  }
117
- class M extends R {
129
+ class W extends L {
118
130
  constructor(t) {
119
131
  super(t), this.name = "CircularDependencyError inside @PostConstruct";
120
132
  }
121
133
  }
122
- const C = class C {
134
+ const N = class N {
123
135
  constructor(t, e) {
124
- o(this, "container");
125
- o(this, "context");
126
- o(this, "token");
127
- o(this, "type", p.INVALID);
128
- o(this, "status", f.DEFAULT);
129
- o(this, "classValue");
130
- o(this, "constantValue");
131
- o(this, "dynamicValue");
132
- o(this, "cache");
133
- o(this, "postConstructResult", A);
136
+ r(this, "container");
137
+ r(this, "context");
138
+ r(this, "token");
139
+ r(this, "type", p.INVALID);
140
+ r(this, "status", f.DEFAULT);
141
+ r(this, "classValue");
142
+ r(this, "constantValue");
143
+ r(this, "dynamicValue");
144
+ r(this, "cache");
145
+ r(this, "postConstructResult", E);
134
146
  // 是否为瞬态作用域,默认 false(单例)
135
- o(this, "transient", !1);
136
- o(this, "onActivationHandler");
137
- o(this, "onDeactivationHandler");
147
+ r(this, "transient", !1);
148
+ r(this, "onActivationHandler");
149
+ r(this, "onDeactivationHandler");
138
150
  this.container = e, this.context = { container: this.container }, this.token = t;
139
151
  }
140
152
  onActivation(t) {
@@ -167,21 +179,21 @@ const C = class C {
167
179
  }
168
180
  toService(t) {
169
181
  return this.toDynamicValue(
170
- (e) => e.container.get(t, { parent: { token: this.token } })
182
+ (e) => e.container._resolveWithInternalOpts(t, { parent: { token: this.token } })
171
183
  );
172
184
  }
173
185
  get(t) {
174
186
  if (f.INITING === this.status)
175
- throw new R(t);
187
+ throw new L(t);
176
188
  if (f.ACTIVATED === this.status)
177
189
  if (this.transient)
178
190
  this.status = f.DEFAULT;
179
191
  else
180
192
  return this.cache;
181
- const e = C._resolvers[this.type];
193
+ const e = N._resolvers.get(this.type);
182
194
  if (e)
183
- return this[e](t);
184
- throw new H(this.token);
195
+ return e.call(this, t);
196
+ throw new F(this.token);
185
197
  }
186
198
  _getAwaitBindings(t, e) {
187
199
  return e === !0 ? t : Array.isArray(e) ? t.filter((i) => e.includes(i.token)) : typeof e == "function" ? t.filter(e) : [];
@@ -201,20 +213,20 @@ const C = class C {
201
213
  */
202
214
  _postConstruct(t, e) {
203
215
  if (p.INSTANCE === this.type) {
204
- const { key: i, value: s } = P(this.classValue) || {};
216
+ const { key: i, value: s } = V(this.classValue) || {};
205
217
  if (i)
206
218
  if (s) {
207
- const r = e.filter(
208
- (c) => p.INSTANCE === (c == null ? void 0 : c.type)
209
- ), a = this._getAwaitBindings(r, s);
210
- for (const c of a)
211
- if (c && c.postConstructResult === A)
212
- throw new M({
213
- token: c.token,
219
+ const o = e.filter(
220
+ (u) => p.INSTANCE === (u == null ? void 0 : u.type)
221
+ ), a = this._getAwaitBindings(o, s);
222
+ for (const u of a)
223
+ if (u && u.postConstructResult === E)
224
+ throw new W({
225
+ token: u.token,
214
226
  parent: t
215
227
  });
216
- const l = a.map((c) => c.postConstructResult);
217
- this.postConstructResult = Promise.all(l).then(
228
+ const c = a.map((u) => u.postConstructResult);
229
+ this.postConstructResult = Promise.all(c).then(
218
230
  () => this._execute(i)
219
231
  );
220
232
  } else
@@ -224,11 +236,11 @@ const C = class C {
224
236
  }
225
237
  }
226
238
  preDestroy() {
227
- if (p.INSTANCE === this.type) {
228
- const { key: t } = V(this.classValue) || {};
239
+ if (p.INSTANCE === this.type && this.cache !== void 0) {
240
+ const { key: t } = w(this.classValue) || {};
229
241
  t && this._execute(t);
230
242
  }
231
- I._instanceContainerMap.delete(this.cache), this.container = null, this.context = null, this.classValue = void 0, this.constantValue = void 0, this.dynamicValue = void 0, this.cache = void 0, this.postConstructResult = A, this.onActivationHandler = void 0, this.onDeactivationHandler = void 0;
243
+ this.container && !this.container._destroyed && v._instanceContainerMap.delete(this.cache), this.container = void 0, this.context = void 0, this.classValue = void 0, this.constantValue = void 0, this.dynamicValue = void 0, this.cache = void 0, this.postConstructResult = E, this.onActivationHandler = void 0, this.onDeactivationHandler = void 0;
232
244
  }
233
245
  _execute(t) {
234
246
  const e = this.cache[t];
@@ -248,7 +260,7 @@ const C = class C {
248
260
  }
249
261
  // 注册实例与容器的映射关系
250
262
  _registerInstance() {
251
- I._instanceContainerMap.set(this.cache, this.container);
263
+ v._instanceContainerMap.set(this.cache, this.container);
252
264
  }
253
265
  // 将解析后的属性注入到实例上
254
266
  _injectProperties(t) {
@@ -263,51 +275,68 @@ const C = class C {
263
275
  return this.cache = this.activate(t), this.status = f.ACTIVATED, this.cache;
264
276
  }
265
277
  _getInjectProperties(t) {
266
- const e = w(this.classValue) || {}, i = Object.keys(e), s = /* @__PURE__ */ Object.create(null), r = [];
278
+ const e = j(this.classValue) || {}, i = Object.keys(e), s = /* @__PURE__ */ Object.create(null), o = [];
267
279
  for (let a = 0; a < i.length; a++) {
268
- const l = i[a], c = e[l], h = Object.assign({}, c);
280
+ const c = i[a], u = e[c], h = Object.assign({}, u);
269
281
  h.parent = t;
270
- const d = this.container.get(
271
- S(h.inject),
282
+ const d = this.container._resolveWithInternalOpts(
283
+ D(h.inject),
272
284
  h
273
285
  );
274
- d === void 0 && h.optional || (s[l] = d), r.push(h.binding);
286
+ d === void 0 && h.optional || (s[c] = d), o.push(h.binding);
275
287
  }
276
- return { properties: s, bindings: r };
288
+ return { properties: s, bindings: o };
277
289
  }
278
290
  };
279
- // 类型到解析方法的静态映射表,用于替代 get 方法中的 if-else 链
280
- o(C, "_resolvers", {
281
- [p.INSTANCE]: "_resolveInstanceValue",
282
- [p.CONSTANT]: "_resolveConstantValue",
283
- [p.DYNAMIC]: "_resolveDynamicValue"
284
- });
285
- let m = C;
286
- class x extends T {
287
- constructor(t) {
288
- super("No matching binding found for token: ", t);
291
+ // 类型到解析函数的静态映射表,直接存储函数引用,消除字符串查表和 as any 间接调用
292
+ r(N, "_resolvers", /* @__PURE__ */ new Map([
293
+ [p.INSTANCE, function(t) {
294
+ return this._resolveInstanceValue(t);
295
+ }],
296
+ [p.CONSTANT, function(t) {
297
+ return this._resolveConstantValue();
298
+ }],
299
+ [p.DYNAMIC, function(t) {
300
+ return this._resolveDynamicValue();
301
+ }]
302
+ ]));
303
+ let A = N;
304
+ class z extends _ {
305
+ constructor(t, e) {
306
+ if (super("No matching binding found for token: ", t), e != null && e.parent) {
307
+ const i = R(e.parent);
308
+ i.length > 0 && (this.message += `
309
+ ` + i.map((s) => " required by: " + s).join(`
310
+ `));
311
+ }
289
312
  }
290
313
  }
291
- class F extends T {
314
+ class U extends _ {
292
315
  constructor(t) {
293
316
  super("Cannot bind token multiple times: ", t);
294
317
  }
295
318
  }
296
- const _ = class _ {
319
+ class Y extends _ {
320
+ constructor(t) {
321
+ super("Container has been destroyed. Cannot call get() for token: ", t);
322
+ }
323
+ }
324
+ const I = class I {
297
325
  constructor() {
298
- o(this, "parent");
299
- o(this, "children");
300
- o(this, "_bindings", /* @__PURE__ */ new Map());
301
- o(this, "_onActivationHandler");
302
- o(this, "_onDeactivationHandler");
326
+ r(this, "parent");
327
+ r(this, "children");
328
+ r(this, "_bindings", /* @__PURE__ */ new Map());
329
+ r(this, "_destroyed", !1);
330
+ r(this, "_onActivationHandler");
331
+ r(this, "_onDeactivationHandler");
303
332
  }
304
333
  // 查询实例所属的容器
305
334
  static getContainerOf(t) {
306
- return _._instanceContainerMap.get(t);
335
+ return I._instanceContainerMap.get(t);
307
336
  }
308
337
  bind(t) {
309
338
  if (this._bindings.has(t))
310
- throw new F(t);
339
+ throw new U(t);
311
340
  const e = this._buildBinding(t);
312
341
  return this._bindings.set(t, e), e;
313
342
  }
@@ -317,6 +346,12 @@ const _ = class _ {
317
346
  this.deactivate(e), e.deactivate(), e.preDestroy(), this._bindings.delete(t);
318
347
  }
319
348
  }
349
+ tryGet(t) {
350
+ return this.get(t, { optional: !0 });
351
+ }
352
+ rebind(t) {
353
+ return this._bindings.has(t) && this.unbind(t), this.bind(t);
354
+ }
320
355
  unbindAll() {
321
356
  const t = Array.from(this._bindings.keys());
322
357
  for (const e of t)
@@ -329,12 +364,12 @@ const _ = class _ {
329
364
  return this.isCurrentBound(t) || !!this.parent && this.parent.isBound(t);
330
365
  }
331
366
  createChild() {
332
- const t = new _();
367
+ const t = new I();
333
368
  return t.parent = this, this.children || (this.children = /* @__PURE__ */ new Set()), this.children.add(t), t;
334
369
  }
335
370
  destroy() {
336
371
  var t, e;
337
- if (this.children) {
372
+ if (this._destroyed = !0, this.children) {
338
373
  const i = Array.from(this.children);
339
374
  for (const s of i)
340
375
  s.destroy();
@@ -342,21 +377,33 @@ const _ = class _ {
342
377
  this.unbindAll(), this._bindings.clear(), (e = (t = this.parent) == null ? void 0 : t.children) == null || e.delete(this), this.parent = void 0, this.children = void 0, this._onActivationHandler = void 0, this._onDeactivationHandler = void 0;
343
378
  }
344
379
  get(t, e = {}) {
345
- return e.skipSelf ? this._resolveSkipSelf(t, e) : e.self ? this._resolveSelf(t, e) : this._resolveDefault(t, e);
380
+ const i = Object.assign({}, e);
381
+ return this._resolveWithInternalOpts(t, i);
346
382
  }
347
383
  getAsync(t, e = {}) {
348
- let i;
384
+ const i = Object.assign({}, e);
385
+ let s;
349
386
  try {
350
- i = this.get(t, e);
351
- } catch (r) {
352
- return Promise.reject(r);
387
+ s = this._resolveWithInternalOpts(t, i);
388
+ } catch (a) {
389
+ return Promise.reject(a);
353
390
  }
354
- const s = e.binding;
355
- return (s == null ? void 0 : s.postConstructResult) instanceof Promise ? s.postConstructResult.then(() => i) : Promise.resolve(i);
391
+ const o = i.binding;
392
+ return (o == null ? void 0 : o.postConstructResult) instanceof Promise ? o.postConstructResult.then(() => s) : Promise.resolve(s);
393
+ }
394
+ // 内部解析入口,接受完整 Options;被 getAsync、toService、_getInjectProperties 等内部路径调用
395
+ _resolveWithInternalOpts(t, e) {
396
+ if (this._destroyed)
397
+ throw new Y(t);
398
+ return e.skipSelf ? this._resolveSkipSelf(t, e) : e.self ? this._resolveSelf(t, e) : this._resolveDefault(t, e);
356
399
  }
357
400
  // 处理 skipSelf 选项:跳过当前容器,委托父容器解析
358
401
  _resolveSkipSelf(t, e) {
359
- return this.parent ? (e.skipSelf = !1, this.parent.get(t, e)) : this._checkBindingNotFoundError(t, e);
402
+ if (this.parent) {
403
+ const i = Object.assign({}, e, { skipSelf: !1 });
404
+ return this.parent._resolveWithInternalOpts(t, i);
405
+ }
406
+ return this._checkBindingNotFoundError(t, e);
360
407
  }
361
408
  // 处理 self 选项:仅在当前容器中查找
362
409
  _resolveSelf(t, e) {
@@ -366,7 +413,7 @@ const _ = class _ {
366
413
  // 默认解析流程:当前容器 → 父容器 → 抛错
367
414
  _resolveDefault(t, e) {
368
415
  const i = this._getBinding(t);
369
- return i ? (e.token = t, e.binding = i, i.get(e)) : this.parent ? this.parent.get(t, e) : this._checkBindingNotFoundError(t, e);
416
+ return i ? (e.token = t, e.binding = i, i.get(e)) : this.parent ? this.parent._resolveWithInternalOpts(t, e) : this._checkBindingNotFoundError(t, e);
370
417
  }
371
418
  onActivation(t) {
372
419
  this._onActivationHandler = t;
@@ -381,14 +428,14 @@ const _ = class _ {
381
428
  this._onDeactivationHandler && this._onDeactivationHandler(t.cache, t.token);
382
429
  }
383
430
  _buildBinding(t) {
384
- return new m(t, this);
431
+ return new A(t, this);
385
432
  }
386
433
  _getBinding(t) {
387
434
  return this._bindings.get(t);
388
435
  }
389
436
  _checkBindingNotFoundError(t, e) {
390
437
  if (!e.optional)
391
- throw new x(t);
438
+ throw new z(t, e);
392
439
  }
393
440
  };
394
441
  // 实例到容器的映射表,用于 @LazyInject 查找实例所属容器
@@ -397,9 +444,9 @@ const _ = class _ {
397
444
  // 同一对象可能通过 toConstantValue 被绑定到多个容器,WeakMap 只能保留最后一次映射,
398
445
  // 会导致 @LazyInject 从错误的容器解析依赖。
399
446
  // 由于 Instance 类型每次都通过 new ClassName() 创建新实例,不存在同一实例被多个容器注册的覆盖风险
400
- o(_, "_instanceContainerMap", /* @__PURE__ */ new WeakMap());
401
- let I = _;
402
- class z extends T {
447
+ r(I, "_instanceContainerMap", /* @__PURE__ */ new WeakMap());
448
+ let v = I;
449
+ class J extends _ {
403
450
  constructor(t, e) {
404
451
  super(
405
452
  `@LazyInject(${t == null ? void 0 : t.name}) in class ${e.name} requires a registered container but none was found. Token: `,
@@ -407,128 +454,129 @@ class z extends T {
407
454
  );
408
455
  }
409
456
  }
410
- function y(n, t) {
457
+ function O(n, t) {
411
458
  return function(e) {
412
459
  return function(i, s) {
413
- const r = s.name, a = s.metadata;
414
- v(a, u.INJECTED_PROPS) || (a[u.INJECTED_PROPS] = {});
415
- const l = a[u.INJECTED_PROPS];
416
- l[r] || (l[r] = {}), l[r][n] = e === void 0 ? t : e;
460
+ const o = s.name, a = s.metadata;
461
+ m(a, l.INJECTED_PROPS) || (a[l.INJECTED_PROPS] = {});
462
+ const c = a[l.INJECTED_PROPS];
463
+ c[o] || (c[o] = {}), c[o][n] = e === void 0 ? t : e;
417
464
  };
418
465
  };
419
466
  }
420
- function j(n, t) {
467
+ function k(n, t) {
421
468
  return (e) => (i, s) => {
422
- const r = s.name, a = s.metadata;
423
- if (v(a, n))
469
+ const o = s.name, a = s.metadata;
470
+ if (m(a, n))
424
471
  throw new Error(t);
425
- a[n] = { key: r, value: e };
472
+ a[n] = { key: o, value: e };
426
473
  };
427
474
  }
428
- const $ = y(u.INJECT), Z = y(u.SELF, !0), q = y(u.SKIP_SELF, !0), W = y(u.OPTIONAL, !0), Q = j(
429
- u.POST_CONSTRUCT,
430
- g.POST_CONSTRUCT
431
- ), X = j(
432
- u.PRE_DESTROY,
433
- g.PRE_DESTROY
475
+ const Q = O(l.INJECT), X = O(l.SELF, !0), tt = O(l.SKIP_SELF, !0), et = O(l.OPTIONAL, !0), nt = k(
476
+ l.POST_CONSTRUCT,
477
+ T.POST_CONSTRUCT
478
+ ), it = k(
479
+ l.PRE_DESTROY,
480
+ T.PRE_DESTROY
434
481
  );
435
- function tt() {
482
+ function st() {
436
483
  return function(n, t) {
437
484
  const e = t.metadata;
438
- O(n, e);
485
+ P(n, e);
439
486
  };
440
487
  }
441
- function U(n, t, e, i) {
488
+ function G(n, t, e, i) {
442
489
  if (e == null)
443
- throw new Error(g.LAZY_INJECT_INVALID_TOKEN);
444
- const s = Symbol.for(t);
490
+ throw new Error(T.LAZY_INJECT_INVALID_TOKEN);
491
+ let s, o = !1;
445
492
  Object.defineProperty(n, t, {
446
493
  configurable: !0,
447
494
  enumerable: !0,
448
495
  get() {
449
- if (!v(n, s)) {
450
- const r = i || I.getContainerOf(n), a = n.constructor;
451
- if (!r)
452
- throw new z(S(e), a);
453
- n[s] = r.get(S(e), {
454
- parent: { token: a }
455
- });
496
+ if (!o) {
497
+ const a = i || v.getContainerOf(n), c = n.constructor;
498
+ if (!a)
499
+ throw new J(D(e), c);
500
+ s = a._resolveWithInternalOpts(D(e), {
501
+ parent: { token: c }
502
+ }), o = !0;
456
503
  }
457
- return n[s];
504
+ return s;
458
505
  },
459
- set(r) {
460
- n[s] = r;
506
+ set(a) {
507
+ s = a, o = !0;
461
508
  }
462
509
  });
463
510
  }
464
- function Y(n, t) {
511
+ function K(n, t) {
465
512
  return function(e, i) {
466
513
  const s = i.name;
467
514
  i.addInitializer(function() {
468
- U(this, s, n, t);
515
+ G(this, s, n, t);
469
516
  });
470
517
  };
471
518
  }
472
- function et(n) {
519
+ function rt(n) {
473
520
  return function(t) {
474
- return Y(t, n);
521
+ return K(t, n);
475
522
  };
476
523
  }
477
- function nt(n, t) {
524
+ function ot(n, t) {
478
525
  const e = t.name;
479
526
  t.addInitializer(function() {
480
527
  this[e] = n.bind(this);
481
528
  });
482
529
  }
483
- const D = Symbol("decorate.metadata");
484
- function it(n, t, e) {
485
- const i = Array.isArray(n) ? n : [n], s = t.prototype, r = typeof s[e] == "function", a = [];
486
- v(t, D) || (t[D] = {});
487
- const l = t[D], c = {
488
- kind: r ? "method" : "field",
530
+ const b = /* @__PURE__ */ new WeakMap();
531
+ function at(n, t, e) {
532
+ const i = Array.isArray(n) ? n : [n], s = t.prototype, o = typeof s[e] == "function", a = [];
533
+ b.has(t) || b.set(t, {});
534
+ const c = b.get(t), u = {
535
+ kind: o ? "method" : "field",
489
536
  name: e,
490
537
  static: !1,
491
538
  private: !1,
492
539
  addInitializer(d) {
493
540
  a.push(d);
494
541
  },
495
- metadata: l
542
+ metadata: c
496
543
  };
497
- let h = r ? s[e] : void 0;
544
+ let h = o ? s[e] : void 0;
498
545
  for (let d = i.length - 1; d >= 0; d--) {
499
- const N = i[d](h, c);
500
- r && typeof N == "function" && (h = N);
546
+ const C = i[d](h, u);
547
+ o && typeof C == "function" && (h = C);
501
548
  }
502
- if (r && h !== s[e] && (s[e] = h), O(t, l), a.length > 0) {
549
+ if (o && h !== s[e] && (s[e] = h), P(t, c), a.length > 0) {
503
550
  const d = Object.create(s);
504
- for (const N of a)
505
- N.call(d);
551
+ for (const C of a)
552
+ C.call(d);
506
553
  }
507
554
  }
508
555
  export {
509
- T as BaseError,
510
- m as Binding,
511
- x as BindingNotFoundError,
512
- H as BindingNotValidError,
513
- R as CircularDependencyError,
514
- I as Container,
515
- z as ContainerNotFoundError,
516
- F as DuplicateBindingError,
517
- g as ERRORS,
518
- $ as Inject,
519
- tt as Injectable,
520
- Y as LazyInject,
521
- B as LazyToken,
522
- W as Optional,
523
- Q as PostConstruct,
524
- M as PostConstructError,
525
- X as PreDestroy,
526
- Z as Self,
527
- q as SkipSelf,
528
- G as Token,
529
- nt as autobind,
530
- et as createLazyInject,
531
- it as decorate,
532
- v as hasOwn,
533
- K as isObject
556
+ _ as BaseError,
557
+ A as Binding,
558
+ z as BindingNotFoundError,
559
+ F as BindingNotValidError,
560
+ L as CircularDependencyError,
561
+ v as Container,
562
+ Y as ContainerDestroyedError,
563
+ J as ContainerNotFoundError,
564
+ U as DuplicateBindingError,
565
+ T as ERRORS,
566
+ Q as Inject,
567
+ st as Injectable,
568
+ K as LazyInject,
569
+ x as LazyToken,
570
+ et as Optional,
571
+ nt as PostConstruct,
572
+ W as PostConstructError,
573
+ it as PreDestroy,
574
+ X as Self,
575
+ tt as SkipSelf,
576
+ $ as Token,
577
+ ot as autobind,
578
+ rt as createLazyInject,
579
+ at as decorate,
580
+ m as hasOwn,
581
+ Z as isObject
534
582
  };
@@ -12,11 +12,13 @@ export interface Context {
12
12
  }
13
13
  export type DynamicValue<T> = (ctx: Context) => T;
14
14
  export type RecordObject = Record<string, unknown>;
15
- export interface Options<T = unknown> {
16
- inject?: GenericToken<T>;
15
+ export interface GetOptions {
17
16
  optional?: boolean;
18
17
  self?: boolean;
19
18
  skipSelf?: boolean;
19
+ }
20
+ export interface Options<T = unknown> extends GetOptions {
21
+ inject?: GenericToken<T>;
20
22
  token?: CommonToken<T>;
21
23
  binding?: Binding<T>;
22
24
  parent?: Options<any>;
@@ -12,11 +12,13 @@ export interface Context {
12
12
  }
13
13
  export type DynamicValue<T> = (ctx: Context) => T;
14
14
  export type RecordObject = Record<string, unknown>;
15
- export interface Options<T = unknown> {
16
- inject?: GenericToken<T>;
15
+ export interface GetOptions {
17
16
  optional?: boolean;
18
17
  self?: boolean;
19
18
  skipSelf?: boolean;
19
+ }
20
+ export interface Options<T = unknown> extends GetOptions {
21
+ inject?: GenericToken<T>;
20
22
  token?: CommonToken<T>;
21
23
  binding?: Binding<T>;
22
24
  parent?: Options<any>;
@@ -0,0 +1,2 @@
1
+ import { Options } from './interfaces';
2
+ export declare function buildTokenChain(options: Options): string[];
@@ -0,0 +1,2 @@
1
+ import { Options } from './interfaces';
2
+ export declare function buildTokenChain(options: Options): string[];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kaokei/di",
3
- "version": "5.0.3",
3
+ "version": "5.0.5",
4
4
  "type": "module",
5
5
  "description": "Tiny di library depends on typescript decorator.",
6
6
  "main": "./dist/index.cjs",