@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
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 AsenaJs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,220 @@
1
- # Temporary Holding Version
1
+ <p width="%100" align="center">
2
+ <img src="https://avatars.githubusercontent.com/u/179836938?s=200&v=4" width="150" align="center"/>
3
+ </p>
2
4
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
5
+ # @asenajs/ioc
6
+
7
+ [![Version](https://img.shields.io/npm/v/@asenajs/ioc.svg)](https://github.com/AsenaJs/ioc)
8
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://opensource.org/licenses/MIT)
9
+ [![Bun Version](https://img.shields.io/badge/Bun-1.4%2B-blueviolet)](https://bun.sh)
10
+
11
+ An IoC container for Bun: components declared with decorators, field-based dependency injection,
12
+ and a start/stop lifecycle. It knows nothing about what the components are for - a CLI, a worker
13
+ and a framework all sit on the same container.
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ bun add @asenajs/ioc
19
+ ```
20
+
21
+ ## Requirements
22
+
23
+ - Bun >= 1.4
24
+ - A `tsconfig.json` with `experimentalDecorators` enabled. `emitDecoratorMetadata` is not needed:
25
+ every injection names its dependency explicitly.
26
+
27
+ Bun 1.4.5 picks the decorator dialect for TypeScript it runs from source from the `tsconfig.json`
28
+ in the working directory, not from the one beside the file. Run from anywhere else, the same
29
+ source gets standard decorators, and the first `@Inject`, `@Strategy`, `@Value`, `@OnStart` or
30
+ `@OnStop` throws an error that says so. Anything started from another directory has to ship built
31
+ output (`tsc`, `bun build` or `bun build --compile`), where the decorators are already compiled,
32
+ or be started with `bun --tsconfig-override=<path>`.
33
+
34
+ ## Usage
35
+
36
+ ```typescript
37
+ import { Inject, IocApplication, OnStart, OnStop, Service } from '@asenajs/ioc';
38
+
39
+ @Service()
40
+ class Database {
41
+ @OnStart()
42
+ public open(): void {}
43
+
44
+ @OnStop()
45
+ public close(): void {}
46
+ }
47
+
48
+ @Service()
49
+ class UserService {
50
+ @Inject(Database)
51
+ private database: Database;
52
+ }
53
+
54
+ const app = await IocApplication.create({ components: [Database, UserService] });
55
+
56
+ await app.start();
57
+
58
+ const users = await app.resolve(UserService);
59
+
60
+ await app.stop();
61
+ ```
62
+
63
+ `create()` constructs every singleton and wires its fields. Their start hooks are held back until
64
+ `start()`, so a hook sees the finished graph; `stop()` runs the stop hooks in reverse order.
65
+
66
+ Three kinds of component run their start hooks at construction instead: a `@PostProcessor`, the
67
+ components it depends on, and anything with `Scope.PROTOTYPE`. A prototype-scoped component is
68
+ built per resolve and never stopped.
69
+
70
+ Components are constructed with `new Class()` and no arguments, and their fields are wired after
71
+ the constructor returns: an injected field is `undefined` inside the constructor and in a field
72
+ initializer. Work that needs a dependency belongs in an `@OnStart` method. A class that takes
73
+ constructor arguments is not a component - build it with `new` where it is used.
74
+
75
+ ## Component sources
76
+
77
+ | Option | Behaviour |
78
+ | -------------- | ------------------------------------------------------------------------------------------------------ |
79
+ | `components` | Explicit classes. When non-empty, nothing is scanned and the file system is never touched. A listed class without a component decorator fails `create()`. |
80
+ | `sourceFolder` | Folder scanned for decorated classes, plus those declared in the entry file above the `create()` call. |
81
+ | `imports` | Always added on top of whichever of the two applied. |
82
+
83
+ ```typescript
84
+ const app = await IocApplication.create({ sourceFolder: 'src' });
85
+ ```
86
+
87
+ The scan imports every `.ts`/`.js` file under the folder, so the folder has to exist at runtime
88
+ and hold nothing that must not run. A relative `sourceFolder` is resolved against the working
89
+ directory.
90
+
91
+ ### Command-line programs
92
+
93
+ Use `components`. It is the only source that works in every way a CLI is shipped:
94
+
95
+ | Shipped as | `components` | `sourceFolder` |
96
+ | ----------------------------------- | ------------ | ------------------------------------------------------------------------- |
97
+ | `tsc` output, installed as a `bin` | works | only with an absolute path (`import.meta.dir`); `'src'` is the user's src |
98
+ | `bun build` bundle | works | no source files to scan |
99
+ | `bun build --compile` binary | works | no source files to scan |
100
+
101
+ A CLI started in somebody else's project that scans a relative folder imports *their* files.
102
+
103
+ ```typescript
104
+ @Service()
105
+ @Implements('Command')
106
+ class BuildCommand {
107
+ public command(): Command { ... }
108
+ }
109
+
110
+ @Service()
111
+ class Cli {
112
+ @Strategy('Command')
113
+ private commands: { command: () => Command }[];
114
+ }
115
+
116
+ const app = await IocApplication.create({ components: [Cli, BuildCommand] });
117
+ ```
118
+
119
+ `--help`, `--version` and a `process.exit()` inside a command end the process before `stop()`
120
+ runs. Parse in a `try`/`finally` around `stop()`, and let the parser throw instead of exiting
121
+ (`exitOverride()` in commander).
122
+
123
+ ### Names and minification
124
+
125
+ A component is registered under the name given to its decorator, or under its class name. Minifying
126
+ identifiers renames classes, so with `bun build --minify`:
127
+
128
+ - `@Inject(UserService)` and `app.resolve(UserService)` keep working - the name is read from the
129
+ class, whatever it became.
130
+ - `@Inject('UserService')`, `app.resolve('UserService')` and `overrides: { UserService: ... }` only
131
+ work when the component was named explicitly: `@Service('UserService')`.
132
+
133
+ `--minify-whitespace --minify-syntax` leaves names alone.
134
+
135
+ ## Decorators
136
+
137
+ | Decorator | Purpose |
138
+ | ----------------------------- | ---------------------------------------------------------- |
139
+ | `@Service()` / `@Component()` | Mark a class as a component. Singleton unless scoped. |
140
+ | `@Inject(ClassOrName)` | Inject a single dependency into a field. |
141
+ | `@Implements('Key')` | Register the component under an interface key as well. |
142
+ | `@Strategy('Key')` | Inject every implementation of an interface key, as array. |
143
+ | `@Value('ENV_NAME', options)` | Inject a value from `process.env`. |
144
+ | `@OnStart()` / `@OnStop()` | Lifecycle hooks, run by `start()` and `stop()`. |
145
+ | `@PostProcessor()` | Inspect or wrap every component after it is constructed. |
146
+
147
+ ## Pre-built instances
148
+
149
+ Values that are built outside the container - the environment, a clock, parsed arguments - go in
150
+ by name through `instances` and are injected like any component:
151
+
152
+ ```typescript
153
+ @Service()
154
+ class DeployCommand {
155
+ @Inject('Environment')
156
+ private environment: NodeJS.ProcessEnv;
157
+
158
+ @Inject('Now')
159
+ private now: () => number;
160
+ }
161
+
162
+ const app = await IocApplication.create({
163
+ components: [DeployCommand],
164
+ instances: { Environment: process.env, Now: Date.now, Verbose: false },
165
+ });
166
+ ```
167
+
168
+ - Any value except `null` and `undefined` is accepted: objects, functions, strings, numbers,
169
+ booleans, arrays. An optional value is left out of the record, not registered as `undefined`.
170
+ - Instances are registered before the components and are never started or stopped: whoever built
171
+ one owns its lifetime.
172
+ - A component that claims the name of an instance, or of one of the container's own services,
173
+ fails `create()`.
174
+
175
+ ## Test doubles
176
+
177
+ ```typescript
178
+ const app = await IocApplication.create({
179
+ components: [Database, UserService],
180
+ instances: { Now: Date.now },
181
+ overrides: { Database: fakeDatabase, Now: () => 0 },
182
+ });
183
+ ```
184
+
185
+ `overrides` replaces whatever is registered under a name. A component under an overridden name is
186
+ never constructed, an instance under it is ignored, and every dependent receives the double.
187
+ Overrides have to be objects or functions.
188
+
189
+ ## The container's own services
190
+
191
+ Registered by `IocApplication` under these names and injectable like any component:
192
+
193
+ | `ICoreServiceNames` | Name | What |
194
+ | ------------------- | -------------------- | ---------------------------------------- |
195
+ | `CONTAINER` | `'Container'` | The `Container` itself. |
196
+ | `LOGGER` | `'IocLogger'` | The `logger` option, or the console. |
197
+ | `IOC_ENGINE` | `'IocEngine'` | Discovers and registers components. |
198
+ | `LIFECYCLE_SERVICE` | `'LifecycleService'` | Runs the start and stop hooks. |
199
+
200
+ ## Building on the container
201
+
202
+ `IocApplication` is one way to wire the pieces; a framework that needs more registers them itself
203
+ and drives `Container`, `IocEngine` and `LifecycleService` directly.
204
+
205
+ - **Component kinds.** `defineComponent(kind, params, extra)` is what `@Service` is made of. The
206
+ kind is any string or symbol, and `container.resolveAll(kind)` returns every component of it. A
207
+ string `params` is the component name; a decorator whose string argument means something else
208
+ passes an object.
209
+ - **Metadata keys.** `ComponentConstants` is a class of static symbols, so `class MyConstants
210
+ extends ComponentConstants` keeps a framework's keys beside the container's. The keys are plain
211
+ `Symbol()`s: two installed copies of this package do not see each other's components, so a
212
+ framework re-exporting these decorators should depend on the package as a peer.
213
+ - **Core services.** `@CoreService(name)` marks infrastructure that is registered by hand with
214
+ `container.register(name, Class, true)` before the components that inject it.
215
+ - **Wrapping decorators.** A decorator that wraps the one `defineComponent` returns in its own
216
+ function must call `skipDeclarationFramesUnder(directory)` once for the directory it lives in,
217
+ or components declared in the entry file are attributed to it and not found.
218
+ - **Wording.** `warnAboutLateEntryComponents(bootstrapCall)` and the protected
219
+ `Container.injectedFieldHint` let the framework name its own entry point and test utilities in
220
+ the two messages that would otherwise name `IocApplication`.
@@ -0,0 +1 @@
1
+ export * from './lib';
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export * from './lib';
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":"AAAA,cAAc,OAAO,CAAC"}
@@ -0,0 +1,49 @@
1
+ /**
2
+ * @description Custom error class for circular dependency detection
3
+ * Provides detailed information about the circular dependency chain
4
+ */
5
+ export declare class CircularDependencyError extends Error {
6
+ constructor(message: string);
7
+ }
8
+ /**
9
+ * @description Detector for circular dependencies in the IoC container
10
+ * Tracks the resolution stack and detects cycles during dependency injection
11
+ */
12
+ export declare class CircularDependencyDetector {
13
+ private resolutionStack;
14
+ /**
15
+ * @description Check if service creates circular dependency
16
+ * @param {string} serviceName - The service being resolved
17
+ * @throws {CircularDependencyError} If circular dependency is detected
18
+ * @returns {void}
19
+ */
20
+ checkCircular(serviceName: string): void;
21
+ /**
22
+ * @description Push service to resolution stack
23
+ * @param {string} serviceName - The service being resolved
24
+ * @returns {void}
25
+ */
26
+ push(serviceName: string): void;
27
+ /**
28
+ * @description Pop service from resolution stack
29
+ * @param {string} serviceName - The service that was resolved
30
+ * @returns {void}
31
+ */
32
+ pop(serviceName: string): void;
33
+ /**
34
+ * @description Clear the resolution stack
35
+ * Useful for testing or manual stack reset
36
+ * @returns {void}
37
+ */
38
+ clear(): void;
39
+ /**
40
+ * @description Get current resolution stack as array
41
+ * @returns {string[]} Array of service names in resolution order
42
+ */
43
+ getStack(): string[];
44
+ /**
45
+ * @description Check if stack is empty
46
+ * @returns {boolean}
47
+ */
48
+ isEmpty(): boolean;
49
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * @description Custom error class for circular dependency detection
3
+ * Provides detailed information about the circular dependency chain
4
+ */
5
+ export class CircularDependencyError extends Error {
6
+ constructor(message) {
7
+ super(message);
8
+ this.name = 'CircularDependencyError';
9
+ }
10
+ }
11
+ /**
12
+ * @description Detector for circular dependencies in the IoC container
13
+ * Tracks the resolution stack and detects cycles during dependency injection
14
+ */
15
+ export class CircularDependencyDetector {
16
+ resolutionStack = new Set();
17
+ /**
18
+ * @description Check if service creates circular dependency
19
+ * @param {string} serviceName - The service being resolved
20
+ * @throws {CircularDependencyError} If circular dependency is detected
21
+ * @returns {void}
22
+ */
23
+ checkCircular(serviceName) {
24
+ if (this.resolutionStack.has(serviceName)) {
25
+ const stack = Array.from(this.resolutionStack);
26
+ const chain = [...stack, serviceName].join(' -> ');
27
+ throw new CircularDependencyError(`Circular dependency detected: ${chain}`);
28
+ }
29
+ }
30
+ /**
31
+ * @description Push service to resolution stack
32
+ * @param {string} serviceName - The service being resolved
33
+ * @returns {void}
34
+ */
35
+ push(serviceName) {
36
+ this.resolutionStack.add(serviceName);
37
+ }
38
+ /**
39
+ * @description Pop service from resolution stack
40
+ * @param {string} serviceName - The service that was resolved
41
+ * @returns {void}
42
+ */
43
+ pop(serviceName) {
44
+ this.resolutionStack.delete(serviceName);
45
+ }
46
+ /**
47
+ * @description Clear the resolution stack
48
+ * Useful for testing or manual stack reset
49
+ * @returns {void}
50
+ */
51
+ clear() {
52
+ this.resolutionStack.clear();
53
+ }
54
+ /**
55
+ * @description Get current resolution stack as array
56
+ * @returns {string[]} Array of service names in resolution order
57
+ */
58
+ getStack() {
59
+ return Array.from(this.resolutionStack);
60
+ }
61
+ /**
62
+ * @description Check if stack is empty
63
+ * @returns {boolean}
64
+ */
65
+ isEmpty() {
66
+ return this.resolutionStack.size === 0;
67
+ }
68
+ }
69
+ //# sourceMappingURL=CircularDependencyDetector.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CircularDependencyDetector.js","sourceRoot":"","sources":["../../lib/CircularDependencyDetector.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,OAAO,uBAAwB,SAAQ,KAAK;IAChD,YAAmB,OAAe;QAChC,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,yBAAyB,CAAC;IACxC,CAAC;CACF;AAED;;;GAGG;AACH,MAAM,OAAO,0BAA0B;IAC7B,eAAe,GAAgB,IAAI,GAAG,EAAE,CAAC;IAEjD;;;;;OAKG;IACI,aAAa,CAAC,WAAmB;QACtC,IAAI,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;YAC1C,MAAM,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;YAC/C,MAAM,KAAK,GAAG,CAAC,GAAG,KAAK,EAAE,WAAW,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YAEnD,MAAM,IAAI,uBAAuB,CAAC,iCAAiC,KAAK,EAAE,CAAC,CAAC;QAC9E,CAAC;IACH,CAAC;IAED;;;;OAIG;IACI,IAAI,CAAC,WAAmB;QAC7B,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;IACxC,CAAC;IAED;;;;OAIG;IACI,GAAG,CAAC,WAAmB;QAC5B,IAAI,CAAC,eAAe,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;IAC3C,CAAC;IAED;;;;OAIG;IACI,KAAK;QACV,IAAI,CAAC,eAAe,CAAC,KAAK,EAAE,CAAC;IAC/B,CAAC;IAED;;;OAGG;IACI,QAAQ;QACb,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;IAC1C,CAAC;IAED;;;OAGG;IACI,OAAO;QACZ,OAAO,IAAI,CAAC,eAAe,CAAC,IAAI,KAAK,CAAC,CAAC;IACzC,CAAC;CACF"}
@@ -0,0 +1,259 @@
1
+ import type { Class, ComponentKind, ComponentPostProcessor, ContainerService, LifecycleComponent, StartHookMode } from './types';
2
+ /**
3
+ * Thrown by {@link Container.resolve} when the requested key has no registration.
4
+ *
5
+ * Carries no information about who needed the key - `resolve` cannot know that - so
6
+ * `injectDependencies` catches it and rethrows with the dependent class and field attached.
7
+ * The subclass identity is what tells an unwrapped miss (wrap it) from any other failure
8
+ * (rethrow untouched), including an already-wrapped nested miss.
9
+ */
10
+ export declare class UnregisteredDependencyError extends Error {
11
+ constructor(message: string);
12
+ }
13
+ /**
14
+ * Thrown when an `@OnStart` (or `@PostConstruct`) hook throws or rejects.
15
+ *
16
+ * The original error is the `cause`; `component` and `hook` name the method that failed, so an
17
+ * application can tell a failed start hook apart from any other error without reading the message.
18
+ */
19
+ export declare class StartHookError extends Error {
20
+ readonly component: string;
21
+ readonly hook: string;
22
+ constructor(component: string, hook: string, cause: unknown);
23
+ }
24
+ export declare class Container {
25
+ private _services;
26
+ private circularDetector;
27
+ private postProcessors;
28
+ private overriddenKeys;
29
+ /** Key -> entries that live there only as an alias of their own key (see `registerAlias`). */
30
+ private aliases;
31
+ /**
32
+ * How the error for an assignment to a wired field ends: what to do instead. Whatever wraps
33
+ * the container names its own way of seeding a test double here.
34
+ */
35
+ protected injectedFieldHint: string;
36
+ /**
37
+ * Whether construction runs start hooks itself.
38
+ *
39
+ * `immediate` is the original behaviour and stays that way for core services, for the
40
+ * post-processor closure the IoC engine registers ahead of everything else, and for every
41
+ * transient. `deferred` holds the hooks back so `LifecycleService` can run them from
42
+ * `start()`, once the whole graph exists.
43
+ */
44
+ private startHookMode;
45
+ /**
46
+ * Every singleton built by `register()`, in registration order - which the IoC engine has
47
+ * already topologically sorted, so dependencies come before dependents. Start hooks walk it
48
+ * forwards, stop hooks backwards.
49
+ *
50
+ * Instances handed in through `registerInstance()` are deliberately absent: nothing ever ran
51
+ * a start hook on them, so there is no started/stopped pair to keep symmetric.
52
+ */
53
+ private lifecycleComponents;
54
+ constructor(services?: {
55
+ [key: string]: ContainerService | ContainerService[];
56
+ });
57
+ /**
58
+ * @returns {Promise<ContainerService>} The new entry, or the test double's entry when `key` is overridden
59
+ */
60
+ register(key: string, Class: Class, singleton: boolean): Promise<ContainerService>;
61
+ /**
62
+ * @description Make an entry registered under one key reachable under another as well.
63
+ *
64
+ * The entry object itself is shared, so a singleton keeps one instance and one lifecycle no
65
+ * matter how many keys reach it - `@Implements` registers a component under its name and its
66
+ * interface key this way. Component scans (`resolveAll`) skip alias positions, so the
67
+ * component is still found exactly once.
68
+ *
69
+ * @param {string} key - The additional key, e.g. an `@Implements` interface name
70
+ * @param {ContainerService} entry - An entry returned by `register()`
71
+ * @returns {void}
72
+ */
73
+ registerAlias(key: string, entry: ContainerService): void;
74
+ private store;
75
+ /**
76
+ * @description Record a singleton for the start/stop lifecycle.
77
+ *
78
+ * `started` reflects what already happened rather than what is planned: a component built in
79
+ * immediate mode has run its start hooks by the time it gets here, so it is stoppable at once.
80
+ * A deferred one is not started until `LifecycleService` says so - and a component that never
81
+ * started must never be stopped.
82
+ *
83
+ * @param {string} key - Service identifier
84
+ * @param {unknown} instance - The post-processed instance
85
+ * @param {Class} Class - The class it was built from
86
+ * @returns {void}
87
+ */
88
+ private trackLifecycle;
89
+ /**
90
+ * @description Register an already-created instance directly
91
+ * Useful for dependencies created outside the container, like the logger. Any value except
92
+ * `null` and `undefined` can be registered, including `0`, `''`, `false` and an empty array.
93
+ * @param {string} key - Service identifier
94
+ * @param {T} instance - Pre-created instance
95
+ * @returns {Promise<void>}
96
+ */
97
+ registerInstance<T>(key: string, instance: T): Promise<void>;
98
+ /**
99
+ * @description Replace a service with a pre-created test double (Spring's @MockBean).
100
+ *
101
+ * Seeds the container before user components are registered: any later `register()`
102
+ * call for the same key becomes a no-op, so the real class is never constructed and
103
+ * dependents capture the override in their injection closures.
104
+ *
105
+ * @param {string} key - Service identifier to override
106
+ * @param {T} instance - Replacement instance
107
+ * @returns {void}
108
+ */
109
+ overrideInstance<T>(key: string, instance: T): void;
110
+ /**
111
+ * @description Check whether a key has been replaced by an override
112
+ * @param {string} key - Service key
113
+ * @returns {boolean}
114
+ */
115
+ isOverridden(key: string): boolean;
116
+ resolve<T>(key: string): Promise<(T | T[]) | null>;
117
+ /**
118
+ * @description Check if a service is registered without resolving it
119
+ * @param {string} key - Service key
120
+ * @returns {boolean}
121
+ */
122
+ has(key: string): boolean;
123
+ /**
124
+ * @description Resolve every implementation registered under a strategy key.
125
+ *
126
+ * Cardinality is normalized here rather than borrowed from resolve(). `_services[key]` has
127
+ * three shapes - absent, a bare ContainerService, an array - and resolve() maps them to
128
+ * throw / T / T[]. That is right for @Inject, whose dependency is single-valued: it is
129
+ * either there or the component is broken. @Strategy is multi-valued by construction, so
130
+ * zero is a cardinality it has to be able to take (a plugin point before its first plugin)
131
+ * and one has to arrive as a one-element array like any other count.
132
+ *
133
+ * This used to be a cast over resolve(), which made it correct at exactly one cardinality:
134
+ * an empty key aborted the boot, and a single implementation was injected as a bare
135
+ * instance whose first `.length` / `for...of` / `.map()` failed at runtime.
136
+ *
137
+ * @param {string} key - Strategy (interface) key
138
+ * @returns {Promise<T[]>} Every implementation, empty when the key has none
139
+ */
140
+ resolveStrategy<T>(key: string): Promise<T[]>;
141
+ /**
142
+ * @description Resolve every component of a kind.
143
+ * @param {ComponentKind} typeOfComponent - The kind the components were declared with
144
+ * @returns {Promise<(T | T[])[]>} One entry per key, empty when no component has the kind
145
+ */
146
+ resolveAll<T>(typeOfComponent: ComponentKind): Promise<(T | T[])[]>;
147
+ private filterServices;
148
+ private resolveContainerService;
149
+ private resolveMultipleContainerService;
150
+ /**
151
+ * @description Register a ComponentPostProcessor for post-processing newly created instances.
152
+ * PostProcessors are called in FIFO order after DI + PostConstruct.
153
+ * @param {ComponentPostProcessor} processor - The post-processor to register
154
+ */
155
+ registerPostProcessor(processor: ComponentPostProcessor): void;
156
+ /**
157
+ * @description Choose whether construction runs start hooks or hands them to LifecycleService.
158
+ *
159
+ * The IoC engine switches to `deferred` around user components only. Post-processors keep
160
+ * running theirs at construction because `postProcess()` reads state a start hook sets - defer
161
+ * that and every component the processor wraps is built against an uninitialised processor.
162
+ *
163
+ * @param {StartHookMode} mode - immediate (default) or deferred
164
+ * @returns {void}
165
+ */
166
+ setStartHookMode(mode: StartHookMode): void;
167
+ /**
168
+ * @description Singletons in registration order, for the start/stop lifecycle.
169
+ * @returns {LifecycleComponent[]} The live list - LifecycleService flips `started` on it
170
+ */
171
+ get lifecycle(): LifecycleComponent[];
172
+ private prepareInstance;
173
+ /**
174
+ * @description Run every @OnStart (and its @PostConstruct alias) method on an instance.
175
+ *
176
+ * Walks the prototype chain ancestors-first and runs each method name once, so a hook
177
+ * inherited by three classes still fires once.
178
+ *
179
+ * A failing hook is rethrown as a {@link StartHookError} naming the class and the method, with
180
+ * the original error as `cause` - the boot fails, the process decides what to do about it.
181
+ *
182
+ * @param {any} instance - The instance to run hooks on
183
+ * @param {Class} Class - The class of the instance
184
+ * @returns {Promise<void>}
185
+ * @throws {StartHookError} When a hook throws or rejects
186
+ */
187
+ executeStartHooks(instance: any, Class: Class): Promise<void>;
188
+ /**
189
+ * @description The @OnStop method names for a class, in the order they should run.
190
+ *
191
+ * Reversed relative to the start hooks so a component tears down in the opposite order it
192
+ * was brought up, matching how LifecycleService walks the components themselves.
193
+ *
194
+ * @param {Class} Class - The class to inspect
195
+ * @returns {string[]} Method names, empty when the class declares none
196
+ */
197
+ getStopHooks(Class: Class): string[];
198
+ /**
199
+ * @description The @OnStart method names for a class, in the order they run.
200
+ * @param {Class} Class - The class to inspect
201
+ * @returns {string[]} Method names, empty when the class declares none
202
+ */
203
+ getStartHooks(Class: Class): string[];
204
+ /**
205
+ * @description Collect decorated method names across the prototype chain, de-duplicated.
206
+ * @param {Class} Class - The class to inspect
207
+ * @param {symbol} metadataKey - Which hook list to read
208
+ * @returns {string[]} Method names, ancestors first
209
+ */
210
+ private collectHookMethods;
211
+ private injectStrategies;
212
+ /**
213
+ * @description Assigns every @Value field of the instance from process.env.
214
+ *
215
+ * Values land as plain writable properties - unlike @Inject fields they hold no
216
+ * resolved service to protect, and tests overwrite them freely. The own-property
217
+ * guard mirrors injectDependencies: a field initializer wins over the environment.
218
+ *
219
+ * @param {any} newInstance - The freshly constructed instance
220
+ * @param {Class} Class - The class of the instance
221
+ * @returns {void}
222
+ */
223
+ private injectValues;
224
+ private injectDependencies;
225
+ /**
226
+ * The message behind an assignment to a wired field.
227
+ *
228
+ * Injected fields are installed as accessors with no setter, so assigning to one throws the
229
+ * engine's own `TypeError: Attempted to assign to readonly property.` - no field name, no class,
230
+ * no hint at what to do instead. Everybody reaches for `Object.assign(instance, {dep: fake})`
231
+ * once; this turns that minute into a sentence.
232
+ */
233
+ private injectedFieldMessage;
234
+ /**
235
+ * @description Checks if a class is a framework class (CoreService)
236
+ * Framework classes can traverse the prototype chain even if they contain native code patterns
237
+ * @param {any} cls - The class to check
238
+ * @returns {boolean} True if the class is a framework class
239
+ */
240
+ private isFrameworkClass;
241
+ /**
242
+ * Deliberately NOT `getPrototypeChainOf` from utils, even though the two overlap.
243
+ *
244
+ * This walk carries two rules the generic helper does not: it bails out at a class whose
245
+ * source reads `[native code]` (so injection never tries to walk into a built-in or a bound
246
+ * constructor), with an escape hatch for `@CoreService` classes, and it returns leaf-first
247
+ * because every caller here reverses it themselves.
248
+ *
249
+ * The generic helper is the right reader for decorator metadata; this one guards instance
250
+ * construction. Merging them would mean picking one set of stop conditions for both.
251
+ */
252
+ private getPrototypeChain;
253
+ get services(): {
254
+ [p: string]: ContainerService | ContainerService[];
255
+ };
256
+ set services(value: {
257
+ [p: string]: ContainerService | ContainerService[];
258
+ });
259
+ }