@codefast/di 0.5.0-canary.7 → 0.5.0-canary.8

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 (100) hide show
  1. package/CHANGELOG.md +68 -0
  2. package/README.md +3 -1
  3. package/dist/binding.d.ts +47 -5
  4. package/dist/binding.d.ts.map +1 -1
  5. package/dist/binding.js +44 -0
  6. package/dist/binding.js.map +1 -1
  7. package/dist/constructor-type.d.ts +4 -5
  8. package/dist/constructor-type.d.ts.map +1 -1
  9. package/dist/container/binding-builders.d.ts +32 -11
  10. package/dist/container/binding-builders.d.ts.map +1 -1
  11. package/dist/container/binding-builders.js +140 -191
  12. package/dist/container/binding-builders.js.map +1 -1
  13. package/dist/container/container.d.ts.map +1 -1
  14. package/dist/container/container.js +75 -92
  15. package/dist/container/container.js.map +1 -1
  16. package/dist/decorators/inject.d.ts +2 -4
  17. package/dist/decorators/inject.d.ts.map +1 -1
  18. package/dist/decorators/inject.js.map +1 -1
  19. package/dist/errors.d.ts +14 -0
  20. package/dist/errors.d.ts.map +1 -1
  21. package/dist/errors.js +17 -0
  22. package/dist/errors.js.map +1 -1
  23. package/dist/index.d.ts +1 -1
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +1 -1
  26. package/dist/index.js.map +1 -1
  27. package/dist/introspection/inspector.js +1 -1
  28. package/dist/introspection/inspector.js.map +1 -1
  29. package/dist/metadata/metadata-keys.d.ts +3 -6
  30. package/dist/metadata/metadata-keys.d.ts.map +1 -1
  31. package/dist/metadata/metadata-keys.js +3 -6
  32. package/dist/metadata/metadata-keys.js.map +1 -1
  33. package/dist/registry.d.ts +14 -2
  34. package/dist/registry.d.ts.map +1 -1
  35. package/dist/registry.js +35 -45
  36. package/dist/registry.js.map +1 -1
  37. package/dist/resolution/activation-need.d.ts +25 -0
  38. package/dist/resolution/activation-need.d.ts.map +1 -0
  39. package/dist/resolution/activation-need.js +64 -0
  40. package/dist/resolution/activation-need.js.map +1 -0
  41. package/dist/resolution/binding-lookup-cache.d.ts +41 -0
  42. package/dist/resolution/binding-lookup-cache.d.ts.map +1 -0
  43. package/dist/resolution/binding-lookup-cache.js +102 -0
  44. package/dist/resolution/binding-lookup-cache.js.map +1 -0
  45. package/dist/resolution/binding-select.js +1 -4
  46. package/dist/resolution/binding-select.js.map +1 -1
  47. package/dist/resolution/class-introspector.d.ts +27 -0
  48. package/dist/resolution/class-introspector.d.ts.map +1 -0
  49. package/dist/resolution/class-introspector.js +60 -0
  50. package/dist/resolution/class-introspector.js.map +1 -0
  51. package/dist/resolution/diagnostics.d.ts +41 -0
  52. package/dist/resolution/diagnostics.d.ts.map +1 -0
  53. package/dist/resolution/diagnostics.js +18 -0
  54. package/dist/resolution/diagnostics.js.map +1 -0
  55. package/dist/resolution/environment.d.ts +22 -1
  56. package/dist/resolution/environment.d.ts.map +1 -1
  57. package/dist/resolution/environment.js +27 -1
  58. package/dist/resolution/environment.js.map +1 -1
  59. package/dist/resolution/instantiation-plan.d.ts +15 -15
  60. package/dist/resolution/instantiation-plan.d.ts.map +1 -1
  61. package/dist/resolution/instantiation-plan.js +68 -48
  62. package/dist/resolution/instantiation-plan.js.map +1 -1
  63. package/dist/resolution/lifecycle.d.ts +2 -0
  64. package/dist/resolution/lifecycle.d.ts.map +1 -1
  65. package/dist/resolution/lifecycle.js +16 -11
  66. package/dist/resolution/lifecycle.js.map +1 -1
  67. package/dist/resolution/resolution-path.d.ts +4 -13
  68. package/dist/resolution/resolution-path.d.ts.map +1 -1
  69. package/dist/resolution/resolution-path.js +3 -16
  70. package/dist/resolution/resolution-path.js.map +1 -1
  71. package/dist/resolution/resolver.d.ts +7 -2
  72. package/dist/resolution/resolver.d.ts.map +1 -1
  73. package/dist/resolution/resolver.js +116 -328
  74. package/dist/resolution/resolver.js.map +1 -1
  75. package/dist/resolution/scope.d.ts +7 -15
  76. package/dist/resolution/scope.d.ts.map +1 -1
  77. package/dist/resolution/scope.js +48 -44
  78. package/dist/resolution/scope.js.map +1 -1
  79. package/package.json +7 -97
  80. package/src/binding.ts +104 -5
  81. package/src/constructor-type.ts +4 -5
  82. package/src/container/binding-builders.ts +180 -283
  83. package/src/container/container.ts +90 -103
  84. package/src/decorators/inject.ts +3 -5
  85. package/src/errors.ts +21 -0
  86. package/src/index.ts +1 -0
  87. package/src/introspection/inspector.ts +1 -1
  88. package/src/metadata/metadata-keys.ts +3 -6
  89. package/src/registry.ts +38 -59
  90. package/src/resolution/activation-need.ts +81 -0
  91. package/src/resolution/binding-lookup-cache.ts +132 -0
  92. package/src/resolution/binding-select.ts +1 -4
  93. package/src/resolution/class-introspector.ts +74 -0
  94. package/src/resolution/diagnostics.ts +43 -0
  95. package/src/resolution/environment.ts +31 -1
  96. package/src/resolution/instantiation-plan.ts +113 -61
  97. package/src/resolution/lifecycle.ts +16 -11
  98. package/src/resolution/resolution-path.ts +5 -20
  99. package/src/resolution/resolver.ts +142 -371
  100. package/src/resolution/scope.ts +50 -49
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Per binding: does resolving it have to go through the activation pipeline?
3
+ *
4
+ * @remarks Versioned on the lifecycle manager, since `onActivation` can be registered at any time.
5
+ */
6
+ import type { Binding } from "#/binding";
7
+ import type { ClassIntrospector } from "#/resolution/class-introspector";
8
+ import type { LifecycleManager } from "#/resolution/lifecycle";
9
+ import type { BindingIdentifier } from "#/types";
10
+
11
+ /**
12
+ * @since 0.5.0-canary.8
13
+ */
14
+ export class ActivationNeedCache {
15
+ readonly #needByBindingId = new Map<BindingIdentifier, boolean>();
16
+ #version = -1;
17
+ readonly #lifecycle: LifecycleManager;
18
+ readonly #classes: ClassIntrospector;
19
+
20
+ constructor(lifecycle: LifecycleManager, classes: ClassIntrospector) {
21
+ this.#lifecycle = lifecycle;
22
+ this.#classes = classes;
23
+ }
24
+
25
+ needsActivation<const Value>(binding: Binding<Value>): boolean {
26
+ const lifecycleVersion = this.#lifecycle.activationVersion;
27
+ // No hooks registered anywhere and none on the binding: only classes can still surprise us,
28
+ // via a @postConstruct we have not looked for yet.
29
+ if (
30
+ lifecycleVersion === 0 &&
31
+ binding.kind !== "class" &&
32
+ binding.kind !== "alias" &&
33
+ binding.onActivation === undefined
34
+ ) {
35
+ return false;
36
+ }
37
+ if (this.#version !== lifecycleVersion) {
38
+ this.#needByBindingId.clear();
39
+ this.#version = lifecycleVersion;
40
+ }
41
+ const cached = this.#needByBindingId.get(binding.id);
42
+ if (cached !== undefined) {
43
+ return cached;
44
+ }
45
+ const needsActivation =
46
+ binding.kind === "class" ? this.#classNeedsActivation(binding) : this.#nonClassNeedsActivation(binding);
47
+ this.#needByBindingId.set(binding.id, needsActivation);
48
+ return needsActivation;
49
+ }
50
+
51
+ /**
52
+ * Settles a class binding's answer once its lifecycle metadata has actually been read, which
53
+ * only happens on the first instantiation.
54
+ *
55
+ * @returns the answer to use for this resolve — possibly now `false` where it was a
56
+ * conservative `true`.
57
+ */
58
+ refreshAfterFirstInstantiation<Value>(binding: Binding<Value>, needsActivation: boolean): boolean {
59
+ if (binding.kind !== "class" || this.#classes.knownPostConstruct(binding.target) !== undefined) {
60
+ return needsActivation;
61
+ }
62
+ this.#classes.discoverPostConstruct(binding.target);
63
+ this.#needByBindingId.delete(binding.id);
64
+ return this.needsActivation(binding);
65
+ }
66
+
67
+ #classNeedsActivation<const Value>(binding: Binding<Value> & { kind: "class" }): boolean {
68
+ if (this.#lifecycle.hasActivationHandlers(binding.token) || binding.onActivation !== undefined) {
69
+ return true;
70
+ }
71
+ // Unknown lifecycle metadata: activate once so the first instantiation can settle it.
72
+ return this.#classes.knownPostConstruct(binding.target) !== false;
73
+ }
74
+
75
+ #nonClassNeedsActivation<const Value>(binding: Binding<Value>): boolean {
76
+ if (binding.kind !== "alias" && binding.onActivation !== undefined) {
77
+ return true;
78
+ }
79
+ return this.#lifecycle.hasActivationHandlers(binding.token);
80
+ }
81
+ }
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Options-less token → terminal binding, memoized per container chain.
3
+ *
4
+ * @see `ARCHITECTURE.md` — why these caches form their own parent chain.
5
+ */
6
+ import type { Binding } from "#/binding";
7
+ import type { BindingRegistry } from "#/registry";
8
+ import type { Token } from "#/token";
9
+ import type { Constructor } from "#/types";
10
+
11
+ /**
12
+ * A token's terminal binding with alias hops already folded, plus the container that owns it.
13
+ *
14
+ * @typeParam Owner - the resolver type, kept generic so this module stays free of resolver internals
15
+ *
16
+ * @since 0.5.0-canary.8
17
+ */
18
+ export interface DefaultLookupEntry<Owner> {
19
+ readonly binding: Binding;
20
+ readonly owner: Owner;
21
+ }
22
+
23
+ /**
24
+ * Alias folding gives up past this many hops and defers to the full resolve loop, whose
25
+ * Set-based traversal detects genuine cycles exactly rather than by an arbitrary cap.
26
+ *
27
+ * @since 0.5.0-canary.8
28
+ */
29
+ export const ALIAS_HOP_LIMIT = 32;
30
+
31
+ /**
32
+ * @since 0.5.0-canary.8
33
+ */
34
+ export class BindingLookupCache<Owner> {
35
+ readonly #byToken = new Map<Token<unknown> | Constructor, DefaultLookupEntry<Owner> | null>();
36
+ #version = -1;
37
+ readonly #byTokenAndName = new Map<Token<unknown> | Constructor, Map<string, DefaultLookupEntry<Owner> | null>>();
38
+ #namedVersion = -1;
39
+
40
+ readonly #registry: BindingRegistry;
41
+ readonly #owner: Owner;
42
+ readonly #parent: BindingLookupCache<Owner> | undefined;
43
+
44
+ constructor(registry: BindingRegistry, owner: Owner, parent: BindingLookupCache<Owner> | undefined) {
45
+ this.#registry = registry;
46
+ this.#owner = owner;
47
+ this.#parent = parent;
48
+ }
49
+
50
+ /** Summed registry versions of this cache's whole chain — the memo stamp. */
51
+ chainVersion(): number {
52
+ let version = this.#registry.version;
53
+ for (let cache = this.#parent; cache !== undefined; cache = cache.#parent) {
54
+ version += cache.#registry.version;
55
+ }
56
+ return version;
57
+ }
58
+
59
+ /** `null` when the token's shape needs the full selection path. */
60
+ defaultEntry(token: Token<unknown> | Constructor): DefaultLookupEntry<Owner> | null {
61
+ const version = this.chainVersion();
62
+ if (version !== this.#version) {
63
+ this.#byToken.clear();
64
+ this.#version = version;
65
+ }
66
+ let entry = this.#byToken.get(token);
67
+ if (entry === undefined) {
68
+ entry = this.#foldAliases(token);
69
+ this.#byToken.set(token, entry);
70
+ }
71
+ return entry;
72
+ }
73
+
74
+ /** `null` when the name's shape needs the full selection path. */
75
+ namedEntry(token: Token<unknown> | Constructor, name: string): DefaultLookupEntry<Owner> | null {
76
+ const version = this.chainVersion();
77
+ if (version !== this.#namedVersion) {
78
+ this.#byTokenAndName.clear();
79
+ this.#namedVersion = version;
80
+ }
81
+ // ✓ TS6.0: Map.getOrInsert (ES2025)
82
+ const byName = this.#byTokenAndName.getOrInsert(token, new Map<string, DefaultLookupEntry<Owner> | null>());
83
+ let entry = byName.get(name);
84
+ if (entry === undefined) {
85
+ entry = this.#findNamedInChain(token, name);
86
+ byName.set(name, entry);
87
+ }
88
+ return entry;
89
+ }
90
+
91
+ #foldAliases(token: Token<unknown> | Constructor): DefaultLookupEntry<Owner> | null {
92
+ let current = token;
93
+ for (let hop = 0; hop < ALIAS_HOP_LIMIT; hop += 1) {
94
+ const entry = this.#findDefaultInChain(current);
95
+ if (entry === null) {
96
+ return null;
97
+ }
98
+ if (entry.binding.kind !== "alias") {
99
+ return entry;
100
+ }
101
+ current = entry.binding.target;
102
+ }
103
+ return null;
104
+ }
105
+
106
+ #findDefaultInChain(token: Token<unknown> | Constructor): DefaultLookupEntry<Owner> | null {
107
+ const fast = this.#registry.getFastDefault(token);
108
+ if (fast !== undefined) {
109
+ return { binding: fast, owner: this.#owner };
110
+ }
111
+ // A level with non-fast bindings (multi-slot / predicate) needs full selection — bail.
112
+ if (this.#registry.has(token)) {
113
+ return null;
114
+ }
115
+ return this.#parent === undefined ? null : this.#parent.#findDefaultInChain(token);
116
+ }
117
+
118
+ #findNamedInChain(token: Token<unknown> | Constructor, name: string): DefaultLookupEntry<Owner> | null {
119
+ const named = this.#registry.getSimpleNamed(token, name);
120
+ if (named !== undefined) {
121
+ // Predicates need a live context; aliases carry options through the full path.
122
+ if (named.predicate !== undefined || named.kind === "alias") {
123
+ return null;
124
+ }
125
+ return { binding: named, owner: this.#owner };
126
+ }
127
+ if (this.#registry.has(token)) {
128
+ return null;
129
+ }
130
+ return this.#parent === undefined ? null : this.#parent.#findNamedInChain(token, name);
131
+ }
132
+ }
@@ -135,10 +135,7 @@ function matchesSlot(binding: Binding, options: ResolveOptions | undefined): boo
135
135
  }
136
136
  }
137
137
  } else if (hasRequestedTags) {
138
- // Binding has no tags but options requires tags — no match for tagged slots
139
- // But: default slot (no tags, no name) can match when options has tags if there are no tag-slotted bindings
140
- // Actually per spec: resolveAll with tags only returns bindings that have those tags
141
- // and resolve with tags requires exact match
138
+ // Requested tags require a tagged slot: an untagged binding never matches (SPEC §6.9).
142
139
  return false;
143
140
  }
144
141
 
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Per-class decorator metadata, cached by constructor.
3
+ *
4
+ * @remarks Metadata cannot change once a class is defined, so nothing here needs version stamping.
5
+ */
6
+
7
+ import type { ConstructorInvocation } from "#/constructor-type";
8
+ import type { Container } from "#/container/container";
9
+ import type { ConstructorMetadata, MetadataReader } from "#/metadata/metadata-types";
10
+ import { runWithContainer } from "#/resolution/environment";
11
+ import type { Constructor } from "#/types";
12
+
13
+ /**
14
+ * @since 0.5.0-canary.8
15
+ */
16
+ export class ClassIntrospector {
17
+ // Unallocated until the container resolves its first class binding — a container bound entirely
18
+ // to constants, factories or aliases never introspects one.
19
+ #constructorMetadata: WeakMap<Constructor, ConstructorMetadata | null> | undefined;
20
+ #hasPostConstruct: WeakMap<Constructor, boolean> | undefined;
21
+ #needsActiveContainer: WeakMap<Constructor, boolean> | undefined;
22
+ readonly #reader: MetadataReader;
23
+ readonly #container: Container;
24
+
25
+ constructor(reader: MetadataReader, container: Container) {
26
+ this.#reader = reader;
27
+ this.#container = container;
28
+ }
29
+
30
+ constructorMetadata(target: Constructor): ConstructorMetadata | undefined {
31
+ const cached = this.#constructorMetadata?.get(target);
32
+ if (cached !== undefined) {
33
+ return cached === null ? undefined : cached;
34
+ }
35
+ const metadata = this.#reader.getConstructorMetadata(target);
36
+ (this.#constructorMetadata ??= new WeakMap()).set(target, metadata ?? null);
37
+ return metadata;
38
+ }
39
+
40
+ /**
41
+ * Whether the class has a `@postConstruct` hook, or `undefined` until {@link discoverPostConstruct}.
42
+ *
43
+ * @remarks Callers treat unknown as "assume it does", so the first activation settles it.
44
+ */
45
+ knownPostConstruct(target: Constructor): boolean | undefined {
46
+ return this.#hasPostConstruct?.get(target);
47
+ }
48
+
49
+ discoverPostConstruct(target: Constructor): void {
50
+ const lifecycle = this.#reader.getLifecycleMetadata(target);
51
+ (this.#hasPostConstruct ??= new WeakMap()).set(
52
+ target,
53
+ lifecycle !== undefined && lifecycle.postConstruct !== undefined && lifecycle.postConstruct.length > 0,
54
+ );
55
+ }
56
+
57
+ /** True when the class has accessor injection, which reads the container during construction. */
58
+ needsActiveContainer(target: Constructor): boolean {
59
+ let needsActiveContainer = this.#needsActiveContainer?.get(target);
60
+ if (needsActiveContainer === undefined) {
61
+ needsActiveContainer = (this.#reader.getAccessorMetadata?.(target)?.length ?? 0) > 0;
62
+ (this.#needsActiveContainer ??= new WeakMap()).set(target, needsActiveContainer);
63
+ }
64
+ return needsActiveContainer;
65
+ }
66
+
67
+ instantiate(target: Constructor, deps: Array<unknown>): unknown {
68
+ const invokable = target as ConstructorInvocation;
69
+ if (!this.needsActiveContainer(target)) {
70
+ return new invokable(...deps);
71
+ }
72
+ return runWithContainer(this.#container, () => new invokable(...deps));
73
+ }
74
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Internal seam letting tests assert that an optimization is *active*, not merely that the result
3
+ * is correct.
4
+ *
5
+ * @remarks Timing belongs in the benchmark, which needs a quiet machine and twenty minutes; these
6
+ * are structural counts, so CI can hold the invariants that make the benchmark fast. Reached
7
+ * through a symbol from a module the package does not publish, so it is not public API.
8
+ */
9
+
10
+ /**
11
+ * Key for the diagnostics accessor on a container.
12
+ *
13
+ * @remarks A symbol rather than a method name, so it cannot collide with the public surface or be
14
+ * reached by anyone who has not imported this module.
15
+ *
16
+ * @since 0.5.0-canary.8
17
+ */
18
+ export const RESOLUTION_DIAGNOSTICS: unique symbol = Symbol("di:resolution-diagnostics");
19
+
20
+ /**
21
+ * Structural facts about a container's resolution caches.
22
+ *
23
+ * @since 0.5.0-canary.8
24
+ */
25
+ export interface ResolutionDiagnostics {
26
+ /** Bindings with a compiled instantiation plan. */
27
+ readonly compiledPlanCount: number;
28
+ /** Contexts held by the depth-indexed sync pool. */
29
+ readonly syncContextPoolSize: number;
30
+ /** Contexts returned to the async chain pool and available for reuse. */
31
+ readonly asyncContextPoolSize: number;
32
+ /** Deferred collaborators this container has had to build. */
33
+ readonly builtSubsystems: ReadonlyArray<string>;
34
+ }
35
+
36
+ /**
37
+ * A container that can report on its resolution caches.
38
+ *
39
+ * @since 0.5.0-canary.8
40
+ */
41
+ export interface DiagnosableContainer {
42
+ [RESOLUTION_DIAGNOSTICS](): ResolutionDiagnostics;
43
+ }
@@ -56,6 +56,7 @@ export interface ResolverCallbacks {
56
56
  token: Token<Value> | Constructor<Value>,
57
57
  resolutionPath: Array<string>,
58
58
  resolutionStack: Array<ResolutionFrame>,
59
+ callerContext?: DefaultResolutionContext,
59
60
  ): Promise<Value>;
60
61
  resolveAsync<const Value>(
61
62
  token: Token<Value> | Constructor<Value>,
@@ -105,6 +106,7 @@ export class DefaultResolutionContext implements ResolutionContext {
105
106
  currentOptions: ResolveOptions | undefined,
106
107
  ) {
107
108
  this.#resolver = resolver;
109
+ this.owner = resolver;
108
110
  this.#resolutionPath = resolutionPath;
109
111
  this.#resolutionStack = resolutionStack;
110
112
  this.#currentOptions = currentOptions;
@@ -112,6 +114,30 @@ export class DefaultResolutionContext implements ResolutionContext {
112
114
 
113
115
  #graph: ConstraintContext | undefined;
114
116
 
117
+ /**
118
+ * The unwind callback shared by every level of the async chain this context serves.
119
+ *
120
+ * @remarks A plain field, not a lazy accessor — a getter taking a factory would allocate that
121
+ * factory on every level, which is the allocation this exists to avoid.
122
+ */
123
+ chainSettle: (() => void) | undefined;
124
+
125
+ /**
126
+ * How many levels of the async chain are still in flight on this context.
127
+ *
128
+ * @remarks The chain's first level acquires the context and every level increments; the last
129
+ * one to settle returns it to the resolver's pool. Counting here rather than on the resolver
130
+ * is what lets two concurrent chains run without a shared counter to get wrong.
131
+ */
132
+ chainLevels = 0;
133
+
134
+ /**
135
+ * The resolver this context speaks to — an inner async level checks it before reusing this.
136
+ *
137
+ * @remarks A field, not a method, because the check runs on every hop of every chain.
138
+ */
139
+ owner: ResolverCallbacks;
140
+
115
141
  get graph(): ConstraintContext {
116
142
  if (this.#graph === undefined) {
117
143
  this.#graph = new DefaultConstraintContext(this.#resolutionPath, this.#resolutionStack, this.#currentOptions);
@@ -126,10 +152,13 @@ export class DefaultResolutionContext implements ResolutionContext {
126
152
  currentOptions: ResolveOptions | undefined,
127
153
  ): void {
128
154
  this.#resolver = resolver;
155
+ this.owner = resolver;
129
156
  this.#resolutionPath = resolutionPath;
130
157
  this.#resolutionStack = resolutionStack;
131
158
  this.#currentOptions = currentOptions;
132
159
  this.#graph = undefined;
160
+ this.chainSettle = undefined;
161
+ this.chainLevels = 0;
133
162
  }
134
163
 
135
164
  resolve<const Value>(token: Token<Value> | Constructor<Value>, options?: ResolveOptions): Value {
@@ -141,7 +170,8 @@ export class DefaultResolutionContext implements ResolutionContext {
141
170
 
142
171
  resolveAsync<const Value>(token: Token<Value> | Constructor<Value>, options?: ResolveOptions): Promise<Value> {
143
172
  if (options === undefined) {
144
- return this.#resolver.resolveAsyncFromContext(token, this.#resolutionPath, this.#resolutionStack);
173
+ // Hand the callee this context: an inner level of the same chain reuses it as-is.
174
+ return this.#resolver.resolveAsyncFromContext(token, this.#resolutionPath, this.#resolutionStack, this);
145
175
  }
146
176
  return this.#resolver.resolveAsync(token, options, this.#resolutionPath, this.#resolutionStack);
147
177
  }