@navios/core 1.0.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.
- package/CHANGELOG.md +97 -11
- package/README.md +67 -220
- package/lib/async-context-6pdlnNLA.d.mts +237 -0
- package/lib/async-context-6pdlnNLA.d.mts.map +1 -0
- package/lib/async-context-Dqk7pE-D.d.cts +237 -0
- package/lib/async-context-Dqk7pE-D.d.cts.map +1 -0
- package/lib/attribute-factory-B3VuYnp7.d.cts +70 -0
- package/lib/attribute-factory-B3VuYnp7.d.cts.map +1 -0
- package/lib/attribute-factory-mKOXoVnV.d.mts +70 -0
- package/lib/attribute-factory-mKOXoVnV.d.mts.map +1 -0
- package/lib/attribute-value-CjX9ZkLq.cjs +172 -0
- package/lib/attribute-value-CjX9ZkLq.cjs.map +1 -0
- package/lib/attribute-value-DMEA255r.mjs +119 -0
- package/lib/attribute-value-DMEA255r.mjs.map +1 -0
- package/lib/basic-execution-context-CeGuhMOz.mjs +246 -0
- package/lib/basic-execution-context-CeGuhMOz.mjs.map +1 -0
- package/lib/basic-execution-context-DSk5MNtc.cjs +281 -0
- package/lib/basic-execution-context-DSk5MNtc.cjs.map +1 -0
- package/lib/execution-context-BPD3FeFb.d.mts +71 -0
- package/lib/execution-context-BPD3FeFb.d.mts.map +1 -0
- package/lib/execution-context-BTJdHhbf.d.cts +71 -0
- package/lib/execution-context-BTJdHhbf.d.cts.map +1 -0
- package/lib/execution-context-token-BXUKB2hf.cjs +112 -0
- package/lib/execution-context-token-BXUKB2hf.cjs.map +1 -0
- package/lib/execution-context-token-CrXmTvk2.mjs +77 -0
- package/lib/execution-context-token-CrXmTvk2.mjs.map +1 -0
- package/lib/index.cjs +1687 -4409
- package/lib/index.cjs.map +1 -1
- package/lib/index.d.cts +838 -3
- package/lib/index.d.cts.map +1 -0
- package/lib/index.d.mts +838 -3
- package/lib/index.d.mts.map +1 -0
- package/lib/index.mjs +1573 -4219
- package/lib/index.mjs.map +1 -1
- package/lib/legacy-compat/index.cjs +72 -371
- package/lib/legacy-compat/index.cjs.map +1 -1
- package/lib/legacy-compat/index.d.cts +42 -382
- package/lib/legacy-compat/index.d.cts.map +1 -1
- package/lib/legacy-compat/index.d.mts +41 -382
- package/lib/legacy-compat/index.d.mts.map +1 -1
- package/lib/legacy-compat/index.mjs +51 -345
- package/lib/legacy-compat/index.mjs.map +1 -1
- package/lib/module-Bha7GER_.mjs +135 -0
- package/lib/module-Bha7GER_.mjs.map +1 -0
- package/lib/module-DZewk_2r.cjs +164 -0
- package/lib/module-DZewk_2r.cjs.map +1 -0
- package/lib/module-graph-DCP9MHG0.cjs +147 -0
- package/lib/module-graph-DCP9MHG0.cjs.map +1 -0
- package/lib/module-graph-xvVEykFM.mjs +142 -0
- package/lib/module-graph-xvVEykFM.mjs.map +1 -0
- package/lib/module-metadata-C8S92seK.cjs +95 -0
- package/lib/module-metadata-C8S92seK.cjs.map +1 -0
- package/lib/module-metadata-k3RTt20x.mjs +66 -0
- package/lib/module-metadata-k3RTt20x.mjs.map +1 -0
- package/lib/module-options-Dmse0gii.d.mts +51 -0
- package/lib/module-options-Dmse0gii.d.mts.map +1 -0
- package/lib/module-options-IuDO-p8u.d.cts +51 -0
- package/lib/module-options-IuDO-p8u.d.cts.map +1 -0
- package/lib/testing/index.cjs +96 -414
- package/lib/testing/index.cjs.map +1 -1
- package/lib/testing/index.d.cts +25 -385
- package/lib/testing/index.d.cts.map +1 -1
- package/lib/testing/index.d.mts +24 -385
- package/lib/testing/index.d.mts.map +1 -1
- package/lib/testing/index.mjs +94 -408
- package/lib/testing/index.mjs.map +1 -1
- package/lib/transport.cjs +25 -0
- package/lib/transport.d.cts +190 -0
- package/lib/transport.d.cts.map +1 -0
- package/lib/transport.d.mts +190 -0
- package/lib/transport.d.mts.map +1 -0
- package/lib/transport.mjs +7 -0
- package/package.json +37 -17
- package/docs/README.md +0 -316
- package/docs/adapters.md +0 -308
- package/docs/application-setup.md +0 -524
- package/docs/attributes.md +0 -689
- package/docs/controllers.md +0 -373
- package/docs/endpoints.md +0 -444
- package/docs/exceptions.md +0 -352
- package/docs/guards.md +0 -550
- package/docs/legacy-compat.md +0 -356
- package/docs/modules.md +0 -377
- package/docs/quick-start.md +0 -290
- package/docs/services.md +0 -427
- package/docs/testing.md +0 -827
- package/lib/index-C0Sg16Eb.d.cts +0 -3365
- package/lib/index-C0Sg16Eb.d.cts.map +0 -1
- package/lib/index-DySQ6Dpd.d.mts +0 -3365
- package/lib/index-DySQ6Dpd.d.mts.map +0 -1
- package/lib/navios.factory-CO5MB_OK.cjs +0 -4125
- package/lib/navios.factory-CO5MB_OK.cjs.map +0 -1
- package/lib/navios.factory-D6Y94P9B.mjs +0 -3828
- package/lib/navios.factory-D6Y94P9B.mjs.map +0 -1
- package/lib/tokens-4J9sredA.mjs +0 -100
- package/lib/tokens-4J9sredA.mjs.map +0 -1
- package/lib/tokens-CWw9kyeD.cjs +0 -196
- package/lib/tokens-CWw9kyeD.cjs.map +0 -1
- package/lib/use-guards.decorator-BecoQSmE.mjs +0 -339
- package/lib/use-guards.decorator-BecoQSmE.mjs.map +0 -1
- package/lib/use-guards.decorator-C4ml9XaT.cjs +0 -447
- package/lib/use-guards.decorator-C4ml9XaT.cjs.map +0 -1
- package/project.json +0 -66
- package/src/__tests__/attribute.factory.spec.mts +0 -300
- package/src/__tests__/config.service.spec.mts +0 -43
- package/src/__tests__/console-logger.service.spec.mts +0 -312
- package/src/__tests__/controller-resolver.spec.mts +0 -229
- package/src/__tests__/controller.spec.mts +0 -58
- package/src/__tests__/guard-runner.service.spec.mts +0 -399
- package/src/__tests__/logger.service.spec.mts +0 -147
- package/src/__tests__/responders.spec.mts +0 -340
- package/src/__tests__/testing-module.spec.mts +0 -459
- package/src/__tests__/unit-testing-module.spec.mts +0 -424
- package/src/attribute.factory.mts +0 -325
- package/src/config/config-service.interface.mts +0 -47
- package/src/config/config.provider.mts +0 -69
- package/src/config/config.service.mts +0 -176
- package/src/config/index.mts +0 -5
- package/src/config/types.mts +0 -58
- package/src/config/utils/helpers.mts +0 -23
- package/src/config/utils/index.mts +0 -1
- package/src/decorators/controller.decorator.mts +0 -81
- package/src/decorators/endpoint.decorator.mts +0 -181
- package/src/decorators/header.decorator.mts +0 -38
- package/src/decorators/http-code.decorator.mts +0 -38
- package/src/decorators/index.mts +0 -8
- package/src/decorators/module.decorator.mts +0 -106
- package/src/decorators/multipart.decorator.mts +0 -169
- package/src/decorators/stream.decorator.mts +0 -155
- package/src/decorators/use-guards.decorator.mts +0 -73
- package/src/exceptions/bad-request.exception.mts +0 -28
- package/src/exceptions/conflict.exception.mts +0 -31
- package/src/exceptions/forbidden.exception.mts +0 -30
- package/src/exceptions/http.exception.mts +0 -33
- package/src/exceptions/index.mts +0 -7
- package/src/exceptions/internal-server-error.exception.mts +0 -33
- package/src/exceptions/not-found.exception.mts +0 -33
- package/src/exceptions/unauthorized.exception.mts +0 -30
- package/src/factories/adapter.factory.mts +0 -20
- package/src/factories/endpoint-adapter.factory.mts +0 -21
- package/src/factories/http-adapter.factory.mts +0 -20
- package/src/factories/index.mts +0 -8
- package/src/factories/multipart-adapter.factory.mts +0 -21
- package/src/factories/reply.factory.mts +0 -21
- package/src/factories/request.factory.mts +0 -21
- package/src/factories/stream-adapter.factory.mts +0 -20
- package/src/factories/xml-stream-adapter.factory.mts +0 -20
- package/src/index.mts +0 -16
- package/src/interfaces/abstract-adapter.interface.mts +0 -32
- package/src/interfaces/abstract-execution-context.inteface.mts +0 -48
- package/src/interfaces/abstract-http-adapter.interface.mts +0 -79
- package/src/interfaces/abstract-http-cors-options.interface.mts +0 -59
- package/src/interfaces/abstract-http-handler-adapter.interface.mts +0 -127
- package/src/interfaces/abstract-http-listen-options.interface.mts +0 -4
- package/src/interfaces/adapter-environment.interface.mts +0 -74
- package/src/interfaces/can-activate.mts +0 -38
- package/src/interfaces/http-header.mts +0 -18
- package/src/interfaces/index.mts +0 -11
- package/src/interfaces/navios-module.mts +0 -28
- package/src/interfaces/plugin.interface.mts +0 -139
- package/src/legacy-compat/__type-tests__/legacy-decorators.spec-d.mts +0 -521
- package/src/legacy-compat/__type-tests__/tsconfig.json +0 -15
- package/src/legacy-compat/attribute.factory.mts +0 -351
- package/src/legacy-compat/decorators/controller.decorator.mts +0 -31
- package/src/legacy-compat/decorators/endpoint.decorator.mts +0 -73
- package/src/legacy-compat/decorators/header.decorator.mts +0 -43
- package/src/legacy-compat/decorators/http-code.decorator.mts +0 -39
- package/src/legacy-compat/decorators/index.mts +0 -11
- package/src/legacy-compat/decorators/module.decorator.mts +0 -37
- package/src/legacy-compat/decorators/multipart.decorator.mts +0 -72
- package/src/legacy-compat/decorators/stream.decorator.mts +0 -89
- package/src/legacy-compat/decorators/use-guards.decorator.mts +0 -80
- package/src/legacy-compat/index.mts +0 -57
- package/src/logger/README.md +0 -3
- package/src/logger/console-logger.service.mts +0 -714
- package/src/logger/index.mts +0 -6
- package/src/logger/log-levels.mts +0 -21
- package/src/logger/logger-service.interface.mts +0 -42
- package/src/logger/logger.service.mts +0 -113
- package/src/logger/logger.tokens.mts +0 -44
- package/src/logger/utils/cli-colors.util.mts +0 -17
- package/src/logger/utils/filter-log-levelts.util.mts +0 -29
- package/src/logger/utils/index.mts +0 -5
- package/src/logger/utils/is-log-level-enabled.mts +0 -33
- package/src/logger/utils/is-log-level.util.mts +0 -10
- package/src/logger/utils/shared.utils.mts +0 -51
- package/src/metadata/controller.metadata.mts +0 -72
- package/src/metadata/handler.metadata.mts +0 -80
- package/src/metadata/index.mts +0 -4
- package/src/metadata/module.metadata.mts +0 -108
- package/src/metadata/navios-managed.metadata.mts +0 -42
- package/src/navios.application.mts +0 -484
- package/src/navios.environment.mts +0 -42
- package/src/navios.factory.mts +0 -158
- package/src/responders/enums/framework-error.enum.mts +0 -38
- package/src/responders/enums/index.mts +0 -1
- package/src/responders/index.mts +0 -4
- package/src/responders/interfaces/error-responder.interface.mts +0 -42
- package/src/responders/interfaces/error-response.interface.mts +0 -22
- package/src/responders/interfaces/index.mts +0 -3
- package/src/responders/interfaces/problem-details.interface.mts +0 -34
- package/src/responders/services/error-response-producer.service.mts +0 -143
- package/src/responders/services/forbidden-responder.service.mts +0 -77
- package/src/responders/services/index.mts +0 -5
- package/src/responders/services/internal-server-error-responder.service.mts +0 -57
- package/src/responders/services/not-found-responder.service.mts +0 -76
- package/src/responders/services/validation-error-responder.service.mts +0 -78
- package/src/responders/tokens/index.mts +0 -1
- package/src/responders/tokens/responder.tokens.mts +0 -84
- package/src/services/abstract-handler-adapter.service.mts +0 -366
- package/src/services/guard-runner.service.mts +0 -152
- package/src/services/index.mts +0 -4
- package/src/services/instance-resolver.service.mts +0 -177
- package/src/services/module-loader.service.mts +0 -252
- package/src/stores/index.mts +0 -1
- package/src/stores/request-id.store.mts +0 -85
- package/src/testing/index.mts +0 -3
- package/src/testing/testing-module.mts +0 -393
- package/src/testing/unit-testing-module.mts +0 -298
- package/src/tokens/adapter.token.mts +0 -6
- package/src/tokens/endpoint-adapter.token.mts +0 -8
- package/src/tokens/execution-context.token.mts +0 -9
- package/src/tokens/http-adapter.token.mts +0 -8
- package/src/tokens/index.mts +0 -10
- package/src/tokens/multipart-adapter.token.mts +0 -8
- package/src/tokens/navios-options.token.mts +0 -6
- package/src/tokens/reply.token.mts +0 -3
- package/src/tokens/request.token.mts +0 -3
- package/src/tokens/stream-adapter.token.mts +0 -8
- package/src/tokens/xml-stream-adapter.token.mts +0 -8
- package/src/utils/adapter-supports.util.mts +0 -47
- package/src/utils/index.mts +0 -1
- package/tsconfig.json +0 -21
- package/tsconfig.lib.json +0 -8
- package/tsconfig.spec.json +0 -15
- package/tsdown.config.mts +0 -35
- package/vitest.config.mts +0 -15
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
const require_attribute_value = require("./attribute-value-CjX9ZkLq.cjs");
|
|
2
|
+
const require_execution_context_token = require("./execution-context-token-BXUKB2hf.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: the interceptors of the application, then the guards from the module
|
|
62
|
+
* chain, the owning class and the handler, then the interceptors of the same
|
|
63
|
+
* three. A class that appears twice is kept where it first appears.
|
|
64
|
+
*
|
|
65
|
+
* An interceptor of the application sees every execution, denied ones
|
|
66
|
+
* included, as tracing and logging need. One that is attached to handlers runs
|
|
67
|
+
* only for what their guards let through.
|
|
68
|
+
*
|
|
69
|
+
* Throws when the handler would inherit an attribute that the importers of its
|
|
70
|
+
* module do not agree about.
|
|
71
|
+
*
|
|
72
|
+
* Every transport uses this, so the rule is the same everywhere. `runChain`
|
|
73
|
+
* runs the chain.
|
|
74
|
+
*/
|
|
75
|
+
function handlerChain(input) {
|
|
76
|
+
assertUndisputed(input);
|
|
77
|
+
const { application, node, owner, member } = input;
|
|
78
|
+
const outer = new Set(application);
|
|
79
|
+
const attached = [
|
|
80
|
+
...node.interceptors,
|
|
81
|
+
...owner.interceptors,
|
|
82
|
+
...member.interceptors
|
|
83
|
+
];
|
|
84
|
+
const inner = new Set(attached.filter((interceptor) => !outer.has(interceptor)));
|
|
85
|
+
return {
|
|
86
|
+
guards: Array.from(/* @__PURE__ */ new Set([
|
|
87
|
+
...node.guards,
|
|
88
|
+
...owner.guards,
|
|
89
|
+
...member.guards
|
|
90
|
+
])),
|
|
91
|
+
interceptors: [...outer, ...inner],
|
|
92
|
+
outer: Array.from(outer),
|
|
93
|
+
inner: Array.from(inner)
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
// src/metadata/run-chain.mts
|
|
97
|
+
async function resolve(container, type, kind, method) {
|
|
98
|
+
const instance = await container.get(type);
|
|
99
|
+
if (typeof instance?.[method] !== "function") throw new Error(`[Navios] ${kind} ${type.name} does not implement ${method}()`);
|
|
100
|
+
return instance;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Resolves the classes of a chain. A transport does this once per handler,
|
|
104
|
+
* while it is set up.
|
|
105
|
+
*/
|
|
106
|
+
async function resolveChain(container, chain) {
|
|
107
|
+
const outer = [];
|
|
108
|
+
const guards = [];
|
|
109
|
+
const inner = [];
|
|
110
|
+
for (const type of chain.outer) outer.push(await resolve(container, type, "Interceptor", "intercept"));
|
|
111
|
+
for (const type of chain.guards) guards.push({
|
|
112
|
+
type,
|
|
113
|
+
guard: await resolve(container, type, "Guard", "canActivate")
|
|
114
|
+
});
|
|
115
|
+
for (const type of chain.inner) inner.push(await resolve(container, type, "Interceptor", "intercept"));
|
|
116
|
+
return {
|
|
117
|
+
outer,
|
|
118
|
+
guards,
|
|
119
|
+
inner
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
function intercepted(ctx, interceptors, innermost) {
|
|
123
|
+
let next = async () => innermost();
|
|
124
|
+
for (let i = interceptors.length - 1; i >= 0; i--) {
|
|
125
|
+
const interceptor = interceptors[i];
|
|
126
|
+
const inner = next;
|
|
127
|
+
next = async () => interceptor.intercept(ctx, inner);
|
|
128
|
+
}
|
|
129
|
+
return next;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Runs a handler with what applies to it: the outer interceptors, the guards
|
|
133
|
+
* one after another, the inner interceptors, the handler. When a guard refuses,
|
|
134
|
+
* nothing further runs and `onDenied` says what becomes of the execution: what
|
|
135
|
+
* it returns is the result, and what it throws is the failure.
|
|
136
|
+
*/
|
|
137
|
+
function runChain(ctx, chain, handler, onDenied) {
|
|
138
|
+
const guarded = async () => {
|
|
139
|
+
for (const { type, guard } of chain.guards) if (await guard.canActivate(ctx) !== true) return onDenied(type);
|
|
140
|
+
return intercepted(ctx, chain.inner, handler)();
|
|
141
|
+
};
|
|
142
|
+
return intercepted(ctx, chain.outer, guarded)();
|
|
143
|
+
}
|
|
144
|
+
// src/execution/basic-execution-context.mts
|
|
145
|
+
/**
|
|
146
|
+
* An `ExecutionContext` for transports that need nothing beyond the neutral
|
|
147
|
+
* contract. The transport creates one per execution and calls `finish()` when
|
|
148
|
+
* the handler is done.
|
|
149
|
+
*/
|
|
150
|
+
var BasicExecutionContext = class {
|
|
151
|
+
kind;
|
|
152
|
+
id;
|
|
153
|
+
handler;
|
|
154
|
+
host;
|
|
155
|
+
givenSignal;
|
|
156
|
+
ownSignal = null;
|
|
157
|
+
slots = null;
|
|
158
|
+
scope = null;
|
|
159
|
+
finishers = null;
|
|
160
|
+
finished = false;
|
|
161
|
+
finishing = null;
|
|
162
|
+
constructor(init) {
|
|
163
|
+
this.kind = init.kind;
|
|
164
|
+
this.id = init.id;
|
|
165
|
+
this.handler = init.handler;
|
|
166
|
+
this.host = init.host;
|
|
167
|
+
this.givenSignal = init.signal;
|
|
168
|
+
}
|
|
169
|
+
/** Not shared between contexts: listeners would outlive their execution. */
|
|
170
|
+
get signal() {
|
|
171
|
+
return this.givenSignal ?? (this.ownSignal ??= new AbortController().signal);
|
|
172
|
+
}
|
|
173
|
+
get(key) {
|
|
174
|
+
const slots = this.slots;
|
|
175
|
+
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().`);
|
|
176
|
+
return slots.get(key);
|
|
177
|
+
}
|
|
178
|
+
find(key) {
|
|
179
|
+
return this.slots?.get(key);
|
|
180
|
+
}
|
|
181
|
+
set(key, value) {
|
|
182
|
+
(this.slots ??= /* @__PURE__ */ new Map()).set(key, value);
|
|
183
|
+
}
|
|
184
|
+
has(key) {
|
|
185
|
+
return this.slots?.has(key) ?? false;
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* What resolves a token for this execution: its DI scope, which is created
|
|
189
|
+
* when something needs it.
|
|
190
|
+
* @internal
|
|
191
|
+
*/
|
|
192
|
+
resolverFor(token) {
|
|
193
|
+
const { container } = this.host;
|
|
194
|
+
if (this.scope === null && !require_execution_context_token.needsScope(container, token)) return container;
|
|
195
|
+
this.host.onScopedUse?.(token);
|
|
196
|
+
if (this.scope === null) {
|
|
197
|
+
if (this.finished) throw new Error("[Navios] Request-scoped services cannot be used: the execution has finished, so nothing would dispose them.");
|
|
198
|
+
this.scope = container.createScope();
|
|
199
|
+
this.scope.addInstance(require_execution_context_token.ExecutionContextToken, this);
|
|
200
|
+
}
|
|
201
|
+
return this.scope;
|
|
202
|
+
}
|
|
203
|
+
onFinish(callback) {
|
|
204
|
+
if (this.finished) {
|
|
205
|
+
this.runFinisher(callback);
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
(this.finishers ??= []).push(callback);
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Runs the `onFinish` callbacks in reverse order, those they register
|
|
212
|
+
* included, then disposes the DI scope. Runs once, however often it is
|
|
213
|
+
* called; every caller waits for that run.
|
|
214
|
+
*/
|
|
215
|
+
finish() {
|
|
216
|
+
return this.finishing ??= this.runFinishers();
|
|
217
|
+
}
|
|
218
|
+
async runFinishers() {
|
|
219
|
+
let finisher;
|
|
220
|
+
while ((finisher = this.finishers?.pop()) !== void 0) await this.runFinisher(finisher);
|
|
221
|
+
this.finished = true;
|
|
222
|
+
this.ownSignal = null;
|
|
223
|
+
const scope = this.scope;
|
|
224
|
+
this.scope = null;
|
|
225
|
+
if (scope !== null) await scope.dispose();
|
|
226
|
+
}
|
|
227
|
+
/** Runs a callback whose failure must not stop what follows. */
|
|
228
|
+
async runFinisher(callback) {
|
|
229
|
+
try {
|
|
230
|
+
await callback();
|
|
231
|
+
} catch (error) {
|
|
232
|
+
try {
|
|
233
|
+
this.host.logger?.error(`Error in an onFinish callback of ${this.kind} ${this.id}`, error);
|
|
234
|
+
} catch {}
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
};
|
|
238
|
+
BasicExecutionContext.prototype.use = function use(token, args) {
|
|
239
|
+
return this.resolverFor(token).getSync(token, args);
|
|
240
|
+
};
|
|
241
|
+
BasicExecutionContext.prototype.resolve = function resolve(token, args) {
|
|
242
|
+
return this.resolverFor(token).get(token, args);
|
|
243
|
+
};
|
|
244
|
+
Object.defineProperty(exports, "BasicExecutionContext", {
|
|
245
|
+
enumerable: true,
|
|
246
|
+
get: function() {
|
|
247
|
+
return BasicExecutionContext;
|
|
248
|
+
}
|
|
249
|
+
});
|
|
250
|
+
Object.defineProperty(exports, "defineTransport", {
|
|
251
|
+
enumerable: true,
|
|
252
|
+
get: function() {
|
|
253
|
+
return defineTransport;
|
|
254
|
+
}
|
|
255
|
+
});
|
|
256
|
+
Object.defineProperty(exports, "describeHandlerClass", {
|
|
257
|
+
enumerable: true,
|
|
258
|
+
get: function() {
|
|
259
|
+
return describeHandlerClass;
|
|
260
|
+
}
|
|
261
|
+
});
|
|
262
|
+
Object.defineProperty(exports, "handlerChain", {
|
|
263
|
+
enumerable: true,
|
|
264
|
+
get: function() {
|
|
265
|
+
return handlerChain;
|
|
266
|
+
}
|
|
267
|
+
});
|
|
268
|
+
Object.defineProperty(exports, "resolveChain", {
|
|
269
|
+
enumerable: true,
|
|
270
|
+
get: function() {
|
|
271
|
+
return resolveChain;
|
|
272
|
+
}
|
|
273
|
+
});
|
|
274
|
+
Object.defineProperty(exports, "runChain", {
|
|
275
|
+
enumerable: true,
|
|
276
|
+
get: function() {
|
|
277
|
+
return runChain;
|
|
278
|
+
}
|
|
279
|
+
});
|
|
280
|
+
|
|
281
|
+
//# sourceMappingURL=basic-execution-context-DSk5MNtc.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"basic-execution-context-DSk5MNtc.cjs","names":["requireMetadata","classAttributes","applyAttributes","prepend","classGuards","classInterceptors","MembersKey","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 { 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' | 'disputed'>\n /** The class that owns the handler. */\n owner: OwnExtras\n /** The handler itself. */\n member: OwnExtras\n}\n\nexport interface HandlerChain {\n guards: ClassType[]\n /** `outer` and `inner`, one after the other. */\n interceptors: ClassType[]\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: the interceptors of the application, then the guards from the module\n * chain, the owning class and the handler, then the interceptors of the same\n * three. A class that appears twice is kept where it first appears.\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. `runChain`\n * runs the chain.\n */\nexport function handlerChain(input: HandlerChainInput): HandlerChain {\n assertUndisputed(input)\n const { application, node, owner, member } = input\n const outer = new Set(application)\n const attached = [...node.interceptors, ...owner.interceptors, ...member.interceptors]\n const inner = new Set(attached.filter((interceptor) => !outer.has(interceptor)))\n return {\n guards: Array.from(new Set([...node.guards, ...owner.guards, ...member.guards])),\n interceptors: [...outer, ...inner],\n outer: Array.from(outer),\n inner: Array.from(inner),\n }\n}\n","import type { ClassType, Container } from '@navios/di'\n\nimport type { ExecutionContext } from '../execution/execution-context.mjs'\nimport type { Guard } from '../guards/guard.mjs'\nimport type { Interceptor } from '../interceptors/interceptor.mjs'\n\nimport type { HandlerChain } from './handler-chain.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. A transport does this once per handler,\n * 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: Pick<HandlerChain, 'outer' | 'guards' | 'inner'>,\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.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","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 /** Defaults to a signal of the context's own that never aborts. */\n signal?: AbortSignal\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 readonly givenSignal: AbortSignal | undefined\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 this.givenSignal = init.signal\n }\n\n /** Not shared between contexts: listeners would outlive their execution. */\n get signal(): AbortSignal {\n return this.givenSignal ?? (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 } = this.host\n if (this.scope === null && !needsScope(container, token)) {\n return container\n }\n this.host.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;CAC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,YAAY,QAAQ;GAC9B;EACF;EACC,CAAC,KAAK,cAAc,CAAC,EAAA,CAAG,KAAK,QAAQ;CACxC;;;;;;CAOA,SAAwB;EACtB,OAAQ,KAAK,cAAc,KAAK,aAAa;CAC/C;CAEA,MAAc,eAA8B;EAC1C,IAAI;EACJ,QAAQ,WAAW,KAAK,WAAW,IAAI,OAAO,KAAA,GAC5C,MAAM,KAAK,YAAY,QAAQ;EAEjC,KAAK,WAAW;EAChB,KAAK,YAAY;EACjB,MAAM,QAAQ,KAAK;EACnB,KAAK,QAAQ;EACb,IAAI,UAAU,MACZ,MAAM,MAAM,QAAQ;CAExB;;CAGA,MAAc,YAAY,UAAqD;EAC7E,IAAI;GACF,MAAM,SAAS;EACjB,SAAS,OAAO;GAEd,IAAI;IACF,KAAK,KAAK,QAAQ,MAAM,oCAAoC,KAAK,KAAK,GAAG,KAAK,MAAM,KAAK;GAC3F,QAAQ,CAER;EACF;CACF;AACF;AAEA,sBAAsB,UAAU,MAAM,SAAS,IAE7C,OACA,MACA;CACA,OAAQ,KAAK,YAAY,KAAK,CAAC,CAAC,QAAgB,OAAO,IAAI;AAC7D;AAEA,sBAAsB,UAAU,UAAU,SAAS,QAEjD,OACA,MACA;CACA,OAAQ,KAAK,YAAY,KAAK,CAAC,CAAC,IAAY,OAAO,IAAI;AACzD"}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { ClassType, ScopedContainer } from "@navios/di";
|
|
2
|
+
/**
|
|
3
|
+
* A typed slot in an execution context. Something sets it (usually a guard),
|
|
4
|
+
* and reading it before that throws.
|
|
5
|
+
*
|
|
6
|
+
* ```ts
|
|
7
|
+
* export const CurrentUser = createContextKey<User>('CurrentUser')
|
|
8
|
+
* ```
|
|
9
|
+
*/
|
|
10
|
+
declare class PlainContextKey<T> {
|
|
11
|
+
readonly name: string;
|
|
12
|
+
readonly __type: T;
|
|
13
|
+
constructor(name: string);
|
|
14
|
+
toString(): string;
|
|
15
|
+
}
|
|
16
|
+
declare function createContextKey<T>(name: string): PlainContextKey<T>;
|
|
17
|
+
/** A key every transport's context accepts. */
|
|
18
|
+
type ContextKey<T = any> = PlainContextKey<T>;
|
|
19
|
+
/**
|
|
20
|
+
* The type `ctx.get(key)` returns: a plain key's type, or, for a key that is
|
|
21
|
+
* a class whose instances compute the value with `resolve`, what `resolve`
|
|
22
|
+
* returns (a promise when it returns a thenable). A transport decides whether
|
|
23
|
+
* it accepts such classes as keys.
|
|
24
|
+
*/
|
|
25
|
+
type ContextValue<K> = K extends PlainContextKey<infer T> ? T : K extends (new () => {
|
|
26
|
+
resolve(ctx: any): infer R;
|
|
27
|
+
}) ? ResolvedValue<R> : never;
|
|
28
|
+
type ResolvedValue<R> = R extends Promise<any> ? R : R extends PromiseLike<infer T> ? Promise<T> : R;
|
|
29
|
+
type AttributeMap = ReadonlyMap<symbol, unknown>;
|
|
30
|
+
/**
|
|
31
|
+
* The handler a context belongs to, the same for every transport: where it
|
|
32
|
+
* is declared and what applies to it.
|
|
33
|
+
*/
|
|
34
|
+
interface HandlerInfo {
|
|
35
|
+
readonly module: ClassType | null;
|
|
36
|
+
/** The class that owns the handler. */
|
|
37
|
+
readonly controller: ClassType;
|
|
38
|
+
readonly handlerName: string;
|
|
39
|
+
readonly guards: readonly ClassType[];
|
|
40
|
+
readonly interceptors: readonly ClassType[];
|
|
41
|
+
readonly attributes: {
|
|
42
|
+
readonly handler: AttributeMap;
|
|
43
|
+
readonly controller: AttributeMap;
|
|
44
|
+
readonly module: AttributeMap;
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* What every transport's context offers. A guard, interceptor or service
|
|
49
|
+
* written against this works on any transport.
|
|
50
|
+
*/
|
|
51
|
+
interface ExecutionContext {
|
|
52
|
+
/** The transport kind, for example `'http'`. */
|
|
53
|
+
readonly kind: string;
|
|
54
|
+
readonly id: string;
|
|
55
|
+
readonly signal: AbortSignal;
|
|
56
|
+
readonly handler: HandlerInfo;
|
|
57
|
+
/** Reads a slot; throws when a plain key is not set. */
|
|
58
|
+
get<K extends ContextKey>(key: K): ContextValue<K>;
|
|
59
|
+
/** Like `get`, but `undefined` for a plain key that is not set. */
|
|
60
|
+
find<K extends ContextKey>(key: K): ContextValue<K> | undefined;
|
|
61
|
+
set<K extends ContextKey>(key: K, value: ContextValue<K>): void;
|
|
62
|
+
has(key: ContextKey): boolean;
|
|
63
|
+
/** Resolves a service from this execution's DI scope, synchronously. */
|
|
64
|
+
use: ScopedContainer['getSync'];
|
|
65
|
+
/** Resolves a service from this execution's DI scope. */
|
|
66
|
+
resolve: ScopedContainer['get'];
|
|
67
|
+
/** Runs `callback` after the handler has finished, whatever the outcome. */
|
|
68
|
+
onFinish(callback: () => void | Promise<void>): void;
|
|
69
|
+
}
|
|
70
|
+
export { ContextValue as a, ContextKey as i, ExecutionContext as n, PlainContextKey as o, HandlerInfo as r, createContextKey as s, AttributeMap as t };
|
|
71
|
+
//# sourceMappingURL=execution-context-BPD3FeFb.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"execution-context-BPD3FeFb.d.mts","names":[],"sources":["../src/execution/context-key.mts","../src/execution/execution-context.mts"],"mappings":";;;;;;;;;cAUa,gBAAgB;WAGC;WAFX,QAAQ;EAEzB,YAA4B;EAE5B;;iBAKc,iBAAiB,GAAG,eAAe,gBAAgB;;KAKvD,WAAW,WAAW,gBAAgB;;;;;;;KAQtC,aAAa,KACvB,UAAU,sBAAsB,KAC5B,IACA;EAAsB,QAAQ,iBAAiB;KAC7C,cAAc;KAGjB,cAAc,KAAK,UAAU,eAAe,IAAI,UAAU,kBAAkB,KAAK,QAAQ,KAAK;KCpCvF,eAAe;;;;;UAMV;WACN,QAAQ;;WAER,YAAY;WACZ;WACA,iBAAiB;WACjB,uBAAuB;WACvB;aACE,SAAS;aACT,YAAY;aACZ,QAAQ;;;;;;;UAQJ;;WAEN;WACA;WACA,QAAQ;WACR,SAAS;;EAElB,IAAI,UAAU,YAAY,KAAK,IAAI,aAAa;;EAEhD,KAAK,UAAU,YAAY,KAAK,IAAI,aAAa;EACjD,IAAI,UAAU,YAAY,KAAK,GAAG,OAAO,aAAa;EACtD,IAAI,KAAK;;EAET,KAAK;;EAEL,SAAS;;EAET,SAAS,uBAAuB"}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { ClassType, ScopedContainer } from "@navios/di";
|
|
2
|
+
/**
|
|
3
|
+
* A typed slot in an execution context. Something sets it (usually a guard),
|
|
4
|
+
* and reading it before that throws.
|
|
5
|
+
*
|
|
6
|
+
* ```ts
|
|
7
|
+
* export const CurrentUser = createContextKey<User>('CurrentUser')
|
|
8
|
+
* ```
|
|
9
|
+
*/
|
|
10
|
+
declare class PlainContextKey<T> {
|
|
11
|
+
readonly name: string;
|
|
12
|
+
readonly __type: T;
|
|
13
|
+
constructor(name: string);
|
|
14
|
+
toString(): string;
|
|
15
|
+
}
|
|
16
|
+
declare function createContextKey<T>(name: string): PlainContextKey<T>;
|
|
17
|
+
/** A key every transport's context accepts. */
|
|
18
|
+
type ContextKey<T = any> = PlainContextKey<T>;
|
|
19
|
+
/**
|
|
20
|
+
* The type `ctx.get(key)` returns: a plain key's type, or, for a key that is
|
|
21
|
+
* a class whose instances compute the value with `resolve`, what `resolve`
|
|
22
|
+
* returns (a promise when it returns a thenable). A transport decides whether
|
|
23
|
+
* it accepts such classes as keys.
|
|
24
|
+
*/
|
|
25
|
+
type ContextValue<K> = K extends PlainContextKey<infer T> ? T : K extends (new () => {
|
|
26
|
+
resolve(ctx: any): infer R;
|
|
27
|
+
}) ? ResolvedValue<R> : never;
|
|
28
|
+
type ResolvedValue<R> = R extends Promise<any> ? R : R extends PromiseLike<infer T> ? Promise<T> : R;
|
|
29
|
+
type AttributeMap = ReadonlyMap<symbol, unknown>;
|
|
30
|
+
/**
|
|
31
|
+
* The handler a context belongs to, the same for every transport: where it
|
|
32
|
+
* is declared and what applies to it.
|
|
33
|
+
*/
|
|
34
|
+
interface HandlerInfo {
|
|
35
|
+
readonly module: ClassType | null;
|
|
36
|
+
/** The class that owns the handler. */
|
|
37
|
+
readonly controller: ClassType;
|
|
38
|
+
readonly handlerName: string;
|
|
39
|
+
readonly guards: readonly ClassType[];
|
|
40
|
+
readonly interceptors: readonly ClassType[];
|
|
41
|
+
readonly attributes: {
|
|
42
|
+
readonly handler: AttributeMap;
|
|
43
|
+
readonly controller: AttributeMap;
|
|
44
|
+
readonly module: AttributeMap;
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* What every transport's context offers. A guard, interceptor or service
|
|
49
|
+
* written against this works on any transport.
|
|
50
|
+
*/
|
|
51
|
+
interface ExecutionContext {
|
|
52
|
+
/** The transport kind, for example `'http'`. */
|
|
53
|
+
readonly kind: string;
|
|
54
|
+
readonly id: string;
|
|
55
|
+
readonly signal: AbortSignal;
|
|
56
|
+
readonly handler: HandlerInfo;
|
|
57
|
+
/** Reads a slot; throws when a plain key is not set. */
|
|
58
|
+
get<K extends ContextKey>(key: K): ContextValue<K>;
|
|
59
|
+
/** Like `get`, but `undefined` for a plain key that is not set. */
|
|
60
|
+
find<K extends ContextKey>(key: K): ContextValue<K> | undefined;
|
|
61
|
+
set<K extends ContextKey>(key: K, value: ContextValue<K>): void;
|
|
62
|
+
has(key: ContextKey): boolean;
|
|
63
|
+
/** Resolves a service from this execution's DI scope, synchronously. */
|
|
64
|
+
use: ScopedContainer['getSync'];
|
|
65
|
+
/** Resolves a service from this execution's DI scope. */
|
|
66
|
+
resolve: ScopedContainer['get'];
|
|
67
|
+
/** Runs `callback` after the handler has finished, whatever the outcome. */
|
|
68
|
+
onFinish(callback: () => void | Promise<void>): void;
|
|
69
|
+
}
|
|
70
|
+
export { ContextValue as a, ContextKey as i, ExecutionContext as n, PlainContextKey as o, HandlerInfo as r, createContextKey as s, AttributeMap as t };
|
|
71
|
+
//# sourceMappingURL=execution-context-BTJdHhbf.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"execution-context-BTJdHhbf.d.cts","names":[],"sources":["../src/execution/context-key.mts","../src/execution/execution-context.mts"],"mappings":";;;;;;;;;cAUa,gBAAgB;WAGC;WAFX,QAAQ;EAEzB,YAA4B;EAE5B;;iBAKc,iBAAiB,GAAG,eAAe,gBAAgB;;KAKvD,WAAW,WAAW,gBAAgB;;;;;;;KAQtC,aAAa,KACvB,UAAU,sBAAsB,KAC5B,IACA;EAAsB,QAAQ,iBAAiB;KAC7C,cAAc;KAGjB,cAAc,KAAK,UAAU,eAAe,IAAI,UAAU,kBAAkB,KAAK,QAAQ,KAAK;KCpCvF,eAAe;;;;;UAMV;WACN,QAAQ;;WAER,YAAY;WACZ;WACA,iBAAiB;WACjB,uBAAuB;WACvB;aACE,SAAS;aACT,YAAY;aACZ,QAAQ;;;;;;;UAQJ;;WAEN;WACA;WACA,QAAQ;WACR,SAAS;;EAElB,IAAI,UAAU,YAAY,KAAK,IAAI,aAAa;;EAEhD,KAAK,UAAU,YAAY,KAAK,IAAI,aAAa;EACjD,IAAI,UAAU,YAAY,KAAK,GAAG,OAAO,aAAa;EACtD,IAAI,KAAK;;EAET,KAAK;;EAEL,SAAS;;EAET,SAAS,uBAAuB"}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
let _navios_di = require("@navios/di");
|
|
2
|
+
// src/execution/async-context.mts
|
|
3
|
+
let storage = null;
|
|
4
|
+
/**
|
|
5
|
+
* Turns on the async context: one `AsyncLocalStorage` holding the current
|
|
6
|
+
* `ExecutionContext`. The `asyncContext: true` option of an application does it.
|
|
7
|
+
*/
|
|
8
|
+
async function enableAsyncContext() {
|
|
9
|
+
if (storage === null) {
|
|
10
|
+
const { AsyncLocalStorage } = await import("node:async_hooks");
|
|
11
|
+
storage = new AsyncLocalStorage();
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Runs `fn` with `ctx` as the current context. A transport does this when its
|
|
16
|
+
* host says that the application has an async context.
|
|
17
|
+
*/
|
|
18
|
+
function runInContext(ctx, fn) {
|
|
19
|
+
return storage === null ? fn() : storage.run(ctx, fn);
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* The context of the handler being run, for code that cannot receive it as an
|
|
23
|
+
* argument. Returns `undefined` outside a handler, and always when the
|
|
24
|
+
* application was not created with `asyncContext: true`.
|
|
25
|
+
*/
|
|
26
|
+
function currentContext() {
|
|
27
|
+
return storage?.getStore();
|
|
28
|
+
}
|
|
29
|
+
// src/execution/context-host.mts
|
|
30
|
+
function tokenName(token) {
|
|
31
|
+
return typeof token === "function" ? token.name : String(token);
|
|
32
|
+
}
|
|
33
|
+
/** The token itself, without the args that are bound to it. */
|
|
34
|
+
function plainToken(token) {
|
|
35
|
+
return token instanceof _navios_di.BoundInjectionToken || token instanceof _navios_di.FactoryInjectionToken ? token.token : token;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Whether a context resolves `token` from a DI scope of its execution. A
|
|
39
|
+
* singleton is the same in all of them.
|
|
40
|
+
*/
|
|
41
|
+
function needsScope(container, token) {
|
|
42
|
+
return container.getProvider(plainToken(token))?.scope !== _navios_di.InjectableScope.Singleton;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Builds the host for an application's contexts, applying its policy for
|
|
46
|
+
* request-scoped services.
|
|
47
|
+
*/
|
|
48
|
+
function createContextHost(container, mode, logger) {
|
|
49
|
+
if (mode === "allow") return {
|
|
50
|
+
container,
|
|
51
|
+
onScopedUse: null,
|
|
52
|
+
logger
|
|
53
|
+
};
|
|
54
|
+
const seen = /* @__PURE__ */ new Set();
|
|
55
|
+
return {
|
|
56
|
+
container,
|
|
57
|
+
logger,
|
|
58
|
+
onScopedUse: (used) => {
|
|
59
|
+
if (!needsScope(container, used)) return;
|
|
60
|
+
const token = plainToken(used);
|
|
61
|
+
if (mode === "forbid") throw new Error(`[Navios] ${tokenName(token)} was requested with ctx.use()/ctx.resolve(), but this application forbids request-scoped services (requestScopedServices: 'forbid'). Keep per-execution data in a context key instead.`);
|
|
62
|
+
if (!seen.has(token)) {
|
|
63
|
+
seen.add(token);
|
|
64
|
+
logger.warn(`${tokenName(token)} is resolved for every execution with ctx.use()/ctx.resolve(). If it only carries data derived from the context, a context key is cheaper and needs no DI scope. Set requestScopedServices: 'allow' to silence this.`);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
// src/execution/execution-context-token.mts
|
|
70
|
+
/**
|
|
71
|
+
* The context of the current execution, on any transport. Injectable in
|
|
72
|
+
* request-scoped services.
|
|
73
|
+
*/
|
|
74
|
+
const ExecutionContextToken = _navios_di.InjectionToken.create("ExecutionContext", { scope: _navios_di.InjectableScope.Request });
|
|
75
|
+
Object.defineProperty(exports, "ExecutionContextToken", {
|
|
76
|
+
enumerable: true,
|
|
77
|
+
get: function() {
|
|
78
|
+
return ExecutionContextToken;
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
Object.defineProperty(exports, "createContextHost", {
|
|
82
|
+
enumerable: true,
|
|
83
|
+
get: function() {
|
|
84
|
+
return createContextHost;
|
|
85
|
+
}
|
|
86
|
+
});
|
|
87
|
+
Object.defineProperty(exports, "currentContext", {
|
|
88
|
+
enumerable: true,
|
|
89
|
+
get: function() {
|
|
90
|
+
return currentContext;
|
|
91
|
+
}
|
|
92
|
+
});
|
|
93
|
+
Object.defineProperty(exports, "enableAsyncContext", {
|
|
94
|
+
enumerable: true,
|
|
95
|
+
get: function() {
|
|
96
|
+
return enableAsyncContext;
|
|
97
|
+
}
|
|
98
|
+
});
|
|
99
|
+
Object.defineProperty(exports, "needsScope", {
|
|
100
|
+
enumerable: true,
|
|
101
|
+
get: function() {
|
|
102
|
+
return needsScope;
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
Object.defineProperty(exports, "runInContext", {
|
|
106
|
+
enumerable: true,
|
|
107
|
+
get: function() {
|
|
108
|
+
return runInContext;
|
|
109
|
+
}
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
//# sourceMappingURL=execution-context-token-BXUKB2hf.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"execution-context-token-BXUKB2hf.cjs","names":["BoundInjectionToken","FactoryInjectionToken","InjectableScope","InjectionToken","InjectableScope"],"sources":["../src/execution/async-context.mts","../src/execution/context-host.mts","../src/execution/execution-context-token.mts"],"sourcesContent":["import type { ExecutionContext } from './execution-context.mjs'\n\ninterface Storage {\n run<R>(store: ExecutionContext, fn: () => R): R\n getStore(): ExecutionContext | undefined\n}\n\nlet storage: Storage | null = null\n\n/**\n * Turns on the async context: one `AsyncLocalStorage` holding the current\n * `ExecutionContext`. The `asyncContext: true` option of an application does it.\n */\nexport async function enableAsyncContext(): Promise<void> {\n if (storage === null) {\n const { AsyncLocalStorage } = await import('node:async_hooks')\n storage = new AsyncLocalStorage<ExecutionContext>()\n }\n}\n\n/**\n * Runs `fn` with `ctx` as the current context. A transport does this when its\n * host says that the application has an async context.\n */\nexport function runInContext<R>(ctx: ExecutionContext, fn: () => R): R {\n return storage === null ? fn() : storage.run(ctx, fn)\n}\n\n/**\n * The context of the handler being run, for code that cannot receive it as an\n * argument. Returns `undefined` outside a handler, and always when the\n * application was not created with `asyncContext: true`.\n */\nexport function currentContext(): ExecutionContext | undefined {\n return storage?.getStore()\n}\n","import { BoundInjectionToken, FactoryInjectionToken, InjectableScope } from '@navios/di'\n\nimport type { AnyInjectableType, ClassType, Container, InjectionToken } from '@navios/di'\n\nimport type { LoggerService } from '../logger/logger-output.mjs'\n\n/**\n * Dependencies shared by every execution context of an application.\n */\nexport interface ContextHost {\n readonly container: Container\n /**\n * Called when a token is used through a context; may throw. Does nothing for\n * a token that `needsScope` is false for.\n */\n onScopedUse: ((token: AnyInjectableType) => void) | null\n /** Receives what an `onFinish` callback throws; without it that is dropped. */\n readonly logger?: Pick<LoggerService, 'error'>\n}\n\nfunction tokenName(token: unknown): string {\n return typeof token === 'function' ? token.name : String(token)\n}\n\ntype PlainToken = ClassType | InjectionToken<unknown, unknown>\n\n/** The token itself, without the args that are bound to it. */\nfunction plainToken(token: AnyInjectableType): PlainToken {\n return (\n token instanceof BoundInjectionToken || token instanceof FactoryInjectionToken\n ? token.token\n : token\n ) as PlainToken\n}\n\n/**\n * Whether a context resolves `token` from a DI scope of its execution. A\n * singleton is the same in all of them.\n */\nexport function needsScope(container: Container, token: AnyInjectableType): boolean {\n return container.getProvider(plainToken(token))?.scope !== InjectableScope.Singleton\n}\n\n/**\n * Builds the host for an application's contexts, applying its policy for\n * request-scoped services.\n */\nexport function createContextHost(\n container: Container,\n mode: 'allow' | 'warn' | 'forbid',\n logger: LoggerService,\n): ContextHost {\n if (mode === 'allow') {\n return { container, onScopedUse: null, logger }\n }\n const seen = new Set<PlainToken>()\n return {\n container,\n logger,\n onScopedUse: (used) => {\n if (!needsScope(container, used)) {\n return\n }\n const token = plainToken(used)\n if (mode === 'forbid') {\n throw new Error(\n `[Navios] ${tokenName(token)} was requested with ctx.use()/ctx.resolve(), but this ` +\n `application forbids request-scoped services (requestScopedServices: 'forbid'). ` +\n `Keep per-execution data in a context key instead.`,\n )\n }\n if (!seen.has(token)) {\n seen.add(token)\n logger.warn(\n `${tokenName(token)} is resolved for every execution with ctx.use()/ctx.resolve(). ` +\n `If it only carries data derived from the context, a context key is cheaper and ` +\n `needs no DI scope. Set requestScopedServices: 'allow' to silence this.`,\n )\n }\n },\n }\n}\n","import { InjectableScope, InjectionToken } from '@navios/di'\n\nimport type { ExecutionContext } from './execution-context.mjs'\n\n/**\n * The context of the current execution, on any transport. Injectable in\n * request-scoped services.\n */\nexport const ExecutionContextToken = InjectionToken.create<ExecutionContext>('ExecutionContext', {\n scope: InjectableScope.Request,\n})\n"],"mappings":";;AAOA,IAAI,UAA0B;;;;;AAM9B,eAAsB,qBAAoC;CACxD,IAAI,YAAY,MAAM;EACpB,MAAM,EAAE,sBAAsB,MAAM,OAAO;EAC3C,UA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