@codefast/di 0.12.0 → 0.14.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.
Files changed (54) hide show
  1. package/CHANGELOG.md +192 -0
  2. package/README.md +142 -43
  3. package/dist/ambient-container.d.ts +46 -0
  4. package/dist/ambient-container.js +72 -1
  5. package/dist/container/binding-chain.js +3 -3
  6. package/dist/container/container.d.ts +41 -30
  7. package/dist/container/container.js +59 -243
  8. package/dist/container/introspect.d.ts +47 -0
  9. package/dist/container/introspect.js +53 -0
  10. package/dist/core/binding-builders.d.ts +27 -3
  11. package/dist/core/binding-declaration.d.ts +2 -2
  12. package/dist/core/binding-declaration.js +4 -4
  13. package/dist/core/module.d.ts +4 -25
  14. package/dist/core/module.js +3 -27
  15. package/dist/core/state-epoch.d.ts +1 -1
  16. package/dist/core/state-epoch.js +1 -1
  17. package/dist/core/types.d.ts +16 -7
  18. package/dist/decorators/inject.d.ts +3 -1
  19. package/dist/decorators/inject.js +27 -22
  20. package/dist/decorators/injectable.d.ts +14 -18
  21. package/dist/decorators/injectable.js +23 -2
  22. package/dist/decorators/lifecycle.d.ts +9 -3
  23. package/dist/decorators/lifecycle.js +5 -1
  24. package/dist/errors.d.ts +33 -15
  25. package/dist/errors.js +41 -21
  26. package/dist/index.d.ts +9 -8
  27. package/dist/index.js +4 -3
  28. package/dist/injection/dependency-slot.d.ts +17 -0
  29. package/dist/injection/dependency-slot.js +46 -0
  30. package/dist/injection/descriptor.d.ts +9 -3
  31. package/dist/injection/descriptor.js +10 -1
  32. package/dist/introspection/explanation.js +26 -8
  33. package/dist/introspection/validation.d.ts +28 -0
  34. package/dist/introspection/validation.js +244 -0
  35. package/dist/lifecycle/hooks.d.ts +13 -2
  36. package/dist/lifecycle/hooks.js +36 -18
  37. package/dist/lifecycle/scopes.d.ts +21 -2
  38. package/dist/lifecycle/scopes.js +86 -2
  39. package/dist/metadata/keys.d.ts +1 -1
  40. package/dist/metadata/keys.js +1 -1
  41. package/dist/resolution/cache/class-introspector.d.ts +7 -8
  42. package/dist/resolution/cache/class-introspector.js +40 -3
  43. package/dist/resolution/cache/lookup.d.ts +10 -0
  44. package/dist/resolution/cache/lookup.js +27 -0
  45. package/dist/resolution/context.d.ts +12 -12
  46. package/dist/resolution/path.d.ts +12 -2
  47. package/dist/resolution/path.js +22 -2
  48. package/dist/resolution/plan/codegen.d.ts +2 -1
  49. package/dist/resolution/plan/codegen.js +1 -1
  50. package/dist/resolution/plan/compiler.d.ts +6 -6
  51. package/dist/resolution/plan/compiler.js +152 -22
  52. package/dist/resolution/resolver.d.ts +6 -0
  53. package/dist/resolution/resolver.js +39 -84
  54. package/package.json +11 -3
@@ -1,3 +1,73 @@
1
+ // Slots whose initializer asks for a prepared value — an `@inject` accessor's own descriptor.
2
+ const preparableSlots = new WeakSet();
3
+ /**
4
+ * Marks a slot whose accessor initializer takes a prepared value when one is offered.
5
+ *
6
+ * @since 0.14.0
7
+ */
8
+ export function markPreparableSlot(slot) {
9
+ preparableSlots.add(slot);
10
+ }
11
+ /**
12
+ * Whether an initializer will ask for this slot's prepared value, so preparing it is never wasted.
13
+ *
14
+ * @since 0.14.0
15
+ */
16
+ export function isPreparableSlot(slot) {
17
+ return preparableSlots.has(slot);
18
+ }
19
+ /**
20
+ * The answer {@link AmbientResolution.takePrepared} gives for an accessor it holds no value for.
21
+ *
22
+ * @since 0.14.0
23
+ */
24
+ export const NOT_PREPARED = Symbol("di:not-prepared");
25
+ /**
26
+ * Accessor values a compiled plan resolved before construction, handed to the initializers in order.
27
+ *
28
+ * @remarks An initializer takes the next value only when its slot is the next one prepared and it
29
+ * initializes the instance that took the first, so a class constructed inside the constructor
30
+ * resolves for itself instead of taking another instance's value.
31
+ *
32
+ * @since 0.14.0
33
+ */
34
+ export class PreparedAccessorResolution {
35
+ #fallback;
36
+ #slots;
37
+ #values;
38
+ #next = 0;
39
+ #owner = undefined;
40
+ /**
41
+ * @param fallback - Resolves an accessor the plan did not prepare, with the class on the path.
42
+ * @param slots - The accessors' slots, in the order their initializers run.
43
+ * @param values - One resolved value per slot.
44
+ */
45
+ constructor(fallback, slots, values) {
46
+ this.#fallback = fallback;
47
+ this.#slots = slots;
48
+ this.#values = values;
49
+ }
50
+ resolve(token, options) {
51
+ return this.#fallback.resolve(token, options);
52
+ }
53
+ resolveOptional(token, options) {
54
+ return this.#fallback.resolveOptional(token, options);
55
+ }
56
+ takePrepared(instance, slot) {
57
+ const index = this.#next;
58
+ if (this.#slots[index] !== slot) {
59
+ return NOT_PREPARED;
60
+ }
61
+ if (index === 0) {
62
+ this.#owner = instance;
63
+ }
64
+ else if (this.#owner !== instance) {
65
+ return NOT_PREPARED;
66
+ }
67
+ this.#next = index + 1;
68
+ return this.#values[index];
69
+ }
70
+ }
1
71
  let activeContainer;
2
72
  let activeResolution;
3
73
  /**
@@ -45,7 +115,8 @@ export function constructWithAmbientResolution(container, resolution, target, de
45
115
  activeContainer = container;
46
116
  activeResolution = resolution;
47
117
  try {
48
- return new target(...deps);
118
+ // A spread call is not inlined, and most accessor classes take no constructor arguments.
119
+ return deps.length === 0 ? new target() : new target(...deps);
49
120
  }
50
121
  finally {
51
122
  activeContainer = previousContainer;
@@ -3,7 +3,7 @@ import { mergingConstraintRequirements } from "#core/constraint-requirement";
3
3
  import { slotName } from "#core/tag";
4
4
  import { tokenName } from "#core/token";
5
5
  import { ChainAlreadyRegisteredError, ChainNotRegisteredError, ManyBindingSlotError, SelfBindingRequiresClassError, } from "#errors";
6
- import { normalizeToDescriptor } from "#injection/descriptor";
6
+ import { settledDescriptorsOf } from "#injection/descriptor";
7
7
  // ── BindingChain ─────────────────────────────────────────────────────────────────────────────────────────────────────
8
8
  /**
9
9
  * The one builder behind `bind()` and every `to*()` return type — and the binding it registers.
@@ -149,13 +149,13 @@ export class BindingChain {
149
149
  toResolved(factory, deps) {
150
150
  this.#requireUnregistered();
151
151
  this.factory = factory;
152
- this.deps = deps.map((dependency) => normalizeToDescriptor(dependency));
152
+ this.deps = settledDescriptorsOf(deps);
153
153
  return this.#register("resolved", "transient");
154
154
  }
155
155
  toResolvedAsync(factory, deps) {
156
156
  this.#requireUnregistered();
157
157
  this.factory = factory;
158
- this.deps = deps.map((dependency) => normalizeToDescriptor(dependency));
158
+ this.deps = settledDescriptorsOf(deps);
159
159
  return this.#register("resolved-async", "transient");
160
160
  }
161
161
  toAlias(target) {
@@ -1,57 +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 type { AutoRegisterRegistry } from "#decorators/injectable";
6
- import type { ContainerGraphJson, GraphOptions } from "#introspection/dependency-graph";
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, Names extends string = string>(token: Token<Value, Names> | Constructor<Value>): BindToBuilder<Value, Names>;
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
- dispose(): Promise<void>;
31
+ disposeAsync(): Promise<void>;
38
32
  [Symbol.asyncDispose](): Promise<void>;
39
- [Symbol.dispose](): never;
40
33
  initializeAsync(): Promise<void>;
41
- validate(): void;
42
34
  has<Names extends string = string>(token: Token<unknown, Names> | Constructor, options?: NoInfer<ResolveOptions<Names>>): boolean;
43
35
  hasOwn<Names extends string = string>(token: Token<unknown, Names> | Constructor, options?: NoInfer<ResolveOptions<Names>>): boolean;
44
- lookupBindings<Value>(token: Token<Value> | Constructor<Value>): ReadonlyArray<BindingSnapshot>;
45
- inspect(): ContainerSnapshot;
46
- /**
47
- * Explains why a request selects the binding it does, reading each registry the way `resolve` does and deciding
48
- * by the same rules, without instantiating anything.
49
- *
50
- * @remarks A `when()` predicate runs here as it would in `resolve`. `options.ancestors` names the resolutions the
51
- * request is nested in, so a predicate that reads the parent sees the one it would.
52
- */
53
- explain<Names extends string = string>(token: Token<unknown, Names> | Constructor, options?: NoInfer<ExplainOptions<Names>>): ResolutionExplanation;
54
- generateDependencyGraph(options?: GraphOptions): ContainerGraphJson;
55
36
  }
56
37
  /**
57
38
  * What a container has to be told before it exists, as opposed to what it can be bound later.
@@ -78,6 +59,36 @@ export interface ContainerStatic {
78
59
  fromModules(...modules: Array<SyncModule>): Container;
79
60
  fromModulesAsync(...modules: Array<SyncModule | AsyncModule>): Promise<Container>;
80
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;
81
92
  /**
82
93
  * The companion factory that creates containers, empty or preloaded from modules.
83
94
  *
@@ -1,51 +1,41 @@
1
1
  import { BindingChain } from "#container/binding-chain";
2
2
  import { effectiveBindingScope, NO_INSTANCE } from "#core/binding";
3
- import { constraintRequirementsOf } from "#core/constraint-requirement";
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, CircularDependencyError, DisposedContainerError, InternalError, RebindUnboundTokenError, ScopeViolationError, SyncDisposalNotSupportedError, UnreachableConstraintError, UnreachableLifecycleHookError, } from "#errors";
10
- import { injectionSlotToResolveOptions, bindingSlotToResolveOptions } from "#injection/dependency-slot";
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
- import { ScopeManager } from "#lifecycle/scopes";
13
+ import { SCOPED_MISS, ScopeManager } from "#lifecycle/scopes";
17
14
  import { MetadataReaderToken } from "#metadata/reader-token";
18
15
  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
- /** Whether a requirement's name is declared — on its token when it names one, on any token otherwise. */
23
- function isSlotNameDeclared(declared, requirement) {
24
- if (requirement.tokenName !== undefined) {
25
- return declared.get(requirement.tokenName)?.has(requirement.name) ?? false;
26
- }
27
- for (const names of declared.values()) {
28
- if (names.has(requirement.name)) {
29
- return true;
30
- }
31
- }
32
- return false;
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 dispose() call returns it once it exists.
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
- // ── Binding ────────────────────────────────────────────────────────────────────────────────────────────────────────
144
- bind(token) {
135
+ bind(key) {
145
136
  this.#assertNotDisposed();
146
- return this.#createBindToBuilder(token);
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() {
@@ -223,7 +214,10 @@ class DefaultContainer {
223
214
  else if (this.#owesConstantDeactivation(binding)) {
224
215
  (pairs ??= []).push(binding, binding.value);
225
216
  }
226
- this.#scope.deleteScoped(binding.scopedCacheKey);
217
+ const scopedInstance = this.#scope.takeScoped(binding.scopedCacheKey);
218
+ if (scopedInstance !== SCOPED_MISS) {
219
+ (pairs ??= []).push(binding, scopedInstance);
220
+ }
227
221
  return pairs;
228
222
  }
229
223
  /**
@@ -430,7 +424,7 @@ class DefaultContainer {
430
424
  #createModuleBuilder(moduleRef) {
431
425
  const registration = this.#moduleRegistration(moduleRef);
432
426
  return {
433
- bind: (token) => this.#createBindToBuilder(token, registration),
427
+ bind: (key) => this.#createBindToBuilder(key, registration),
434
428
  import: (...modules) => {
435
429
  this.#recordModuleImports(moduleRef, modules);
436
430
  this.#loadSyncModules(modules);
@@ -440,7 +434,7 @@ class DefaultContainer {
440
434
  #createAsyncModuleBuilder(moduleRef, importPromises) {
441
435
  const registration = this.#moduleRegistration(moduleRef);
442
436
  return {
443
- bind: (token) => this.#createBindToBuilder(token, registration),
437
+ bind: (key) => this.#createBindToBuilder(key, registration),
444
438
  import: (...modules) => {
445
439
  this.#recordModuleImports(moduleRef, modules);
446
440
  for (const module of modules) {
@@ -516,14 +510,6 @@ class DefaultContainer {
516
510
  this.#moduleRefs.set(ref, count - 1);
517
511
  }
518
512
  }
519
- loadAutoRegistered(registry) {
520
- this.#assertNotDisposed();
521
- const entries = registry.entries();
522
- for (const { target, scope } of entries) {
523
- APPLY_BINDING_SCOPE[scope](this.#createBindToBuilder(target).toSelf());
524
- }
525
- return entries.length;
526
- }
527
513
  // ── Lifecycle hooks ────────────────────────────────────────────────────────────────────────────────────────────────
528
514
  onActivation(token, handler) {
529
515
  this.#assertNotDisposed();
@@ -623,7 +609,7 @@ class DefaultContainer {
623
609
  return child;
624
610
  }
625
611
  // ── Dispose ────────────────────────────────────────────────────────────────────────────────────────────────────────
626
- dispose() {
612
+ disposeAsync() {
627
613
  // One teardown, shared: a second caller awaits the same run instead of returning early while
628
614
  // hooks from the first are still executing.
629
615
  return (this.#disposePromise ??= this.#runDispose());
@@ -637,6 +623,11 @@ class DefaultContainer {
637
623
  await this.#scope.settleInflight();
638
624
  const reader = this.#getMetadataReader();
639
625
  const errors = [];
626
+ // A scoped instance may hold this container's singletons and never the reverse, so it goes first, latest first.
627
+ const scopedTeardown = this.#scope.deactivateScoped(errors);
628
+ if (scopedTeardown !== undefined) {
629
+ await scopedTeardown;
630
+ }
640
631
  // Iterate a copy: a deactivation handler is user code, and the live list is what
641
632
  // materializing or dropping a singleton mutates. Reverse materialization order, so a
642
633
  // dependent tears down before the dependencies it may still reach through.
@@ -679,13 +670,10 @@ class DefaultContainer {
679
670
  }
680
671
  }
681
672
  this.#scope.clearAll();
682
- throwCollected(errors, "dispose() completed, but deactivation hooks threw");
673
+ throwCollected(errors, "disposeAsync() completed, but deactivation hooks threw");
683
674
  }
684
675
  [Symbol.asyncDispose]() {
685
- return this.dispose();
686
- }
687
- [Symbol.dispose]() {
688
- throw new SyncDisposalNotSupportedError();
676
+ return this.disposeAsync();
689
677
  }
690
678
  // ── Initialization ─────────────────────────────────────────────────────────────────────────────────────────────────
691
679
  async initializeAsync() {
@@ -714,182 +702,6 @@ class DefaultContainer {
714
702
  }
715
703
  }
716
704
  }
717
- // ── Validate ───────────────────────────────────────────────────────────────────────────────────────────────────────
718
- validate() {
719
- this.#assertNotDisposed();
720
- const reader = this.#getMetadataReader();
721
- const allBindings = this.#registry.allBindings();
722
- for (const binding of allBindings) {
723
- if (!this.#isSingletonStaticAnalyzableBinding(binding)) {
724
- continue;
725
- }
726
- this.#validateSingletonBindingGraph(binding, reader);
727
- }
728
- for (const [hookToken, phase] of this.#lifecycle.hookedTokens()) {
729
- if (!this.#isBoundInChain(hookToken)) {
730
- throw new UnreachableLifecycleHookError(tokenName(hookToken), phase);
731
- }
732
- // A deactivation only ever runs for a singleton or constant, so a hook on a token whose every
733
- // binding is scoped or transient can never fire — the builder blocks it, `container.onDeactivation` cannot.
734
- if (phase === "onDeactivation" && !this.#hasDeactivatableBindingInChain(hookToken)) {
735
- throw new UnreachableLifecycleHookError(tokenName(hookToken), phase, "no-deactivatable-binding");
736
- }
737
- }
738
- this.#validateConstraintRequirements(allBindings);
739
- }
740
- /** A constraint waiting on a slot name no binding declares can never hold. */
741
- #validateConstraintRequirements(allBindings) {
742
- let declaredSlotNames;
743
- for (const binding of allBindings) {
744
- const { predicate } = binding;
745
- if (predicate === undefined) {
746
- continue;
747
- }
748
- const requirements = constraintRequirementsOf(predicate);
749
- if (requirements.length === 0) {
750
- continue;
751
- }
752
- declaredSlotNames ??= this.#slotNamesInChain();
753
- for (const requirement of requirements) {
754
- if (!isSlotNameDeclared(declaredSlotNames, requirement)) {
755
- throw new UnreachableConstraintError(tokenName(binding.token), requirement);
756
- }
757
- }
758
- }
759
- }
760
- /** Every slot name declared anywhere a resolve through this container could reach, by declaring token. */
761
- #slotNamesInChain() {
762
- const names = this.#parent === undefined ? new Map() : this.#parent.#slotNamesInChain();
763
- for (const binding of this.#registry.allBindings()) {
764
- const name = binding.slot.name;
765
- if (name !== undefined) {
766
- getOrInsertComputed(names, tokenName(binding.token), newSlotNameSet).add(name);
767
- }
768
- }
769
- return names;
770
- }
771
- // Ancestors count: a parent-owned binding is one this container can still resolve through.
772
- #isBoundInChain(token) {
773
- if (this.#registry.has(token)) {
774
- return true;
775
- }
776
- const parent = this.#parent;
777
- return parent !== undefined && parent.#isBoundInChain(token);
778
- }
779
- // Whether the token has a binding a deactivation hook can run for — a singleton or a constant.
780
- #hasDeactivatableBindingInChain(token) {
781
- for (const binding of this.#registry.getAll(token)) {
782
- if (effectiveBindingScope(binding) === "singleton") {
783
- return true;
784
- }
785
- }
786
- const parent = this.#parent;
787
- return parent !== undefined && parent.#hasDeactivatableBindingInChain(token);
788
- }
789
- #isSingletonStaticAnalyzableBinding(binding) {
790
- if (effectiveBindingScope(binding) !== "singleton") {
791
- return false;
792
- }
793
- return binding.kind === "class" || binding.kind === "resolved" || binding.kind === "resolved-async";
794
- }
795
- /**
796
- * DFS over explicit constructor / `toResolved*` dependency edges. Follows `toAlias` chains to the
797
- * terminal binding for scope checks.
798
- *
799
- * @remarks A `toDynamic*` dependency is scope-checked like any other — its declared scope is what
800
- * makes it captive — but the DFS does not descend into the factory, whose body is opaque.
801
- */
802
- #validateSingletonBindingGraph(root, reader) {
803
- const rootName = tokenName(root.token);
804
- const dfs = (current, pathNames, pathBindingIds) => {
805
- if (pathBindingIds.has(current.identifier)) {
806
- return;
807
- }
808
- const extendedPathIds = new Set(pathBindingIds);
809
- extendedPathIds.add(current.identifier);
810
- for (const edge of this.#collectStaticDependencyEdges(current, reader)) {
811
- const { terminal, depTokenName } = edge;
812
- const depScope = this.#validationScopeFromTerminal(terminal);
813
- if (depScope !== "singleton") {
814
- throw new ScopeViolationError({
815
- consumerToken: rootName,
816
- consumerScope: "singleton",
817
- dependencyToken: depTokenName,
818
- dependencyScope: depScope,
819
- path: [...pathNames, depTokenName],
820
- });
821
- }
822
- if (terminal.kind === "class" || terminal.kind === "resolved" || terminal.kind === "resolved-async") {
823
- dfs(terminal, [...pathNames, depTokenName], extendedPathIds);
824
- }
825
- }
826
- };
827
- dfs(root, [rootName], new Set());
828
- }
829
- /**
830
- * The scope this edge is judged against.
831
- *
832
- * @remarks A factory's *body* is not statically analyzable, but the scope it was bound with is
833
- * declared like any other — so the captive-dependency check applies to it too. The DFS still
834
- * refuses to descend into a factory; only the edge is judged.
835
- */
836
- #validationScopeFromTerminal(terminal) {
837
- if (terminal.kind === "alias") {
838
- throw new InternalError("validate: expected terminal binding after alias resolution");
839
- }
840
- return terminal.scope;
841
- }
842
- #followAliasChainToTerminal(binding, options) {
843
- const cyclePath = [];
844
- const seenAliasIds = new Set();
845
- let current = binding;
846
- while (current !== undefined && current.kind === "alias") {
847
- if (seenAliasIds.has(current.identifier)) {
848
- throw new CircularDependencyError(cyclePath);
849
- }
850
- seenAliasIds.add(current.identifier);
851
- cyclePath.push(tokenName(current.token));
852
- const nextToken = current.target;
853
- const next = this.#resolver.peekBindingForValidate(nextToken, options);
854
- if (next === undefined) {
855
- return undefined;
856
- }
857
- current = next.binding;
858
- }
859
- return current;
860
- }
861
- /** What one dependency could resolve to: every candidate for `injectAll`, else at most one. */
862
- #peekDependencyCandidates(dep, options) {
863
- if (dep.multi) {
864
- return this.#resolver.peekCandidateBindingsForValidate(dep.token, options);
865
- }
866
- const found = this.#resolver.peekBindingForValidate(dep.token, options);
867
- return found === undefined ? [] : [found.binding];
868
- }
869
- /** What a binding declares up front — a class's params, a factory's descriptors, else nothing. */
870
- #staticDependencies(binding, reader) {
871
- if (binding.kind === "class") {
872
- return reader.getConstructorMetadata(binding.target)?.params ?? [];
873
- }
874
- if (binding.kind === "resolved" || binding.kind === "resolved-async") {
875
- return binding.deps;
876
- }
877
- return [];
878
- }
879
- #collectStaticDependencyEdges(binding, reader) {
880
- const edges = [];
881
- for (const dep of this.#staticDependencies(binding, reader)) {
882
- // An optional dependency that is absent peeks no candidate; one that is bound is captured like any other.
883
- const depOptions = injectionSlotToResolveOptions(dep);
884
- for (const candidate of this.#peekDependencyCandidates(dep, depOptions)) {
885
- const terminal = this.#followAliasChainToTerminal(candidate, depOptions);
886
- if (terminal !== undefined) {
887
- edges.push({ terminal, depTokenName: tokenName(terminal.token) });
888
- }
889
- }
890
- }
891
- return edges;
892
- }
893
705
  // ── Introspection ──────────────────────────────────────────────────────────────────────────────────────────────────
894
706
  has(token, options) {
895
707
  this.#assertNotDisposed();
@@ -908,21 +720,25 @@ class DefaultContainer {
908
720
  this.#assertNotDisposed();
909
721
  return this.#getInspector().hasOwn(token, options);
910
722
  }
911
- lookupBindings(token) {
912
- this.#assertNotDisposed();
913
- return this.#getInspector().lookupBindings(token);
914
- }
915
- inspect() {
916
- this.#assertNotDisposed();
917
- return this.#getInspector().inspect();
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
+ });
918
732
  }
919
- explain(token, options) {
920
- this.#assertNotDisposed();
921
- return explainRequest([this.#registry, ...this.#ancestorRegistries()], token, options);
733
+ static inspectorOf(container) {
734
+ return DefaultContainer.#live(container).#getInspector();
922
735
  }
923
- generateDependencyGraph(options) {
924
- this.#assertNotDisposed();
925
- return buildDependencyGraph(this.#registry, this.#getMetadataReader(), options, this.#ancestorRegistries());
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;
926
742
  }
927
743
  /** The registries above this container, nearest first — the order every chain walk reads them in. */
928
744
  #ancestorRegistries() {