node-dependency-injection 4.0.0-alpha.0 โ†’ 4.1.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 (101) hide show
  1. package/.eslintrc +16 -0
  2. package/.github/workflows/build.yml +24 -0
  3. package/.github/workflows/publish.yml +43 -0
  4. package/.mocharc.yaml +0 -1
  5. package/CHANGELOG-3.md +6 -1
  6. package/CONTRIBUTING.md +2 -2
  7. package/README.md +340 -112
  8. package/UPGRADE-3.0.md +4 -1
  9. package/UPGRADE-4.0.md +50 -0
  10. package/assets/logo.png +0 -0
  11. package/bin/Resources/services.yaml +7 -0
  12. package/bin/Services/File/XmlAdapter.js +53 -0
  13. package/bin/ndi-config:create.js +2 -1
  14. package/bin/ndi-container:graph.js +82 -0
  15. package/bin/ndi-container:service.js +5 -0
  16. package/bin/ndi-container:validate.js +120 -0
  17. package/bin/ndi.js +2 -0
  18. package/dist/bin/Resources/services.yaml +7 -0
  19. package/dist/bin/Services/File/BaseAdapter.js +1 -50
  20. package/dist/bin/Services/File/FileManager.js +1 -55
  21. package/dist/bin/Services/File/JsAdapter.js +1 -62
  22. package/dist/bin/Services/File/JsonAdapter.js +1 -60
  23. package/dist/bin/Services/File/XmlAdapter.js +1 -0
  24. package/dist/bin/Services/File/YamlAdapter.js +1 -67
  25. package/dist/bin/ndi-config:check.js +1 -55
  26. package/dist/bin/ndi-config:create.js +1 -40
  27. package/dist/bin/ndi-container:graph.js +2 -0
  28. package/dist/bin/ndi-container:service.js +1 -131
  29. package/dist/bin/ndi-container:validate.js +2 -0
  30. package/dist/bin/ndi.js +1 -9
  31. package/dist/lib/Autowire.js +1 -281
  32. package/dist/lib/AutowireIdentifier.js +1 -0
  33. package/dist/lib/Compiler.js +1 -101
  34. package/dist/lib/CompilerPass/AutowireOverridePass.js +1 -0
  35. package/dist/lib/CompilerPass/DecoratePass.js +1 -118
  36. package/dist/lib/CompilerPass/OptimizePass.js +1 -60
  37. package/dist/lib/CompilerPass/RemovePass.js +1 -57
  38. package/dist/lib/CompilerPass/index.js +1 -131
  39. package/dist/lib/Condition.js +1 -0
  40. package/dist/lib/ContainerBuilder.js +1 -463
  41. package/dist/lib/ContainerValidator.js +1 -0
  42. package/dist/lib/Definition.js +1 -371
  43. package/dist/lib/Dump/Dumper.js +1 -0
  44. package/dist/lib/Dump/JsDumper.js +1 -0
  45. package/dist/lib/Dump/JsonDumper.js +1 -0
  46. package/dist/lib/Dump/XmlDumper.js +1 -0
  47. package/dist/lib/Dump/YamlDumper.js +1 -0
  48. package/dist/lib/Exception/AbstractServiceException.js +1 -47
  49. package/dist/lib/Exception/AttributesMapException.js +1 -44
  50. package/dist/lib/Exception/CannotAutowireOverrideSearch.js +1 -0
  51. package/dist/lib/Exception/ConfigurationFileNotFoundException.js +1 -47
  52. package/dist/lib/Exception/ContainerDefaultDirMustBeSet.js +1 -0
  53. package/dist/lib/Exception/ContainerValidationError.js +1 -0
  54. package/dist/lib/Exception/DefinitionNotFoundException.js +1 -47
  55. package/dist/lib/Exception/FrozenContainerException.js +1 -44
  56. package/dist/lib/Exception/KeyedGroupNoDefaultException.js +1 -0
  57. package/dist/lib/Exception/KeyedGroupNotFoundException.js +1 -0
  58. package/dist/lib/Exception/KeyedServiceNotFoundException.js +1 -0
  59. package/dist/lib/Exception/LoadMethodNotFoundException.js +1 -47
  60. package/dist/lib/Exception/LoggerWarnMethodNotFoundException.js +1 -44
  61. package/dist/lib/Exception/MethodCallEmptyException.js +1 -44
  62. package/dist/lib/Exception/MethodCallNotFoundException.js +1 -47
  63. package/dist/lib/Exception/NotAbstractServiceException.js +1 -47
  64. package/dist/lib/Exception/PrivateServiceException.js +1 -47
  65. package/dist/lib/Exception/ProcessMethodNotFoundException.js +1 -47
  66. package/dist/lib/Exception/RootDirectoryMustBeAbsolute.js +1 -0
  67. package/dist/lib/Exception/RootDirectoryNotFound.js +1 -0
  68. package/dist/lib/Exception/ServiceCircularReferenceException.js +1 -44
  69. package/dist/lib/Exception/ServiceFileNotAbsolute.js +1 -0
  70. package/dist/lib/Exception/ServiceFileNotFoundException.js +1 -47
  71. package/dist/lib/Exception/ServiceFileNotLoadedException.js +1 -47
  72. package/dist/lib/Exception/ServiceFileNotValidExtension.js +1 -0
  73. package/dist/lib/Exception/ServiceNotFoundException.js +1 -48
  74. package/dist/lib/Exception/UnableToGetInstanceFromId.js +1 -0
  75. package/dist/lib/Exception/WrongCompilerPassTypeException.js +1 -47
  76. package/dist/lib/Exception/WrongDefinitionException.js +1 -44
  77. package/dist/lib/GraphExporter.js +1 -0
  78. package/dist/lib/InstanceManager.js +1 -363
  79. package/dist/lib/KeyedGroupReference.js +1 -0
  80. package/dist/lib/KeyedReference.js +1 -0
  81. package/dist/lib/Loader/Argument.js +1 -0
  82. package/dist/lib/Loader/FileLoader.js +1 -417
  83. package/dist/lib/Loader/JsFileLoader.js +1 -68
  84. package/dist/lib/Loader/JsonFileLoader.js +1 -40
  85. package/dist/lib/Loader/XmlFileLoader.js +1 -0
  86. package/dist/lib/Loader/YamlFileLoader.js +1 -88
  87. package/dist/lib/LoggerHelper.js +1 -0
  88. package/dist/lib/PackageReference.js +1 -37
  89. package/dist/lib/ParameterReference.js +1 -0
  90. package/dist/lib/PassConfig.js +1 -78
  91. package/dist/lib/Reference.js +1 -49
  92. package/dist/lib/ServiceFile.js +1 -0
  93. package/dist/lib/TagReference.js +1 -37
  94. package/dist/lib/ValidationResult.js +1 -0
  95. package/dist/lib/index.js +1 -79
  96. package/dist/lib/schema/services.xsd +163 -0
  97. package/dist/lib/types/index.d.ts +218 -10
  98. package/dist/lib/types/tests.ts +36 -2
  99. package/package.json +25 -11
  100. package/tsconfig.json +8 -1
  101. package/.travis.yml +0 -14
package/.eslintrc ADDED
@@ -0,0 +1,16 @@
1
+ {
2
+ "extends": [
3
+ "plugin:sonarjs/recommended"
4
+ ],
5
+ "plugins": [
6
+ "sonarjs"
7
+ ],
8
+ "parserOptions": {
9
+ "ecmaVersion": "latest",
10
+ "sourceType": "module"
11
+ },
12
+ "rules": {
13
+ "sonarjs/cognitive-complexity": "error",
14
+ "sonarjs/no-identical-expressions": "error"
15
+ }
16
+ }
@@ -0,0 +1,24 @@
1
+ name: Build
2
+
3
+ on:
4
+ push:
5
+ branches: [ master ]
6
+ pull_request:
7
+ branches: [ master ]
8
+
9
+ jobs:
10
+ build:
11
+ runs-on: ubuntu-latest
12
+ strategy:
13
+ matrix:
14
+ node-version: [ 15.x, 16.x, 17.x, 18.x, 19.x, 20.x, 21.x, 22.x, 23.x, 24.x, 25.x ]
15
+ steps:
16
+ - uses: actions/checkout@v3
17
+ - name: Use Node.js ${{ matrix.node-version }}
18
+ uses: actions/setup-node@v3
19
+ with:
20
+ node-version: ${{ matrix.node-version }}
21
+ - run: npm ci
22
+ - run: npm run build --if-present
23
+ - run: npm run test:standard
24
+ - run: npm test
@@ -0,0 +1,43 @@
1
+ name: Publish
2
+
3
+ on:
4
+ release:
5
+ types: [created]
6
+
7
+ permissions:
8
+ contents: read
9
+ id-token: write
10
+
11
+ jobs:
12
+ publish:
13
+ runs-on: ubuntu-latest
14
+ steps:
15
+ - uses: actions/checkout@v4
16
+
17
+ - uses: actions/setup-node@v4
18
+ with:
19
+ node-version: 20
20
+ registry-url: https://registry.npmjs.org/
21
+
22
+ # Ensure npm CLI is new enough for Trusted Publishing flows
23
+ - run: npm i -g npm@latest
24
+ - run: npm -v
25
+
26
+ - run: npm ci
27
+
28
+ # Set package.json version from the release tag (e.g. v3.2.7 โ†’ 3.2.7)
29
+ - name: Set version from tag
30
+ run: |
31
+ VERSION="${GITHUB_REF_NAME#v}"
32
+ echo "GITHUB_REF_NAME=${GITHUB_REF_NAME}"
33
+ echo "VERSION=${VERSION}"
34
+ if [ -z "${VERSION}" ]; then
35
+ echo "Error: could not determine version from GITHUB_REF_NAME='${GITHUB_REF_NAME}'"
36
+ exit 1
37
+ fi
38
+ npm version "${VERSION}" --no-git-tag-version --ignore-scripts
39
+
40
+ - run: npm run build
41
+
42
+ # Public packages sometimes need this explicitly (safe even if already public)
43
+ - run: npm publish --access public
package/.mocharc.yaml CHANGED
@@ -2,4 +2,3 @@ require: '@babel/register'
2
2
  spec: test/node-dependency-injection/**/*.spec.js
3
3
  color: true
4
4
  ui: bdd
5
- reporter: nyan
package/CHANGELOG-3.md CHANGED
@@ -1,7 +1,12 @@
1
1
  # Change Log
2
2
 
3
- # [3.0.0] - 2022-05-09
3
+ # [3.0.0] - 2022-05-19
4
4
  ### Changed
5
+ - File Loader load method is now Promised
6
+ - ContainerBuilder compile is now Promised
7
+ - ContainerBuilder findDefinition is now Promised
8
+ - Custom Compiler Pass process needs to be Promised
9
+ - Container Builder findTaggedServiceIds returns an Iterable object instead of Map
5
10
  ### Added
6
11
  - Autowire support for TypeScript
7
12
  - Get container service from a class instance
package/CONTRIBUTING.md CHANGED
@@ -52,13 +52,13 @@ $ npm test || test:coverage
52
52
  Please, follow [Standard JS Coding Guidelines](http://standardjs.com)
53
53
 
54
54
  ```console
55
- $ npm run test:standard
55
+ $ npx standard
56
56
  ```
57
57
 
58
58
  and if you want to fix automatically some of your source code
59
59
 
60
60
  ```console
61
- $ npm run test:standard:fix
61
+ $ npx standard --fix
62
62
  ```
63
63
 
64
64
  ### 5. Documentation/Wiki ###
package/README.md CHANGED
@@ -1,81 +1,259 @@
1
- Node Dependency Injection
2
- =========================
1
+ <p align="center">
2
+ <img src="assets/logo.png" alt="Node Dependency Injection" width="480" />
3
+ </p>
3
4
 
4
- ![NDI Logo](http://image.ibb.co/iGnCUn/logojoy.png)
5
+ <h1 align="center">Node Dependency Injection</h1>
5
6
 
6
- #### A special thanks to [Symfony](http://symfony.com) which was a great inspiration and example for this project.
7
+ <p align="center">
8
+ <strong>Standardize and centralize the way objects are constructed in your application.</strong><br/>
9
+ Inspired by the battle-tested <a href="http://symfony.com">Symfony</a> DI container, built for Node.js &amp; TypeScript.
10
+ </p>
7
11
 
8
- The Node Dependency Injection component allows you to standardize and centralize the way objects are constructed in your application.
12
+ <p align="center">
13
+ <a href="https://badge.fury.io/js/node-dependency-injection"><img src="https://badge.fury.io/js/node-dependency-injection.svg" alt="Npm Version" /></a>
14
+ <img src="https://github.com/zazoomauro/node-dependency-injection/actions/workflows/build.yml/badge.svg" alt="Build Status" />
15
+ <a href="https://codecov.io/gh/zazoomauro/node-dependency-injection"><img src="https://codecov.io/gh/zazoomauro/node-dependency-injection/branch/master/graph/badge.svg?token=faEAqrimPR" alt="Code Coverage" /></a>
16
+ <a href="https://www.npmjs.com/package/node-dependency-injection"><img src="https://img.shields.io/npm/dm/node-dependency-injection.svg" alt="Npm Downloads" /></a>
17
+ <a href="https://snyk.io/test/github/zazoomauro/node-dependency-injection"><img src="https://snyk.io/test/github/zazoomauro/node-dependency-injection/badge.svg" alt="Known Vulnerabilities" /></a>
18
+ <a href="https://github.com/zazoomauro/node-dependency-injection/blob/master/LICENCE"><img src="https://img.shields.io/npm/l/node-dependency-injection.svg" alt="License" /></a>
19
+ </p>
9
20
 
10
- [![Npm Version](https://badge.fury.io/js/node-dependency-injection.svg)](https://badge.fury.io/js/node-dependency-injection)
11
- [![Build Status](https://travis-ci.org/zazoomauro/node-dependency-injection.svg?branch=master)](https://travis-ci.org/zazoomauro/node-dependency-injection)
12
- [![Dependencies](https://david-dm.org/zazoomauro/node-dependency-injection.svg)](https://david-dm.org/zazoomauro/node-dependency-injection)
13
- [![DevDependencies](https://david-dm.org/zazoomauro/node-dependency-injection/dev-status.svg)](https://david-dm.org/zazoomauro/node-dependency-injection#info=devDependencies)
14
- [![Code Coverage](https://codecov.io/gh/zazoomauro/node-dependency-injection/branch/master/graph/badge.svg)](https://codecov.io/gh/zazoomauro/node-dependency-injection)
15
- [![Code Climate](https://codeclimate.com/github/zazoomauro/node-dependency-injection/badges/gpa.svg)](https://codeclimate.com/github/zazoomauro/node-dependency-injection)
16
- [![Coding Standard](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](http://standardjs.com/)
17
- [![Known Vulnerabilities](https://snyk.io/test/github/zazoomauro/node-dependency-injection/badge.svg)](https://snyk.io/test/github/zazoomauro/node-dependency-injection)
18
- [![Npm Downloads](https://img.shields.io/npm/dm/node-dependency-injection.svg?maxAge=2592000)](https://www.npmjs.com/package/node-dependency-injection)
19
- [![License](https://img.shields.io/npm/l/node-dependency-injection.svg?maxAge=2592000?style=plastic)](https://github.com/zazoomauro/node-dependency-injection/blob/master/LICENCE)
21
+ ---
20
22
 
21
- Installation
22
- ------------
23
+ ## Why Node Dependency Injection?
24
+
25
+ Managing dependencies manually leads to tightly coupled, hard-to-test code. **Node Dependency Injection** gives you a powerful, flexible IoC container that wires your application together โ€” keeping your classes clean, your tests simple, and your architecture solid.
26
+
27
+ ---
28
+
29
+ ## โœจ Features
30
+
31
+ | | |
32
+ |---|---|
33
+ | ๐Ÿ”„ **Autowire** โ€” zero-config DI for TypeScript | ๐Ÿ“ **Config files** โ€” YAML, JSON or JS |
34
+ | ๐Ÿญ **Factory pattern** โ€” flexible service creation | ๐Ÿท๏ธ **Service tagging** โ€” group & inject by tag |
35
+ | ๐Ÿ’ค **Lazy services** โ€” instantiate only when needed | ๐ŸŽจ **Decorators** โ€” wrap services transparently |
36
+ | โšก **Compiler passes** โ€” transform the container at build time | ๐Ÿ”’ **Private services** โ€” encapsulate internals |
37
+ | ๐ŸŒณ **Parent / Abstract services** โ€” share config via inheritance | ๐Ÿงฉ **Non-shared services** โ€” new instance per call |
38
+ | ๐ŸŒฟ **Environment parameters** โ€” `%env(VAR)%` support | ๐Ÿ—‘๏ธ **Deprecation warnings** โ€” mark services as deprecated |
39
+ | ๐Ÿ“ฆ **Express middleware** โ€” first-class web framework support | ๐Ÿ–ฅ๏ธ **CLI** โ€” inspect &amp; validate your container |
40
+ | ๐Ÿ”€ **Conditional services** โ€” register services based on env or other services | ๐Ÿ—๏ธ **Keyed services** โ€” named strategy pattern with `registerKeyed` |
41
+ | ๐Ÿ”— **Autowire + Keyed** โ€” inject keyed services via parameter binds | |
42
+
43
+ ---
44
+
45
+ ## ๐Ÿ“Š Feature Comparison (NDI vs InversifyJS vs tsyringe vs Awilix)
46
+
47
+ | Feature | node-dependency-injection | InversifyJS | tsyringe | Awilix |
48
+ |---|---|---|---|---|
49
+ | Config files (YAML / JSON / JS) | โœ… Native | โš ๏ธ Programmatic-first | โš ๏ธ Programmatic-first | โš ๏ธ Programmatic-first |
50
+ | TypeScript autowire without decorators | โœ… Native | โŒ | โŒ | โŒ |
51
+ | Keyed services (named strategy groups) | โœ… Native | โš ๏ธ Via custom patterns | โš ๏ธ Via tokens/patterns | โš ๏ธ Via aliases/patterns |
52
+ | Conditional service registration | โœ… Native | โš ๏ธ Manual logic | โš ๏ธ Manual logic | โš ๏ธ Manual logic |
53
+ | Compiler passes / compile-time transforms | โœ… Native | โŒ | โŒ | โŒ |
54
+ | Service tags and tagged lookup | โœ… Native | โš ๏ธ Manual metadata patterns | โš ๏ธ Manual token patterns | โš ๏ธ Naming/registration patterns |
55
+ | Private services | โœ… Native | โš ๏ธ Container conventions | โš ๏ธ Container conventions | โš ๏ธ Container conventions |
56
+ | CLI container inspection / validation | โœ… Native (`ndi`) | โŒ | โŒ | โŒ |
57
+ | Parent / abstract definitions | โœ… Native | โš ๏ธ Composition-based | โš ๏ธ Composition-based | โš ๏ธ Composition-based |
58
+ | Lazy services | โœ… Native | โœ… | โš ๏ธ Partial patterns | โš ๏ธ Partial patterns |
59
+
60
+ > Legend: โœ… built-in, โš ๏ธ possible with custom conventions or extra setup, โŒ not available as a first-class feature.
61
+
62
+ ---
63
+
64
+ ## ๐Ÿš€ Installation
23
65
 
24
66
  ```sh
25
67
  npm install --save node-dependency-injection
26
68
  ```
27
69
 
28
- Usage: register and get services
29
- -----------
70
+ ---
30
71
 
31
- Imagine you have a `Mailer` class like this:
72
+ ## ๐Ÿ Quick Start
73
+
74
+ Register services and wire them together in seconds:
32
75
 
33
76
  ```js
34
- // services/Mailer.js
77
+ import { ContainerBuilder } from 'node-dependency-injection'
78
+ import Mailer from './services/Mailer'
79
+ import ExampleService from './services/ExampleService'
80
+
81
+ const container = new ContainerBuilder()
82
+
83
+ container.register('service.example', ExampleService)
84
+ container.register('service.mailer', Mailer).addArgument('service.example')
85
+
86
+ await container.compile()
87
+
88
+ const mailer = container.get('service.mailer')
89
+ ```
90
+
91
+ ---
92
+
93
+ ## ๐Ÿ”„ Autowire (TypeScript)
94
+
95
+ Zero-configuration dependency injection โ€” NDI reads your TypeScript type annotations and wires everything automatically:
96
+
97
+ ```ts
98
+ import { ContainerBuilder, Autowire } from 'node-dependency-injection'
99
+
100
+ const container = new ContainerBuilder(false, '/path/to/src')
101
+ const autowire = new Autowire(container)
102
+ await autowire.process()
103
+ await container.compile()
35
104
 
36
- export default class Mailer {
37
- /**
38
- * @param {ExampleService} exampleService
39
- */
40
- constructor(exampleService) {
41
- this._exampleService = exampleService;
42
- }
105
+ // Retrieve by class โ€” no string IDs needed
106
+ import SomeService from '@src/service/SomeService'
107
+ const service = container.get(SomeService)
43
108
 
44
- ...
109
+ // Or retrieve by ID with an explicit type
110
+ const typedService = container.get<SomeService>('service.some')
111
+ ```
112
+
113
+ > **Production tip:** dump the autowired config to a YAML file and load it directly in prod โ€” no TypeScript scanning overhead.
114
+
115
+ ```ts
116
+ if (process.env.NODE_ENV === 'development') {
117
+ const autowire = new Autowire(container)
118
+ autowire.serviceFile = new ServiceFile('/dist/services.yaml')
119
+ await autowire.process()
120
+ } else {
121
+ const loader = new YamlFileLoader(container)
122
+ await loader.load('/dist/services.yaml')
45
123
  }
124
+ await container.compile()
46
125
  ```
47
126
 
48
- You can register this in the container as a service:
127
+ The generated `services.yaml` uses **human-readable service IDs** derived from the file path relative to your source root (e.g. `Service/Mailer`), making it easy to review, audit, and debug your application's service graph:
49
128
 
50
- ```js
51
- import {ContainerBuilder} from 'node-dependency-injection'
52
- import Mailer from './services/Mailer'
53
- import ExampleService from './services/ExampleService'
129
+ ```yaml
130
+ # services.yaml (human-readable โ€” default since v4.0)
131
+ services:
132
+ Service/Mailer:
133
+ class: /Service/Mailer
134
+ arguments:
135
+ - '@Service/Transport'
136
+ Service/Transport:
137
+ class: /Service/Transport
138
+ arguments: []
139
+ ```
54
140
 
55
- let container = new ContainerBuilder()
141
+ ### Service ID strategy
56
142
 
57
- container
58
- .register('service.example', ExampleService)
143
+ | Strategy | Default | Service ID example | Description |
144
+ |---|---|---|---|
145
+ | `readable` | โœ… v4.0+ | `Service/Mailer` | Path relative to `defaultDir`, extension stripped |
146
+ | `legacy` | v3.x | `U2VydmljZS9NYWlsZXI=` | Base64-encoded absolute path |
59
147
 
60
- container
61
- .register('service.mailer', Mailer)
62
- .addArgument('service.example')
148
+ To opt back in to the legacy strategy (e.g. for gradual migration):
149
+
150
+ ```ts
151
+ const autowire = new Autowire(container)
152
+ autowire.makeIdLegacy() // switch back to base64-encoded IDs
63
153
  ```
64
154
 
65
- And get services from your container
155
+ ---
156
+
157
+ ## ๐Ÿ—๏ธ Keyed Services
158
+
159
+ Keyed services let you register multiple implementations of the same interface under a named group, then retrieve a specific one by key or inject the entire group as a `Map`.
160
+
161
+ ### Programmatic API
66
162
 
67
163
  ```js
68
- const mailer = container.get('service.mailer')
164
+ import { ContainerBuilder, KeyedReference, KeyedGroupReference } from 'node-dependency-injection'
165
+ import StripePayment from './payments/StripePayment'
166
+ import PaypalPayment from './payments/PaypalPayment'
167
+ import CheckoutService from './CheckoutService'
168
+ import PaymentRouter from './PaymentRouter'
169
+
170
+ const container = new ContainerBuilder()
171
+
172
+ // Register implementations under the 'payment' group
173
+ container.registerKeyed('payment', 'stripe', StripePayment).setDefault(true)
174
+ container.registerKeyed('payment', 'paypal', PaypalPayment)
175
+
176
+ // Inject a specific key
177
+ container.register('checkout', CheckoutService)
178
+ .addArgument(new KeyedReference('payment', 'stripe'))
179
+
180
+ // Inject the full group as a Map<key, instance>
181
+ container.register('payment.router', PaymentRouter)
182
+ .addArgument(new KeyedGroupReference('payment'))
183
+
184
+ // Retrieve by key or get the default
185
+ const stripe = container.getKeyed('payment', 'stripe')
186
+ const defaultPayment = container.getKeyed('payment') // returns the .setDefault(true) one
187
+ const allPayments = container.getKeyedGroup('payment') // Map { 'stripe' => โ€ฆ, 'paypal' => โ€ฆ }
188
+ ```
189
+
190
+ ### YAML configuration
191
+
192
+ ```yaml
193
+ services:
194
+ payment.stripe:
195
+ class: 'payments/StripePayment'
196
+ keyed:
197
+ group: payment
198
+ key: stripe
199
+ default: true
200
+
201
+ payment.paypal:
202
+ class: 'payments/PaypalPayment'
203
+ keyed:
204
+ group: payment
205
+ key: paypal
206
+
207
+ checkout:
208
+ class: 'CheckoutService'
209
+ arguments: ['@keyed(payment, stripe)']
210
+
211
+ payment.router:
212
+ class: 'PaymentRouter'
213
+ arguments: ['@keyed_group(payment)']
69
214
  ```
70
215
 
216
+ ### Autowire integration
217
+
218
+ When using Autowire you can inject keyed services into **typed** constructor parameters by registering a bind whose name matches the parameter name:
71
219
 
72
- Configuration files: how to load and use configuration files
73
- ------------
220
+ ```typescript
221
+ // TypeScript service
222
+ export default class CheckoutService {
223
+ constructor(private readonly payment: IPaymentService) {}
224
+ }
74
225
 
75
- You can also use configuration files to improve your service configuration
226
+ export default class PaymentRouter {
227
+ constructor(private readonly payments: Map<string, IPaymentService>) {}
228
+ }
229
+ ```
230
+
231
+ ```js
232
+ container.registerKeyed('payment', 'stripe', StripePaymentService)
233
+ container.registerKeyed('payment', 'paypal', PaypalPaymentService)
234
+
235
+ // The bind name must match the constructor parameter name exactly
236
+ container.addBind('payment', new KeyedReference('payment', 'stripe'))
237
+ container.addBind('payments', new KeyedGroupReference('payment'))
238
+
239
+ const autowire = new Autowire(container)
240
+ await autowire.process()
241
+ await container.compile()
242
+
243
+ // container.get(CheckoutService).payment โ†’ StripePaymentService
244
+ // container.get(PaymentRouter).payments โ†’ Map { 'stripe' => โ€ฆ, 'paypal' => โ€ฆ }
245
+ ```
246
+
247
+ > **Note:** binds take priority over type-based resolution. The same mechanism works for scalar values โ€” `container.addBind('apiKey', '%env(API_KEY)%')` โ€” so keyed service binds fit naturally into the existing bind API.
248
+
249
+ ---
250
+
251
+ ## ๐Ÿ“ Configuration Files
252
+
253
+ Prefer declarative config? Use YAML, JSON or JS:
76
254
 
77
255
  ```yaml
78
- # /path/to/file.yml
256
+ # services.yaml
79
257
  services:
80
258
  service.example:
81
259
  class: 'services/ExampleService'
@@ -86,97 +264,147 @@ services:
86
264
  ```
87
265
 
88
266
  ```js
89
- import {ContainerBuilder, YamlFileLoader} from 'node-dependency-injection'
267
+ import { ContainerBuilder, YamlFileLoader } from 'node-dependency-injection'
268
+
269
+ const container = new ContainerBuilder()
270
+ const loader = new YamlFileLoader(container)
271
+ await loader.load('/path/to/services.yaml')
272
+ await container.compile()
90
273
 
91
- let container = new ContainerBuilder()
92
- let loader = new YamlFileLoader(container)
93
- loader.load('/path/to/file.yml')
274
+ const mailer = container.get('service.mailer')
94
275
  ```
95
276
 
96
- And get services from your container easily
277
+ ---
278
+
279
+ ## ๐Ÿ”€ Conditional Services
280
+
281
+ Register services only when specific conditions are met โ€” evaluated at `compile()` time.
97
282
 
98
283
  ```js
99
- ...
100
- const mailer = container.get('service.mailer')
284
+ import { ContainerBuilder, Condition } from 'node-dependency-injection'
285
+
286
+ const container = new ContainerBuilder()
287
+
288
+ // Register only when an environment variable is set
289
+ container.register('cache.redis', RedisCache)
290
+ .setCondition(Condition.envExists('REDIS_URL'))
291
+
292
+ // Fallback: register only when another service was NOT registered (TryAdd)
293
+ container.register('cache.memory', InMemoryCache)
294
+ .whenMissing('cache.redis')
295
+
296
+ // Register only when a sibling service IS registered
297
+ container.register('metrics', Prometheus)
298
+ .whenServiceExists('http.server')
299
+
300
+ // Combine conditions
301
+ container.register('feature.x', FeatureX)
302
+ .setCondition(Condition.all(
303
+ Condition.envEquals('NODE_ENV', 'production'),
304
+ Condition.envExists('FEATURE_X_ENABLED')
305
+ ))
306
+
307
+ await container.compile()
308
+ ```
309
+
310
+ The same conditions are available declaratively in YAML:
311
+
312
+ ```yaml
313
+ services:
314
+ cache.redis:
315
+ class: 'services/cache/RedisCache'
316
+ when:
317
+ env_exists: REDIS_URL
318
+
319
+ cache.memory:
320
+ class: 'services/cache/InMemoryCache'
321
+ when:
322
+ missing: cache.redis
323
+
324
+ metrics.prometheus:
325
+ class: 'services/metrics/Prometheus'
326
+ when:
327
+ service_exists: http.server
328
+
329
+ logger.verbose:
330
+ class: 'services/logger/VerboseLogger'
331
+ when:
332
+ env_equals: { var: LOG_LEVEL, value: debug }
101
333
  ```
102
334
 
103
- List of features
104
- ------------
105
-
106
- - Configuration files with JS, YAML or JSON.
107
- - Multiple configuration files
108
- - Custom relative service directory
109
- - Compiling container
110
- - Custom compiler pass
111
- - Change definition behaviour
112
- - Using a factory to create services
113
- - Nullable Dependencies
114
- - Public or private services
115
- - Service Aliasing
116
- - Service Tagging
117
- - Parameters Injection
118
- - Lazy Services
119
- - Deprecate Services
120
- - Decorate Services
121
- - Synthetic Services
122
- - Non Shared Services
123
- - Parent and Abstract Services
124
- - Custom Logger
125
- - Container as Service
126
-
127
- > Please read [full documentation](https://github.com/zazoomauro/node-dependency-injection/wiki)
128
-
129
- ExpressJS Usage
130
- ----------------
131
-
132
- If you are using expressJS and you like Node Dependency Injection Framework then I strongly recommend
133
- you to use the `node-dependency-injection-express-middleware` package.
134
- That gives you the possibility to retrieve the container from the request.
335
+ > See the [Conditional Services wiki page](https://github.com/zazoomauro/node-dependency-injection/wiki/ConditionalServices) for the full API reference and advanced usage.
336
+
337
+ ---
338
+
339
+ ## ๐Ÿ“ฆ Ecosystem
340
+
341
+ ### Express Middleware
342
+
343
+ Use NDI seamlessly with Express โ€” retrieve the container directly from any request:
135
344
 
136
345
  ```bash
137
346
  npm install --save node-dependency-injection-express-middleware
138
347
  ```
139
348
 
140
- ```javascript
349
+ ```js
141
350
  import NDIMiddleware from 'node-dependency-injection-express-middleware'
142
351
  import express from 'express'
143
352
 
144
353
  const app = express()
145
-
146
- const options = {serviceFilePath: 'some/path/to/config.yml'}
147
- app.use(new NDIMiddleware(options).middleware())
354
+ app.use(new NDIMiddleware({ serviceFilePath: 'services.yaml' }).middleware())
148
355
  ```
149
356
 
150
357
  > [Express Middleware Documentation](https://github.com/zazoomauro/node-dependency-injection-express-middleware)
151
358
 
152
- TypeScript Usage
153
- ----------------
359
+ ### CLI
154
360
 
155
- If you are using typescript and you like Node Dependency Injection Framework then typing are now provided at `node-dependency-injection` so
156
- you do not have to create custom typing anymore.
361
+ Inspect and validate your container from the command line:
157
362
 
158
363
  ```bash
159
- npm install --save node-dependency-injection
160
- ```
364
+ # Validate a config file
365
+ ndi config:check /path/to/services.yaml
161
366
 
162
- ```typescript
163
- import { ContainerBuilder } from 'node-dependency-injection'
164
- import MongoClient from './services/MongoClient'
165
- import { Env } from './EnvType'
166
-
167
- export async function boot(container = new ContainerBuilder(), env: Env) {
168
- container.register('Service.MongoClient', MongoClient).addArgument({
169
- host: env.HOST,
170
- port: env.PORT,
171
- })
172
- }
367
+ # Inspect a specific service
368
+ ndi container:service /path/to/services.yaml service.mailer
173
369
  ```
174
370
 
175
- Resources
176
- ---------
371
+ ---
372
+
373
+ ## ๐Ÿ“– Documentation
374
+
375
+ The full documentation lives in the [**project wiki**](https://github.com/zazoomauro/node-dependency-injection/wiki), including guides on:
376
+
377
+ - [Getting Started](https://github.com/zazoomauro/node-dependency-injection/wiki/GettingStarted)
378
+ - [Autowire](https://github.com/zazoomauro/node-dependency-injection/wiki/Autowire)
379
+ - [Keyed Services](https://github.com/zazoomauro/node-dependency-injection/wiki/KeyedServices)
380
+ - [Configuration Files](https://github.com/zazoomauro/node-dependency-injection/wiki/ConfigurationFiles)
381
+ - [Compiler Passes](https://github.com/zazoomauro/node-dependency-injection/wiki/CompilerPass)
382
+ - [Conditional Services](https://github.com/zazoomauro/node-dependency-injection/wiki/ConditionalServices)
383
+ - [Tagging Services](https://github.com/zazoomauro/node-dependency-injection/wiki/Tagging)
384
+ - [Factory](https://github.com/zazoomauro/node-dependency-injection/wiki/Factory)
385
+ - [Lazy Services](https://github.com/zazoomauro/node-dependency-injection/wiki/LazyService)
386
+ - [Decorators](https://github.com/zazoomauro/node-dependency-injection/wiki/Decorate)
387
+ - [And much more...](https://github.com/zazoomauro/node-dependency-injection/wiki)
388
+
389
+ ---
390
+
391
+ ## ๐Ÿค Contributing
177
392
 
178
- - [Documentation](https://github.com/zazoomauro/node-dependency-injection/wiki)
179
- - [Collaboration and pull requests](CONTRIBUTING.md)
180
- - [Milestones](https://github.com/zazoomauro/node-dependency-injection/milestones)
181
- - [Twitter @zazoomauro](https://twitter.com/zazoomauro)
393
+ Contributions are welcome! Please read the [contribution guide](CONTRIBUTING.md) before submitting a pull request.
394
+
395
+ - [Open an issue](https://github.com/zazoomauro/node-dependency-injection/issues)
396
+ - [View milestones](https://github.com/zazoomauro/node-dependency-injection/milestones)
182
397
  - [Changelog](CHANGELOG.md)
398
+
399
+ ---
400
+
401
+ ## ๐Ÿ™ Credits
402
+
403
+ Inspired by the [Symfony](http://symfony.com) Dependency Injection component โ€” a special thanks to the Symfony team for their outstanding work.
404
+
405
+ ---
406
+
407
+ <p align="center">
408
+ <a href="https://github.com/zazoomauro/node-dependency-injection/blob/master/LICENCE">MIT License</a> &nbsp;ยท&nbsp;
409
+ Made with โค๏ธ by <a href="https://twitter.com/zazoomauro">@zazoomauro</a>
410
+ </p>
package/UPGRADE-3.0.md CHANGED
@@ -3,4 +3,7 @@ UPGRADE FROM 2.x to 3.x
3
3
 
4
4
  ### Removed deprecations
5
5
 
6
- - Nothing
6
+ - FileLoader load method is now Promised. Add await to be sync
7
+ - ContainerBuilder compile method is now Promised. Add await to be sync
8
+ - All your custom Compiler Pass process method needs to be promised
9
+ - Container Builder findTaggedServiceIds returns an Iterable object instead of Map