@asenajs/ioc 0.0.0-stage → 0.2.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 (147) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +219 -2
  3. package/dist/index.d.ts +1 -0
  4. package/dist/index.js +2 -0
  5. package/dist/index.js.map +1 -0
  6. package/dist/lib/CircularDependencyDetector.d.ts +49 -0
  7. package/dist/lib/CircularDependencyDetector.js +69 -0
  8. package/dist/lib/CircularDependencyDetector.js.map +1 -0
  9. package/dist/lib/Container.d.ts +259 -0
  10. package/dist/lib/Container.js +577 -0
  11. package/dist/lib/Container.js.map +1 -0
  12. package/dist/lib/IocApplication.d.ts +88 -0
  13. package/dist/lib/IocApplication.js +110 -0
  14. package/dist/lib/IocApplication.js.map +1 -0
  15. package/dist/lib/IocEngine.d.ts +173 -0
  16. package/dist/lib/IocEngine.js +723 -0
  17. package/dist/lib/IocEngine.js.map +1 -0
  18. package/dist/lib/component/Scope.d.ts +4 -0
  19. package/dist/lib/component/Scope.js +6 -0
  20. package/dist/lib/component/Scope.js.map +1 -0
  21. package/dist/lib/component/componentRegistry.d.ts +34 -0
  22. package/dist/lib/component/componentRegistry.js +134 -0
  23. package/dist/lib/component/componentRegistry.js.map +1 -0
  24. package/dist/lib/component/componentUtils.d.ts +16 -0
  25. package/dist/lib/component/componentUtils.js +44 -0
  26. package/dist/lib/component/componentUtils.js.map +1 -0
  27. package/dist/lib/component/decorators/Component.d.ts +8 -0
  28. package/dist/lib/component/decorators/Component.js +12 -0
  29. package/dist/lib/component/decorators/Component.js.map +1 -0
  30. package/dist/lib/component/decorators/Implements.d.ts +7 -0
  31. package/dist/lib/component/decorators/Implements.js +14 -0
  32. package/dist/lib/component/decorators/Implements.js.map +1 -0
  33. package/dist/lib/component/decorators/Inject.d.ts +29 -0
  34. package/dist/lib/component/decorators/Inject.js +82 -0
  35. package/dist/lib/component/decorators/Inject.js.map +1 -0
  36. package/dist/lib/component/decorators/OnStart.d.ts +20 -0
  37. package/dist/lib/component/decorators/OnStart.js +33 -0
  38. package/dist/lib/component/decorators/OnStart.js.map +1 -0
  39. package/dist/lib/component/decorators/OnStop.d.ts +15 -0
  40. package/dist/lib/component/decorators/OnStop.js +28 -0
  41. package/dist/lib/component/decorators/OnStop.js.map +1 -0
  42. package/dist/lib/component/decorators/PostConstruct.d.ts +14 -0
  43. package/dist/lib/component/decorators/PostConstruct.js +16 -0
  44. package/dist/lib/component/decorators/PostConstruct.js.map +1 -0
  45. package/dist/lib/component/decorators/PostProcessor.d.ts +25 -0
  46. package/dist/lib/component/decorators/PostProcessor.js +29 -0
  47. package/dist/lib/component/decorators/PostProcessor.js.map +1 -0
  48. package/dist/lib/component/decorators/Service.d.ts +8 -0
  49. package/dist/lib/component/decorators/Service.js +12 -0
  50. package/dist/lib/component/decorators/Service.js.map +1 -0
  51. package/dist/lib/component/decorators/Strategy.d.ts +9 -0
  52. package/dist/lib/component/decorators/Strategy.js +29 -0
  53. package/dist/lib/component/decorators/Strategy.js.map +1 -0
  54. package/dist/lib/component/decorators/Value.d.ts +29 -0
  55. package/dist/lib/component/decorators/Value.js +41 -0
  56. package/dist/lib/component/decorators/Value.js.map +1 -0
  57. package/dist/lib/component/decorators/index.d.ts +11 -0
  58. package/dist/lib/component/decorators/index.js +12 -0
  59. package/dist/lib/component/decorators/index.js.map +1 -0
  60. package/dist/lib/component/decorators/legacyDecorator.d.ts +15 -0
  61. package/dist/lib/component/decorators/legacyDecorator.js +24 -0
  62. package/dist/lib/component/decorators/legacyDecorator.js.map +1 -0
  63. package/dist/lib/component/index.d.ts +3 -0
  64. package/dist/lib/component/index.js +4 -0
  65. package/dist/lib/component/index.js.map +1 -0
  66. package/dist/lib/constants/ComponentConstants.d.ts +21 -0
  67. package/dist/lib/constants/ComponentConstants.js +25 -0
  68. package/dist/lib/constants/ComponentConstants.js.map +1 -0
  69. package/dist/lib/constants/index.d.ts +1 -0
  70. package/dist/lib/constants/index.js +2 -0
  71. package/dist/lib/constants/index.js.map +1 -0
  72. package/dist/lib/decorators/CoreService.d.ts +11 -0
  73. package/dist/lib/decorators/CoreService.js +30 -0
  74. package/dist/lib/decorators/CoreService.js.map +1 -0
  75. package/dist/lib/decorators/index.d.ts +1 -0
  76. package/dist/lib/decorators/index.js +2 -0
  77. package/dist/lib/decorators/index.js.map +1 -0
  78. package/dist/lib/helper/fileHelper.d.ts +1 -0
  79. package/dist/lib/helper/fileHelper.js +29 -0
  80. package/dist/lib/helper/fileHelper.js.map +1 -0
  81. package/dist/lib/helper/iocHelper.d.ts +2 -0
  82. package/dist/lib/helper/iocHelper.js +12 -0
  83. package/dist/lib/helper/iocHelper.js.map +1 -0
  84. package/dist/lib/helper/valueResolver.d.ts +24 -0
  85. package/dist/lib/helper/valueResolver.js +37 -0
  86. package/dist/lib/helper/valueResolver.js.map +1 -0
  87. package/dist/lib/index.d.ts +12 -0
  88. package/dist/lib/index.js +13 -0
  89. package/dist/lib/index.js.map +1 -0
  90. package/dist/lib/lifecycle/LifecycleService.d.ts +78 -0
  91. package/dist/lib/lifecycle/LifecycleService.js +181 -0
  92. package/dist/lib/lifecycle/LifecycleService.js.map +1 -0
  93. package/dist/lib/lifecycle/LifecycleState.d.ts +20 -0
  94. package/dist/lib/lifecycle/LifecycleState.js +22 -0
  95. package/dist/lib/lifecycle/LifecycleState.js.map +1 -0
  96. package/dist/lib/lifecycle/index.d.ts +2 -0
  97. package/dist/lib/lifecycle/index.js +3 -0
  98. package/dist/lib/lifecycle/index.js.map +1 -0
  99. package/dist/lib/logger/IocLogger.d.ts +35 -0
  100. package/dist/lib/logger/IocLogger.js +2 -0
  101. package/dist/lib/logger/IocLogger.js.map +1 -0
  102. package/dist/lib/logger/index.d.ts +1 -0
  103. package/dist/lib/logger/index.js +2 -0
  104. package/dist/lib/logger/index.js.map +1 -0
  105. package/dist/lib/types/Class.d.ts +1 -0
  106. package/dist/lib/types/Class.js +2 -0
  107. package/dist/lib/types/Class.js.map +1 -0
  108. package/dist/lib/types/ComponentPostProcessor.d.ts +30 -0
  109. package/dist/lib/types/ComponentPostProcessor.js +2 -0
  110. package/dist/lib/types/ComponentPostProcessor.js.map +1 -0
  111. package/dist/lib/types/ContainerService.d.ts +6 -0
  112. package/dist/lib/types/ContainerService.js +2 -0
  113. package/dist/lib/types/ContainerService.js.map +1 -0
  114. package/dist/lib/types/ICoreService.d.ts +9 -0
  115. package/dist/lib/types/ICoreService.js +2 -0
  116. package/dist/lib/types/ICoreService.js.map +1 -0
  117. package/dist/lib/types/ICoreServiceNames.d.ts +10 -0
  118. package/dist/lib/types/ICoreServiceNames.js +12 -0
  119. package/dist/lib/types/ICoreServiceNames.js.map +1 -0
  120. package/dist/lib/types/InjectableComponent.d.ts +42 -0
  121. package/dist/lib/types/InjectableComponent.js +2 -0
  122. package/dist/lib/types/InjectableComponent.js.map +1 -0
  123. package/dist/lib/types/IocConfig.d.ts +11 -0
  124. package/dist/lib/types/IocConfig.js +2 -0
  125. package/dist/lib/types/IocConfig.js.map +1 -0
  126. package/dist/lib/types/LifecycleComponent.d.ts +29 -0
  127. package/dist/lib/types/LifecycleComponent.js +2 -0
  128. package/dist/lib/types/LifecycleComponent.js.map +1 -0
  129. package/dist/lib/types/decorators/ComponentParams.d.ts +5 -0
  130. package/dist/lib/types/decorators/ComponentParams.js +2 -0
  131. package/dist/lib/types/decorators/ComponentParams.js.map +1 -0
  132. package/dist/lib/types/decorators/ComponentType.d.ts +14 -0
  133. package/dist/lib/types/decorators/ComponentType.js +10 -0
  134. package/dist/lib/types/decorators/ComponentType.js.map +1 -0
  135. package/dist/lib/types/decorators/ServiceParams.d.ts +2 -0
  136. package/dist/lib/types/decorators/ServiceParams.js +2 -0
  137. package/dist/lib/types/decorators/ServiceParams.js.map +1 -0
  138. package/dist/lib/types/index.d.ts +11 -0
  139. package/dist/lib/types/index.js +12 -0
  140. package/dist/lib/types/index.js.map +1 -0
  141. package/dist/lib/utils/errorChain.d.ts +4 -0
  142. package/dist/lib/utils/errorChain.js +29 -0
  143. package/dist/lib/utils/errorChain.js.map +1 -0
  144. package/dist/lib/utils/typedMetadata.d.ts +54 -0
  145. package/dist/lib/utils/typedMetadata.js +97 -0
  146. package/dist/lib/utils/typedMetadata.js.map +1 -0
  147. package/package.json +73 -4
@@ -0,0 +1,723 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ import { ComponentType, ICoreServiceNames, } from './types';
11
+ import { getAllFiles } from './helper/fileHelper';
12
+ import * as path from 'node:path';
13
+ import { ComponentConstants } from './constants';
14
+ import * as process from 'node:process';
15
+ import { getStrategyClass } from './helper/iocHelper';
16
+ import { getOwnTypedMetadata, getTypedMetadata } from './utils/typedMetadata';
17
+ import { getComponentsDeclaredIn, Inject, Scope } from './component';
18
+ import { CoreService } from './decorators';
19
+ import { CircularDependencyError } from './CircularDependencyDetector';
20
+ /**
21
+ * @description IoC Engine - Manages component registration and dependency injection
22
+ * Core service that handles automatic component discovery and registration
23
+ */
24
+ /**
25
+ * @description How long a single component file may take to import before the
26
+ * engine points at it. Only a warning - the import is never cancelled.
27
+ */
28
+ const DEFAULT_IMPORT_TIMEOUT = 10_000;
29
+ let IocEngine = class IocEngine {
30
+ serviceName = 'IocEngine';
31
+ _container;
32
+ logger;
33
+ injectables = [];
34
+ config;
35
+ /** Entry files kept out of the scan, empty unless the scan actually ran */
36
+ entryFiles = new Set();
37
+ /** Entry-declared components that existed by the time the scan ran */
38
+ entryComponents = new Set();
39
+ /**
40
+ * @description Set IoC configuration
41
+ * @param {IocConfig} config - IoC configuration object
42
+ * @returns {void}
43
+ */
44
+ setConfig(config) {
45
+ this.config = config;
46
+ }
47
+ async searchAndRegister(components, imports) {
48
+ // load components
49
+ await this.loadComponents(components, imports);
50
+ this.rejectTakenNames();
51
+ this.reportEmptyStrategyKeys();
52
+ const injectableClasses = this.injectables.map((c) => c.Class);
53
+ // Two-phase registration for PostProcessor support
54
+ const { postProcessorClasses, remainingClasses } = this.separatePostProcessors(injectableClasses);
55
+ // Phase A: Register PostProcessors and their dependencies first (without post-processing)
56
+ if (postProcessorClasses.length > 0) {
57
+ await this.validateAndRegisterComponents(postProcessorClasses);
58
+ // Resolve only actual PostProcessor instances (not their dependencies) and activate them
59
+ for (const cls of postProcessorClasses) {
60
+ const isPostProcessor = getOwnTypedMetadata(ComponentType.POST_PROCESSOR, cls);
61
+ if (isPostProcessor) {
62
+ const name = getTypedMetadata(ComponentConstants.NameKey, cls) || cls.name;
63
+ const instance = await this._container.resolve(name);
64
+ this._container.registerPostProcessor(instance);
65
+ }
66
+ }
67
+ }
68
+ // Phase B: Register remaining components (post-processing is now active)
69
+ //
70
+ // Their start hooks are held back for LifecycleService to run from start(), so a
71
+ // hook sees the finished graph. Phase A deliberately keeps the old timing: a
72
+ // post-processor's postProcess() reads what its own start hook set up, so deferring it
73
+ // would wrap every component in Phase B against an uninitialised processor.
74
+ if (remainingClasses.length > 0) {
75
+ this._container.setStartHookMode('deferred');
76
+ try {
77
+ await this.validateAndRegisterComponents(remainingClasses);
78
+ }
79
+ finally {
80
+ this._container.setStartHookMode('immediate');
81
+ }
82
+ }
83
+ }
84
+ async loadComponents(components, imports) {
85
+ const importInjectables = this.processImports(imports);
86
+ if (components?.length) {
87
+ const invalid = components.find((component) => !this.isValidComponent(component.Class));
88
+ if (invalid) {
89
+ throw new Error(this.describeInvalidListedComponent(invalid.Class));
90
+ }
91
+ this.injectables = this.dedupeInjectables([...components, ...importInjectables]);
92
+ return;
93
+ }
94
+ if (!this.config) {
95
+ // Imports alone are a valid component source: a package-only app has no sourceFolder
96
+ // to scan, and silently skipping them would be exactly the failure `imports` prevents
97
+ if (importInjectables.length) {
98
+ this.injectables = this.dedupeInjectables(importInjectables);
99
+ return;
100
+ }
101
+ throw new Error('No components or configuration found');
102
+ }
103
+ const entryFiles = (this.entryFiles = this.resolveEntryFiles());
104
+ // The entry file must not be imported. While it awaits the bootstrap call
105
+ // at module scope it is in the evaluating-async state, so importing it here is a
106
+ // cyclic dynamic import that can only settle once this scan returns - a deadlock
107
+ // (Bun >= 1.3.14 follows the spec and waits, older versions short-circuited it).
108
+ const files = getAllFiles(this.config.sourceFolder).filter((file) => !entryFiles.has(this.toAbsolutePath(file)));
109
+ const scanned = await this.getInjectables(files);
110
+ // Components declared directly in the entry file are still supported: their
111
+ // decorators ran before the bootstrap call, so they come from the registry
112
+ // rather than from a module namespace
113
+ const entryClasses = getComponentsDeclaredIn(entryFiles);
114
+ this.entryComponents = new Set(entryClasses);
115
+ const declaredInEntry = this.processComponents(entryClasses);
116
+ this.injectables = this.dedupeInjectables([
117
+ ...this.injectables,
118
+ ...scanned,
119
+ ...declaredInEntry,
120
+ ...importInjectables,
121
+ ]);
122
+ if (!this.injectables.length) {
123
+ throw new Error('No components found');
124
+ }
125
+ }
126
+ describeClass(candidate) {
127
+ return typeof candidate === 'function' ? candidate.name || '(anonymous class)' : `(${typeof candidate})`;
128
+ }
129
+ /**
130
+ * @description Refuse a component whose name is already held by something registered ahead of
131
+ * the components: one of the container's own services, or a pre-built instance.
132
+ *
133
+ * `Container.register` promotes a key that is registered twice to an array, which is how
134
+ * several implementations share an interface key. Under a component's own name it means
135
+ * every dependent is handed `[instance, component]` instead of either one, so the collision
136
+ * is reported here, before anything is constructed. An overridden name is exempt: there the
137
+ * double replaces the component on purpose.
138
+ * @returns {void}
139
+ * @throws When a component name is already registered
140
+ */
141
+ rejectTakenNames() {
142
+ for (const { Class: component } of this.injectables) {
143
+ const name = getTypedMetadata(ComponentConstants.NameKey, component) || component.name;
144
+ if (!this._container.has(name) || this._container.isOverridden(name)) {
145
+ continue;
146
+ }
147
+ throw new Error(`Component name '${name}' (class ${this.describeClass(component)}) is already registered in the ` +
148
+ 'container - by one of its own services or by a pre-built instance. Give the component another ' +
149
+ "name, e.g. @Service('...').");
150
+ }
151
+ }
152
+ /**
153
+ * @description Report components that were declared in the entry file *after* the
154
+ * bootstrap call. Their decorators had not run yet when the scan read the registry,
155
+ * so they never made it into the container - and without this they would just be
156
+ * quietly missing at runtime.
157
+ * @param {string} bootstrapCall - How the warning names the call that built the container
158
+ * @returns {void}
159
+ */
160
+ warnAboutLateEntryComponents(bootstrapCall = 'IocApplication.create()') {
161
+ if (!this.entryFiles.size) {
162
+ return;
163
+ }
164
+ const late = getComponentsDeclaredIn(this.entryFiles).filter((cls) => !this.entryComponents.has(cls));
165
+ if (!late.length) {
166
+ return;
167
+ }
168
+ this.logger.warn(`[IocEngine] ${late.length} component(s) declared after the ${bootstrapCall} call were not ` +
169
+ `registered: ${late.map((cls) => cls.name).join(', ')}. ` +
170
+ 'Move them above the bootstrap call, or into their own file under sourceFolder.');
171
+ }
172
+ /**
173
+ * @description Absolute paths of the files that must be kept out of the scan:
174
+ * the entry declared in the config, and the module actually being executed.
175
+ * They are usually the same file, but not always - a project may declare one
176
+ * `rootFile` and start another, or run without a config at all.
177
+ * @returns {Set<string>} Resolved absolute entry paths
178
+ */
179
+ resolveEntryFiles() {
180
+ const entryFiles = new Set();
181
+ if (this.config?.rootFile) {
182
+ entryFiles.add(path.resolve(process.cwd(), this.config.rootFile));
183
+ }
184
+ const runningModule = typeof Bun !== 'undefined' ? Bun.main : process.argv[1];
185
+ if (runningModule) {
186
+ entryFiles.add(path.resolve(runningModule));
187
+ }
188
+ return entryFiles;
189
+ }
190
+ /**
191
+ * @description Resolve a scanned path against the working directory. `getAllFiles`
192
+ * mirrors the form of the folder it was given, so a `sourceFolder` configured as an
193
+ * absolute path yields absolute entries that must not be joined onto cwd again.
194
+ * @param {string} file - Path as returned by the scan
195
+ * @returns {string} Absolute path
196
+ */
197
+ toAbsolutePath(file) {
198
+ return path.isAbsolute(file) ? path.normalize(file) : path.resolve(process.cwd(), file);
199
+ }
200
+ /**
201
+ * @description Collapse components that arrived from more than one source - a class
202
+ * re-exported through a barrel file, or one found by both the scan and the registry.
203
+ *
204
+ * Deduplication is by class identity, not by name: `Container.register` promotes a
205
+ * key to an array when the same name is registered twice, which would construct the
206
+ * component a second time (running @PostConstruct again) and hand every dependent an
207
+ * array instead of an instance.
208
+ * @param {InjectableComponent[]} components - Components from every source
209
+ * @returns {InjectableComponent[]} Components with duplicates removed
210
+ */
211
+ dedupeInjectables(components) {
212
+ const seen = new Set();
213
+ const byName = new Map();
214
+ const unique = [];
215
+ for (const component of components) {
216
+ if (seen.has(component.Class))
217
+ continue;
218
+ seen.add(component.Class);
219
+ const name = getTypedMetadata(ComponentConstants.NameKey, component.Class) || component.Class.name;
220
+ const claimed = byName.get(name);
221
+ if (claimed && claimed !== component.Class) {
222
+ // A component name is an identity, so two classes claiming one is a conflict, not a
223
+ // preference. It used to be a warning, and the resolution was silent and arbitrary:
224
+ // `initializeGraph` keyed classes by name in a Map, so whichever came last in scan order
225
+ // won and the other was never registered, and `@Inject(Loser)` returned an instance of
226
+ // the winner. On the explicit `components: [...]` path there was not even a warning.
227
+ throw new Error(`Duplicate component name detected: '${name}' is claimed by both ` +
228
+ `${claimed.name} and ${component.Class.name}. A component name must be unique - ` +
229
+ "give one of them an explicit name, e.g. @Service({ name: '...' }).");
230
+ }
231
+ byName.set(name, component.Class);
232
+ unique.push(component);
233
+ }
234
+ return unique;
235
+ }
236
+ async validateAndRegisterComponents(injectableClasses) {
237
+ const sortedInjectables = this.topologicalSort(injectableClasses, this.injectables);
238
+ await this.register(sortedInjectables);
239
+ }
240
+ async register(injectables) {
241
+ for (const injectable of injectables) {
242
+ const name = getTypedMetadata(ComponentConstants.NameKey, injectable) || injectable.name;
243
+ const isSingleton = getTypedMetadata(ComponentConstants.ScopeKey, injectable) === Scope.SINGLETON;
244
+ if (!isSingleton) {
245
+ this.warnAboutTransientLifecycleHooks(name, injectable);
246
+ }
247
+ const entry = await this._container.register(name, injectable, isSingleton);
248
+ const _interface = getTypedMetadata(ComponentConstants.InterfaceKey, injectable);
249
+ // When `name` is overridden this is the double's entry, so the interface key reaches it too.
250
+ if (_interface && _interface !== name) {
251
+ this._container.registerAlias(_interface, entry);
252
+ }
253
+ }
254
+ }
255
+ /**
256
+ * @description Warn when a transient declares lifecycle hooks.
257
+ *
258
+ * A transient is constructed per resolve and the container keeps no handle on it, so there is
259
+ * nothing for the lifecycle to start or stop. Its @OnStart still runs at construction, but its
260
+ * @OnStop can never run - and a component that acquires something it never releases is worth
261
+ * saying out loud rather than leaving to be discovered as a leak.
262
+ *
263
+ * @param {string} name - Registered component name
264
+ * @param {Class} injectable - The component class
265
+ * @returns {void}
266
+ */
267
+ warnAboutTransientLifecycleHooks(name, injectable) {
268
+ // The container's own walk, not a metadata read: it is the one that de-duplicates an
269
+ // inherited hook and stops at native code, so the two can never disagree about what would
270
+ // have run.
271
+ const stopHooks = this._container.getStopHooks(injectable);
272
+ if (stopHooks.length === 0) {
273
+ return;
274
+ }
275
+ this.logger.warn(`[IocEngine] '${name}' is transient and declares @OnStop (${stopHooks.join(', ')}), which will never ` +
276
+ 'run - the container keeps no handle on a transient instance. Make it a singleton, or release the ' +
277
+ 'resource where it is used.');
278
+ }
279
+ async getInjectables(files) {
280
+ const validFiles = files.filter((file) => file.endsWith('.ts') || file.endsWith('.js') || file.endsWith('.tsx') || file.endsWith('.jsx'));
281
+ const components = await this.importFiles(validFiles);
282
+ return this.processComponents(components);
283
+ }
284
+ async importFiles(files) {
285
+ const timeout = this.config?.importTimeout ?? DEFAULT_IMPORT_TIMEOUT;
286
+ const importPromises = files.map(async (file) => {
287
+ try {
288
+ const module = await this.importFile(this.toAbsolutePath(file), file, timeout);
289
+ return Object.values(module);
290
+ }
291
+ catch (error) {
292
+ // A file inside sourceFolder that cannot be imported used to be skipped, which
293
+ // started the application with that component silently missing - the first symptom
294
+ // being an injection failure much later
295
+ this.logger.error(`[IocEngine] Failed to import component file '${file}':`, error);
296
+ throw new Error(`Failed to import component file '${file}'`, { cause: error });
297
+ }
298
+ });
299
+ const results = await Promise.all(importPromises);
300
+ return results.flat();
301
+ }
302
+ /**
303
+ * @description Import a single component file, pointing at it if it takes suspiciously
304
+ * long. A module whose top-level await never settles would otherwise hang the boot with
305
+ * no output at all; the import itself is left alone, only reported.
306
+ * @param {string} filePath - Absolute path to import
307
+ * @param {string} file - Path as scanned, for the message
308
+ * @param {number} timeout - Milliseconds before warning, 0 disables
309
+ * @returns {Promise<any>} The imported module namespace
310
+ */
311
+ async importFile(filePath, file, timeout) {
312
+ const timer = timeout > 0
313
+ ? setTimeout(() => {
314
+ this.logger.warn(`[IocEngine] Import of '${file}' has not settled after ${timeout}ms. ` +
315
+ 'A top-level await in that file that never resolves will hang startup.');
316
+ }, timeout)
317
+ : undefined;
318
+ try {
319
+ return await import(filePath);
320
+ }
321
+ finally {
322
+ if (timer !== undefined)
323
+ clearTimeout(timer);
324
+ }
325
+ }
326
+ processComponents(components) {
327
+ const valid = [];
328
+ for (const component of components) {
329
+ if (this.isValidComponent(component)) {
330
+ valid.push(component);
331
+ continue;
332
+ }
333
+ this.warnAboutUndecoratedSubclass(component);
334
+ }
335
+ return valid.map((component) => this.createComponentObject(component));
336
+ }
337
+ /**
338
+ * Validates and converts the `imports` list. Like an explicitly listed component, and unlike a
339
+ * scanned class, an import that carries no decorator of its own is a hard error: a silently
340
+ * dropped import is exactly the failure the option exists to prevent.
341
+ */
342
+ processImports(imports) {
343
+ if (!imports?.length) {
344
+ return [];
345
+ }
346
+ const injectables = [];
347
+ for (const entry of imports) {
348
+ if (!this.isValidComponent(entry)) {
349
+ throw new Error(this.describeInvalidImport(entry));
350
+ }
351
+ injectables.push(this.createComponentObject(entry));
352
+ }
353
+ return injectables;
354
+ }
355
+ /**
356
+ * The error for an `imports` entry that failed the identity check. A class that extends a
357
+ * component but carries no decorator of its own is told so explicitly: whoever can see
358
+ * `@Service` on the base class reads the generic message as a contradiction.
359
+ * @param {any} entry - The rejected entry
360
+ * @returns {string} The message to throw
361
+ */
362
+ describeInvalidImport(entry) {
363
+ const name = typeof entry === 'function' ? entry.name : String(entry);
364
+ const ancestor = this.findDecoratedAncestor(entry);
365
+ if (ancestor) {
366
+ return (`imports entry ${name} extends the component ${ancestor.name} but carries no decorator of its own - ` +
367
+ `component identity is not inherited. Decorate ${name} (@Service, @Component, ...) or import ` +
368
+ `${ancestor.name} itself if that is what you meant.`);
369
+ }
370
+ return (`imports entry ${name} carries no component decorator - only classes decorated with ` +
371
+ '@Service, @Component, ... can be imported');
372
+ }
373
+ describeInvalidListedComponent(entry) {
374
+ const name = this.describeClass(entry);
375
+ const ancestor = this.findDecoratedAncestor(entry);
376
+ const inherited = ancestor
377
+ ? ` It extends the component '${ancestor.name}', but component identity is not inherited - ` +
378
+ `decorate '${name}' itself, or list '${ancestor.name}' if that is what you meant.`
379
+ : '';
380
+ return (`'${name}' is listed in components but carries no component decorator (@Service, @Component, ...).` +
381
+ inherited +
382
+ ' The decorator has to be applied by this copy of the package - a class decorated through a second ' +
383
+ 'installed copy is not recognised.');
384
+ }
385
+ /**
386
+ * @description The nearest class up the prototype chain that carries its own component
387
+ * decorator, or undefined when none does.
388
+ * @param {any} component - A class, or anything else (yields undefined)
389
+ * @returns {Class | undefined} The decorated ancestor
390
+ */
391
+ findDecoratedAncestor(component) {
392
+ if (typeof component !== 'function') {
393
+ return undefined;
394
+ }
395
+ let ancestor = Object.getPrototypeOf(component);
396
+ while (typeof ancestor === 'function' && ancestor !== Function.prototype) {
397
+ if (getOwnTypedMetadata(ComponentConstants.IOCObjectKey, ancestor)) {
398
+ return ancestor;
399
+ }
400
+ ancestor = Object.getPrototypeOf(ancestor);
401
+ }
402
+ return undefined;
403
+ }
404
+ /**
405
+ * Reports a scanned class that extends a component but carries no decorator of its own. An
406
+ * explicitly listed one never gets here: `loadComponents` rejects it outright.
407
+ *
408
+ * Component identity is read own-only, so such a class is simply skipped. Registering it
409
+ * under its *base's* name blew up on first inject - ugly, but at least detectable. Skipping
410
+ * it silently is worse: whatever the class was meant to do never happens and nothing
411
+ * anywhere says so.
412
+ *
413
+ * Only fires when an ancestor carries the marker, so an ordinary undecorated helper class in
414
+ * the scan folder stays quiet. A decorator that returns a wrapper subclass and applies
415
+ * `@Service` to the wrapper gives the wrapper its own marker, so it never reaches here.
416
+ */
417
+ warnAboutUndecoratedSubclass(component) {
418
+ const ancestor = this.findDecoratedAncestor(component);
419
+ if (!ancestor) {
420
+ return;
421
+ }
422
+ this.logger.warn(`[IocEngine] '${component.name}' extends the component '${ancestor.name}' but carries no decorator of ` +
423
+ 'its own, so it was NOT registered. Decorate it (@Service, @Component, ...) or remove it ' +
424
+ 'from the scan folder.');
425
+ }
426
+ isValidComponent(component) {
427
+ try {
428
+ // Own-only. A class is whatever its OWN decorator says it is - component identity is not
429
+ // inherited. Reading this off the chain made an *undecorated* subclass a component, and
430
+ // since NameKey is read the same way it registered under its base's name: the container
431
+ // promoted the entry to an array and every @Inject(Base) started returning [Base, Sub].
432
+ return !!getOwnTypedMetadata(ComponentConstants.IOCObjectKey, component);
433
+ }
434
+ catch {
435
+ return false;
436
+ }
437
+ }
438
+ createComponentObject(component) {
439
+ return {
440
+ Class: component,
441
+ interface: getTypedMetadata(ComponentConstants.InterfaceKey, component),
442
+ };
443
+ }
444
+ topologicalSort(classes, injectables) {
445
+ const inDegree = new Map();
446
+ const adjacencyList = new Map();
447
+ const nameToClass = new Map();
448
+ this.initializeGraph(classes, injectables, inDegree, adjacencyList, nameToClass);
449
+ const queue = [];
450
+ inDegree.forEach((degree, node) => {
451
+ if (degree === 0)
452
+ queue.push(node);
453
+ });
454
+ const sorted = [];
455
+ let visitedCount = 0;
456
+ while (queue.length > 0) {
457
+ const currentNode = queue.shift();
458
+ visitedCount++;
459
+ const currentClass = nameToClass.get(currentNode);
460
+ if (currentClass) {
461
+ sorted.push(currentClass);
462
+ }
463
+ const neighbors = adjacencyList.get(currentNode) || [];
464
+ for (const neighbor of neighbors) {
465
+ const newDegree = inDegree.get(neighbor) - 1;
466
+ inDegree.set(neighbor, newDegree);
467
+ if (newDegree === 0) {
468
+ queue.push(neighbor);
469
+ }
470
+ }
471
+ }
472
+ if (visitedCount !== inDegree.size) {
473
+ const cycle = this.findCycle(adjacencyList);
474
+ throw new CircularDependencyError(`Circular dependency detected: ${cycle.join(' -> ')}`);
475
+ }
476
+ return sorted.reverse();
477
+ }
478
+ initializeGraph(classes, injectables, inDegree, adjacencyList, nameToClass) {
479
+ classes.forEach((cls) => {
480
+ const name = getTypedMetadata(ComponentConstants.NameKey, cls) || cls.name;
481
+ nameToClass.set(name, cls);
482
+ inDegree.set(name, 0);
483
+ adjacencyList.set(name, []);
484
+ });
485
+ classes.forEach((cls) => {
486
+ const name = getTypedMetadata(ComponentConstants.NameKey, cls) || cls.name;
487
+ const dependencies = [
488
+ ...this.getDependencies(cls).flatMap((dep) => this.expandInterfaceDependency(dep, name, nameToClass, injectables)),
489
+ ...this.getStrategyDependencies(cls, injectables),
490
+ ];
491
+ dependencies.forEach((dep) => {
492
+ if (dep) {
493
+ adjacencyList.get(name)?.push(dep);
494
+ inDegree.set(dep, (inDegree.get(dep) || 0) + 1);
495
+ }
496
+ });
497
+ });
498
+ }
499
+ /**
500
+ * `@Inject('IMailer')` names an `@Implements` interface key, not a component, so it has no node
501
+ * in the graph. Its implementations are the components that must be registered first.
502
+ */
503
+ expandInterfaceDependency(dep, selfName, nameToClass, injectables) {
504
+ // An overridden interface key already holds its double; ordering the real classes could only add false cycles.
505
+ if (!dep || nameToClass.has(dep) || this._container.isOverridden(dep)) {
506
+ return [dep];
507
+ }
508
+ const implementations = getStrategyClass({ dep }, injectables).filter((implementation) => implementation && implementation !== selfName);
509
+ return implementations.length ? implementations : [dep];
510
+ }
511
+ findCycle(adjacencyList) {
512
+ const visited = new Set();
513
+ const recStack = new Set();
514
+ const cycle = [];
515
+ const dfs = (node) => {
516
+ if (recStack.has(node)) {
517
+ cycle.push(node);
518
+ return true;
519
+ }
520
+ if (visited.has(node))
521
+ return false;
522
+ visited.add(node);
523
+ recStack.add(node);
524
+ const neighbors = adjacencyList.get(node) || [];
525
+ for (const neighbor of neighbors) {
526
+ if (dfs(neighbor)) {
527
+ if (cycle[0] !== cycle[cycle.length - 1]) {
528
+ cycle.push(node);
529
+ }
530
+ return true;
531
+ }
532
+ }
533
+ recStack.delete(node);
534
+ return false;
535
+ };
536
+ for (const node of adjacencyList.keys()) {
537
+ if (dfs(node))
538
+ break;
539
+ }
540
+ return cycle.reverse();
541
+ }
542
+ /**
543
+ * @description Separates PostProcessor classes and their transitive dependencies from other components.
544
+ * PostProcessors and their deps are registered in Phase A (before post-processing is active).
545
+ * Non-PostProcessor dependencies pulled into Phase A will NOT be post-processed (by design).
546
+ */
547
+ separatePostProcessors(classes) {
548
+ // Find all PostProcessor classes
549
+ const postProcessorSet = new Set();
550
+ const nameToClass = new Map();
551
+ for (const cls of classes) {
552
+ const name = getTypedMetadata(ComponentConstants.NameKey, cls) || cls.name;
553
+ nameToClass.set(name, cls);
554
+ }
555
+ // Identify PostProcessor classes
556
+ for (const cls of classes) {
557
+ if (getOwnTypedMetadata(ComponentType.POST_PROCESSOR, cls)) {
558
+ postProcessorSet.add(cls);
559
+ }
560
+ }
561
+ if (postProcessorSet.size === 0) {
562
+ return { postProcessorClasses: [], remainingClasses: classes };
563
+ }
564
+ // Compute transitive dependency closure for all PostProcessors
565
+ const closureSet = new Set(postProcessorSet);
566
+ const addDependencyClosure = (cls) => {
567
+ const deps = [...this.getDependencies(cls), ...this.getStrategyDependencies(cls, this.injectables)];
568
+ for (const depName of deps) {
569
+ const depClass = nameToClass.get(depName);
570
+ if (depClass && !closureSet.has(depClass)) {
571
+ closureSet.add(depClass);
572
+ // Log warning for non-PostProcessor dependencies pulled into Phase A
573
+ if (!getOwnTypedMetadata(ComponentType.POST_PROCESSOR, depClass)) {
574
+ const ppName = getTypedMetadata(ComponentConstants.NameKey, cls) || cls.name;
575
+ this.logger.warn(`[IocEngine] PostProcessor '${ppName}' depends on '${depName}'. ${depName} will not be post-processed.`);
576
+ }
577
+ // Recurse into this dependency's own dependencies
578
+ addDependencyClosure(depClass);
579
+ }
580
+ }
581
+ };
582
+ for (const ppClass of postProcessorSet) {
583
+ addDependencyClosure(ppClass);
584
+ }
585
+ // Split into two groups
586
+ const postProcessorClasses = [];
587
+ const remainingClasses = [];
588
+ for (const cls of classes) {
589
+ if (closureSet.has(cls)) {
590
+ postProcessorClasses.push(cls);
591
+ }
592
+ else {
593
+ remainingClasses.push(cls);
594
+ }
595
+ }
596
+ return { postProcessorClasses, remainingClasses };
597
+ }
598
+ getDependencies(component) {
599
+ try {
600
+ const directDependencies = Object.values(getOwnTypedMetadata(ComponentConstants.DependencyKey, component) || {});
601
+ const softDependencies = Object.values(getOwnTypedMetadata(ComponentConstants.SoftDependencyKey, component) || {});
602
+ const parentClass = Object.getPrototypeOf(component);
603
+ if (parentClass &&
604
+ parentClass !== Object.prototype &&
605
+ // circular detection
606
+ parentClass.toString() !== 'function () {\n' + ' [native code]\n' + '}') {
607
+ const parentDependencies = this.getDependencies(parentClass);
608
+ const parentName = getTypedMetadata(ComponentConstants.NameKey, parentClass) || parentClass.name;
609
+ const selfName = getTypedMetadata(ComponentConstants.NameKey, component) || component.name;
610
+ // A decorator may return a subclass of the class it decorates and register the
611
+ // subclass under the decorated class's own name.
612
+ // The parent then resolves to the component's own name, which is not a cycle -
613
+ // reporting it as one made the component unresolvable.
614
+ const parentEntry = parentName && parentName !== selfName ? [parentName] : [];
615
+ return [
616
+ ...new Set([
617
+ ...directDependencies,
618
+ ...parentDependencies,
619
+ ...softDependencies,
620
+ // Parent is registered as a soft dep so subclasses are created after it
621
+ ...parentEntry,
622
+ ]),
623
+ ];
624
+ }
625
+ return [...new Set([...directDependencies, ...softDependencies])];
626
+ }
627
+ catch {
628
+ return [];
629
+ }
630
+ }
631
+ /**
632
+ * Every strategy key a component consumes, keyed by the field that declares it. Walks the
633
+ * prototype chain like getStrategyDependencies does - a @Strategy field on a base class is
634
+ * injected into the subclass too, so it has to be reported against the subclass. Own class
635
+ * first, so a field redeclared in a subclass wins the same way injection resolves it.
636
+ */
637
+ collectStrategyFields(component) {
638
+ const fields = new Map();
639
+ const own = getOwnTypedMetadata(ComponentConstants.StrategyKey, component);
640
+ for (const [field, key] of Object.entries(own ?? {})) {
641
+ if (typeof key === 'string' && key) {
642
+ fields.set(field, key);
643
+ }
644
+ }
645
+ const parent = Object.getPrototypeOf(component);
646
+ if (typeof parent === 'function' && parent !== Function.prototype) {
647
+ for (const [field, key] of this.collectStrategyFields(parent)) {
648
+ if (!fields.has(field)) {
649
+ fields.set(field, key);
650
+ }
651
+ }
652
+ }
653
+ return fields;
654
+ }
655
+ /**
656
+ * Reports strategy keys nothing implements, once per injection site, at boot.
657
+ *
658
+ * An empty key is a legitimate plugin point and is injected as `[]`, which means a *typo'd*
659
+ * interface name no longer fails at boot either - it surfaces much later as a collection
660
+ * that is silently always empty. This line is what keeps the two apart.
661
+ *
662
+ * `debug` with no fallback to `info`, deliberately: a deliberate plugin point should stay
663
+ * quiet unless someone is looking.
664
+ */
665
+ reportEmptyStrategyKeys() {
666
+ // Optional twice over: `debug` is optional on IocLogger, and `logger` itself is absent
667
+ // whenever an IocEngine is built directly instead of through DI - which several suites do.
668
+ // A diagnostic must not be the thing that decides whether registration runs. The warn/error
669
+ // paths elsewhere stay unguarded, so genuinely broken wiring still fails loudly.
670
+ const debug = this.logger?.debug;
671
+ if (!debug) {
672
+ return;
673
+ }
674
+ const implemented = new Set(this.injectables.map((injectable) => injectable.interface).filter(Boolean));
675
+ for (const { Class: component } of this.injectables) {
676
+ const name = getTypedMetadata(ComponentConstants.NameKey, component) || component.name;
677
+ for (const [field, key] of this.collectStrategyFields(component)) {
678
+ // A double seeded through `overrides` is a real implementation of that key - warning
679
+ // here would fire on every slice test that mocks a plugin point
680
+ if (implemented.has(key) || this._container.isOverridden(key)) {
681
+ continue;
682
+ }
683
+ debug.call(this.logger, `[IocEngine] Strategy key '${key}' has no implementations - ${name}.${field} will be injected as []`);
684
+ }
685
+ }
686
+ }
687
+ getStrategyDependencies(component, injectables) {
688
+ try {
689
+ const strategyMeta = getOwnTypedMetadata(ComponentConstants.StrategyKey, component);
690
+ const directStrategies = getStrategyClass(strategyMeta, injectables);
691
+ const parentClass = Object.getPrototypeOf(component);
692
+ // Recurse on the parent class itself. This used to recurse on
693
+ // `parentClass.constructor`, which for a class is always `Function` - so the walk
694
+ // stopped at the first level and a @Strategy field declared on a base class was
695
+ // missing from the dependency graph. The component then resolved before the
696
+ // implementations it needed were registered ("<interface> is not registered").
697
+ if (typeof parentClass === 'function' && parentClass !== Function.prototype) {
698
+ const parentStrategies = this.getStrategyDependencies(parentClass, injectables);
699
+ return [...new Set([...directStrategies, ...parentStrategies])];
700
+ }
701
+ return directStrategies;
702
+ }
703
+ catch {
704
+ return [];
705
+ }
706
+ }
707
+ get container() {
708
+ return this._container;
709
+ }
710
+ };
711
+ __decorate([
712
+ Inject('Container'),
713
+ __metadata("design:type", Function)
714
+ ], IocEngine.prototype, "_container", void 0);
715
+ __decorate([
716
+ Inject(ICoreServiceNames.LOGGER),
717
+ __metadata("design:type", Object)
718
+ ], IocEngine.prototype, "logger", void 0);
719
+ IocEngine = __decorate([
720
+ CoreService(ICoreServiceNames.IOC_ENGINE)
721
+ ], IocEngine);
722
+ export { IocEngine };
723
+ //# sourceMappingURL=IocEngine.js.map