@navios/core 1.1.0 → 2.0.0-alpha.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 (241) hide show
  1. package/CHANGELOG.md +53 -11
  2. package/README.md +67 -220
  3. package/lib/async-context-6pdlnNLA.d.mts +237 -0
  4. package/lib/async-context-6pdlnNLA.d.mts.map +1 -0
  5. package/lib/async-context-Dqk7pE-D.d.cts +237 -0
  6. package/lib/async-context-Dqk7pE-D.d.cts.map +1 -0
  7. package/lib/attribute-factory-B3VuYnp7.d.cts +70 -0
  8. package/lib/attribute-factory-B3VuYnp7.d.cts.map +1 -0
  9. package/lib/attribute-factory-mKOXoVnV.d.mts +70 -0
  10. package/lib/attribute-factory-mKOXoVnV.d.mts.map +1 -0
  11. package/lib/attribute-value-CjX9ZkLq.cjs +172 -0
  12. package/lib/attribute-value-CjX9ZkLq.cjs.map +1 -0
  13. package/lib/attribute-value-DMEA255r.mjs +119 -0
  14. package/lib/attribute-value-DMEA255r.mjs.map +1 -0
  15. package/lib/basic-execution-context-CeGuhMOz.mjs +246 -0
  16. package/lib/basic-execution-context-CeGuhMOz.mjs.map +1 -0
  17. package/lib/basic-execution-context-DSk5MNtc.cjs +281 -0
  18. package/lib/basic-execution-context-DSk5MNtc.cjs.map +1 -0
  19. package/lib/execution-context-BPD3FeFb.d.mts +71 -0
  20. package/lib/execution-context-BPD3FeFb.d.mts.map +1 -0
  21. package/lib/execution-context-BTJdHhbf.d.cts +71 -0
  22. package/lib/execution-context-BTJdHhbf.d.cts.map +1 -0
  23. package/lib/execution-context-token-BXUKB2hf.cjs +112 -0
  24. package/lib/execution-context-token-BXUKB2hf.cjs.map +1 -0
  25. package/lib/execution-context-token-CrXmTvk2.mjs +77 -0
  26. package/lib/execution-context-token-CrXmTvk2.mjs.map +1 -0
  27. package/lib/index.cjs +1687 -4424
  28. package/lib/index.cjs.map +1 -1
  29. package/lib/index.d.cts +838 -3
  30. package/lib/index.d.cts.map +1 -0
  31. package/lib/index.d.mts +838 -3
  32. package/lib/index.d.mts.map +1 -0
  33. package/lib/index.mjs +1573 -4219
  34. package/lib/index.mjs.map +1 -1
  35. package/lib/legacy-compat/index.cjs +72 -371
  36. package/lib/legacy-compat/index.cjs.map +1 -1
  37. package/lib/legacy-compat/index.d.cts +42 -382
  38. package/lib/legacy-compat/index.d.cts.map +1 -1
  39. package/lib/legacy-compat/index.d.mts +41 -382
  40. package/lib/legacy-compat/index.d.mts.map +1 -1
  41. package/lib/legacy-compat/index.mjs +51 -345
  42. package/lib/legacy-compat/index.mjs.map +1 -1
  43. package/lib/module-Bha7GER_.mjs +135 -0
  44. package/lib/module-Bha7GER_.mjs.map +1 -0
  45. package/lib/module-DZewk_2r.cjs +164 -0
  46. package/lib/module-DZewk_2r.cjs.map +1 -0
  47. package/lib/module-graph-DCP9MHG0.cjs +147 -0
  48. package/lib/module-graph-DCP9MHG0.cjs.map +1 -0
  49. package/lib/module-graph-xvVEykFM.mjs +142 -0
  50. package/lib/module-graph-xvVEykFM.mjs.map +1 -0
  51. package/lib/module-metadata-C8S92seK.cjs +95 -0
  52. package/lib/module-metadata-C8S92seK.cjs.map +1 -0
  53. package/lib/module-metadata-k3RTt20x.mjs +66 -0
  54. package/lib/module-metadata-k3RTt20x.mjs.map +1 -0
  55. package/lib/module-options-Dmse0gii.d.mts +51 -0
  56. package/lib/module-options-Dmse0gii.d.mts.map +1 -0
  57. package/lib/module-options-IuDO-p8u.d.cts +51 -0
  58. package/lib/module-options-IuDO-p8u.d.cts.map +1 -0
  59. package/lib/testing/index.cjs +96 -414
  60. package/lib/testing/index.cjs.map +1 -1
  61. package/lib/testing/index.d.cts +25 -385
  62. package/lib/testing/index.d.cts.map +1 -1
  63. package/lib/testing/index.d.mts +24 -385
  64. package/lib/testing/index.d.mts.map +1 -1
  65. package/lib/testing/index.mjs +94 -408
  66. package/lib/testing/index.mjs.map +1 -1
  67. package/lib/transport.cjs +25 -0
  68. package/lib/transport.d.cts +190 -0
  69. package/lib/transport.d.cts.map +1 -0
  70. package/lib/transport.d.mts +190 -0
  71. package/lib/transport.d.mts.map +1 -0
  72. package/lib/transport.mjs +7 -0
  73. package/package.json +37 -17
  74. package/docs/README.md +0 -316
  75. package/docs/adapters.md +0 -308
  76. package/docs/application-setup.md +0 -524
  77. package/docs/attributes.md +0 -689
  78. package/docs/controllers.md +0 -373
  79. package/docs/endpoints.md +0 -444
  80. package/docs/exceptions.md +0 -352
  81. package/docs/guards.md +0 -550
  82. package/docs/legacy-compat.md +0 -356
  83. package/docs/modules.md +0 -377
  84. package/docs/quick-start.md +0 -290
  85. package/docs/services.md +0 -427
  86. package/docs/testing.md +0 -827
  87. package/lib/index-3LcTrbxz.d.mts +0 -3804
  88. package/lib/index-3LcTrbxz.d.mts.map +0 -1
  89. package/lib/index-B14SekVb.d.cts +0 -3804
  90. package/lib/index-B14SekVb.d.cts.map +0 -1
  91. package/lib/navios.factory-CUrO_p6K.cjs +0 -4538
  92. package/lib/navios.factory-CUrO_p6K.cjs.map +0 -1
  93. package/lib/navios.factory-DjUOOVVL.mjs +0 -4151
  94. package/lib/navios.factory-DjUOOVVL.mjs.map +0 -1
  95. package/lib/tokens-BEuBMGGX.cjs +0 -193
  96. package/lib/tokens-BEuBMGGX.cjs.map +0 -1
  97. package/lib/tokens-COyNGV1I.mjs +0 -97
  98. package/lib/tokens-COyNGV1I.mjs.map +0 -1
  99. package/lib/use-guards.decorator-DLmRl2CV.mjs +0 -336
  100. package/lib/use-guards.decorator-DLmRl2CV.mjs.map +0 -1
  101. package/lib/use-guards.decorator-DhumFTk3.cjs +0 -444
  102. package/lib/use-guards.decorator-DhumFTk3.cjs.map +0 -1
  103. package/project.json +0 -66
  104. package/src/__tests__/attribute.factory.spec.mts +0 -300
  105. package/src/__tests__/config.service.spec.mts +0 -43
  106. package/src/__tests__/console-logger.service.spec.mts +0 -312
  107. package/src/__tests__/controller-resolver.spec.mts +0 -229
  108. package/src/__tests__/controller.spec.mts +0 -58
  109. package/src/__tests__/guard-runner.service.spec.mts +0 -399
  110. package/src/__tests__/logger.service.spec.mts +0 -147
  111. package/src/__tests__/responders.spec.mts +0 -340
  112. package/src/__tests__/testing-module.spec.mts +0 -459
  113. package/src/__tests__/unit-testing-module.spec.mts +0 -424
  114. package/src/attribute.factory.mts +0 -325
  115. package/src/config/config-service.interface.mts +0 -47
  116. package/src/config/config.provider.mts +0 -69
  117. package/src/config/config.service.mts +0 -176
  118. package/src/config/index.mts +0 -5
  119. package/src/config/types.mts +0 -58
  120. package/src/config/utils/helpers.mts +0 -23
  121. package/src/config/utils/index.mts +0 -1
  122. package/src/decorators/controller.decorator.mts +0 -81
  123. package/src/decorators/endpoint.decorator.mts +0 -181
  124. package/src/decorators/header.decorator.mts +0 -38
  125. package/src/decorators/http-code.decorator.mts +0 -38
  126. package/src/decorators/index.mts +0 -8
  127. package/src/decorators/module.decorator.mts +0 -106
  128. package/src/decorators/multipart.decorator.mts +0 -169
  129. package/src/decorators/stream.decorator.mts +0 -155
  130. package/src/decorators/use-guards.decorator.mts +0 -73
  131. package/src/exceptions/bad-request.exception.mts +0 -28
  132. package/src/exceptions/conflict.exception.mts +0 -31
  133. package/src/exceptions/forbidden.exception.mts +0 -30
  134. package/src/exceptions/http.exception.mts +0 -33
  135. package/src/exceptions/index.mts +0 -7
  136. package/src/exceptions/internal-server-error.exception.mts +0 -33
  137. package/src/exceptions/not-found.exception.mts +0 -33
  138. package/src/exceptions/unauthorized.exception.mts +0 -30
  139. package/src/factories/adapter.factory.mts +0 -20
  140. package/src/factories/endpoint-adapter.factory.mts +0 -21
  141. package/src/factories/http-adapter.factory.mts +0 -20
  142. package/src/factories/index.mts +0 -8
  143. package/src/factories/multipart-adapter.factory.mts +0 -21
  144. package/src/factories/reply.factory.mts +0 -21
  145. package/src/factories/request.factory.mts +0 -21
  146. package/src/factories/stream-adapter.factory.mts +0 -20
  147. package/src/factories/xml-stream-adapter.factory.mts +0 -20
  148. package/src/index.mts +0 -16
  149. package/src/interfaces/abstract-adapter.interface.mts +0 -32
  150. package/src/interfaces/abstract-execution-context.inteface.mts +0 -48
  151. package/src/interfaces/abstract-http-adapter.interface.mts +0 -79
  152. package/src/interfaces/abstract-http-cors-options.interface.mts +0 -59
  153. package/src/interfaces/abstract-http-handler-adapter.interface.mts +0 -127
  154. package/src/interfaces/abstract-http-listen-options.interface.mts +0 -4
  155. package/src/interfaces/adapter-environment.interface.mts +0 -74
  156. package/src/interfaces/can-activate.mts +0 -38
  157. package/src/interfaces/http-header.mts +0 -18
  158. package/src/interfaces/index.mts +0 -14
  159. package/src/interfaces/navios-module.mts +0 -28
  160. package/src/interfaces/plugin-context.mts +0 -104
  161. package/src/interfaces/plugin-stage.mts +0 -62
  162. package/src/interfaces/plugin.interface.mts +0 -119
  163. package/src/interfaces/staged-plugin.interface.mts +0 -209
  164. package/src/legacy-compat/__type-tests__/legacy-decorators.spec-d.mts +0 -521
  165. package/src/legacy-compat/__type-tests__/tsconfig.json +0 -15
  166. package/src/legacy-compat/attribute.factory.mts +0 -351
  167. package/src/legacy-compat/decorators/controller.decorator.mts +0 -31
  168. package/src/legacy-compat/decorators/endpoint.decorator.mts +0 -73
  169. package/src/legacy-compat/decorators/header.decorator.mts +0 -43
  170. package/src/legacy-compat/decorators/http-code.decorator.mts +0 -39
  171. package/src/legacy-compat/decorators/index.mts +0 -11
  172. package/src/legacy-compat/decorators/module.decorator.mts +0 -37
  173. package/src/legacy-compat/decorators/multipart.decorator.mts +0 -72
  174. package/src/legacy-compat/decorators/stream.decorator.mts +0 -89
  175. package/src/legacy-compat/decorators/use-guards.decorator.mts +0 -80
  176. package/src/legacy-compat/index.mts +0 -57
  177. package/src/logger/README.md +0 -3
  178. package/src/logger/console-logger.service.mts +0 -714
  179. package/src/logger/index.mts +0 -6
  180. package/src/logger/log-levels.mts +0 -21
  181. package/src/logger/logger-service.interface.mts +0 -42
  182. package/src/logger/logger.service.mts +0 -113
  183. package/src/logger/logger.tokens.mts +0 -44
  184. package/src/logger/utils/cli-colors.util.mts +0 -17
  185. package/src/logger/utils/filter-log-levelts.util.mts +0 -29
  186. package/src/logger/utils/index.mts +0 -5
  187. package/src/logger/utils/is-log-level-enabled.mts +0 -33
  188. package/src/logger/utils/is-log-level.util.mts +0 -10
  189. package/src/logger/utils/shared.utils.mts +0 -51
  190. package/src/metadata/controller.metadata.mts +0 -79
  191. package/src/metadata/handler.metadata.mts +0 -80
  192. package/src/metadata/index.mts +0 -4
  193. package/src/metadata/module.metadata.mts +0 -116
  194. package/src/metadata/navios-managed.metadata.mts +0 -42
  195. package/src/navios.application.mts +0 -678
  196. package/src/navios.environment.mts +0 -42
  197. package/src/navios.factory.mts +0 -158
  198. package/src/responders/enums/framework-error.enum.mts +0 -38
  199. package/src/responders/enums/index.mts +0 -1
  200. package/src/responders/index.mts +0 -4
  201. package/src/responders/interfaces/error-responder.interface.mts +0 -42
  202. package/src/responders/interfaces/error-response.interface.mts +0 -22
  203. package/src/responders/interfaces/index.mts +0 -3
  204. package/src/responders/interfaces/problem-details.interface.mts +0 -34
  205. package/src/responders/services/error-response-producer.service.mts +0 -143
  206. package/src/responders/services/forbidden-responder.service.mts +0 -77
  207. package/src/responders/services/index.mts +0 -5
  208. package/src/responders/services/internal-server-error-responder.service.mts +0 -57
  209. package/src/responders/services/not-found-responder.service.mts +0 -76
  210. package/src/responders/services/validation-error-responder.service.mts +0 -78
  211. package/src/responders/tokens/index.mts +0 -1
  212. package/src/responders/tokens/responder.tokens.mts +0 -84
  213. package/src/services/abstract-handler-adapter.service.mts +0 -366
  214. package/src/services/guard-runner.service.mts +0 -152
  215. package/src/services/index.mts +0 -4
  216. package/src/services/instance-resolver.service.mts +0 -177
  217. package/src/services/module-loader.service.mts +0 -255
  218. package/src/stores/index.mts +0 -1
  219. package/src/stores/request-id.store.mts +0 -85
  220. package/src/testing/index.mts +0 -3
  221. package/src/testing/testing-module.mts +0 -393
  222. package/src/testing/unit-testing-module.mts +0 -298
  223. package/src/tokens/adapter.token.mts +0 -6
  224. package/src/tokens/endpoint-adapter.token.mts +0 -8
  225. package/src/tokens/execution-context.token.mts +0 -9
  226. package/src/tokens/http-adapter.token.mts +0 -8
  227. package/src/tokens/index.mts +0 -10
  228. package/src/tokens/multipart-adapter.token.mts +0 -8
  229. package/src/tokens/navios-options.token.mts +0 -6
  230. package/src/tokens/reply.token.mts +0 -3
  231. package/src/tokens/request.token.mts +0 -3
  232. package/src/tokens/stream-adapter.token.mts +0 -8
  233. package/src/tokens/xml-stream-adapter.token.mts +0 -8
  234. package/src/utils/adapter-supports.util.mts +0 -47
  235. package/src/utils/define-plugin.mts +0 -251
  236. package/src/utils/index.mts +0 -2
  237. package/tsconfig.json +0 -21
  238. package/tsconfig.lib.json +0 -8
  239. package/tsconfig.spec.json +0 -15
  240. package/tsdown.config.mts +0 -35
  241. package/vitest.config.mts +0 -15
@@ -1,152 +0,0 @@
1
- import type { ClassTypeWithInstance, ScopedContainer } from '@navios/di'
2
-
3
- import { inject, Injectable, InjectionToken } from '@navios/di'
4
-
5
- import type {
6
- AbstractExecutionContext,
7
- CanActivate,
8
- } from '../interfaces/index.mjs'
9
- import type {
10
- ControllerMetadata,
11
- HandlerMetadata,
12
- ModuleMetadata,
13
- } from '../metadata/index.mjs'
14
-
15
- import { HttpException } from '../exceptions/index.mjs'
16
- import { Logger } from '../logger/index.mjs'
17
- import { FrameworkError } from '../responders/enums/framework-error.enum.mjs'
18
- import { ErrorResponseProducerService } from '../responders/services/error-response-producer.service.mjs'
19
-
20
- @Injectable()
21
- export class GuardRunnerService {
22
- private readonly errorProducer = inject(ErrorResponseProducerService)
23
- private readonly logger = inject(Logger, {
24
- context: GuardRunnerService.name,
25
- })
26
-
27
- /**
28
- * Runs guards that need to be resolved from a scoped container.
29
- * Use this when guards have request-scoped dependencies.
30
- */
31
- async runGuards(
32
- allGuards: Set<
33
- | ClassTypeWithInstance<CanActivate>
34
- | InjectionToken<CanActivate, undefined>
35
- >,
36
- executionContext: AbstractExecutionContext,
37
- context: ScopedContainer,
38
- ) {
39
- // Reverse order: module guards run first, then controller, then endpoint
40
- const guardsArray = Array.from(allGuards).reverse()
41
-
42
- // Resolve all guards in parallel
43
- const guardInstances = await Promise.all(
44
- guardsArray.map(async (guard) => {
45
- const guardInstance = await context.get(
46
- guard as InjectionToken<CanActivate, undefined>,
47
- )
48
- if (!guardInstance.canActivate) {
49
- throw new Error(
50
- `[Navios] Guard ${guard.name as string} does not implement canActivate()`,
51
- )
52
- }
53
- return guardInstance
54
- }),
55
- )
56
-
57
- return this.executeGuards(guardInstances, executionContext)
58
- }
59
-
60
- /**
61
- * Runs pre-resolved guard instances.
62
- * Use this when all guards are singletons and have been pre-resolved at startup.
63
- */
64
- async runGuardsStatic(
65
- guardInstances: CanActivate[],
66
- executionContext: AbstractExecutionContext,
67
- ) {
68
- return this.executeGuards(guardInstances, executionContext)
69
- }
70
-
71
- /**
72
- * Shared guard execution logic.
73
- * Iterates through guard instances and calls canActivate on each.
74
- */
75
- private async executeGuards(
76
- guardInstances: CanActivate[],
77
- executionContext: AbstractExecutionContext,
78
- ): Promise<boolean> {
79
- let canActivate = true
80
- for (const guardInstance of guardInstances) {
81
- try {
82
- canActivate = await guardInstance.canActivate(executionContext)
83
- if (!canActivate) {
84
- break
85
- }
86
- } catch (error) {
87
- if (error instanceof HttpException) {
88
- executionContext
89
- .getReply()
90
- .status(error.statusCode)
91
- .send(error.response)
92
- return false
93
- } else {
94
- this.logger.error('Error running guard', error)
95
- const errorResponse = this.errorProducer.respond(
96
- FrameworkError.InternalServerError,
97
- error,
98
- )
99
- executionContext
100
- .getReply()
101
- .status(errorResponse.statusCode)
102
- .send(errorResponse.payload)
103
- return false
104
- }
105
- }
106
- }
107
- if (!canActivate) {
108
- const errorResponse = this.errorProducer.respond(
109
- FrameworkError.Forbidden,
110
- null,
111
- )
112
- executionContext
113
- .getReply()
114
- .status(errorResponse.statusCode)
115
- .send(errorResponse.payload)
116
- return false
117
- }
118
- return canActivate
119
- }
120
-
121
- makeContext(
122
- moduleMetadata: ModuleMetadata,
123
- controllerMetadata: ControllerMetadata,
124
- endpoint: HandlerMetadata,
125
- ): Set<
126
- ClassTypeWithInstance<CanActivate> | InjectionToken<CanActivate, undefined>
127
- > {
128
- const guards = new Set<
129
- | ClassTypeWithInstance<CanActivate>
130
- | InjectionToken<CanActivate, undefined>
131
- >()
132
- const endpointGuards = endpoint.guards
133
- const controllerGuards = controllerMetadata.guards
134
- const moduleGuards = moduleMetadata.guards
135
- if (endpointGuards.size > 0) {
136
- for (const guard of endpointGuards) {
137
- guards.add(guard)
138
- }
139
- }
140
- if (controllerGuards.size > 0) {
141
- for (const guard of controllerGuards) {
142
- guards.add(guard)
143
- }
144
- }
145
- if (moduleGuards.size > 0) {
146
- for (const guard of moduleGuards) {
147
- guards.add(guard)
148
- }
149
- }
150
- return guards
151
- }
152
- }
@@ -1,4 +0,0 @@
1
- export * from './abstract-handler-adapter.service.mjs'
2
- export * from './instance-resolver.service.mjs'
3
- export * from './guard-runner.service.mjs'
4
- export * from './module-loader.service.mjs'
@@ -1,177 +0,0 @@
1
- import type { ClassType, ScopedContainer } from '@navios/di'
2
-
3
- import {
4
- Container,
5
- getInjectableToken,
6
- inject,
7
- Injectable,
8
- InjectableScope,
9
- } from '@navios/di'
10
-
11
- /**
12
- * Result of instance resolution attempt.
13
- * Contains either a cached singleton instance or a resolver function
14
- * that can be used to get a fresh instance per request.
15
- */
16
- export interface InstanceResolution<T = any> {
17
- /**
18
- * Whether the instance was successfully cached as a singleton.
19
- * If true, `instance` contains the cached instance.
20
- * If false, the class has request-scoped dependencies and
21
- * must be resolved per-request using `resolve()`.
22
- */
23
- cached: boolean
24
-
25
- /**
26
- * The cached instance (only available if `cached` is true).
27
- */
28
- instance: T | null
29
-
30
- /**
31
- * Resolves the instance from a scoped container.
32
- * Use this when `cached` is false to get a fresh instance per request.
33
- */
34
- resolve: (scoped: ScopedContainer) => Promise<T>
35
- }
36
-
37
- /**
38
- * Result of resolving multiple instances.
39
- * Contains either all cached singleton instances or a resolver function.
40
- */
41
- export interface MultiInstanceResolution<T = any> {
42
- /**
43
- * Whether ALL instances were successfully cached as singletons.
44
- * If true, `instances` contains all cached instances.
45
- * If false, at least one class has request-scoped dependencies.
46
- */
47
- cached: boolean
48
-
49
- /**
50
- * The cached instances (only available if `cached` is true).
51
- * Order matches the input array order.
52
- */
53
- instances: T[] | null
54
-
55
- /**
56
- * The original class types for dynamic resolution.
57
- */
58
- classTypes: ClassType[]
59
-
60
- /**
61
- * Resolves all instances from a scoped container.
62
- * Use this when `cached` is false to get fresh instances per request.
63
- */
64
- resolve: (scoped: ScopedContainer) => Promise<T[]>
65
- }
66
-
67
- /**
68
- * Service responsible for resolving class instances with automatic scope detection.
69
- *
70
- * This service attempts to resolve classes as singletons from the root container.
71
- * If resolution fails (because the class has request-scoped dependencies),
72
- * it automatically updates the class's scope to Request and provides a
73
- * resolver function for per-request instantiation.
74
- *
75
- * This enables optimal performance:
76
- * - Classes without request-scoped deps stay as singletons (faster)
77
- * - Classes with request-scoped deps are automatically promoted to request scope
78
- *
79
- * @example
80
- * ```ts
81
- * const resolution = await instanceResolver.resolve(UserController)
82
- *
83
- * if (resolution.cached) {
84
- * // Use cached singleton
85
- * return resolution.instance.handleRequest(req)
86
- * } else {
87
- * // Resolve per request
88
- * const controller = await resolution.resolve(scopedContainer)
89
- * return controller.handleRequest(req)
90
- * }
91
- * ```
92
- */
93
- @Injectable()
94
- export class InstanceResolverService {
95
- private container = inject(Container)
96
-
97
- /**
98
- * Attempts to resolve a class instance, automatically detecting if it needs
99
- * request scope based on its dependencies.
100
- *
101
- * @param classType - The class to resolve
102
- * @returns A resolution result containing either a cached instance or resolver function
103
- */
104
- async resolve<T>(classType: ClassType): Promise<InstanceResolution<T>> {
105
- let cachedInstance: T | null = null
106
-
107
- try {
108
- cachedInstance = await this.container.get(classType)
109
- } catch {
110
- // Class has request-scoped dependencies, update its scope to Request
111
- // so it will be resolved per-request from the scoped container
112
- const token = getInjectableToken(classType)
113
- this.container.getRegistry().updateScope(token, InjectableScope.Request)
114
- }
115
-
116
- return {
117
- cached: cachedInstance !== null,
118
- instance: cachedInstance,
119
- resolve: (scoped: ScopedContainer) => scoped.get(classType) as Promise<T>,
120
- }
121
- }
122
-
123
- /**
124
- * Attempts to resolve multiple class instances, automatically detecting if any need
125
- * request scope based on their dependencies.
126
- *
127
- * Returns `cached: true` only if ALL classes can be resolved as singletons.
128
- * If any class has request-scoped dependencies, returns `cached: false`.
129
- *
130
- * @param classTypes - The classes to resolve
131
- * @returns A resolution result containing either all cached instances or resolver function
132
- */
133
- async resolveMany<T>(
134
- classTypes: ClassType[],
135
- ): Promise<MultiInstanceResolution<T>> {
136
- if (classTypes.length === 0) {
137
- return {
138
- cached: true,
139
- instances: [],
140
- classTypes: [],
141
- resolve: async () => [],
142
- }
143
- }
144
-
145
- // Resolve all classes in parallel
146
- const results = await Promise.all(
147
- classTypes.map(async (classType) => {
148
- try {
149
- const instance = await this.container.get(classType)
150
- return { success: true, instance: instance as T }
151
- } catch {
152
- // Class has request-scoped dependencies, update its scope to Request
153
- const token = getInjectableToken(classType)
154
- this.container
155
- .getRegistry()
156
- .updateScope(token, InjectableScope.Request)
157
- return { success: false, instance: null }
158
- }
159
- }),
160
- )
161
-
162
- const allCached = results.every((r) => r.success)
163
- const cachedInstances = allCached
164
- ? results.map((r) => r.instance as T)
165
- : null
166
-
167
- return {
168
- cached: allCached,
169
- instances: cachedInstances,
170
- classTypes,
171
- resolve: (scoped: ScopedContainer) =>
172
- Promise.all(
173
- classTypes.map((classType) => scoped.get(classType) as Promise<T>),
174
- ),
175
- }
176
- }
177
- }
@@ -1,255 +0,0 @@
1
- import type { ClassType, ClassTypeWithInstance } from '@navios/di'
2
-
3
- import { Container, getInjectableToken, inject, Injectable } from '@navios/di'
4
-
5
- import type { NaviosModule } from '../interfaces/index.mjs'
6
- import type { ModuleMetadata } from '../metadata/index.mjs'
7
-
8
- import { Logger } from '../logger/index.mjs'
9
- import { extractModuleMetadata } from '../metadata/index.mjs'
10
-
11
- /**
12
- * Extension definition for dynamically adding to the module tree.
13
- * Used by plugins to inject controllers or entire modules.
14
- */
15
- export interface ModuleExtension {
16
- /**
17
- * Module class to add. If provided, the module and all its
18
- * controllers/imports will be processed.
19
- */
20
- module?: ClassTypeWithInstance<NaviosModule>
21
-
22
- /**
23
- * Controllers to add directly without a wrapper module.
24
- * Will be registered under a synthetic module named after the plugin.
25
- */
26
- controllers?: ClassType[]
27
-
28
- /**
29
- * Name for the synthetic module when using controllers directly.
30
- * Required if `controllers` is provided without `module`.
31
- */
32
- moduleName?: string
33
- }
34
-
35
- @Injectable()
36
- export class ModuleLoaderService {
37
- private logger = inject(Logger, {
38
- context: ModuleLoaderService.name,
39
- })
40
- protected container = inject(Container)
41
- private modulesMetadata: Map<string, ModuleMetadata> = new Map()
42
- private loadedModules: Map<string, any> = new Map()
43
- private initialized = false
44
-
45
- async loadModules(appModule: ClassTypeWithInstance<NaviosModule>) {
46
- if (this.initialized) {
47
- return
48
- }
49
- await this.traverseModules(appModule)
50
- this.initialized = true
51
- }
52
-
53
- /**
54
- * Extends the module tree with additional modules or controllers.
55
- *
56
- * This method is designed to be called by plugins during registration,
57
- * which happens after initial module loading but before route registration.
58
- *
59
- * @param extensions - Array of module extensions to add
60
- * @throws Error if not initialized (loadModules must be called first)
61
- *
62
- * @example
63
- * ```typescript
64
- * // In plugin registration
65
- * const moduleLoader = await context.container.get(ModuleLoaderService)
66
- * await moduleLoader.extendModules([{
67
- * controllers: [OpenApiJsonController, OpenApiYamlController],
68
- * moduleName: 'OpenApiBunModule',
69
- * }])
70
- * ```
71
- */
72
- async extendModules(extensions: ModuleExtension[]): Promise<void> {
73
- if (!this.initialized) {
74
- throw new Error(
75
- 'ModuleLoaderService must be initialized before extending. Call loadModules() first.',
76
- )
77
- }
78
-
79
- for (const extension of extensions) {
80
- if (extension.module) {
81
- await this.traverseModules(extension.module)
82
- continue
83
- }
84
-
85
- if (!extension.controllers) {
86
- continue
87
- }
88
-
89
- if (!extension.moduleName) {
90
- throw new Error(
91
- 'moduleName is required when providing controllers without a module',
92
- )
93
- }
94
-
95
- await this.registerControllers(extension.controllers, extension.moduleName)
96
- }
97
- }
98
-
99
- /**
100
- * Registers controllers under a synthetic module.
101
- * Used when plugins want to add controllers without a full module class.
102
- */
103
- private async registerControllers(
104
- controllers: ClassType[],
105
- moduleName: string,
106
- ): Promise<void> {
107
- if (this.modulesMetadata.has(moduleName)) {
108
- // Merge controllers into existing module
109
- const existing = this.modulesMetadata.get(moduleName)!
110
- for (const controller of controllers) {
111
- existing.controllers.add(controller)
112
- }
113
- this.logger.debug(
114
- `Extended module ${moduleName} with ${controllers.length} controllers`,
115
- )
116
- } else {
117
- // Create new synthetic module metadata
118
- const metadata: ModuleMetadata = {
119
- name: moduleName,
120
- controllers: new Set(controllers),
121
- imports: new Set(),
122
- guards: new Set(),
123
- overrides: new Set(),
124
- customAttributes: new Map(),
125
- customEntries: new Map(),
126
- }
127
- this.modulesMetadata.set(moduleName, metadata)
128
-
129
- this.logger.debug(
130
- `Created module ${moduleName} with ${controllers.length} controllers`,
131
- )
132
- }
133
- }
134
-
135
- private async traverseModules(
136
- module: ClassTypeWithInstance<NaviosModule>,
137
- parentMetadata?: ModuleMetadata,
138
- ) {
139
- const metadata = extractModuleMetadata(module)
140
- if (parentMetadata) {
141
- this.mergeMetadata(metadata, parentMetadata)
142
- }
143
- const moduleToken = getInjectableToken(module)
144
- const moduleName = moduleToken.id
145
- if (this.modulesMetadata.has(moduleName)) {
146
- return
147
- }
148
- try {
149
- this.modulesMetadata.set(moduleName, metadata)
150
- const imports = metadata.imports ?? new Set()
151
- const loadingPromises = Array.from(imports).map(async (importedModule) =>
152
- this.traverseModules(importedModule, metadata),
153
- )
154
- await Promise.all(loadingPromises)
155
- this.validateOverrides(metadata, moduleName)
156
- const instance = await this.container.get(module)
157
- if (instance.onModuleInit) {
158
- await instance.onModuleInit()
159
- }
160
- this.logger.debug(`Module ${moduleName} loaded`)
161
- this.loadedModules.set(moduleName, instance)
162
- } catch (error) {
163
- this.logger.error(`Error loading module ${moduleName}`, error)
164
- throw error
165
- }
166
- }
167
-
168
- private validateOverrides(
169
- metadata: ModuleMetadata,
170
- moduleName: string,
171
- ): void {
172
- if (!metadata.overrides || metadata.overrides.size === 0) {
173
- return
174
- }
175
-
176
- const registry = this.container.getRegistry()
177
-
178
- for (const overrideClass of metadata.overrides) {
179
- try {
180
- // Get the token for the override class
181
- const overrideToken = getInjectableToken(overrideClass)
182
-
183
- // Get all registrations for this token (sorted by priority, highest first)
184
- const allRegistrations = registry.getAll(overrideToken)
185
-
186
- if (allRegistrations.length === 0) {
187
- this.logger.warn(
188
- `[Navios] Override ${overrideClass.name} in module ${moduleName} is not registered. ` +
189
- `Make sure it has @Injectable decorator.`,
190
- )
191
- continue
192
- }
193
-
194
- // Check if the override class has the highest priority
195
- const highestPriorityRegistration = allRegistrations[0]
196
- if (highestPriorityRegistration.target !== overrideClass) {
197
- const overrideRegistration = allRegistrations.find(
198
- (r) => r.target === overrideClass,
199
- )
200
-
201
- if (!overrideRegistration) {
202
- this.logger.warn(
203
- `[Navios] Override ${overrideClass.name} in module ${moduleName} is registered ` +
204
- `but not found in registry for token ${overrideToken.toString()}.`,
205
- )
206
- } else {
207
- this.logger.warn(
208
- `[Navios] Override ${overrideClass.name} in module ${moduleName} is not active. ` +
209
- `Current active service: ${highestPriorityRegistration.target.name} ` +
210
- `(priority: ${highestPriorityRegistration.priority}). ` +
211
- `Override priority: ${overrideRegistration.priority}. ` +
212
- `Override needs higher priority to take effect.`,
213
- )
214
- }
215
- } else {
216
- this.logger.debug(
217
- `[Navios] Override ${overrideClass.name} in module ${moduleName} is active ` +
218
- `(priority: ${highestPriorityRegistration.priority})`,
219
- )
220
- }
221
- } catch (error) {
222
- this.logger.warn(
223
- `[Navios] Failed to validate override ${overrideClass.name} in module ${moduleName}: ${error}`,
224
- )
225
- }
226
- }
227
- }
228
-
229
- private mergeMetadata(
230
- metadata: ModuleMetadata,
231
- parentMetadata: ModuleMetadata,
232
- ): void {
233
- if (parentMetadata.guards) {
234
- for (const guard of parentMetadata.guards) {
235
- metadata.guards.add(guard)
236
- }
237
- }
238
- if (parentMetadata.customAttributes) {
239
- for (const [key, value] of parentMetadata.customAttributes) {
240
- if (metadata.customAttributes.has(key)) {
241
- continue
242
- }
243
- metadata.customAttributes.set(key, value)
244
- }
245
- }
246
- }
247
- getAllModules(): Map<string, ModuleMetadata> {
248
- return this.modulesMetadata
249
- }
250
- dispose() {
251
- this.modulesMetadata.clear()
252
- this.loadedModules.clear()
253
- this.initialized = false
254
- }
255
- }
@@ -1 +0,0 @@
1
- export * from './request-id.store.mjs'
@@ -1,85 +0,0 @@
1
- import { AsyncLocalStorage } from 'node:async_hooks'
2
-
3
- let requestCounter = 0
4
-
5
- /**
6
- * Generates a simple incremental request ID.
7
- * Much faster than crypto.randomUUID() and sufficient for request tracking.
8
- *
9
- * @returns A unique request ID string (e.g., "req-1", "req-2", ...)
10
- */
11
- export function generateRequestId(): string {
12
- return `req-${++requestCounter}`
13
- }
14
-
15
- /**
16
- * AsyncLocalStorage store for the current request ID.
17
- *
18
- * This allows logging and other services to access the current request ID
19
- * without explicitly passing it through the call stack.
20
- *
21
- * @example
22
- * ```typescript
23
- * import { requestIdStore, runWithRequestId, getRequestId } from '@navios/core'
24
- *
25
- * // Run code with a request ID in context
26
- * runWithRequestId('req-123', () => {
27
- * // Inside this callback, getRequestId() returns 'req-123'
28
- * logger.log('Processing request') // Will include request ID if logger is configured
29
- * })
30
- *
31
- * // Get current request ID (returns undefined if not in a request context)
32
- * const currentId = getRequestId()
33
- * ```
34
- */
35
- let requestIdStore: AsyncLocalStorage<string> | null = null
36
-
37
- function getRequestIdStore(): AsyncLocalStorage<string> {
38
- if (!requestIdStore) {
39
- requestIdStore = new AsyncLocalStorage<string>()
40
- }
41
- return requestIdStore!
42
- }
43
- /**
44
- * Whether request ID propagation is enabled.
45
- * When disabled, runWithRequestId is a pass-through for better performance.
46
- */
47
- let requestIdEnabled = false
48
-
49
- /**
50
- * Enables or disables request ID propagation.
51
- * Called by NaviosFactory based on the enableRequestId option.
52
- *
53
- * @param enabled - Whether to enable request ID propagation
54
- */
55
- export function setRequestIdEnabled(enabled: boolean): void {
56
- requestIdEnabled = enabled
57
- }
58
-
59
- /**
60
- * Runs a function with a request ID in the async local storage context.
61
- * If request ID propagation is disabled, the function is called directly
62
- * without AsyncLocalStorage overhead.
63
- *
64
- * @param requestId - The request ID to set for this context
65
- * @param fn - The function to run within this context
66
- * @returns The return value of the function
67
- */
68
- export function runWithRequestId<R>(requestId: string, fn: () => R): R {
69
- if (!requestIdEnabled) {
70
- return fn()
71
- }
72
- return getRequestIdStore().run(requestId, fn)
73
- }
74
-
75
- /**
76
- * Gets the current request ID from the async local storage context.
77
- *
78
- * @returns The current request ID, or undefined if not in a request context
79
- */
80
- export function getRequestId(): string | undefined {
81
- if (!requestIdEnabled) {
82
- return undefined
83
- }
84
- return getRequestIdStore().getStore()
85
- }
@@ -1,3 +0,0 @@
1
- export * from '@navios/di/testing'
2
- export * from './testing-module.mjs'
3
- export * from './unit-testing-module.mjs'