@codefast/di 0.13.0 → 0.15.0
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/CHANGELOG.md +161 -0
- package/README.md +48 -32
- package/dist/ambient-container.d.ts +46 -0
- package/dist/ambient-container.js +72 -1
- package/dist/container/binding-chain.js +3 -3
- package/dist/container/container.d.ts +41 -29
- package/dist/container/container.js +49 -264
- package/dist/container/introspect.d.ts +47 -0
- package/dist/container/introspect.js +53 -0
- package/dist/core/binding-builders.d.ts +22 -1
- package/dist/core/binding-declaration.js +2 -2
- package/dist/core/module.d.ts +4 -25
- package/dist/core/module.js +3 -27
- package/dist/core/state-epoch.d.ts +1 -1
- package/dist/core/state-epoch.js +1 -1
- package/dist/core/types.d.ts +16 -7
- package/dist/decorators/inject.js +27 -22
- package/dist/decorators/injectable.d.ts +14 -18
- package/dist/decorators/injectable.js +23 -2
- package/dist/errors.d.ts +11 -2
- package/dist/errors.js +6 -3
- package/dist/index.d.ts +8 -7
- package/dist/index.js +3 -2
- package/dist/injection/dependency-slot.d.ts +17 -0
- package/dist/injection/dependency-slot.js +46 -0
- package/dist/injection/descriptor.d.ts +9 -3
- package/dist/injection/descriptor.js +10 -1
- package/dist/introspection/validation.d.ts +28 -0
- package/dist/introspection/validation.js +244 -0
- package/dist/lifecycle/hooks.d.ts +11 -2
- package/dist/lifecycle/hooks.js +30 -18
- package/dist/resolution/cache/class-introspector.d.ts +7 -8
- package/dist/resolution/cache/class-introspector.js +40 -3
- package/dist/resolution/cache/lookup.d.ts +10 -0
- package/dist/resolution/cache/lookup.js +27 -0
- package/dist/resolution/context.d.ts +12 -12
- package/dist/resolution/plan/codegen.d.ts +2 -1
- package/dist/resolution/plan/codegen.js +1 -1
- package/dist/resolution/plan/compiler.d.ts +6 -6
- package/dist/resolution/plan/compiler.js +152 -22
- package/dist/resolution/resolver.d.ts +2 -8
- package/dist/resolution/resolver.js +17 -93
- package/package.json +10 -2
|
@@ -1,56 +1,38 @@
|
|
|
1
|
-
import type { BindToBuilder } from "#core/binding-builders";
|
|
1
|
+
import type { Binder, BindToBuilder, ClassBindToBuilder } from "#core/binding-builders";
|
|
2
2
|
import type { AsyncModule, SyncModule } from "#core/module";
|
|
3
|
+
import { BindingRegistry } from "#core/registry";
|
|
3
4
|
import type { Token } from "#core/token";
|
|
4
|
-
import type { ActivationHandler, BindingIdentifier, Constructor, DeactivationHandler, ResolveOptions } from "#core/types";
|
|
5
|
-
import
|
|
6
|
-
import
|
|
7
|
-
import type { ExplainOptions, ResolutionExplanation } from "#introspection/explanation";
|
|
8
|
-
import type { BindingSnapshot, ContainerSnapshot } from "#introspection/inspector";
|
|
5
|
+
import type { ActivationHandler, BindingIdentifier, Constructor, DeactivationHandler, Resolver, ResolveOptions } from "#core/types";
|
|
6
|
+
import { Inspector } from "#introspection/inspector";
|
|
7
|
+
import { LifecycleManager } from "#lifecycle/hooks";
|
|
9
8
|
import type { MetadataReader } from "#metadata/types";
|
|
9
|
+
import { DependencyResolver } from "#resolution/resolver";
|
|
10
10
|
/**
|
|
11
11
|
* The public surface: binding, resolving, modules, lifecycle hooks, child scopes, and disposal.
|
|
12
12
|
*
|
|
13
13
|
* @since 0.3.16-canary.0
|
|
14
14
|
*/
|
|
15
|
-
export interface Container {
|
|
15
|
+
export interface Container extends Resolver, Binder {
|
|
16
16
|
readonly isDisposed: boolean;
|
|
17
|
-
bind<Value, Names extends string = string>(token: Token<Value, Names> | Constructor<Value>): BindToBuilder<Value, Names>;
|
|
18
17
|
unbind(tokenOrId: Token<unknown> | Constructor | BindingIdentifier): void;
|
|
19
18
|
unbindAsync(tokenOrId: Token<unknown> | Constructor | BindingIdentifier): Promise<void>;
|
|
20
19
|
unbindAll(): void;
|
|
21
20
|
unbindAllAsync(): Promise<void>;
|
|
22
|
-
rebind<Value
|
|
21
|
+
rebind<Value>(type: Constructor<Value>): ClassBindToBuilder<Value>;
|
|
22
|
+
rebind<Value, Names extends string = string>(token: Token<Value, Names>): BindToBuilder<Value, Names>;
|
|
23
|
+
rebind<Value, Names extends string = string>(key: Token<Value, Names> | Constructor<Value>): BindToBuilder<Value, Names>;
|
|
23
24
|
load(...modules: Array<SyncModule>): void;
|
|
24
25
|
loadAsync(...modules: Array<SyncModule | AsyncModule>): Promise<void>;
|
|
25
26
|
unload(...modules: Array<SyncModule>): void;
|
|
26
27
|
unloadAsync(...modules: Array<SyncModule | AsyncModule>): Promise<void>;
|
|
27
|
-
loadAutoRegistered(registry: AutoRegisterRegistry): number;
|
|
28
28
|
onActivation<Value>(token: Token<Value> | Constructor<Value>, handler: ActivationHandler<Value>): void;
|
|
29
29
|
onDeactivation<Value>(token: Token<Value> | Constructor<Value>, handler: DeactivationHandler<Value>): void;
|
|
30
|
-
resolve<Value, Names extends string = string>(token: Token<Value, Names> | Constructor<Value>, options?: NoInfer<ResolveOptions<Names>>): Value;
|
|
31
|
-
resolveAsync<Value, Names extends string = string>(token: Token<Value, Names> | Constructor<Value>, options?: NoInfer<ResolveOptions<Names>>): Promise<Value>;
|
|
32
|
-
resolveOptional<Value, Names extends string = string>(token: Token<Value, Names> | Constructor<Value>, options?: NoInfer<ResolveOptions<Names>>): Value | undefined;
|
|
33
|
-
resolveOptionalAsync<Value, Names extends string = string>(token: Token<Value, Names> | Constructor<Value>, options?: NoInfer<ResolveOptions<Names>>): Promise<Value | undefined>;
|
|
34
|
-
resolveAll<Value, Names extends string = string>(token: Token<Value, Names> | Constructor<Value>, options?: NoInfer<ResolveOptions<Names>>): ReadonlyArray<Value>;
|
|
35
|
-
resolveAllAsync<Value, Names extends string = string>(token: Token<Value, Names> | Constructor<Value>, options?: NoInfer<ResolveOptions<Names>>): Promise<ReadonlyArray<Value>>;
|
|
36
30
|
createChild(): Container;
|
|
37
|
-
|
|
31
|
+
disposeAsync(): Promise<void>;
|
|
38
32
|
[Symbol.asyncDispose](): Promise<void>;
|
|
39
33
|
initializeAsync(): Promise<void>;
|
|
40
|
-
validate(): void;
|
|
41
34
|
has<Names extends string = string>(token: Token<unknown, Names> | Constructor, options?: NoInfer<ResolveOptions<Names>>): boolean;
|
|
42
35
|
hasOwn<Names extends string = string>(token: Token<unknown, Names> | Constructor, options?: NoInfer<ResolveOptions<Names>>): boolean;
|
|
43
|
-
lookupBindings<Value>(token: Token<Value> | Constructor<Value>): ReadonlyArray<BindingSnapshot>;
|
|
44
|
-
inspect(): ContainerSnapshot;
|
|
45
|
-
/**
|
|
46
|
-
* Explains why a request selects the binding it does, reading each registry the way `resolve` does and deciding
|
|
47
|
-
* by the same rules, without instantiating anything.
|
|
48
|
-
*
|
|
49
|
-
* @remarks A `when()` predicate runs here as it would in `resolve`. `options.ancestors` names the resolutions the
|
|
50
|
-
* request is nested in, so a predicate that reads the parent sees the one it would.
|
|
51
|
-
*/
|
|
52
|
-
explain<Names extends string = string>(token: Token<unknown, Names> | Constructor, options?: NoInfer<ExplainOptions<Names>>): ResolutionExplanation;
|
|
53
|
-
generateDependencyGraph(options?: GraphOptions): ContainerGraphJson;
|
|
54
36
|
}
|
|
55
37
|
/**
|
|
56
38
|
* What a container has to be told before it exists, as opposed to what it can be bound later.
|
|
@@ -77,6 +59,36 @@ export interface ContainerStatic {
|
|
|
77
59
|
fromModules(...modules: Array<SyncModule>): Container;
|
|
78
60
|
fromModulesAsync(...modules: Array<SyncModule | AsyncModule>): Promise<Container>;
|
|
79
61
|
}
|
|
62
|
+
/**
|
|
63
|
+
* The state the container functions read off a container, kept off its public surface.
|
|
64
|
+
*
|
|
65
|
+
* @remarks `registries` lists the container's own registry, then each ancestor's nearest first — the order every chain
|
|
66
|
+
* walk reads them in.
|
|
67
|
+
*
|
|
68
|
+
* @since 0.14.0
|
|
69
|
+
*/
|
|
70
|
+
export interface ContainerInternals {
|
|
71
|
+
readonly registries: readonly [BindingRegistry, ...Array<BindingRegistry>];
|
|
72
|
+
readonly resolver: DependencyResolver;
|
|
73
|
+
readonly metadataReader: MetadataReader;
|
|
74
|
+
readonly lifecycle: LifecycleManager;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Reads the internals of a live container `Container` created, built on first use.
|
|
78
|
+
*
|
|
79
|
+
* @throws `TypeError` for an object `Container` did not create, `DisposedContainerError` for a disposed chain.
|
|
80
|
+
*
|
|
81
|
+
* @since 0.14.0
|
|
82
|
+
*/
|
|
83
|
+
export declare function containerInternals(container: Container): ContainerInternals;
|
|
84
|
+
/**
|
|
85
|
+
* Reads the inspector of a live container `Container` created, built on first use.
|
|
86
|
+
*
|
|
87
|
+
* @throws `TypeError` for an object `Container` did not create, `DisposedContainerError` for a disposed chain.
|
|
88
|
+
*
|
|
89
|
+
* @since 0.14.0
|
|
90
|
+
*/
|
|
91
|
+
export declare function containerInspector(container: Container): Inspector;
|
|
80
92
|
/**
|
|
81
93
|
* The companion factory that creates containers, empty or preloaded from modules.
|
|
82
94
|
*
|
|
@@ -1,16 +1,13 @@
|
|
|
1
1
|
import { BindingChain } from "#container/binding-chain";
|
|
2
2
|
import { effectiveBindingScope, NO_INSTANCE } from "#core/binding";
|
|
3
|
-
import {
|
|
4
|
-
import { getOrInsert, getOrInsertComputed } from "#core/map-upsert";
|
|
3
|
+
import { getOrInsert } from "#core/map-upsert";
|
|
5
4
|
import { isSyncModule, MODULE_SETUP } from "#core/module";
|
|
6
5
|
import { BindingRegistry } from "#core/registry";
|
|
7
6
|
import { advanceDisposeEpoch, disposeEpochRef } from "#core/state-epoch";
|
|
8
7
|
import { tokenName } from "#core/token";
|
|
9
|
-
import { AsyncModuleLoadError,
|
|
10
|
-
import {
|
|
11
|
-
import { buildDependencyGraph } from "#introspection/dependency-graph";
|
|
8
|
+
import { AsyncModuleLoadError, DisposedContainerError, RebindUnboundTokenError } from "#errors";
|
|
9
|
+
import { bindingSlotToResolveOptions } from "#injection/dependency-slot";
|
|
12
10
|
import { RESOLUTION_DIAGNOSTICS } from "#introspection/diagnostics";
|
|
13
|
-
import { explainRequest } from "#introspection/explanation";
|
|
14
11
|
import { Inspector } from "#introspection/inspector";
|
|
15
12
|
import { LifecycleManager } from "#lifecycle/hooks";
|
|
16
13
|
import { SCOPED_MISS, ScopeManager } from "#lifecycle/scopes";
|
|
@@ -19,33 +16,26 @@ import { defaultMetadataReader } from "#metadata/symbol-reader";
|
|
|
19
16
|
import { verifyingMetadataReader } from "#metadata/verifying-reader";
|
|
20
17
|
import { ROOT_BRANCH } from "#resolution/path";
|
|
21
18
|
import { DependencyResolver } from "#resolution/resolver";
|
|
22
|
-
/**
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
19
|
+
/**
|
|
20
|
+
* Reads the internals of a live container `Container` created, built on first use.
|
|
21
|
+
*
|
|
22
|
+
* @throws `TypeError` for an object `Container` did not create, `DisposedContainerError` for a disposed chain.
|
|
23
|
+
*
|
|
24
|
+
* @since 0.14.0
|
|
25
|
+
*/
|
|
26
|
+
export function containerInternals(container) {
|
|
27
|
+
return DefaultContainer.internalsOf(container);
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Reads the inspector of a live container `Container` created, built on first use.
|
|
31
|
+
*
|
|
32
|
+
* @throws `TypeError` for an object `Container` did not create, `DisposedContainerError` for a disposed chain.
|
|
33
|
+
*
|
|
34
|
+
* @since 0.14.0
|
|
35
|
+
*/
|
|
36
|
+
export function containerInspector(container) {
|
|
37
|
+
return DefaultContainer.inspectorOf(container);
|
|
33
38
|
}
|
|
34
|
-
/** Hoisted so the slot-name index's `getOrInsertComputed` allocates only on a miss, no closure per call. */
|
|
35
|
-
const newSlotNameSet = () => new Set();
|
|
36
|
-
// A Record rather than an if-chain, so a new `BindingScope` is a compile error here instead of
|
|
37
|
-
// silently landing in whichever branch happened to be last.
|
|
38
|
-
const APPLY_BINDING_SCOPE = {
|
|
39
|
-
singleton: (builder) => {
|
|
40
|
-
builder.singleton();
|
|
41
|
-
},
|
|
42
|
-
scoped: (builder) => {
|
|
43
|
-
builder.scoped();
|
|
44
|
-
},
|
|
45
|
-
transient: (builder) => {
|
|
46
|
-
builder.transient();
|
|
47
|
-
},
|
|
48
|
-
};
|
|
49
39
|
const NO_DEACTIVATION_PAIRS = Object.freeze([]);
|
|
50
40
|
// ── DefaultContainer ─────────────────────────────────────────────────────────────────────────────────────────────────
|
|
51
41
|
class DefaultContainer {
|
|
@@ -53,7 +43,7 @@ class DefaultContainer {
|
|
|
53
43
|
// The dispose epoch at which this child's chain was last confirmed live. Every dispose anywhere
|
|
54
44
|
// bumps the epoch, so an unchanged epoch means no ancestor closed since — the chain needs no walk.
|
|
55
45
|
#liveGeneration = -1;
|
|
56
|
-
// The one teardown run — every
|
|
46
|
+
// The one teardown run — every disposeAsync() call returns it once it exists.
|
|
57
47
|
#disposePromise;
|
|
58
48
|
#registry;
|
|
59
49
|
#scope;
|
|
@@ -63,6 +53,8 @@ class DefaultContainer {
|
|
|
63
53
|
#hasConfiguredReader = false;
|
|
64
54
|
// Built on the first introspecting call — a container that only binds and resolves never needs it.
|
|
65
55
|
#inspector;
|
|
56
|
+
// Built on the first container function that reads it; every field it holds is fixed once the container exists.
|
|
57
|
+
#internals;
|
|
66
58
|
#parent;
|
|
67
59
|
// Module tracking: module -> ref count. Both tables stay unallocated until a module is loaded.
|
|
68
60
|
#moduleRefs;
|
|
@@ -140,10 +132,9 @@ class DefaultContainer {
|
|
|
140
132
|
get isDisposed() {
|
|
141
133
|
return this.#isChainDisposed();
|
|
142
134
|
}
|
|
143
|
-
|
|
144
|
-
bind(token) {
|
|
135
|
+
bind(key) {
|
|
145
136
|
this.#assertNotDisposed();
|
|
146
|
-
return this.#createBindToBuilder(
|
|
137
|
+
return this.#createBindToBuilder(key);
|
|
147
138
|
}
|
|
148
139
|
/** The registration every non-module chain shares, so `bind()` allocates only the builder. */
|
|
149
140
|
#ownRegistration() {
|
|
@@ -433,7 +424,7 @@ class DefaultContainer {
|
|
|
433
424
|
#createModuleBuilder(moduleRef) {
|
|
434
425
|
const registration = this.#moduleRegistration(moduleRef);
|
|
435
426
|
return {
|
|
436
|
-
bind: (
|
|
427
|
+
bind: (key) => this.#createBindToBuilder(key, registration),
|
|
437
428
|
import: (...modules) => {
|
|
438
429
|
this.#recordModuleImports(moduleRef, modules);
|
|
439
430
|
this.#loadSyncModules(modules);
|
|
@@ -443,7 +434,7 @@ class DefaultContainer {
|
|
|
443
434
|
#createAsyncModuleBuilder(moduleRef, importPromises) {
|
|
444
435
|
const registration = this.#moduleRegistration(moduleRef);
|
|
445
436
|
return {
|
|
446
|
-
bind: (
|
|
437
|
+
bind: (key) => this.#createBindToBuilder(key, registration),
|
|
447
438
|
import: (...modules) => {
|
|
448
439
|
this.#recordModuleImports(moduleRef, modules);
|
|
449
440
|
for (const module of modules) {
|
|
@@ -519,14 +510,6 @@ class DefaultContainer {
|
|
|
519
510
|
this.#moduleRefs.set(ref, count - 1);
|
|
520
511
|
}
|
|
521
512
|
}
|
|
522
|
-
loadAutoRegistered(registry) {
|
|
523
|
-
this.#assertNotDisposed();
|
|
524
|
-
const entries = registry.entries();
|
|
525
|
-
for (const { target, scope } of entries) {
|
|
526
|
-
APPLY_BINDING_SCOPE[scope](this.#createBindToBuilder(target).toSelf());
|
|
527
|
-
}
|
|
528
|
-
return entries.length;
|
|
529
|
-
}
|
|
530
513
|
// ── Lifecycle hooks ────────────────────────────────────────────────────────────────────────────────────────────────
|
|
531
514
|
onActivation(token, handler) {
|
|
532
515
|
this.#assertNotDisposed();
|
|
@@ -626,7 +609,7 @@ class DefaultContainer {
|
|
|
626
609
|
return child;
|
|
627
610
|
}
|
|
628
611
|
// ── Dispose ────────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
629
|
-
|
|
612
|
+
disposeAsync() {
|
|
630
613
|
// One teardown, shared: a second caller awaits the same run instead of returning early while
|
|
631
614
|
// hooks from the first are still executing.
|
|
632
615
|
return (this.#disposePromise ??= this.#runDispose());
|
|
@@ -687,10 +670,10 @@ class DefaultContainer {
|
|
|
687
670
|
}
|
|
688
671
|
}
|
|
689
672
|
this.#scope.clearAll();
|
|
690
|
-
throwCollected(errors, "
|
|
673
|
+
throwCollected(errors, "disposeAsync() completed, but deactivation hooks threw");
|
|
691
674
|
}
|
|
692
675
|
[Symbol.asyncDispose]() {
|
|
693
|
-
return this.
|
|
676
|
+
return this.disposeAsync();
|
|
694
677
|
}
|
|
695
678
|
// ── Initialization ─────────────────────────────────────────────────────────────────────────────────────────────────
|
|
696
679
|
async initializeAsync() {
|
|
@@ -719,208 +702,6 @@ class DefaultContainer {
|
|
|
719
702
|
}
|
|
720
703
|
}
|
|
721
704
|
}
|
|
722
|
-
// ── Validate ───────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
723
|
-
validate() {
|
|
724
|
-
this.#assertNotDisposed();
|
|
725
|
-
const reader = this.#getMetadataReader();
|
|
726
|
-
const allBindings = this.#registry.allBindings();
|
|
727
|
-
for (const binding of allBindings) {
|
|
728
|
-
if (!this.#isSingletonStaticAnalyzableBinding(binding)) {
|
|
729
|
-
continue;
|
|
730
|
-
}
|
|
731
|
-
this.#validateSingletonBindingGraph(binding, reader);
|
|
732
|
-
}
|
|
733
|
-
for (const [hookToken, phase] of this.#lifecycle.hookedTokens()) {
|
|
734
|
-
if (!this.#isBoundInChain(hookToken)) {
|
|
735
|
-
throw new UnreachableLifecycleHookError(tokenName(hookToken), phase);
|
|
736
|
-
}
|
|
737
|
-
// A deactivation never runs for a transient, so a hook on a token whose every binding is transient
|
|
738
|
-
// can never fire — the builder blocks it, `container.onDeactivation` cannot.
|
|
739
|
-
if (phase === "onDeactivation" && !this.#hasDeactivatableBindingInChain(hookToken)) {
|
|
740
|
-
throw new UnreachableLifecycleHookError(tokenName(hookToken), phase, "no-deactivatable-binding");
|
|
741
|
-
}
|
|
742
|
-
}
|
|
743
|
-
this.#validateConstraintRequirements(allBindings);
|
|
744
|
-
}
|
|
745
|
-
/** A constraint waiting on a slot name no binding declares can never hold. */
|
|
746
|
-
#validateConstraintRequirements(allBindings) {
|
|
747
|
-
let declaredSlotNames;
|
|
748
|
-
for (const binding of allBindings) {
|
|
749
|
-
const { predicate } = binding;
|
|
750
|
-
if (predicate === undefined) {
|
|
751
|
-
continue;
|
|
752
|
-
}
|
|
753
|
-
const requirements = constraintRequirementsOf(predicate);
|
|
754
|
-
if (requirements.length === 0) {
|
|
755
|
-
continue;
|
|
756
|
-
}
|
|
757
|
-
declaredSlotNames ??= this.#slotNamesInChain();
|
|
758
|
-
for (const requirement of requirements) {
|
|
759
|
-
if (!isSlotNameDeclared(declaredSlotNames, requirement)) {
|
|
760
|
-
throw new UnreachableConstraintError(tokenName(binding.token), requirement);
|
|
761
|
-
}
|
|
762
|
-
}
|
|
763
|
-
}
|
|
764
|
-
}
|
|
765
|
-
/** Every slot name declared anywhere a resolve through this container could reach, by declaring token. */
|
|
766
|
-
#slotNamesInChain() {
|
|
767
|
-
const names = this.#parent === undefined ? new Map() : this.#parent.#slotNamesInChain();
|
|
768
|
-
for (const binding of this.#registry.allBindings()) {
|
|
769
|
-
const name = binding.slot.name;
|
|
770
|
-
if (name !== undefined) {
|
|
771
|
-
getOrInsertComputed(names, tokenName(binding.token), newSlotNameSet).add(name);
|
|
772
|
-
}
|
|
773
|
-
}
|
|
774
|
-
return names;
|
|
775
|
-
}
|
|
776
|
-
// Ancestors count: a parent-owned binding is one this container can still resolve through.
|
|
777
|
-
#isBoundInChain(token) {
|
|
778
|
-
if (this.#registry.has(token)) {
|
|
779
|
-
return true;
|
|
780
|
-
}
|
|
781
|
-
const parent = this.#parent;
|
|
782
|
-
return parent !== undefined && parent.#isBoundInChain(token);
|
|
783
|
-
}
|
|
784
|
-
// Whether the token has a binding a deactivation hook can run for — anything but a transient.
|
|
785
|
-
#hasDeactivatableBindingInChain(token) {
|
|
786
|
-
for (const binding of this.#registry.getAll(token)) {
|
|
787
|
-
if (effectiveBindingScope(binding) !== "transient") {
|
|
788
|
-
return true;
|
|
789
|
-
}
|
|
790
|
-
}
|
|
791
|
-
const parent = this.#parent;
|
|
792
|
-
return parent !== undefined && parent.#hasDeactivatableBindingInChain(token);
|
|
793
|
-
}
|
|
794
|
-
#isSingletonStaticAnalyzableBinding(binding) {
|
|
795
|
-
if (effectiveBindingScope(binding) !== "singleton") {
|
|
796
|
-
return false;
|
|
797
|
-
}
|
|
798
|
-
return binding.kind === "class" || binding.kind === "resolved" || binding.kind === "resolved-async";
|
|
799
|
-
}
|
|
800
|
-
/**
|
|
801
|
-
* DFS over explicit constructor / `toResolved*` dependency edges, following `toAlias` chains to the terminal binding.
|
|
802
|
-
*
|
|
803
|
-
* @remarks Every binding reached is a singleton resolved from its owner's chain, so a required miss or a repeat
|
|
804
|
-
* on one path fails however the graph is entered; a `toDynamic*` edge is scope-checked, its factory not descended.
|
|
805
|
-
*/
|
|
806
|
-
#validateSingletonBindingGraph(root, reader) {
|
|
807
|
-
const rootName = tokenName(root.token);
|
|
808
|
-
const dfs = (current, view, pathNames, pathBindingIds) => {
|
|
809
|
-
if (pathBindingIds.has(current.identifier)) {
|
|
810
|
-
throw new CircularDependencyError(pathNames);
|
|
811
|
-
}
|
|
812
|
-
const extendedPathIds = new Set(pathBindingIds);
|
|
813
|
-
extendedPathIds.add(current.identifier);
|
|
814
|
-
for (const edge of this.#collectStaticDependencyEdges(current, view, reader, pathNames)) {
|
|
815
|
-
const { terminal, owner, depTokenName } = edge;
|
|
816
|
-
const depScope = this.#validationScopeFromTerminal(terminal);
|
|
817
|
-
if (depScope !== "singleton") {
|
|
818
|
-
throw new ScopeViolationError({
|
|
819
|
-
consumerToken: rootName,
|
|
820
|
-
consumerScope: "singleton",
|
|
821
|
-
dependencyToken: depTokenName,
|
|
822
|
-
dependencyScope: depScope,
|
|
823
|
-
path: [...pathNames, depTokenName],
|
|
824
|
-
});
|
|
825
|
-
}
|
|
826
|
-
if (terminal.kind === "class" || terminal.kind === "resolved" || terminal.kind === "resolved-async") {
|
|
827
|
-
dfs(terminal, owner, [...pathNames, depTokenName], extendedPathIds);
|
|
828
|
-
}
|
|
829
|
-
}
|
|
830
|
-
};
|
|
831
|
-
dfs(root, this.#resolver, [rootName], new Set());
|
|
832
|
-
}
|
|
833
|
-
/**
|
|
834
|
-
* The scope this edge is judged against.
|
|
835
|
-
*
|
|
836
|
-
* @remarks A factory's *body* is not statically analyzable, but the scope it was bound with is
|
|
837
|
-
* declared like any other — so the captive-dependency check applies to it too. The DFS still
|
|
838
|
-
* refuses to descend into a factory; only the edge is judged.
|
|
839
|
-
*/
|
|
840
|
-
#validationScopeFromTerminal(terminal) {
|
|
841
|
-
if (terminal.kind === "alias") {
|
|
842
|
-
throw new InternalError("validate: expected terminal binding after alias resolution");
|
|
843
|
-
}
|
|
844
|
-
return terminal.scope;
|
|
845
|
-
}
|
|
846
|
-
/** Where an alias chain ends as `resolve` walks it from `view`: its terminal binding, or the names up to a miss. */
|
|
847
|
-
#followAliasChainToTerminal(entry, view, options) {
|
|
848
|
-
const cyclePath = [];
|
|
849
|
-
const seenAliasIds = new Set();
|
|
850
|
-
let current = entry;
|
|
851
|
-
while (current.binding.kind === "alias") {
|
|
852
|
-
const alias = current.binding;
|
|
853
|
-
if (seenAliasIds.has(alias.identifier)) {
|
|
854
|
-
throw new CircularDependencyError(cyclePath);
|
|
855
|
-
}
|
|
856
|
-
seenAliasIds.add(alias.identifier);
|
|
857
|
-
cyclePath.push(tokenName(alias.token));
|
|
858
|
-
const next = view.peekBindingForValidate(alias.target, options);
|
|
859
|
-
if (next === undefined) {
|
|
860
|
-
return { found: false, missingToken: alias.target, hopNames: cyclePath };
|
|
861
|
-
}
|
|
862
|
-
current = next;
|
|
863
|
-
}
|
|
864
|
-
return { found: true, terminal: current.binding, owner: current.owner };
|
|
865
|
-
}
|
|
866
|
-
/** What one dependency could resolve to from `view`: every candidate for `injectAll`, else at most one. */
|
|
867
|
-
#peekDependencyCandidates(dep, view, options) {
|
|
868
|
-
if (dep.multi) {
|
|
869
|
-
return view
|
|
870
|
-
.peekCandidateBindingsForValidate(dep.token, options)
|
|
871
|
-
.map((binding) => ({ binding, owner: view.ownerForValidate(binding) }));
|
|
872
|
-
}
|
|
873
|
-
const found = view.peekBindingForValidate(dep.token, options);
|
|
874
|
-
return found === undefined ? [] : [found];
|
|
875
|
-
}
|
|
876
|
-
/** What a binding declares up front — a class's params, a factory's descriptors, else nothing. */
|
|
877
|
-
#staticDependencies(binding, reader) {
|
|
878
|
-
if (binding.kind === "class") {
|
|
879
|
-
return reader.getConstructorMetadata(binding.target)?.params ?? [];
|
|
880
|
-
}
|
|
881
|
-
if (binding.kind === "resolved" || binding.kind === "resolved-async") {
|
|
882
|
-
return binding.deps;
|
|
883
|
-
}
|
|
884
|
-
return [];
|
|
885
|
-
}
|
|
886
|
-
/**
|
|
887
|
-
* The bindings a singleton's declared dependencies resolve to, throwing the error `resolve` would for a required one
|
|
888
|
-
* nothing selects.
|
|
889
|
-
*/
|
|
890
|
-
#collectStaticDependencyEdges(binding, view, reader, pathNames) {
|
|
891
|
-
const edges = [];
|
|
892
|
-
for (const dep of this.#staticDependencies(binding, reader)) {
|
|
893
|
-
// An optional dependency that is absent peeks no candidate; one that is bound is captured like any other.
|
|
894
|
-
const depOptions = injectionSlotToResolveOptions(dep);
|
|
895
|
-
// A collection may be empty and an optional dependency absent, so only a required one can miss.
|
|
896
|
-
const required = !dep.multi && !dep.optional;
|
|
897
|
-
const candidates = this.#peekDependencyCandidates(dep, view, depOptions);
|
|
898
|
-
if (required && candidates.length === 0) {
|
|
899
|
-
const miss = view.missForValidate(dep.token, depOptions, [...pathNames, tokenName(dep.token)]);
|
|
900
|
-
if (miss !== undefined) {
|
|
901
|
-
throw miss;
|
|
902
|
-
}
|
|
903
|
-
}
|
|
904
|
-
for (const candidate of candidates) {
|
|
905
|
-
const end = this.#followAliasChainToTerminal(candidate, view, depOptions);
|
|
906
|
-
if (end.found) {
|
|
907
|
-
edges.push({ terminal: end.terminal, owner: end.owner, depTokenName: tokenName(end.terminal.token) });
|
|
908
|
-
continue;
|
|
909
|
-
}
|
|
910
|
-
if (required) {
|
|
911
|
-
const miss = view.missForValidate(end.missingToken, depOptions, [
|
|
912
|
-
...pathNames,
|
|
913
|
-
...end.hopNames,
|
|
914
|
-
tokenName(end.missingToken),
|
|
915
|
-
]);
|
|
916
|
-
if (miss !== undefined) {
|
|
917
|
-
throw miss;
|
|
918
|
-
}
|
|
919
|
-
}
|
|
920
|
-
}
|
|
921
|
-
}
|
|
922
|
-
return edges;
|
|
923
|
-
}
|
|
924
705
|
// ── Introspection ──────────────────────────────────────────────────────────────────────────────────────────────────
|
|
925
706
|
has(token, options) {
|
|
926
707
|
this.#assertNotDisposed();
|
|
@@ -939,21 +720,25 @@ class DefaultContainer {
|
|
|
939
720
|
this.#assertNotDisposed();
|
|
940
721
|
return this.#getInspector().hasOwn(token, options);
|
|
941
722
|
}
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
723
|
+
// Public statics of an unexported class: only this module's container functions can call them.
|
|
724
|
+
static internalsOf(container) {
|
|
725
|
+
const live = DefaultContainer.#live(container);
|
|
726
|
+
return (live.#internals ??= {
|
|
727
|
+
registries: [live.#registry, ...live.#ancestorRegistries()],
|
|
728
|
+
resolver: live.#resolver,
|
|
729
|
+
metadataReader: live.#getMetadataReader(),
|
|
730
|
+
lifecycle: live.#lifecycle,
|
|
731
|
+
});
|
|
949
732
|
}
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
return explainRequest([this.#registry, ...this.#ancestorRegistries()], token, options);
|
|
733
|
+
static inspectorOf(container) {
|
|
734
|
+
return DefaultContainer.#live(container).#getInspector();
|
|
953
735
|
}
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
736
|
+
static #live(container) {
|
|
737
|
+
if (!(#registry in container)) {
|
|
738
|
+
throw new TypeError("Expected a container created by Container.create().");
|
|
739
|
+
}
|
|
740
|
+
container.#assertNotDisposed();
|
|
741
|
+
return container;
|
|
957
742
|
}
|
|
958
743
|
/** The registries above this container, nearest first — the order every chain walk reads them in. */
|
|
959
744
|
#ancestorRegistries() {
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The functions that check and describe a container without resolving from it.
|
|
3
|
+
*/
|
|
4
|
+
import type { Container } from "#container/container";
|
|
5
|
+
import type { Token } from "#core/token";
|
|
6
|
+
import type { Constructor } from "#core/types";
|
|
7
|
+
import type { ContainerGraphJson, GraphOptions } from "#introspection/dependency-graph";
|
|
8
|
+
import type { ExplainOptions, ResolutionExplanation } from "#introspection/explanation";
|
|
9
|
+
import type { BindingSnapshot, ContainerSnapshot } from "#introspection/inspector";
|
|
10
|
+
/**
|
|
11
|
+
* Checks a container's singleton graphs, lifecycle hooks and constraints without instantiating anything.
|
|
12
|
+
*
|
|
13
|
+
* @remarks A singleton graph is followed through its declared dependencies the way `resolve` would follow them, so
|
|
14
|
+
* a missing binding, a cycle or a captive dependency fails here instead of on the first request.
|
|
15
|
+
*
|
|
16
|
+
* @since 0.14.0
|
|
17
|
+
*/
|
|
18
|
+
export declare function validate(container: Container): void;
|
|
19
|
+
/**
|
|
20
|
+
* Describes a container: the bindings it registers itself, its cached singletons, and whether it has a parent and is
|
|
21
|
+
* disposed.
|
|
22
|
+
*
|
|
23
|
+
* @since 0.14.0
|
|
24
|
+
*/
|
|
25
|
+
export declare function inspect(container: Container): ContainerSnapshot;
|
|
26
|
+
/**
|
|
27
|
+
* Describes the bindings a container registers itself for one token, ancestors excluded.
|
|
28
|
+
*
|
|
29
|
+
* @since 0.14.0
|
|
30
|
+
*/
|
|
31
|
+
export declare function lookupBindings<Value>(container: Container, token: Token<Value> | Constructor<Value>): ReadonlyArray<BindingSnapshot>;
|
|
32
|
+
/**
|
|
33
|
+
* Explains why a request selects the binding it does, reading each registry the way `resolve` does and deciding by
|
|
34
|
+
* the same rules, without instantiating anything.
|
|
35
|
+
*
|
|
36
|
+
* @remarks A `when()` predicate runs here as it would in `resolve`. `options.ancestors` names the resolutions the
|
|
37
|
+
* request is nested in, so a predicate that reads the parent sees the one it would.
|
|
38
|
+
*
|
|
39
|
+
* @since 0.14.0
|
|
40
|
+
*/
|
|
41
|
+
export declare function explain<Names extends string = string>(container: Container, token: Token<unknown, Names> | Constructor, options?: NoInfer<ExplainOptions<Names>>): ResolutionExplanation;
|
|
42
|
+
/**
|
|
43
|
+
* Builds the dependency graph of a container's own bindings, with the ancestors they resolve through.
|
|
44
|
+
*
|
|
45
|
+
* @since 0.14.0
|
|
46
|
+
*/
|
|
47
|
+
export declare function generateDependencyGraph(container: Container, options?: GraphOptions): ContainerGraphJson;
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { containerInspector, containerInternals } from "#container/container";
|
|
2
|
+
import { buildDependencyGraph } from "#introspection/dependency-graph";
|
|
3
|
+
import { explainRequest } from "#introspection/explanation";
|
|
4
|
+
import { validateChain } from "#introspection/validation";
|
|
5
|
+
/**
|
|
6
|
+
* Checks a container's singleton graphs, lifecycle hooks and constraints without instantiating anything.
|
|
7
|
+
*
|
|
8
|
+
* @remarks A singleton graph is followed through its declared dependencies the way `resolve` would follow them, so
|
|
9
|
+
* a missing binding, a cycle or a captive dependency fails here instead of on the first request.
|
|
10
|
+
*
|
|
11
|
+
* @since 0.14.0
|
|
12
|
+
*/
|
|
13
|
+
export function validate(container) {
|
|
14
|
+
validateChain(containerInternals(container));
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Describes a container: the bindings it registers itself, its cached singletons, and whether it has a parent and is
|
|
18
|
+
* disposed.
|
|
19
|
+
*
|
|
20
|
+
* @since 0.14.0
|
|
21
|
+
*/
|
|
22
|
+
export function inspect(container) {
|
|
23
|
+
return containerInspector(container).inspect();
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Describes the bindings a container registers itself for one token, ancestors excluded.
|
|
27
|
+
*
|
|
28
|
+
* @since 0.14.0
|
|
29
|
+
*/
|
|
30
|
+
export function lookupBindings(container, token) {
|
|
31
|
+
return containerInspector(container).lookupBindings(token);
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Explains why a request selects the binding it does, reading each registry the way `resolve` does and deciding by
|
|
35
|
+
* the same rules, without instantiating anything.
|
|
36
|
+
*
|
|
37
|
+
* @remarks A `when()` predicate runs here as it would in `resolve`. `options.ancestors` names the resolutions the
|
|
38
|
+
* request is nested in, so a predicate that reads the parent sees the one it would.
|
|
39
|
+
*
|
|
40
|
+
* @since 0.14.0
|
|
41
|
+
*/
|
|
42
|
+
export function explain(container, token, options) {
|
|
43
|
+
return explainRequest(containerInternals(container).registries, token, options);
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Builds the dependency graph of a container's own bindings, with the ancestors they resolve through.
|
|
47
|
+
*
|
|
48
|
+
* @since 0.14.0
|
|
49
|
+
*/
|
|
50
|
+
export function generateDependencyGraph(container, options) {
|
|
51
|
+
const { registries, metadataReader } = containerInternals(container);
|
|
52
|
+
return buildDependencyGraph(registries[0], metadataReader, options, registries.slice(1));
|
|
53
|
+
}
|
|
@@ -25,6 +25,28 @@ export interface SlotConstrainedBuilder<Names extends string = string> {
|
|
|
25
25
|
*/
|
|
26
26
|
many(): this;
|
|
27
27
|
}
|
|
28
|
+
/**
|
|
29
|
+
* The first step of a chain whose key is a class, which can also construct that class itself.
|
|
30
|
+
*
|
|
31
|
+
* @remarks A token names no class to construct, so only this chain offers `toSelf()`.
|
|
32
|
+
*
|
|
33
|
+
* @since 0.14.0
|
|
34
|
+
*/
|
|
35
|
+
export interface ClassBindToBuilder<Value> extends BindToBuilder<Value> {
|
|
36
|
+
toSelf(): BindingBuilder<Value>;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* The `bind` a container and a module builder share, so every place a binding starts is typed by one declaration.
|
|
40
|
+
*
|
|
41
|
+
* @remarks A class key starts a chain that can `toSelf()`; a token, or a key typed as either, starts one that cannot.
|
|
42
|
+
*
|
|
43
|
+
* @since 0.14.0
|
|
44
|
+
*/
|
|
45
|
+
export interface Binder {
|
|
46
|
+
bind<Value>(type: Constructor<Value>): ClassBindToBuilder<Value>;
|
|
47
|
+
bind<Value, Names extends string = string>(token: Token<Value, Names>): BindToBuilder<Value, Names>;
|
|
48
|
+
bind<Value, Names extends string = string>(key: Token<Value, Names> | Constructor<Value>): BindToBuilder<Value, Names>;
|
|
49
|
+
}
|
|
28
50
|
/**
|
|
29
51
|
* The first step of the fluent chain: the slot, then the `to*` strategy that registers the binding.
|
|
30
52
|
*
|
|
@@ -32,7 +54,6 @@ export interface SlotConstrainedBuilder<Names extends string = string> {
|
|
|
32
54
|
*/
|
|
33
55
|
export interface BindToBuilder<Value, Names extends string = string> extends SlotConstrainedBuilder<Names> {
|
|
34
56
|
to(type: Constructor<Value>): BindingBuilder<Value>;
|
|
35
|
-
toSelf(): BindingBuilder<Value>;
|
|
36
57
|
toConstantValue(value: Value): ConstantBindingBuilder<Value>;
|
|
37
58
|
toDynamic(factory: (ctx: ResolutionContext) => Value): BindingBuilder<Value>;
|
|
38
59
|
toDynamicAsync(factory: (ctx: ResolutionContext) => Promise<Value>): BindingBuilder<Value>;
|