@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,76 +0,0 @@
1
- import { Injectable } from '@navios/di'
2
-
3
- import type { ErrorResponder } from '../interfaces/error-responder.interface.mjs'
4
- import type { ErrorResponse } from '../interfaces/error-response.interface.mjs'
5
- import { NotFoundResponderToken } from '../tokens/responder.tokens.mjs'
6
-
7
- /**
8
- * Default responder for not found errors (HTTP 404).
9
- *
10
- * Converts errors to RFC 7807 Problem Details format.
11
- * Registered with low priority (-10) so it can be easily overridden.
12
- *
13
- * @example Override with custom implementation:
14
- * ```typescript
15
- * @Injectable({
16
- * token: NotFoundResponderToken,
17
- * priority: 0,
18
- * })
19
- * export class CustomNotFoundResponder implements ErrorResponder {
20
- * getResponse(error: unknown, description?: string): ErrorResponse {
21
- * return {
22
- * statusCode: 404,
23
- * payload: {
24
- * type: 'https://api.myapp.com/errors/not-found',
25
- * title: 'Resource Not Found',
26
- * status: 404,
27
- * detail: description ?? 'The requested resource was not found',
28
- * },
29
- * headers: { 'Content-Type': 'application/problem+json' },
30
- * }
31
- * }
32
- * }
33
- * ```
34
- */
35
- @Injectable({
36
- token: NotFoundResponderToken,
37
- priority: -10,
38
- })
39
- export class NotFoundResponderService implements ErrorResponder {
40
- getResponse(error: unknown, description?: string): ErrorResponse {
41
- // Explicit description takes priority
42
- if (description) {
43
- return this.createResponse(description)
44
- }
45
-
46
- // Try to extract detail from error with a response property (like NotFoundException)
47
- if (
48
- error &&
49
- typeof error === 'object' &&
50
- 'response' in error &&
51
- error.response
52
- ) {
53
- if (typeof error.response === 'string') {
54
- return this.createResponse(error.response)
55
- }
56
- }
57
-
58
- // Default message
59
- return this.createResponse('The requested resource was not found')
60
- }
61
-
62
- private createResponse(detail: string): ErrorResponse {
63
- return {
64
- statusCode: 404,
65
- payload: {
66
- type: 'about:blank',
67
- title: 'Not Found',
68
- status: 404,
69
- detail,
70
- },
71
- headers: {
72
- 'Content-Type': 'application/problem+json',
73
- },
74
- }
75
- }
76
- }
@@ -1,78 +0,0 @@
1
- import { Injectable } from '@navios/di'
2
- import { treeifyError, ZodError } from 'zod/v4'
3
-
4
- import type { ErrorResponder } from '../interfaces/error-responder.interface.mjs'
5
- import type { ErrorResponse } from '../interfaces/error-response.interface.mjs'
6
- import { ValidationErrorResponderToken } from '../tokens/responder.tokens.mjs'
7
-
8
- /**
9
- * Default responder for validation errors (HTTP 400).
10
- *
11
- * Converts Zod validation errors to RFC 7807 Problem Details format.
12
- * Includes the structured validation errors from treeifyError.
13
- * Registered with low priority (-10) so it can be easily overridden.
14
- *
15
- * @example Override with custom implementation:
16
- * ```typescript
17
- * @Injectable({
18
- * token: ValidationErrorResponderToken,
19
- * priority: 0,
20
- * })
21
- * export class CustomValidationResponder implements ErrorResponder {
22
- * getResponse(error: unknown, description?: string): ErrorResponse {
23
- * const zodError = error as ZodError
24
- * return {
25
- * statusCode: 422, // Use 422 instead of 400
26
- * payload: {
27
- * type: 'https://api.myapp.com/errors/validation',
28
- * title: 'Unprocessable Entity',
29
- * status: 422,
30
- * detail: description ?? 'Validation failed',
31
- * issues: zodError.issues,
32
- * },
33
- * headers: { 'Content-Type': 'application/problem+json' },
34
- * }
35
- * }
36
- * }
37
- * ```
38
- */
39
- @Injectable({
40
- token: ValidationErrorResponderToken,
41
- priority: -10,
42
- })
43
- export class ValidationErrorResponderService implements ErrorResponder {
44
- getResponse(error: unknown, description?: string): ErrorResponse {
45
- // Handle ZodError specifically
46
- if (error instanceof ZodError) {
47
- return {
48
- statusCode: 400,
49
- payload: {
50
- type: 'about:blank',
51
- title: 'Validation Error',
52
- status: 400,
53
- detail: description ?? 'Request validation failed',
54
- errors: treeifyError(error),
55
- },
56
- headers: {
57
- 'Content-Type': 'application/problem+json',
58
- },
59
- }
60
- }
61
-
62
- // Fallback for non-Zod validation errors
63
- return {
64
- statusCode: 400,
65
- payload: {
66
- type: 'about:blank',
67
- title: 'Validation Error',
68
- status: 400,
69
- detail:
70
- description ??
71
- (error instanceof Error ? error.message : 'Validation failed'),
72
- },
73
- headers: {
74
- 'Content-Type': 'application/problem+json',
75
- },
76
- }
77
- }
78
- }
@@ -1 +0,0 @@
1
- export * from './responder.tokens.mjs'
@@ -1,84 +0,0 @@
1
- import { InjectionToken } from '@navios/di'
2
-
3
- import type { ErrorResponder } from '../interfaces/error-responder.interface.mjs'
4
-
5
- /**
6
- * Injection token for the Internal Server Error responder.
7
- * Default implementation returns HTTP 500 with RFC 7807 Problem Details.
8
- *
9
- * @example Override with custom implementation:
10
- * ```typescript
11
- * @Injectable({
12
- * token: InternalServerErrorResponderToken,
13
- * priority: 0, // Higher than default -10
14
- * })
15
- * export class CustomInternalErrorResponder implements ErrorResponder {
16
- * getResponse(error: unknown, description?: string): ErrorResponse {
17
- * // Custom implementation
18
- * }
19
- * }
20
- * ```
21
- */
22
- export const InternalServerErrorResponderToken =
23
- InjectionToken.create<ErrorResponder>('InternalServerErrorResponder')
24
-
25
- /**
26
- * Injection token for the Not Found responder.
27
- * Default implementation returns HTTP 404 with RFC 7807 Problem Details.
28
- *
29
- * @example Override with custom implementation:
30
- * ```typescript
31
- * @Injectable({
32
- * token: NotFoundResponderToken,
33
- * priority: 0, // Higher than default -10
34
- * })
35
- * export class CustomNotFoundResponder implements ErrorResponder {
36
- * getResponse(error: unknown, description?: string): ErrorResponse {
37
- * // Custom implementation
38
- * }
39
- * }
40
- * ```
41
- */
42
- export const NotFoundResponderToken =
43
- InjectionToken.create<ErrorResponder>('NotFoundResponder')
44
-
45
- /**
46
- * Injection token for the Validation Error responder.
47
- * Default implementation returns HTTP 400 with RFC 7807 Problem Details
48
- * and includes validation errors from ZodError.
49
- *
50
- * @example Override with custom implementation:
51
- * ```typescript
52
- * @Injectable({
53
- * token: ValidationErrorResponderToken,
54
- * priority: 0, // Higher than default -10
55
- * })
56
- * export class CustomValidationResponder implements ErrorResponder {
57
- * getResponse(error: unknown, description?: string): ErrorResponse {
58
- * // Custom implementation
59
- * }
60
- * }
61
- * ```
62
- */
63
- export const ValidationErrorResponderToken =
64
- InjectionToken.create<ErrorResponder>('ValidationErrorResponder')
65
-
66
- /**
67
- * Injection token for the Forbidden responder.
68
- * Default implementation returns HTTP 403 with RFC 7807 Problem Details.
69
- *
70
- * @example Override with custom implementation:
71
- * ```typescript
72
- * @Injectable({
73
- * token: ForbiddenResponderToken,
74
- * priority: 0, // Higher than default -10
75
- * })
76
- * export class CustomForbiddenResponder implements ErrorResponder {
77
- * getResponse(error: unknown, description?: string): ErrorResponse {
78
- * // Custom implementation
79
- * }
80
- * }
81
- * ```
82
- */
83
- export const ForbiddenResponderToken =
84
- InjectionToken.create<ErrorResponder>('ForbiddenResponder')
@@ -1,366 +0,0 @@
1
- import type { ClassType, ScopedContainer } from '@navios/di'
2
- import type { BaseEndpointOptions } from '@navios/builder'
3
-
4
- import { inject, optional } from '@navios/di'
5
-
6
- import type { HandlerMetadata } from '../metadata/index.mjs'
7
- import type {
8
- ArgumentGetterFn,
9
- FormatArgumentsFn as InterfaceFormatArgumentsFn,
10
- HttpHeader,
11
- } from '../interfaces/index.mjs'
12
- import type { NaviosApplicationOptions } from '../navios.application.mjs'
13
-
14
- import { NaviosOptionsToken } from '../tokens/index.mjs'
15
- import {
16
- InstanceResolverService,
17
- type InstanceResolution,
18
- } from './instance-resolver.service.mjs'
19
-
20
- // ============================================================================
21
- // Types
22
- // ============================================================================
23
-
24
- /**
25
- * Function type for argument getters that extract data from requests.
26
- * Re-exported from interface for convenience in adapter implementations.
27
- */
28
- export type ArgumentGetter<TRequest> = ArgumentGetterFn<TRequest>
29
-
30
- /**
31
- * Internal alias for FormatArgumentsFn from interface.
32
- * Not re-exported to avoid duplicate exports - use FormatArgumentsFn from interfaces instead.
33
- */
34
- type FormatArgumentsFn<TRequest> = InterfaceFormatArgumentsFn<TRequest>
35
-
36
- /**
37
- * Static handler - can be called without a scoped container.
38
- */
39
- export type AbstractStaticHandler<TRequest, TReply = void> = {
40
- isStatic: true
41
- handler: (request: TRequest, reply: TReply) => Promise<any>
42
- }
43
-
44
- /**
45
- * Dynamic handler - requires a scoped container for resolution.
46
- */
47
- export type AbstractDynamicHandler<TRequest, TReply = void> = {
48
- isStatic: false
49
- handler: (
50
- scoped: ScopedContainer,
51
- request: TRequest,
52
- reply: TReply,
53
- ) => Promise<any>
54
- }
55
-
56
- /**
57
- * Handler result - either static or dynamic.
58
- */
59
- export type AbstractHandlerResult<TRequest, TReply = void> =
60
- | AbstractStaticHandler<TRequest, TReply>
61
- | AbstractDynamicHandler<TRequest, TReply>
62
-
63
- /**
64
- * Context passed to handler creation methods.
65
- */
66
- export interface HandlerContext<
67
- TConfig extends BaseEndpointOptions = BaseEndpointOptions,
68
- > {
69
- methodName: string
70
- statusCode: number
71
- headers: Partial<Record<HttpHeader, number | string | string[] | undefined>>
72
- handlerMetadata: HandlerMetadata<TConfig>
73
- hasArguments: boolean
74
- }
75
-
76
- // ============================================================================
77
- // Default Options
78
- // ============================================================================
79
-
80
- const defaultOptions: NaviosApplicationOptions = {
81
- adapter: [],
82
- validateResponses: true,
83
- enableRequestId: false,
84
- }
85
-
86
- // ============================================================================
87
- // Abstract Base Class
88
- // ============================================================================
89
-
90
- /**
91
- * Abstract base class for HTTP handler adapter services.
92
- *
93
- * Provides shared logic for:
94
- * - Controller resolution (singleton vs request-scoped)
95
- * - Argument formatting (sync/async detection)
96
- * - Handler generation with static/dynamic branching
97
- * - Standardized error handling
98
- *
99
- * Adapters implement abstract methods for framework-specific behavior:
100
- * - Request parsing (query, body, URL params)
101
- * - Response creation
102
- * - Schema provision
103
- *
104
- * Supports all adapter types:
105
- * - Endpoint adapters: JSON request/response with validation
106
- * - Stream adapters: Streaming responses with extra context
107
- * - Multipart adapters: Form data parsing (extends endpoint)
108
- *
109
- * @typeParam TRequest - Framework request type (BunRequest, FastifyRequest)
110
- * @typeParam TReply - Framework reply type (void for Bun, FastifyReply)
111
- * @typeParam TConfig - Endpoint configuration type
112
- */
113
- export abstract class AbstractHandlerAdapterService<
114
- TRequest,
115
- TReply = void,
116
- TConfig extends BaseEndpointOptions = BaseEndpointOptions,
117
- > {
118
- protected instanceResolver = inject(InstanceResolverService)
119
- protected options = optional(NaviosOptionsToken) ?? defaultOptions
120
-
121
- // ==========================================================================
122
- // Abstract Methods - Must be implemented by adapters
123
- // ==========================================================================
124
-
125
- /**
126
- * Creates argument getter functions for extracting data from requests.
127
- *
128
- * Each getter populates a target object with data from the request
129
- * (query params, body, URL params, etc.).
130
- *
131
- * Implementation varies by adapter type:
132
- * - Endpoint: JSON body parsing with schema validation
133
- * - Stream: Same as endpoint (body + query + url params)
134
- * - Multipart: FormData/multipart stream parsing
135
- *
136
- * @param handlerMetadata - Handler metadata with schemas and configuration
137
- * @returns Array of getter functions
138
- */
139
- protected abstract createArgumentGetters(
140
- handlerMetadata: HandlerMetadata<TConfig>,
141
- ): ArgumentGetter<TRequest>[]
142
-
143
- /**
144
- * Creates a static handler for singleton controllers.
145
- *
146
- * Implementation varies by adapter type:
147
- * - Endpoint: Invoke method(args), serialize response as JSON
148
- * - Stream: Invoke method(args, streamContext), return Response/use reply
149
- *
150
- * @param boundMethod - Pre-bound controller method
151
- * @param formatArguments - Function to format request arguments
152
- * @param context - Handler context with metadata
153
- * @returns Static handler result
154
- */
155
- protected abstract createStaticHandler(
156
- boundMethod: (...args: any[]) => Promise<any>,
157
- formatArguments: FormatArgumentsFn<TRequest>,
158
- context: HandlerContext<TConfig>,
159
- ): AbstractStaticHandler<TRequest, TReply>
160
-
161
- /**
162
- * Creates a dynamic handler for request-scoped controllers.
163
- *
164
- * Implementation varies by adapter type:
165
- * - Endpoint: Resolve controller per-request, invoke method(args)
166
- * - Stream: Resolve controller per-request, invoke method(args, streamContext)
167
- *
168
- * @param resolution - Instance resolution with resolve function
169
- * @param formatArguments - Function to format request arguments
170
- * @param context - Handler context with metadata
171
- * @returns Dynamic handler result
172
- */
173
- protected abstract createDynamicHandler(
174
- resolution: InstanceResolution,
175
- formatArguments: FormatArgumentsFn<TRequest>,
176
- context: HandlerContext<TConfig>,
177
- ): AbstractDynamicHandler<TRequest, TReply>
178
-
179
- // ==========================================================================
180
- // Public Interface Methods
181
- // ==========================================================================
182
-
183
- /**
184
- * Prepares argument getters for parsing request data.
185
- *
186
- * Public alias for createArgumentGetters to satisfy interface contracts.
187
- * Subclasses should override createArgumentGetters instead.
188
- *
189
- * @param handlerMetadata - Handler metadata with schemas and configuration
190
- * @returns Array of getter functions
191
- */
192
- prepareArguments(
193
- handlerMetadata: HandlerMetadata<TConfig>,
194
- ): ArgumentGetter<TRequest>[] {
195
- return this.createArgumentGetters(handlerMetadata)
196
- }
197
-
198
- /**
199
- * Checks if the handler has any validation schemas defined.
200
- *
201
- * Override in subclasses to add additional schema checks
202
- * (e.g., response schema validation for endpoint adapters).
203
- *
204
- * @param handlerMetadata - Handler metadata with configuration
205
- * @returns true if handler has schemas
206
- */
207
- hasSchema(handlerMetadata: HandlerMetadata<TConfig>): boolean {
208
- const config = handlerMetadata.config
209
- return !!config.requestSchema || !!config.querySchema
210
- }
211
-
212
- /**
213
- * Provides schema information for the framework's validation system.
214
- *
215
- * Override in subclasses for frameworks that support schema registration
216
- * (e.g., Fastify). Default returns empty object (suitable for Bun).
217
- *
218
- * @param handlerMetadata - Handler metadata with configuration
219
- * @returns Schema object for framework registration
220
- */
221
- provideSchema(
222
- _handlerMetadata: HandlerMetadata<TConfig>,
223
- ): Record<string, any> {
224
- return {}
225
- }
226
-
227
- /**
228
- * Creates a request handler function for the endpoint.
229
- *
230
- * This method orchestrates the entire handler creation:
231
- * 1. Prepares argument getters for request parsing
232
- * 2. Builds optimized formatArguments function (sync/async)
233
- * 3. Resolves the controller (singleton vs request-scoped)
234
- * 4. Creates appropriate handler (static or dynamic)
235
- *
236
- * @param controller - Controller class containing the handler method
237
- * @param handlerMetadata - Handler metadata with configuration
238
- * @returns Handler result (static or dynamic)
239
- */
240
- async provideHandler(
241
- controller: ClassType,
242
- handlerMetadata: HandlerMetadata<TConfig>,
243
- ): Promise<AbstractHandlerResult<TRequest, TReply>> {
244
- // Prepare argument getters
245
- const getters = this.createArgumentGetters(handlerMetadata)
246
- const formatArguments = this.buildFormatArguments(getters)
247
- const hasArguments = getters.length > 0
248
-
249
- // Build handler context
250
- const context: HandlerContext<TConfig> = {
251
- methodName: handlerMetadata.classMethod,
252
- statusCode: handlerMetadata.successStatusCode,
253
- headers: handlerMetadata.headers,
254
- handlerMetadata,
255
- hasArguments,
256
- }
257
-
258
- // Resolve controller with automatic scope detection
259
- const resolution = await this.instanceResolver.resolve(controller)
260
-
261
- // Create appropriate handler based on resolution
262
- if (resolution.cached) {
263
- const cachedController = resolution.instance as any
264
- const boundMethod =
265
- cachedController[context.methodName].bind(cachedController)
266
- return this.createStaticHandler(boundMethod, formatArguments, context)
267
- }
268
-
269
- return this.createDynamicHandler(resolution, formatArguments, context)
270
- }
271
-
272
- // ==========================================================================
273
- // Public Utilities
274
- // ==========================================================================
275
-
276
- /**
277
- * Builds a formatArguments function from argument getters.
278
- *
279
- * Automatically detects sync vs async getters and optimizes accordingly:
280
- * - If all getters are sync: returns sync function (no Promise overhead)
281
- * - If any getter is async: returns async function with Promise.all
282
- * - If no getters: returns frozen empty object (zero allocation)
283
- *
284
- * This method is public to allow composition-based adapters (like XML adapter)
285
- * to reuse the optimized formatArguments logic without inheritance.
286
- *
287
- * @param getters - Array of argument getter functions
288
- * @returns Function to format arguments from request
289
- */
290
- buildFormatArguments(
291
- getters: ArgumentGetter<TRequest>[],
292
- ): FormatArgumentsFn<TRequest> {
293
- if (getters.length === 0) {
294
- const emptyArgs = Object.freeze({})
295
- return () => emptyArgs
296
- }
297
-
298
- // Detect if any getter is async at registration time
299
- const hasAsyncGetters = getters.some(
300
- (g) => g.constructor.name === 'AsyncFunction',
301
- )
302
-
303
- if (hasAsyncGetters) {
304
- return async (request: TRequest) => {
305
- const argument: Record<string, any> = {}
306
- const promises: Promise<void>[] = []
307
- for (const getter of getters) {
308
- const res = getter(argument, request)
309
- if (res instanceof Promise) {
310
- promises.push(res)
311
- }
312
- }
313
- await Promise.all(promises)
314
- return argument
315
- }
316
- }
317
-
318
- return (request: TRequest) => {
319
- const argument: Record<string, any> = {}
320
- for (const getter of getters) {
321
- getter(argument, request)
322
- }
323
- return argument
324
- }
325
- }
326
-
327
- // ==========================================================================
328
- // Protected Utilities
329
- // ==========================================================================
330
-
331
- /**
332
- * Checks if the URL pattern contains URL parameters.
333
- *
334
- * @param config - Endpoint configuration
335
- * @returns true if URL contains '$' parameter markers
336
- */
337
- protected hasUrlParams(config: TConfig): boolean {
338
- return config.url.includes('$')
339
- }
340
-
341
- /**
342
- * Wraps handler execution with standardized error handling.
343
- *
344
- * Re-throws HttpExceptions as-is for framework error handlers.
345
- * Other errors are re-thrown for global error handling.
346
- *
347
- * @param fn - Handler function to wrap
348
- * @returns Wrapped function with error handling
349
- */
350
- protected wrapWithErrorHandling<T extends (...args: any[]) => Promise<any>>(
351
- fn: T,
352
- ): T {
353
- return (async (...args: any[]) => {
354
- try {
355
- return await fn(...args)
356
- } catch (error) {
357
- // Re-throw HttpExceptions as-is for framework error handlers
358
- if (error && typeof error === 'object' && 'statusCode' in error) {
359
- throw error
360
- }
361
- // Re-throw unexpected errors for global error handling
362
- throw error
363
- }
364
- }) as T
365
- }
366
- }