@navios/core 1.1.0 → 2.0.0-alpha.1

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 (237) hide show
  1. package/CHANGELOG.md +85 -13
  2. package/README.md +69 -220
  3. package/lib/async-context-BAdt7bno.d.mts +239 -0
  4. package/lib/async-context-BAdt7bno.d.mts.map +1 -0
  5. package/lib/async-context-RsWmy2Hi.d.cts +239 -0
  6. package/lib/async-context-RsWmy2Hi.d.cts.map +1 -0
  7. package/lib/attribute-factory-BW1kgBqf.d.mts +70 -0
  8. package/lib/attribute-factory-BW1kgBqf.d.mts.map +1 -0
  9. package/lib/attribute-factory-DqN4x5XM.d.cts +70 -0
  10. package/lib/attribute-factory-DqN4x5XM.d.cts.map +1 -0
  11. package/lib/attribute-value-BNiJjxl1.mjs +225 -0
  12. package/lib/attribute-value-BNiJjxl1.mjs.map +1 -0
  13. package/lib/attribute-value-Cux5HhOL.cjs +314 -0
  14. package/lib/attribute-value-Cux5HhOL.cjs.map +1 -0
  15. package/lib/basic-execution-context-5uq2DvEA.cjs +318 -0
  16. package/lib/basic-execution-context-5uq2DvEA.cjs.map +1 -0
  17. package/lib/basic-execution-context-u1VktGoM.mjs +277 -0
  18. package/lib/basic-execution-context-u1VktGoM.mjs.map +1 -0
  19. package/lib/execution-context-BVSmLkYp.d.cts +71 -0
  20. package/lib/execution-context-BVSmLkYp.d.cts.map +1 -0
  21. package/lib/execution-context-C5F9rojO.d.mts +71 -0
  22. package/lib/execution-context-C5F9rojO.d.mts.map +1 -0
  23. package/lib/execution-context-token--cKS4cJv.cjs +270 -0
  24. package/lib/execution-context-token--cKS4cJv.cjs.map +1 -0
  25. package/lib/execution-context-token-Cb3M3Ao0.mjs +223 -0
  26. package/lib/execution-context-token-Cb3M3Ao0.mjs.map +1 -0
  27. package/lib/index.cjs +1672 -4426
  28. package/lib/index.cjs.map +1 -1
  29. package/lib/index.d.cts +842 -3
  30. package/lib/index.d.cts.map +1 -0
  31. package/lib/index.d.mts +842 -3
  32. package/lib/index.d.mts.map +1 -0
  33. package/lib/index.mjs +1559 -4221
  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-Bz83ZnJ5.cjs +173 -0
  44. package/lib/module-Bz83ZnJ5.cjs.map +1 -0
  45. package/lib/module-options-CSqQUSTm.d.mts +51 -0
  46. package/lib/module-options-CSqQUSTm.d.mts.map +1 -0
  47. package/lib/module-options-DSRBri4J.d.cts +51 -0
  48. package/lib/module-options-DSRBri4J.d.cts.map +1 -0
  49. package/lib/module-zPXwR2qp.mjs +138 -0
  50. package/lib/module-zPXwR2qp.mjs.map +1 -0
  51. package/lib/settled-within-B6gpu2XW.cjs +32 -0
  52. package/lib/settled-within-B6gpu2XW.cjs.map +1 -0
  53. package/lib/settled-within-Bc2pj8WB.mjs +21 -0
  54. package/lib/settled-within-Bc2pj8WB.mjs.map +1 -0
  55. package/lib/testing/index.cjs +74 -414
  56. package/lib/testing/index.cjs.map +1 -1
  57. package/lib/testing/index.d.cts +25 -385
  58. package/lib/testing/index.d.cts.map +1 -1
  59. package/lib/testing/index.d.mts +24 -385
  60. package/lib/testing/index.d.mts.map +1 -1
  61. package/lib/testing/index.mjs +72 -408
  62. package/lib/testing/index.mjs.map +1 -1
  63. package/lib/transport.cjs +36 -0
  64. package/lib/transport.d.cts +254 -0
  65. package/lib/transport.d.cts.map +1 -0
  66. package/lib/transport.d.mts +254 -0
  67. package/lib/transport.d.mts.map +1 -0
  68. package/lib/transport.mjs +6 -0
  69. package/package.json +37 -17
  70. package/docs/README.md +0 -316
  71. package/docs/adapters.md +0 -308
  72. package/docs/application-setup.md +0 -524
  73. package/docs/attributes.md +0 -689
  74. package/docs/controllers.md +0 -373
  75. package/docs/endpoints.md +0 -444
  76. package/docs/exceptions.md +0 -352
  77. package/docs/guards.md +0 -550
  78. package/docs/legacy-compat.md +0 -356
  79. package/docs/modules.md +0 -377
  80. package/docs/quick-start.md +0 -290
  81. package/docs/services.md +0 -427
  82. package/docs/testing.md +0 -827
  83. package/lib/index-3LcTrbxz.d.mts +0 -3804
  84. package/lib/index-3LcTrbxz.d.mts.map +0 -1
  85. package/lib/index-B14SekVb.d.cts +0 -3804
  86. package/lib/index-B14SekVb.d.cts.map +0 -1
  87. package/lib/navios.factory-CUrO_p6K.cjs +0 -4538
  88. package/lib/navios.factory-CUrO_p6K.cjs.map +0 -1
  89. package/lib/navios.factory-DjUOOVVL.mjs +0 -4151
  90. package/lib/navios.factory-DjUOOVVL.mjs.map +0 -1
  91. package/lib/tokens-BEuBMGGX.cjs +0 -193
  92. package/lib/tokens-BEuBMGGX.cjs.map +0 -1
  93. package/lib/tokens-COyNGV1I.mjs +0 -97
  94. package/lib/tokens-COyNGV1I.mjs.map +0 -1
  95. package/lib/use-guards.decorator-DLmRl2CV.mjs +0 -336
  96. package/lib/use-guards.decorator-DLmRl2CV.mjs.map +0 -1
  97. package/lib/use-guards.decorator-DhumFTk3.cjs +0 -444
  98. package/lib/use-guards.decorator-DhumFTk3.cjs.map +0 -1
  99. package/project.json +0 -66
  100. package/src/__tests__/attribute.factory.spec.mts +0 -300
  101. package/src/__tests__/config.service.spec.mts +0 -43
  102. package/src/__tests__/console-logger.service.spec.mts +0 -312
  103. package/src/__tests__/controller-resolver.spec.mts +0 -229
  104. package/src/__tests__/controller.spec.mts +0 -58
  105. package/src/__tests__/guard-runner.service.spec.mts +0 -399
  106. package/src/__tests__/logger.service.spec.mts +0 -147
  107. package/src/__tests__/responders.spec.mts +0 -340
  108. package/src/__tests__/testing-module.spec.mts +0 -459
  109. package/src/__tests__/unit-testing-module.spec.mts +0 -424
  110. package/src/attribute.factory.mts +0 -325
  111. package/src/config/config-service.interface.mts +0 -47
  112. package/src/config/config.provider.mts +0 -69
  113. package/src/config/config.service.mts +0 -176
  114. package/src/config/index.mts +0 -5
  115. package/src/config/types.mts +0 -58
  116. package/src/config/utils/helpers.mts +0 -23
  117. package/src/config/utils/index.mts +0 -1
  118. package/src/decorators/controller.decorator.mts +0 -81
  119. package/src/decorators/endpoint.decorator.mts +0 -181
  120. package/src/decorators/header.decorator.mts +0 -38
  121. package/src/decorators/http-code.decorator.mts +0 -38
  122. package/src/decorators/index.mts +0 -8
  123. package/src/decorators/module.decorator.mts +0 -106
  124. package/src/decorators/multipart.decorator.mts +0 -169
  125. package/src/decorators/stream.decorator.mts +0 -155
  126. package/src/decorators/use-guards.decorator.mts +0 -73
  127. package/src/exceptions/bad-request.exception.mts +0 -28
  128. package/src/exceptions/conflict.exception.mts +0 -31
  129. package/src/exceptions/forbidden.exception.mts +0 -30
  130. package/src/exceptions/http.exception.mts +0 -33
  131. package/src/exceptions/index.mts +0 -7
  132. package/src/exceptions/internal-server-error.exception.mts +0 -33
  133. package/src/exceptions/not-found.exception.mts +0 -33
  134. package/src/exceptions/unauthorized.exception.mts +0 -30
  135. package/src/factories/adapter.factory.mts +0 -20
  136. package/src/factories/endpoint-adapter.factory.mts +0 -21
  137. package/src/factories/http-adapter.factory.mts +0 -20
  138. package/src/factories/index.mts +0 -8
  139. package/src/factories/multipart-adapter.factory.mts +0 -21
  140. package/src/factories/reply.factory.mts +0 -21
  141. package/src/factories/request.factory.mts +0 -21
  142. package/src/factories/stream-adapter.factory.mts +0 -20
  143. package/src/factories/xml-stream-adapter.factory.mts +0 -20
  144. package/src/index.mts +0 -16
  145. package/src/interfaces/abstract-adapter.interface.mts +0 -32
  146. package/src/interfaces/abstract-execution-context.inteface.mts +0 -48
  147. package/src/interfaces/abstract-http-adapter.interface.mts +0 -79
  148. package/src/interfaces/abstract-http-cors-options.interface.mts +0 -59
  149. package/src/interfaces/abstract-http-handler-adapter.interface.mts +0 -127
  150. package/src/interfaces/abstract-http-listen-options.interface.mts +0 -4
  151. package/src/interfaces/adapter-environment.interface.mts +0 -74
  152. package/src/interfaces/can-activate.mts +0 -38
  153. package/src/interfaces/http-header.mts +0 -18
  154. package/src/interfaces/index.mts +0 -14
  155. package/src/interfaces/navios-module.mts +0 -28
  156. package/src/interfaces/plugin-context.mts +0 -104
  157. package/src/interfaces/plugin-stage.mts +0 -62
  158. package/src/interfaces/plugin.interface.mts +0 -119
  159. package/src/interfaces/staged-plugin.interface.mts +0 -209
  160. package/src/legacy-compat/__type-tests__/legacy-decorators.spec-d.mts +0 -521
  161. package/src/legacy-compat/__type-tests__/tsconfig.json +0 -15
  162. package/src/legacy-compat/attribute.factory.mts +0 -351
  163. package/src/legacy-compat/decorators/controller.decorator.mts +0 -31
  164. package/src/legacy-compat/decorators/endpoint.decorator.mts +0 -73
  165. package/src/legacy-compat/decorators/header.decorator.mts +0 -43
  166. package/src/legacy-compat/decorators/http-code.decorator.mts +0 -39
  167. package/src/legacy-compat/decorators/index.mts +0 -11
  168. package/src/legacy-compat/decorators/module.decorator.mts +0 -37
  169. package/src/legacy-compat/decorators/multipart.decorator.mts +0 -72
  170. package/src/legacy-compat/decorators/stream.decorator.mts +0 -89
  171. package/src/legacy-compat/decorators/use-guards.decorator.mts +0 -80
  172. package/src/legacy-compat/index.mts +0 -57
  173. package/src/logger/README.md +0 -3
  174. package/src/logger/console-logger.service.mts +0 -714
  175. package/src/logger/index.mts +0 -6
  176. package/src/logger/log-levels.mts +0 -21
  177. package/src/logger/logger-service.interface.mts +0 -42
  178. package/src/logger/logger.service.mts +0 -113
  179. package/src/logger/logger.tokens.mts +0 -44
  180. package/src/logger/utils/cli-colors.util.mts +0 -17
  181. package/src/logger/utils/filter-log-levelts.util.mts +0 -29
  182. package/src/logger/utils/index.mts +0 -5
  183. package/src/logger/utils/is-log-level-enabled.mts +0 -33
  184. package/src/logger/utils/is-log-level.util.mts +0 -10
  185. package/src/logger/utils/shared.utils.mts +0 -51
  186. package/src/metadata/controller.metadata.mts +0 -79
  187. package/src/metadata/handler.metadata.mts +0 -80
  188. package/src/metadata/index.mts +0 -4
  189. package/src/metadata/module.metadata.mts +0 -116
  190. package/src/metadata/navios-managed.metadata.mts +0 -42
  191. package/src/navios.application.mts +0 -678
  192. package/src/navios.environment.mts +0 -42
  193. package/src/navios.factory.mts +0 -158
  194. package/src/responders/enums/framework-error.enum.mts +0 -38
  195. package/src/responders/enums/index.mts +0 -1
  196. package/src/responders/index.mts +0 -4
  197. package/src/responders/interfaces/error-responder.interface.mts +0 -42
  198. package/src/responders/interfaces/error-response.interface.mts +0 -22
  199. package/src/responders/interfaces/index.mts +0 -3
  200. package/src/responders/interfaces/problem-details.interface.mts +0 -34
  201. package/src/responders/services/error-response-producer.service.mts +0 -143
  202. package/src/responders/services/forbidden-responder.service.mts +0 -77
  203. package/src/responders/services/index.mts +0 -5
  204. package/src/responders/services/internal-server-error-responder.service.mts +0 -57
  205. package/src/responders/services/not-found-responder.service.mts +0 -76
  206. package/src/responders/services/validation-error-responder.service.mts +0 -78
  207. package/src/responders/tokens/index.mts +0 -1
  208. package/src/responders/tokens/responder.tokens.mts +0 -84
  209. package/src/services/abstract-handler-adapter.service.mts +0 -366
  210. package/src/services/guard-runner.service.mts +0 -152
  211. package/src/services/index.mts +0 -4
  212. package/src/services/instance-resolver.service.mts +0 -177
  213. package/src/services/module-loader.service.mts +0 -255
  214. package/src/stores/index.mts +0 -1
  215. package/src/stores/request-id.store.mts +0 -85
  216. package/src/testing/index.mts +0 -3
  217. package/src/testing/testing-module.mts +0 -393
  218. package/src/testing/unit-testing-module.mts +0 -298
  219. package/src/tokens/adapter.token.mts +0 -6
  220. package/src/tokens/endpoint-adapter.token.mts +0 -8
  221. package/src/tokens/execution-context.token.mts +0 -9
  222. package/src/tokens/http-adapter.token.mts +0 -8
  223. package/src/tokens/index.mts +0 -10
  224. package/src/tokens/multipart-adapter.token.mts +0 -8
  225. package/src/tokens/navios-options.token.mts +0 -6
  226. package/src/tokens/reply.token.mts +0 -3
  227. package/src/tokens/request.token.mts +0 -3
  228. package/src/tokens/stream-adapter.token.mts +0 -8
  229. package/src/tokens/xml-stream-adapter.token.mts +0 -8
  230. package/src/utils/adapter-supports.util.mts +0 -47
  231. package/src/utils/define-plugin.mts +0 -251
  232. package/src/utils/index.mts +0 -2
  233. package/tsconfig.json +0 -21
  234. package/tsconfig.lib.json +0 -8
  235. package/tsconfig.spec.json +0 -15
  236. package/tsdown.config.mts +0 -35
  237. package/vitest.config.mts +0 -15
@@ -0,0 +1,318 @@
1
+ const require_attribute_value = require("./attribute-value-Cux5HhOL.cjs");
2
+ const require_execution_context_token = require("./execution-context-token--cKS4cJv.cjs");
3
+ // src/transports/transport.mts
4
+ /**
5
+ * Defines a transport.
6
+ *
7
+ * ```ts
8
+ * export const queueTransport = defineTransport({
9
+ * name: 'queue',
10
+ * create(host, options: { url: string }) {
11
+ * return new QueueTransport(host, options)
12
+ * },
13
+ * })
14
+ *
15
+ * const app = createApplication(AppModule, {
16
+ * transports: [queueTransport({ url })],
17
+ * })
18
+ * await app.start()
19
+ * app.transport(queueTransport) // the QueueTransport
20
+ * ```
21
+ *
22
+ * An application can hold several transports of one definition when each has
23
+ * its own name: `queueTransport({ url }, 'orders')`.
24
+ */
25
+ function defineTransport(definition) {
26
+ const factory = (options, instanceName) => ({
27
+ definition,
28
+ options: options ?? {},
29
+ instanceName: instanceName ?? definition.name
30
+ });
31
+ return Object.assign(factory, { definition });
32
+ }
33
+ // src/metadata/handler-class.mts
34
+ /**
35
+ * What decorators attached to a class of handlers and to its members, together
36
+ * with the options of the class decorator that asks. The lists are live:
37
+ * `@UseGuards` and the like placed above that decorator run after it and are
38
+ * still seen.
39
+ */
40
+ function describeHandlerClass(context, options = {}) {
41
+ const metadata = require_attribute_value.requireMetadata(context);
42
+ const attributes = require_attribute_value.classAttributes(context);
43
+ require_attribute_value.applyAttributes(attributes, options.attributes);
44
+ return {
45
+ guards: require_attribute_value.prepend(require_attribute_value.classGuards(context), options.guards),
46
+ interceptors: require_attribute_value.prepend(require_attribute_value.classInterceptors(context), options.interceptors),
47
+ attributes,
48
+ members: metadata[require_attribute_value.MembersKey] ?? /* @__PURE__ */ new Map()
49
+ };
50
+ }
51
+ // src/metadata/handler-chain.mts
52
+ /**
53
+ * An attribute may open the handler to everyone or restrict it, so it is not
54
+ * guessed which of the import paths is meant.
55
+ */
56
+ function assertUndisputed({ node, owner, member }) {
57
+ for (const [key, paths] of node.disputed) if (!owner.attributes.has(key) && !member.attributes.has(key)) throw new Error(`[Navios] Module ${node.module.name} inherits different values of the attribute ${String(key)}: ${paths}. Set it on the controllers or handlers it is meant for, or on ${node.module.name} itself.`);
58
+ }
59
+ /**
60
+ * The guards and interceptors that apply to one handler, in the order they
61
+ * run, and what its contexts tell about it: the interceptors of the
62
+ * application, then the guards from the module chain, the owning class and
63
+ * the handler, then the interceptors of the same three. A class that appears
64
+ * twice is kept where it first appears. `info.guards` are the guards and
65
+ * `info.interceptors` the interceptors, `outer` and then `inner`.
66
+ *
67
+ * An interceptor of the application sees every execution, denied ones
68
+ * included, as tracing and logging need. One that is attached to handlers runs
69
+ * only for what their guards let through.
70
+ *
71
+ * Throws when the handler would inherit an attribute that the importers of its
72
+ * module do not agree about.
73
+ *
74
+ * Every transport uses this, so the rule is the same everywhere.
75
+ * `resolveChain` resolves the chain and `runChain` runs it.
76
+ */
77
+ function handlerChain(input) {
78
+ assertUndisputed(input);
79
+ const { application, node, controller, owner, handlerName, member } = input;
80
+ const everywhere = new Set(application);
81
+ const attached = [
82
+ ...node.interceptors,
83
+ ...owner.interceptors,
84
+ ...member.interceptors
85
+ ];
86
+ const outer = Array.from(everywhere);
87
+ const inner = Array.from(new Set(attached.filter((interceptor) => !everywhere.has(interceptor))));
88
+ return {
89
+ info: {
90
+ module: node.module,
91
+ controller,
92
+ handlerName,
93
+ guards: Array.from(/* @__PURE__ */ new Set([
94
+ ...node.guards,
95
+ ...owner.guards,
96
+ ...member.guards
97
+ ])),
98
+ interceptors: [...outer, ...inner],
99
+ attributes: {
100
+ handler: member.attributes,
101
+ controller: owner.attributes,
102
+ module: node.attributes
103
+ }
104
+ },
105
+ outer,
106
+ inner
107
+ };
108
+ }
109
+ // src/metadata/run-chain.mts
110
+ async function resolve(container, type, kind, method) {
111
+ const instance = await container.get(type);
112
+ if (typeof instance?.[method] !== "function") throw new Error(`[Navios] ${kind} ${type.name} does not implement ${method}()`);
113
+ return instance;
114
+ }
115
+ /**
116
+ * Resolves the classes of a chain that `handlerChain` returned. A transport
117
+ * does this once per handler, while it is set up.
118
+ */
119
+ async function resolveChain(container, chain) {
120
+ const outer = [];
121
+ const guards = [];
122
+ const inner = [];
123
+ for (const type of chain.outer) outer.push(await resolve(container, type, "Interceptor", "intercept"));
124
+ for (const type of chain.info.guards) guards.push({
125
+ type,
126
+ guard: await resolve(container, type, "Guard", "canActivate")
127
+ });
128
+ for (const type of chain.inner) inner.push(await resolve(container, type, "Interceptor", "intercept"));
129
+ return {
130
+ outer,
131
+ guards,
132
+ inner
133
+ };
134
+ }
135
+ function intercepted(ctx, interceptors, innermost) {
136
+ let next = async () => innermost();
137
+ for (let i = interceptors.length - 1; i >= 0; i--) {
138
+ const interceptor = interceptors[i];
139
+ const inner = next;
140
+ next = async () => interceptor.intercept(ctx, inner);
141
+ }
142
+ return next;
143
+ }
144
+ /**
145
+ * Runs a handler with what applies to it: the outer interceptors, the guards
146
+ * one after another, the inner interceptors, the handler. When a guard refuses,
147
+ * nothing further runs and `onDenied` says what becomes of the execution: what
148
+ * it returns is the result, and what it throws is the failure.
149
+ */
150
+ function runChain(ctx, chain, handler, onDenied) {
151
+ const guarded = async () => {
152
+ for (const { type, guard } of chain.guards) if (await guard.canActivate(ctx) !== true) return onDenied(type);
153
+ return intercepted(ctx, chain.inner, handler)();
154
+ };
155
+ return intercepted(ctx, chain.outer, guarded)();
156
+ }
157
+ /**
158
+ * Runs a handler with what applies to it, as `runChain`, in the async context
159
+ * when the application keeps one, and then finishes its context, whatever the
160
+ * outcome. The context is finished inside the async context, so that
161
+ * `currentContext()` still answers in `onFinish` callbacks.
162
+ */
163
+ function executeChain(host, ctx, chain, handler, onDenied) {
164
+ const execute = async () => {
165
+ try {
166
+ return await runChain(ctx, chain, handler, onDenied);
167
+ } finally {
168
+ await ctx.finish();
169
+ }
170
+ };
171
+ return host.asyncContext ? require_execution_context_token.runInContext(ctx, execute) : execute();
172
+ }
173
+ // src/execution/basic-execution-context.mts
174
+ /**
175
+ * An `ExecutionContext` for transports that need nothing beyond the neutral
176
+ * contract. The transport creates one per execution and calls `finish()` when
177
+ * the handler is done.
178
+ */
179
+ var BasicExecutionContext = class {
180
+ kind;
181
+ id;
182
+ handler;
183
+ host;
184
+ ownSignal = null;
185
+ slots = null;
186
+ scope = null;
187
+ finishers = null;
188
+ finished = false;
189
+ finishing = null;
190
+ constructor(init) {
191
+ this.kind = init.kind;
192
+ this.id = init.id;
193
+ this.handler = init.handler;
194
+ this.host = init.host;
195
+ }
196
+ /**
197
+ * A signal that never aborts. Not shared between contexts: listeners would
198
+ * outlive their execution.
199
+ */
200
+ get signal() {
201
+ return this.ownSignal ??= new AbortController().signal;
202
+ }
203
+ get(key) {
204
+ const slots = this.slots;
205
+ if (slots === null || !slots.has(key)) throw new Error(`[Navios] Context key ${key.name} is not set. Set it with ctx.set() (usually in a guard), or read it with ctx.find().`);
206
+ return slots.get(key);
207
+ }
208
+ find(key) {
209
+ return this.slots?.get(key);
210
+ }
211
+ set(key, value) {
212
+ (this.slots ??= /* @__PURE__ */ new Map()).set(key, value);
213
+ }
214
+ has(key) {
215
+ return this.slots?.has(key) ?? false;
216
+ }
217
+ /**
218
+ * What resolves a token for this execution: its DI scope, which is created
219
+ * when something needs it.
220
+ * @internal
221
+ */
222
+ resolverFor(token) {
223
+ const { container, onScopedUse } = this.host;
224
+ if (this.scope !== null && onScopedUse === null) return this.scope;
225
+ if (!require_execution_context_token.needsScope(container, token)) return this.scope ?? container;
226
+ onScopedUse?.(token);
227
+ if (this.scope === null) {
228
+ if (this.finished) throw new Error("[Navios] Request-scoped services cannot be used: the execution has finished, so nothing would dispose them.");
229
+ this.scope = container.createScope();
230
+ this.scope.addInstance(require_execution_context_token.ExecutionContextToken, this);
231
+ }
232
+ return this.scope;
233
+ }
234
+ onFinish(callback) {
235
+ if (this.finished) {
236
+ this.runFinisher(callback);
237
+ return;
238
+ }
239
+ (this.finishers ??= []).push(callback);
240
+ }
241
+ /**
242
+ * Runs the `onFinish` callbacks in reverse order, those they register
243
+ * included, then disposes the DI scope. Runs once, however often it is
244
+ * called; every caller waits for that run.
245
+ */
246
+ finish() {
247
+ return this.finishing ??= this.runFinishers();
248
+ }
249
+ async runFinishers() {
250
+ let finisher;
251
+ while ((finisher = this.finishers?.pop()) !== void 0) await this.runFinisher(finisher);
252
+ this.finished = true;
253
+ this.ownSignal = null;
254
+ const scope = this.scope;
255
+ this.scope = null;
256
+ if (scope !== null) await scope.dispose();
257
+ }
258
+ /** Runs a callback whose failure must not stop what follows. */
259
+ async runFinisher(callback) {
260
+ try {
261
+ await callback();
262
+ } catch (error) {
263
+ try {
264
+ this.host.logger?.error(`Error in an onFinish callback of ${this.kind} ${this.id}`, error);
265
+ } catch {}
266
+ }
267
+ }
268
+ };
269
+ BasicExecutionContext.prototype.use = function use(token, args) {
270
+ return this.resolverFor(token).getSync(token, args);
271
+ };
272
+ BasicExecutionContext.prototype.resolve = function resolve(token, args) {
273
+ return this.resolverFor(token).get(token, args);
274
+ };
275
+ Object.defineProperty(exports, "BasicExecutionContext", {
276
+ enumerable: true,
277
+ get: function() {
278
+ return BasicExecutionContext;
279
+ }
280
+ });
281
+ Object.defineProperty(exports, "defineTransport", {
282
+ enumerable: true,
283
+ get: function() {
284
+ return defineTransport;
285
+ }
286
+ });
287
+ Object.defineProperty(exports, "describeHandlerClass", {
288
+ enumerable: true,
289
+ get: function() {
290
+ return describeHandlerClass;
291
+ }
292
+ });
293
+ Object.defineProperty(exports, "executeChain", {
294
+ enumerable: true,
295
+ get: function() {
296
+ return executeChain;
297
+ }
298
+ });
299
+ Object.defineProperty(exports, "handlerChain", {
300
+ enumerable: true,
301
+ get: function() {
302
+ return handlerChain;
303
+ }
304
+ });
305
+ Object.defineProperty(exports, "resolveChain", {
306
+ enumerable: true,
307
+ get: function() {
308
+ return resolveChain;
309
+ }
310
+ });
311
+ Object.defineProperty(exports, "runChain", {
312
+ enumerable: true,
313
+ get: function() {
314
+ return runChain;
315
+ }
316
+ });
317
+
318
+ //# sourceMappingURL=basic-execution-context-5uq2DvEA.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"basic-execution-context-5uq2DvEA.cjs","names":["requireMetadata","classAttributes","applyAttributes","prepend","classGuards","classInterceptors","MembersKey","runInContext","needsScope","ExecutionContextToken"],"sources":["../src/transports/transport.mts","../src/metadata/handler-class.mts","../src/metadata/handler-chain.mts","../src/metadata/run-chain.mts","../src/execution/basic-execution-context.mts"],"sourcesContent":["import type { ClassType, Container } from '@navios/di'\n\nimport type { ContextHost } from '../execution/context-host.mjs'\nimport type { OptionsArgument } from '../internal/options-argument.mjs'\nimport type { LoggerService } from '../logger/logger-output.mjs'\nimport type { ModuleNode } from '../modules/module-graph.mjs'\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/**\n * What the application gives a transport when it creates it.\n */\nexport interface TransportHost {\n readonly container: Container\n readonly logger: LoggerService\n /** For the transport's execution contexts. */\n readonly contextHost: ContextHost\n /** Whether the application keeps the current context in an async store. */\n readonly asyncContext: boolean\n /**\n * Interceptors around every handler of the application, outermost first.\n * Complete once `setup()` is called.\n */\n readonly interceptors: readonly ClassType[]\n}\n\n/**\n * One way work reaches the application: an HTTP server, a queue consumer, a\n * command line. The application creates it, hands it the module graph, and\n * starts and stops it together with the others.\n */\nexport interface Transport {\n /**\n * Reads the module graph and prepares the transport's handlers. Must not\n * start accepting work.\n */\n setup(graph: readonly ModuleNode[]): void | Promise<void>\n /** Starts accepting work. Called at most once. */\n start?(): void | Promise<void>\n /**\n * Stops accepting work and waits, up to `timeoutMs`, for what is in flight.\n * One that takes much longer is left behind. When the application fails to\n * initialise or to start it is called for every transport that was created,\n * with no time to wait and possibly before `setup` or `start` ran; it must\n * release what `create` acquired. Called once, and again when `start` settles\n * only after that.\n */\n stop(timeoutMs: number): void | Promise<void>\n}\n\nexport interface TransportDefinition<Options, T extends Transport> {\n /** The kind of transport, and the default name of an instance. */\n name: string\n create(host: TransportHost, options: Options): T | Promise<T>\n}\n\n/**\n * A transport as it is listed in an application's options.\n */\nexport interface TransportInstance<T extends Transport = Transport> {\n readonly definition: TransportDefinition<any, T>\n /** `{}` when the transport was given none. */\n readonly options: unknown\n /** Unique within the application. Defaults to the definition's name. */\n readonly instanceName: string\n}\n\n/**\n * What `defineTransport` returns: called with options it gives the instance\n * to list in an application, and it is the key to look the transport up with.\n */\nexport interface TransportFactory<Options, T extends Transport> {\n (...args: OptionsArgument<Options, [instanceName?: string]>): TransportInstance<T>\n readonly definition: TransportDefinition<Options, T>\n}\n\n/**\n * Defines a transport.\n *\n * ```ts\n * export const queueTransport = defineTransport({\n * name: 'queue',\n * create(host, options: { url: string }) {\n * return new QueueTransport(host, options)\n * },\n * })\n *\n * const app = createApplication(AppModule, {\n * transports: [queueTransport({ url })],\n * })\n * await app.start()\n * app.transport(queueTransport) // the QueueTransport\n * ```\n *\n * An application can hold several transports of one definition when each has\n * its own name: `queueTransport({ url }, 'orders')`.\n */\nexport function defineTransport<Options = void, T extends Transport = Transport>(\n definition: TransportDefinition<Options, T>,\n): TransportFactory<Options, T> {\n const factory = (options?: Options, instanceName?: string): TransportInstance<T> => ({\n definition,\n options: options ?? {},\n instanceName: instanceName ?? definition.name,\n })\n return Object.assign(factory, { definition })\n}\n","import type { ClassType } from '@navios/di'\n\nimport { applyAttributes } from '../attributes/attribute-value.mjs'\n\nimport type { AttributeValue } from '../attributes/attribute-value.mjs'\n\nimport { classAttributes, classGuards, classInterceptors, prepend } from './class-metadata.mjs'\nimport { requireMetadata } from './decorator-metadata.mjs'\nimport { MembersKey } from './member-metadata.mjs'\n\nimport type { DecoratorMetadata } from './decorator-metadata.mjs'\nimport type { HandlerExtras, MethodHandlerMetadata } from './member-metadata.mjs'\n\n/** What a transport's decorator for handler classes may take. */\nexport interface HandlerClassOptions {\n guards?: Iterable<ClassType>\n interceptors?: Iterable<ClassType>\n attributes?: AttributeValue[]\n}\n\n/** A class that owns handlers: what applies to all of them, and its members. */\nexport interface HandlerClassMetadata extends HandlerExtras {\n /** The members decorators were applied to, by name. */\n members: Map<string, MethodHandlerMetadata>\n}\n\n/**\n * What decorators attached to a class of handlers and to its members, together\n * with the options of the class decorator that asks. The lists are live:\n * `@UseGuards` and the like placed above that decorator run after it and are\n * still seen.\n */\nexport function describeHandlerClass(\n context: { metadata?: DecoratorMetadata },\n options: HandlerClassOptions = {},\n): HandlerClassMetadata {\n const metadata = requireMetadata(context)\n const attributes = classAttributes(context)\n applyAttributes(attributes, options.attributes)\n return {\n guards: prepend(classGuards(context), options.guards),\n interceptors: prepend(classInterceptors(context), options.interceptors),\n attributes,\n members: (metadata[MembersKey] as Map<string, MethodHandlerMetadata> | undefined) ?? new Map(),\n }\n}\n","import type { ClassType } from '@navios/di'\n\nimport type { HandlerInfo } from '../execution/execution-context.mjs'\nimport type { ModuleNode } from '../modules/module-graph.mjs'\n\ninterface Extras {\n readonly guards: readonly ClassType[]\n readonly interceptors: readonly ClassType[]\n}\n\ninterface OwnExtras extends Extras {\n readonly attributes: ReadonlyMap<symbol, unknown>\n}\n\nexport interface HandlerChainInput {\n /**\n * Interceptors around every handler of the application or of the transport,\n * outermost first.\n */\n application: readonly ClassType[]\n /** The module the handler belongs to, with what it inherits. */\n node: Extras & Pick<ModuleNode, 'module' | 'attributes' | 'disputed'>\n /** The class that owns the handler. */\n controller: ClassType\n /** What applies to every handler of `controller`. */\n owner: OwnExtras\n /** The name of the handler in its class. */\n handlerName: string\n /** The handler itself. */\n member: OwnExtras\n}\n\nexport interface HandlerChain {\n /** What the contexts of the handler tell about it. */\n info: HandlerInfo\n /** Interceptors around the guards: those of the application. */\n outer: ClassType[]\n /** Interceptors inside the guards: those of the module, the class and the handler. */\n inner: ClassType[]\n}\n\n/**\n * An attribute may open the handler to everyone or restrict it, so it is not\n * guessed which of the import paths is meant.\n */\nfunction assertUndisputed({ node, owner, member }: HandlerChainInput): void {\n for (const [key, paths] of node.disputed) {\n if (!owner.attributes.has(key) && !member.attributes.has(key)) {\n throw new Error(\n `[Navios] Module ${node.module.name} inherits different values of the attribute ` +\n `${String(key)}: ${paths}. Set it on the controllers or handlers it is meant for, or ` +\n `on ${node.module.name} itself.`,\n )\n }\n }\n}\n\n/**\n * The guards and interceptors that apply to one handler, in the order they\n * run, and what its contexts tell about it: the interceptors of the\n * application, then the guards from the module chain, the owning class and\n * the handler, then the interceptors of the same three. A class that appears\n * twice is kept where it first appears. `info.guards` are the guards and\n * `info.interceptors` the interceptors, `outer` and then `inner`.\n *\n * An interceptor of the application sees every execution, denied ones\n * included, as tracing and logging need. One that is attached to handlers runs\n * only for what their guards let through.\n *\n * Throws when the handler would inherit an attribute that the importers of its\n * module do not agree about.\n *\n * Every transport uses this, so the rule is the same everywhere.\n * `resolveChain` resolves the chain and `runChain` runs it.\n */\nexport function handlerChain(input: HandlerChainInput): HandlerChain {\n assertUndisputed(input)\n const { application, node, controller, owner, handlerName, member } = input\n const everywhere = new Set(application)\n const attached = [...node.interceptors, ...owner.interceptors, ...member.interceptors]\n const outer = Array.from(everywhere)\n const inner = Array.from(new Set(attached.filter((interceptor) => !everywhere.has(interceptor))))\n return {\n info: {\n module: node.module,\n controller,\n handlerName,\n guards: Array.from(new Set([...node.guards, ...owner.guards, ...member.guards])),\n interceptors: [...outer, ...inner],\n attributes: {\n handler: member.attributes,\n controller: owner.attributes,\n module: node.attributes,\n },\n },\n outer,\n inner,\n }\n}\n","import type { ClassType, Container } from '@navios/di'\n\nimport { runInContext } from '../execution/async-context.mjs'\n\nimport type { ExecutionContext, HandlerInfo } from '../execution/execution-context.mjs'\nimport type { Guard } from '../guards/guard.mjs'\nimport type { Interceptor } from '../interceptors/interceptor.mjs'\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/** A handler's chain with its instances, ready to run. */\nexport interface ResolvedChain<Ctx extends ExecutionContext = ExecutionContext, Result = unknown> {\n readonly outer: ReadonlyArray<Interceptor<Ctx, Result>>\n readonly guards: ReadonlyArray<{ readonly type: ClassType; readonly guard: Guard<Ctx> }>\n readonly inner: ReadonlyArray<Interceptor<Ctx, Result>>\n}\n\nasync function resolve(\n container: Pick<Container, 'get'>,\n type: ClassType,\n kind: string,\n method: string,\n): Promise<any> {\n const instance = (await container.get(type)) as any\n if (typeof instance?.[method] !== 'function') {\n throw new Error(`[Navios] ${kind} ${type.name} does not implement ${method}()`)\n }\n return instance\n}\n\n/**\n * Resolves the classes of a chain that `handlerChain` returned. A transport\n * does this once per handler, while it is set up.\n */\nexport async function resolveChain<\n Ctx extends ExecutionContext = ExecutionContext,\n Result = unknown,\n>(\n container: Pick<Container, 'get'>,\n chain: {\n readonly info: Pick<HandlerInfo, 'guards'>\n readonly outer: readonly ClassType[]\n readonly inner: readonly ClassType[]\n },\n): Promise<ResolvedChain<Ctx, Result>> {\n const outer: Interceptor<Ctx, Result>[] = []\n const guards: Array<{ type: ClassType; guard: Guard<Ctx> }> = []\n const inner: Interceptor<Ctx, Result>[] = []\n for (const type of chain.outer) {\n outer.push(await resolve(container, type, 'Interceptor', 'intercept'))\n }\n for (const type of chain.info.guards) {\n guards.push({ type, guard: await resolve(container, type, 'Guard', 'canActivate') })\n }\n for (const type of chain.inner) {\n inner.push(await resolve(container, type, 'Interceptor', 'intercept'))\n }\n return { outer, guards, inner }\n}\n\nfunction intercepted<Ctx extends ExecutionContext, Result>(\n ctx: Ctx,\n interceptors: ReadonlyArray<Interceptor<Ctx, Result>>,\n innermost: () => Result | Promise<Result>,\n): () => Promise<Result> {\n let next = async () => innermost()\n for (let i = interceptors.length - 1; i >= 0; i--) {\n const interceptor = interceptors[i]\n const inner = next\n next = async () => interceptor.intercept(ctx, inner)\n }\n return next\n}\n\n/**\n * Runs a handler with what applies to it: the outer interceptors, the guards\n * one after another, the inner interceptors, the handler. When a guard refuses,\n * nothing further runs and `onDenied` says what becomes of the execution: what\n * it returns is the result, and what it throws is the failure.\n */\nexport function runChain<Ctx extends ExecutionContext, Result>(\n ctx: Ctx,\n chain: ResolvedChain<Ctx, Result>,\n handler: () => Result | Promise<Result>,\n onDenied: (guard: ClassType) => Result | Promise<Result>,\n): Promise<Result> {\n const guarded = async (): Promise<Result> => {\n for (const { type, guard } of chain.guards) {\n if ((await guard.canActivate(ctx)) !== true) {\n return onDenied(type)\n }\n }\n return intercepted(ctx, chain.inner, handler)()\n }\n return intercepted(ctx, chain.outer, guarded)()\n}\n\n/**\n * Runs a handler with what applies to it, as `runChain`, in the async context\n * when the application keeps one, and then finishes its context, whatever the\n * outcome. The context is finished inside the async context, so that\n * `currentContext()` still answers in `onFinish` callbacks.\n */\nexport function executeChain<Ctx extends ExecutionContext & { finish(): Promise<void> }, Result>(\n host: { readonly asyncContext: boolean },\n ctx: Ctx,\n chain: ResolvedChain<Ctx, Result>,\n handler: () => Result | Promise<Result>,\n onDenied: (guard: ClassType) => Result | Promise<Result>,\n): Promise<Result> {\n const execute = async (): Promise<Result> => {\n try {\n return await runChain(ctx, chain, handler, onDenied)\n } finally {\n await ctx.finish()\n }\n }\n return host.asyncContext ? runInContext(ctx, execute) : execute()\n}\n","import type { AnyInjectableType, Container, ScopedContainer } from '@navios/di'\n\nimport { needsScope } from './context-host.mjs'\nimport { ExecutionContextToken } from './execution-context-token.mjs'\n\nimport type { ContextHost } from './context-host.mjs'\nimport type { ContextKey, ContextValue } from './context-key.mjs'\nimport type { ExecutionContext, HandlerInfo } from './execution-context.mjs'\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nexport interface BasicExecutionContextInit {\n /** The transport kind, for example `'cli'`. */\n kind: string\n id: string\n handler: HandlerInfo\n host: ContextHost\n}\n\n/**\n * An `ExecutionContext` for transports that need nothing beyond the neutral\n * contract. The transport creates one per execution and calls `finish()` when\n * the handler is done.\n */\nexport class BasicExecutionContext implements ExecutionContext {\n readonly kind: string\n readonly id: string\n readonly handler: HandlerInfo\n private readonly host: ContextHost\n private ownSignal: AbortSignal | null = null\n private slots: Map<ContextKey, unknown> | null = null\n private scope: ScopedContainer | null = null\n private finishers: Array<() => void | Promise<void>> | null = null\n private finished = false\n private finishing: Promise<void> | null = null\n\n constructor(init: BasicExecutionContextInit) {\n this.kind = init.kind\n this.id = init.id\n this.handler = init.handler\n this.host = init.host\n }\n\n /**\n * A signal that never aborts. Not shared between contexts: listeners would\n * outlive their execution.\n */\n get signal(): AbortSignal {\n return (this.ownSignal ??= new AbortController().signal)\n }\n\n get<K extends ContextKey>(key: K): ContextValue<K> {\n const slots = this.slots\n if (slots === null || !slots.has(key)) {\n throw new Error(\n `[Navios] Context key ${key.name} is not set. ` +\n `Set it with ctx.set() (usually in a guard), or read it with ctx.find().`,\n )\n }\n return slots.get(key) as ContextValue<K>\n }\n\n find<K extends ContextKey>(key: K): ContextValue<K> | undefined {\n return this.slots?.get(key) as ContextValue<K> | undefined\n }\n\n set<K extends ContextKey>(key: K, value: ContextValue<K>): void {\n ;(this.slots ??= new Map()).set(key, value)\n }\n\n has(key: ContextKey): boolean {\n return this.slots?.has(key) ?? false\n }\n\n /**\n * What resolves a token for this execution: its DI scope, which is created\n * when something needs it.\n * @internal\n */\n resolverFor(token: AnyInjectableType): Container | ScopedContainer {\n const { container, onScopedUse } = this.host\n if (this.scope !== null && onScopedUse === null) {\n return this.scope\n }\n if (!needsScope(container, token)) {\n return this.scope ?? container\n }\n onScopedUse?.(token)\n if (this.scope === null) {\n if (this.finished) {\n throw new Error(\n '[Navios] Request-scoped services cannot be used: the execution has finished, so ' +\n 'nothing would dispose them.',\n )\n }\n this.scope = container.createScope()\n this.scope.addInstance(ExecutionContextToken, this)\n }\n return this.scope\n }\n\n declare use: ScopedContainer['getSync']\n\n declare resolve: ScopedContainer['get']\n\n onFinish(callback: () => void | Promise<void>): void {\n if (this.finished) {\n void this.runFinisher(callback)\n return\n }\n ;(this.finishers ??= []).push(callback)\n }\n\n /**\n * Runs the `onFinish` callbacks in reverse order, those they register\n * included, then disposes the DI scope. Runs once, however often it is\n * called; every caller waits for that run.\n */\n finish(): Promise<void> {\n return (this.finishing ??= this.runFinishers())\n }\n\n private async runFinishers(): Promise<void> {\n let finisher: (() => void | Promise<void>) | undefined\n while ((finisher = this.finishers?.pop()) !== undefined) {\n await this.runFinisher(finisher)\n }\n this.finished = true\n this.ownSignal = null\n const scope = this.scope\n this.scope = null\n if (scope !== null) {\n await scope.dispose()\n }\n }\n\n /** Runs a callback whose failure must not stop what follows. */\n private async runFinisher(callback: () => void | Promise<void>): Promise<void> {\n try {\n await callback()\n } catch (error) {\n // A failing callback must not stop the others, so it is only reported.\n try {\n this.host.logger?.error(`Error in an onFinish callback of ${this.kind} ${this.id}`, error)\n } catch {\n // Nor may a failing logger.\n }\n }\n }\n}\n\nBasicExecutionContext.prototype.use = function use(\n this: BasicExecutionContext,\n token: AnyInjectableType,\n args?: unknown,\n) {\n return (this.resolverFor(token).getSync as any)(token, args)\n} as ScopedContainer['getSync']\n\nBasicExecutionContext.prototype.resolve = function resolve(\n this: BasicExecutionContext,\n token: AnyInjectableType,\n args?: unknown,\n) {\n return (this.resolverFor(token).get as any)(token, args)\n} as ScopedContainer['get']\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAiGA,SAAgB,gBACd,YAC8B;CAC9B,MAAM,WAAW,SAAmB,kBAAiD;EACnF;EACA,SAAS,WAAW,CAAC;EACrB,cAAc,gBAAgB,WAAW;CAC3C;CACA,OAAO,OAAO,OAAO,SAAS,EAAE,WAAW,CAAC;AAC9C;;;;;;;;AC1EA,SAAgB,qBACd,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classAttributes } from "./attribute-value-BNiJjxl1.mjs";
2
+ import { a as needsScope, c as runInContext, t as ExecutionContextToken } from "./execution-context-token-Cb3M3Ao0.mjs";
3
+ // src/transports/transport.mts
4
+ /**
5
+ * Defines a transport.
6
+ *
7
+ * ```ts
8
+ * export const queueTransport = defineTransport({
9
+ * name: 'queue',
10
+ * create(host, options: { url: string }) {
11
+ * return new QueueTransport(host, options)
12
+ * },
13
+ * })
14
+ *
15
+ * const app = createApplication(AppModule, {
16
+ * transports: [queueTransport({ url })],
17
+ * })
18
+ * await app.start()
19
+ * app.transport(queueTransport) // the QueueTransport
20
+ * ```
21
+ *
22
+ * An application can hold several transports of one definition when each has
23
+ * its own name: `queueTransport({ url }, 'orders')`.
24
+ */
25
+ function defineTransport(definition) {
26
+ const factory = (options, instanceName) => ({
27
+ definition,
28
+ options: options ?? {},
29
+ instanceName: instanceName ?? definition.name
30
+ });
31
+ return Object.assign(factory, { definition });
32
+ }
33
+ // src/metadata/handler-class.mts
34
+ /**
35
+ * What decorators attached to a class of handlers and to its members, together
36
+ * with the options of the class decorator that asks. The lists are live:
37
+ * `@UseGuards` and the like placed above that decorator run after it and are
38
+ * still seen.
39
+ */
40
+ function describeHandlerClass(context, options = {}) {
41
+ const metadata = requireMetadata(context);
42
+ const attributes = classAttributes(context);
43
+ applyAttributes(attributes, options.attributes);
44
+ return {
45
+ guards: prepend(classGuards(context), options.guards),
46
+ interceptors: prepend(classInterceptors(context), options.interceptors),
47
+ attributes,
48
+ members: metadata[MembersKey] ?? /* @__PURE__ */ new Map()
49
+ };
50
+ }
51
+ // src/metadata/handler-chain.mts
52
+ /**
53
+ * An attribute may open the handler to everyone or restrict it, so it is not
54
+ * guessed which of the import paths is meant.
55
+ */
56
+ function assertUndisputed({ node, owner, member }) {
57
+ for (const [key, paths] of node.disputed) if (!owner.attributes.has(key) && !member.attributes.has(key)) throw new Error(`[Navios] Module ${node.module.name} inherits different values of the attribute ${String(key)}: ${paths}. Set it on the controllers or handlers it is meant for, or on ${node.module.name} itself.`);
58
+ }
59
+ /**
60
+ * The guards and interceptors that apply to one handler, in the order they
61
+ * run, and what its contexts tell about it: the interceptors of the
62
+ * application, then the guards from the module chain, the owning class and
63
+ * the handler, then the interceptors of the same three. A class that appears
64
+ * twice is kept where it first appears. `info.guards` are the guards and
65
+ * `info.interceptors` the interceptors, `outer` and then `inner`.
66
+ *
67
+ * An interceptor of the application sees every execution, denied ones
68
+ * included, as tracing and logging need. One that is attached to handlers runs
69
+ * only for what their guards let through.
70
+ *
71
+ * Throws when the handler would inherit an attribute that the importers of its
72
+ * module do not agree about.
73
+ *
74
+ * Every transport uses this, so the rule is the same everywhere.
75
+ * `resolveChain` resolves the chain and `runChain` runs it.
76
+ */
77
+ function handlerChain(input) {
78
+ assertUndisputed(input);
79
+ const { application, node, controller, owner, handlerName, member } = input;
80
+ const everywhere = new Set(application);
81
+ const attached = [
82
+ ...node.interceptors,
83
+ ...owner.interceptors,
84
+ ...member.interceptors
85
+ ];
86
+ const outer = Array.from(everywhere);
87
+ const inner = Array.from(new Set(attached.filter((interceptor) => !everywhere.has(interceptor))));
88
+ return {
89
+ info: {
90
+ module: node.module,
91
+ controller,
92
+ handlerName,
93
+ guards: Array.from(/* @__PURE__ */ new Set([
94
+ ...node.guards,
95
+ ...owner.guards,
96
+ ...member.guards
97
+ ])),
98
+ interceptors: [...outer, ...inner],
99
+ attributes: {
100
+ handler: member.attributes,
101
+ controller: owner.attributes,
102
+ module: node.attributes
103
+ }
104
+ },
105
+ outer,
106
+ inner
107
+ };
108
+ }
109
+ // src/metadata/run-chain.mts
110
+ async function resolve(container, type, kind, method) {
111
+ const instance = await container.get(type);
112
+ if (typeof instance?.[method] !== "function") throw new Error(`[Navios] ${kind} ${type.name} does not implement ${method}()`);
113
+ return instance;
114
+ }
115
+ /**
116
+ * Resolves the classes of a chain that `handlerChain` returned. A transport
117
+ * does this once per handler, while it is set up.
118
+ */
119
+ async function resolveChain(container, chain) {
120
+ const outer = [];
121
+ const guards = [];
122
+ const inner = [];
123
+ for (const type of chain.outer) outer.push(await resolve(container, type, "Interceptor", "intercept"));
124
+ for (const type of chain.info.guards) guards.push({
125
+ type,
126
+ guard: await resolve(container, type, "Guard", "canActivate")
127
+ });
128
+ for (const type of chain.inner) inner.push(await resolve(container, type, "Interceptor", "intercept"));
129
+ return {
130
+ outer,
131
+ guards,
132
+ inner
133
+ };
134
+ }
135
+ function intercepted(ctx, interceptors, innermost) {
136
+ let next = async () => innermost();
137
+ for (let i = interceptors.length - 1; i >= 0; i--) {
138
+ const interceptor = interceptors[i];
139
+ const inner = next;
140
+ next = async () => interceptor.intercept(ctx, inner);
141
+ }
142
+ return next;
143
+ }
144
+ /**
145
+ * Runs a handler with what applies to it: the outer interceptors, the guards
146
+ * one after another, the inner interceptors, the handler. When a guard refuses,
147
+ * nothing further runs and `onDenied` says what becomes of the execution: what
148
+ * it returns is the result, and what it throws is the failure.
149
+ */
150
+ function runChain(ctx, chain, handler, onDenied) {
151
+ const guarded = async () => {
152
+ for (const { type, guard } of chain.guards) if (await guard.canActivate(ctx) !== true) return onDenied(type);
153
+ return intercepted(ctx, chain.inner, handler)();
154
+ };
155
+ return intercepted(ctx, chain.outer, guarded)();
156
+ }
157
+ /**
158
+ * Runs a handler with what applies to it, as `runChain`, in the async context
159
+ * when the application keeps one, and then finishes its context, whatever the
160
+ * outcome. The context is finished inside the async context, so that
161
+ * `currentContext()` still answers in `onFinish` callbacks.
162
+ */
163
+ function executeChain(host, ctx, chain, handler, onDenied) {
164
+ const execute = async () => {
165
+ try {
166
+ return await runChain(ctx, chain, handler, onDenied);
167
+ } finally {
168
+ await ctx.finish();
169
+ }
170
+ };
171
+ return host.asyncContext ? runInContext(ctx, execute) : execute();
172
+ }
173
+ // src/execution/basic-execution-context.mts
174
+ /**
175
+ * An `ExecutionContext` for transports that need nothing beyond the neutral
176
+ * contract. The transport creates one per execution and calls `finish()` when
177
+ * the handler is done.
178
+ */
179
+ var BasicExecutionContext = class {
180
+ kind;
181
+ id;
182
+ handler;
183
+ host;
184
+ ownSignal = null;
185
+ slots = null;
186
+ scope = null;
187
+ finishers = null;
188
+ finished = false;
189
+ finishing = null;
190
+ constructor(init) {
191
+ this.kind = init.kind;
192
+ this.id = init.id;
193
+ this.handler = init.handler;
194
+ this.host = init.host;
195
+ }
196
+ /**
197
+ * A signal that never aborts. Not shared between contexts: listeners would
198
+ * outlive their execution.
199
+ */
200
+ get signal() {
201
+ return this.ownSignal ??= new AbortController().signal;
202
+ }
203
+ get(key) {
204
+ const slots = this.slots;
205
+ if (slots === null || !slots.has(key)) throw new Error(`[Navios] Context key ${key.name} is not set. Set it with ctx.set() (usually in a guard), or read it with ctx.find().`);
206
+ return slots.get(key);
207
+ }
208
+ find(key) {
209
+ return this.slots?.get(key);
210
+ }
211
+ set(key, value) {
212
+ (this.slots ??= /* @__PURE__ */ new Map()).set(key, value);
213
+ }
214
+ has(key) {
215
+ return this.slots?.has(key) ?? false;
216
+ }
217
+ /**
218
+ * What resolves a token for this execution: its DI scope, which is created
219
+ * when something needs it.
220
+ * @internal
221
+ */
222
+ resolverFor(token) {
223
+ const { container, onScopedUse } = this.host;
224
+ if (this.scope !== null && onScopedUse === null) return this.scope;
225
+ if (!needsScope(container, token)) return this.scope ?? container;
226
+ onScopedUse?.(token);
227
+ if (this.scope === null) {
228
+ if (this.finished) throw new Error("[Navios] Request-scoped services cannot be used: the execution has finished, so nothing would dispose them.");
229
+ this.scope = container.createScope();
230
+ this.scope.addInstance(ExecutionContextToken, this);
231
+ }
232
+ return this.scope;
233
+ }
234
+ onFinish(callback) {
235
+ if (this.finished) {
236
+ this.runFinisher(callback);
237
+ return;
238
+ }
239
+ (this.finishers ??= []).push(callback);
240
+ }
241
+ /**
242
+ * Runs the `onFinish` callbacks in reverse order, those they register
243
+ * included, then disposes the DI scope. Runs once, however often it is
244
+ * called; every caller waits for that run.
245
+ */
246
+ finish() {
247
+ return this.finishing ??= this.runFinishers();
248
+ }
249
+ async runFinishers() {
250
+ let finisher;
251
+ while ((finisher = this.finishers?.pop()) !== void 0) await this.runFinisher(finisher);
252
+ this.finished = true;
253
+ this.ownSignal = null;
254
+ const scope = this.scope;
255
+ this.scope = null;
256
+ if (scope !== null) await scope.dispose();
257
+ }
258
+ /** Runs a callback whose failure must not stop what follows. */
259
+ async runFinisher(callback) {
260
+ try {
261
+ await callback();
262
+ } catch (error) {
263
+ try {
264
+ this.host.logger?.error(`Error in an onFinish callback of ${this.kind} ${this.id}`, error);
265
+ } catch {}
266
+ }
267
+ }
268
+ };
269
+ BasicExecutionContext.prototype.use = function use(token, args) {
270
+ return this.resolverFor(token).getSync(token, args);
271
+ };
272
+ BasicExecutionContext.prototype.resolve = function resolve(token, args) {
273
+ return this.resolverFor(token).get(token, args);
274
+ };
275
+ export { handlerChain as a, runChain as i, executeChain as n, describeHandlerClass as o, resolveChain as r, defineTransport as s, BasicExecutionContext as t };
276
+
277
+ //# sourceMappingURL=basic-execution-context-u1VktGoM.mjs.map