@navios/core 0.6.0 → 0.7.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 (102) hide show
  1. package/CHANGELOG.md +115 -0
  2. package/README.md +18 -1
  3. package/docs/README.md +1 -0
  4. package/docs/legacy-compat.md +320 -0
  5. package/docs/testing.md +140 -17
  6. package/lib/index-DW9EPAE6.d.mts +2156 -0
  7. package/lib/index-DW9EPAE6.d.mts.map +1 -0
  8. package/lib/index-pHp-dIGt.d.cts +2156 -0
  9. package/lib/index-pHp-dIGt.d.cts.map +1 -0
  10. package/lib/index.cjs +157 -0
  11. package/lib/index.d.cts +3 -0
  12. package/lib/index.d.mts +3 -190
  13. package/lib/index.mjs +4 -1459
  14. package/lib/legacy-compat/index.cjs +315 -0
  15. package/lib/legacy-compat/index.cjs.map +1 -0
  16. package/lib/legacy-compat/index.d.cts +219 -0
  17. package/lib/legacy-compat/index.d.cts.map +1 -0
  18. package/lib/legacy-compat/index.d.mts +219 -0
  19. package/lib/legacy-compat/index.d.mts.map +1 -0
  20. package/lib/legacy-compat/index.mjs +308 -0
  21. package/lib/legacy-compat/index.mjs.map +1 -0
  22. package/lib/src-DyvCDuKO.mjs +5443 -0
  23. package/lib/src-DyvCDuKO.mjs.map +1 -0
  24. package/lib/src-QnxR5b7c.cjs +5800 -0
  25. package/lib/src-QnxR5b7c.cjs.map +1 -0
  26. package/lib/testing/index.cjs +106 -0
  27. package/lib/testing/index.cjs.map +1 -0
  28. package/lib/testing/index.d.cts +156 -0
  29. package/lib/testing/index.d.cts.map +1 -0
  30. package/lib/testing/index.d.mts +156 -0
  31. package/lib/testing/index.d.mts.map +1 -0
  32. package/lib/testing/index.mjs +100 -0
  33. package/lib/testing/index.mjs.map +1 -0
  34. package/lib/use-guards.decorator-B6q_N0sf.cjs +622 -0
  35. package/lib/use-guards.decorator-B6q_N0sf.cjs.map +1 -0
  36. package/lib/use-guards.decorator-kZ3lNK8v.mjs +454 -0
  37. package/lib/use-guards.decorator-kZ3lNK8v.mjs.map +1 -0
  38. package/package.json +28 -8
  39. package/project.json +2 -2
  40. package/src/attribute.factory.mts +154 -0
  41. package/src/config/config-service.interface.mts +31 -0
  42. package/src/config/config.provider.mts +36 -0
  43. package/src/config/config.service.mts +94 -4
  44. package/src/decorators/controller.decorator.mts +28 -0
  45. package/src/decorators/endpoint.decorator.mts +76 -0
  46. package/src/decorators/header.decorator.mts +19 -0
  47. package/src/decorators/http-code.decorator.mts +20 -0
  48. package/src/decorators/module.decorator.mts +34 -0
  49. package/src/decorators/multipart.decorator.mts +41 -0
  50. package/src/decorators/stream.decorator.mts +33 -0
  51. package/src/decorators/use-guards.decorator.mts +29 -0
  52. package/src/exceptions/bad-request.exception.mts +21 -0
  53. package/src/exceptions/conflict.exception.mts +24 -0
  54. package/src/exceptions/forbidden.exception.mts +23 -0
  55. package/src/exceptions/http.exception.mts +26 -0
  56. package/src/exceptions/internal-server-error.exception.mts +26 -0
  57. package/src/exceptions/not-found.exception.mts +23 -0
  58. package/src/exceptions/unauthorized.exception.mts +23 -0
  59. package/src/index.mts +1 -0
  60. package/src/interfaces/abstract-execution-context.inteface.mts +35 -0
  61. package/src/interfaces/abstract-http-adapter.interface.mts +52 -0
  62. package/src/interfaces/abstract-http-handler-adapter.interface.mts +2 -2
  63. package/src/interfaces/can-activate.mts +31 -0
  64. package/src/interfaces/index.mts +1 -0
  65. package/src/interfaces/navios-module.mts +25 -0
  66. package/src/interfaces/plugin.interface.mts +105 -0
  67. package/src/legacy-compat/__type-tests__/legacy-decorators.spec-d.mts +420 -0
  68. package/src/legacy-compat/__type-tests__/tsconfig.json +15 -0
  69. package/src/legacy-compat/context-compat.mts +93 -0
  70. package/src/legacy-compat/decorators/controller.decorator.mts +31 -0
  71. package/src/legacy-compat/decorators/endpoint.decorator.mts +99 -0
  72. package/src/legacy-compat/decorators/header.decorator.mts +42 -0
  73. package/src/legacy-compat/decorators/http-code.decorator.mts +38 -0
  74. package/src/legacy-compat/decorators/index.mts +9 -0
  75. package/src/legacy-compat/decorators/module.decorator.mts +37 -0
  76. package/src/legacy-compat/decorators/multipart.decorator.mts +93 -0
  77. package/src/legacy-compat/decorators/stream.decorator.mts +76 -0
  78. package/src/legacy-compat/decorators/use-guards.decorator.mts +80 -0
  79. package/src/legacy-compat/index.mts +40 -0
  80. package/src/logger/console-logger.service.mts +15 -2
  81. package/src/logger/log-levels.mts +9 -0
  82. package/src/logger/logger.service.mts +21 -0
  83. package/src/logger/logger.tokens.mts +23 -0
  84. package/src/navios.application.mts +228 -4
  85. package/src/navios.factory.mts +60 -1
  86. package/src/services/guard-runner.service.mts +12 -11
  87. package/src/services/module-loader.service.mts +118 -12
  88. package/src/stores/index.mts +1 -0
  89. package/src/stores/request-id.store.mts +43 -0
  90. package/src/testing/index.mts +2 -0
  91. package/src/testing/testing-module.mts +231 -0
  92. package/tsconfig.lib.json +1 -1
  93. package/tsconfig.spec.json +3 -0
  94. package/tsdown.config.mts +35 -0
  95. package/vitest.config.mts +6 -0
  96. package/lib/_tsup-dts-rollup.d.mts +0 -1365
  97. package/lib/_tsup-dts-rollup.d.ts +0 -1365
  98. package/lib/index.d.ts +0 -190
  99. package/lib/index.js +0 -1540
  100. package/lib/index.js.map +0 -1
  101. package/lib/index.mjs.map +0 -1
  102. package/tsup.config.mts +0 -13
package/lib/index.mjs CHANGED
@@ -1,1461 +1,6 @@
1
- import { InjectionToken, Injectable, Factory, InjectableScope, inject, Container, InjectableType } from '@navios/di';
2
- export * from '@navios/di';
3
- import { env } from 'process';
4
- import z, { z as z$1 } from 'zod/v4';
5
- import { NaviosException } from '@navios/builder';
6
- import { inspect } from 'util';
1
+ import { $ as envInt, A as loggerOptionsSchema, B as isObject, C as ConfigServiceOptionsSchema, D as _ConsoleLogger, E as _LoggerInstance, F as isConstructor, G as normalizePath, H as isString, I as isEmpty, J as filterLogLevels, K as stripEndSlash, L as isFunction, M as requestIdStore, N as runWithRequestId, O as Logger, P as addLeadingSlash, Q as yellow, R as isNil, S as provideConfig, T as _ConfigService, U as isSymbol, V as isPlainObject, W as isUndefined, X as LOG_LEVELS, Y as isLogLevel, Z as clc, _ as ForbiddenException, a as _ReplyFactory, b as ConfigProviderOptions, c as _HttpAdapterFactory, d as _ModuleLoaderService, et as envString, f as _GuardRunnerService, g as InternalServerErrorException, h as NotFoundException, i as _StreamAdapterFactory, j as getRequestId, k as LoggerOutput, l as _EndpointAdapterFactory, m as UnauthorizedException, n as _NaviosApplication, o as _RequestFactory, p as ConflictException, q as isLogLevelEnabled, r as _XmlStreamAdapterFactory, s as _MultipartAdapterFactory, t as NaviosFactory, u as AttributeFactory, v as BadRequestException, w as ConfigServiceToken, x as EnvConfigProvider, y as HttpException, z as isNumber } from "./src-DyvCDuKO.mjs";
2
+ import { C as extractControllerMetadata, D as getAllEndpointMetadata, E as EndpointMetadataKey, O as getEndpointMetadata, S as ControllerMetadataKey, T as hasControllerMetadata, _ as Controller, a as HttpCode, b as getModuleMetadata, c as XmlStreamAdapterToken, d as Reply, f as MultipartAdapterToken, g as EndpointAdapterToken, h as ExecutionContextInjectionToken, i as Module, l as StreamAdapterToken, m as ExecutionContext, n as Stream, o as Header, p as HttpAdapterToken, r as Multipart, s as Endpoint, t as UseGuards, u as Request, v as ModuleMetadataKey, w as getControllerMetadata, x as hasModuleMetadata, y as extractModuleMetadata } from "./use-guards.decorator-kZ3lNK8v.mjs";
7
3
 
8
- var __create = Object.create;
9
- var __defProp = Object.defineProperty;
10
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
11
- var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : /* @__PURE__ */ Symbol.for("Symbol." + name);
12
- var __typeError = (msg) => {
13
- throw TypeError(msg);
14
- };
15
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
16
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
17
- var __decoratorStart = (base) => [, , , __create(null)];
18
- var __decoratorStrings = ["class", "method", "getter", "setter", "accessor", "field", "value", "get", "set"];
19
- var __expectFn = (fn) => fn !== void 0 && typeof fn !== "function" ? __typeError("Function expected") : fn;
20
- var __decoratorContext = (kind, name, done, metadata, fns) => ({ kind: __decoratorStrings[kind], name, metadata, addInitializer: (fn) => done._ ? __typeError("Already initialized") : fns.push(__expectFn(fn || null)) });
21
- var __decoratorMetadata = (array, target) => __defNormalProp(target, __knownSymbol("metadata"), array[3]);
22
- var __runInitializers = (array, flags, self, value) => {
23
- for (var i = 0, fns = array[flags >> 1], n = fns && fns.length; i < n; i++) fns[i].call(self) ;
24
- return value;
25
- };
26
- var __decorateElement = (array, flags, name, decorators, target, extra) => {
27
- var it, done, ctx, k = flags & 7, p = false;
28
- var j = 0;
29
- var extraInitializers = array[j] || (array[j] = []);
30
- var desc = k && ((target = target.prototype), k < 5 && (k > 3 || !p) && __getOwnPropDesc(target , name));
31
- __name(target, name);
32
- for (var i = decorators.length - 1; i >= 0; i--) {
33
- ctx = __decoratorContext(k, name, done = {}, array[3], extraInitializers);
34
- it = (0, decorators[i])(target, ctx), done._ = 1;
35
- __expectFn(it) && (target = it);
36
- }
37
- return __decoratorMetadata(array, target), desc && __defProp(target, name, desc), p ? k ^ 4 ? extra : desc : target;
38
- };
39
- function envInt(key, defaultValue) {
40
- const envKey = env[key] || process.env[key];
41
- return envKey ? parseInt(envKey, 10) : defaultValue;
42
- }
43
- function envString(key, defaultValue) {
44
- return env[key] || process.env[key] || defaultValue || void 0;
45
- }
4
+ export * from "@navios/di"
46
5
 
47
- // src/logger/utils/cli-colors.util.mts
48
- var isColorAllowed = () => !process.env.NO_COLOR;
49
- var colorIfAllowed = (colorFn) => (text) => isColorAllowed() ? colorFn(text) : text;
50
- var clc = {
51
- bold: colorIfAllowed((text) => `\x1B[1m${text}\x1B[0m`),
52
- green: colorIfAllowed((text) => `\x1B[32m${text}\x1B[39m`),
53
- yellow: colorIfAllowed((text) => `\x1B[33m${text}\x1B[39m`),
54
- red: colorIfAllowed((text) => `\x1B[31m${text}\x1B[39m`),
55
- magentaBright: colorIfAllowed((text) => `\x1B[95m${text}\x1B[39m`),
56
- cyanBright: colorIfAllowed((text) => `\x1B[96m${text}\x1B[39m`)
57
- };
58
- var yellow = colorIfAllowed(
59
- (text) => `\x1B[38;5;3m${text}\x1B[39m`
60
- );
61
-
62
- // src/logger/log-levels.mts
63
- var LOG_LEVELS = [
64
- "verbose",
65
- "debug",
66
- "log",
67
- "warn",
68
- "error",
69
- "fatal"
70
- ];
71
-
72
- // src/logger/utils/is-log-level.util.mts
73
- function isLogLevel(maybeLogLevel) {
74
- return LOG_LEVELS.includes(maybeLogLevel);
75
- }
76
-
77
- // src/logger/utils/filter-log-levelts.util.mts
78
- function filterLogLevels(parseableString = "") {
79
- const sanitizedString = parseableString.replaceAll(" ", "").toLowerCase();
80
- if (sanitizedString[0] === ">") {
81
- const orEqual = sanitizedString[1] === "=";
82
- const logLevelIndex = LOG_LEVELS.indexOf(
83
- sanitizedString.substring(orEqual ? 2 : 1)
84
- );
85
- if (logLevelIndex === -1) {
86
- throw new Error(`parse error (unknown log level): ${sanitizedString}`);
87
- }
88
- return LOG_LEVELS.slice(orEqual ? logLevelIndex : logLevelIndex + 1);
89
- } else if (sanitizedString.includes(",")) {
90
- return sanitizedString.split(",").filter(isLogLevel);
91
- }
92
- return isLogLevel(sanitizedString) ? [sanitizedString] : LOG_LEVELS;
93
- }
94
-
95
- // src/logger/utils/is-log-level-enabled.mts
96
- var LOG_LEVEL_VALUES = {
97
- verbose: 0,
98
- debug: 1,
99
- log: 2,
100
- warn: 3,
101
- error: 4,
102
- fatal: 5
103
- };
104
- function isLogLevelEnabled(targetLevel, logLevels) {
105
- if (!logLevels || Array.isArray(logLevels) && logLevels?.length === 0) {
106
- return false;
107
- }
108
- if (logLevels.includes(targetLevel)) {
109
- return true;
110
- }
111
- const highestLogLevelValue = logLevels.map((level) => LOG_LEVEL_VALUES[level]).sort((a, b) => b - a)?.[0];
112
- const targetLevelValue = LOG_LEVEL_VALUES[targetLevel];
113
- return targetLevelValue >= highestLogLevelValue;
114
- }
115
-
116
- // src/logger/utils/shared.utils.mts
117
- var isUndefined = (obj) => typeof obj === "undefined";
118
- var isObject = (fn) => !isNil(fn) && typeof fn === "object";
119
- var isPlainObject = (fn) => {
120
- if (!isObject(fn)) {
121
- return false;
122
- }
123
- const proto = Object.getPrototypeOf(fn);
124
- if (proto === null) {
125
- return true;
126
- }
127
- const ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor;
128
- return typeof ctor === "function" && ctor instanceof ctor && Function.prototype.toString.call(ctor) === Function.prototype.toString.call(Object);
129
- };
130
- var addLeadingSlash = (path) => path && typeof path === "string" ? path.charAt(0) !== "/" && path.substring(0, 2) !== "{/" ? "/" + path : path : "";
131
- var normalizePath = (path) => path ? path.startsWith("/") ? ("/" + path.replace(/\/+$/, "")).replace(/\/+/g, "/") : "/" + path.replace(/\/+$/, "") : "/";
132
- var stripEndSlash = (path) => path[path.length - 1] === "/" ? path.slice(0, path.length - 1) : path;
133
- var isFunction = (val) => typeof val === "function";
134
- var isString = (val) => typeof val === "string";
135
- var isNumber = (val) => typeof val === "number";
136
- var isConstructor = (val) => val === "constructor";
137
- var isNil = (val) => isUndefined(val) || val === null;
138
- var isEmpty = (array) => !(array && array.length > 0);
139
- var isSymbol = (val) => typeof val === "symbol";
140
- var LoggerOutput = InjectionToken.create("LoggerOutput");
141
- var loggerOptionsSchema = z.object({
142
- context: z.string().optional()
143
- }).optional();
144
- var Logger = InjectionToken.create("Logger", loggerOptionsSchema);
145
-
146
- // src/logger/console-logger.service.mts
147
- var DEFAULT_DEPTH = 5;
148
- var DEFAULT_LOG_LEVELS = [
149
- "log",
150
- "error",
151
- "warn",
152
- "debug",
153
- "verbose",
154
- "fatal"
155
- ];
156
- var dateTimeFormatter = new Intl.DateTimeFormat(void 0, {
157
- year: "numeric",
158
- hour: "numeric",
159
- minute: "numeric",
160
- second: "numeric",
161
- day: "2-digit",
162
- month: "2-digit"
163
- });
164
- var _ConsoleLogger_decorators, _init;
165
- _ConsoleLogger_decorators = [Injectable({
166
- token: LoggerOutput
167
- })];
168
- var ConsoleLogger = class {
169
- /**
170
- * The options of the logger.
171
- */
172
- options = {};
173
- /**
174
- * The context of the logger (can be set manually or automatically inferred).
175
- */
176
- context;
177
- /**
178
- * The original context of the logger (set in the constructor).
179
- */
180
- originalContext;
181
- /**
182
- * The options used for the "inspect" method.
183
- */
184
- inspectOptions = this.getInspectOptions();
185
- /**
186
- * The last timestamp at which the log message was printed.
187
- */
188
- lastTimestampAt;
189
- setup(contextOrOptions, options) {
190
- let [context, opts] = isString(contextOrOptions) ? [contextOrOptions, options] : options ? [void 0, options] : [contextOrOptions?.context, contextOrOptions];
191
- opts = opts ?? {};
192
- opts.logLevels ??= DEFAULT_LOG_LEVELS;
193
- opts.colors ??= opts.colors ?? (opts.json ? false : true);
194
- opts.prefix ??= "Navios";
195
- this.options = opts;
196
- this.inspectOptions = this.getInspectOptions();
197
- if (context) {
198
- this.context = context;
199
- this.originalContext = context;
200
- }
201
- }
202
- log(message, ...optionalParams) {
203
- if (!this.isLevelEnabled("log")) {
204
- return;
205
- }
206
- const { messages, context } = this.getContextAndMessagesToPrint([
207
- message,
208
- ...optionalParams
209
- ]);
210
- this.printMessages(messages, context, "log");
211
- }
212
- error(message, ...optionalParams) {
213
- if (!this.isLevelEnabled("error")) {
214
- return;
215
- }
216
- const { messages, context, stack } = this.getContextAndStackAndMessagesToPrint([message, ...optionalParams]);
217
- this.printMessages(messages, context, "error", void 0, "stderr", stack);
218
- this.printStackTrace(stack);
219
- }
220
- warn(message, ...optionalParams) {
221
- if (!this.isLevelEnabled("warn")) {
222
- return;
223
- }
224
- const { messages, context } = this.getContextAndMessagesToPrint([
225
- message,
226
- ...optionalParams
227
- ]);
228
- this.printMessages(messages, context, "warn");
229
- }
230
- debug(message, ...optionalParams) {
231
- if (!this.isLevelEnabled("debug")) {
232
- return;
233
- }
234
- const { messages, context } = this.getContextAndMessagesToPrint([
235
- message,
236
- ...optionalParams
237
- ]);
238
- this.printMessages(messages, context, "debug");
239
- }
240
- verbose(message, ...optionalParams) {
241
- if (!this.isLevelEnabled("verbose")) {
242
- return;
243
- }
244
- const { messages, context } = this.getContextAndMessagesToPrint([
245
- message,
246
- ...optionalParams
247
- ]);
248
- this.printMessages(messages, context, "verbose");
249
- }
250
- fatal(message, ...optionalParams) {
251
- if (!this.isLevelEnabled("fatal")) {
252
- return;
253
- }
254
- const { messages, context } = this.getContextAndMessagesToPrint([
255
- message,
256
- ...optionalParams
257
- ]);
258
- this.printMessages(messages, context, "fatal");
259
- }
260
- /**
261
- * Set log levels
262
- * @param levels log levels
263
- */
264
- setLogLevels(levels) {
265
- if (!this.options) {
266
- this.options = {};
267
- }
268
- this.options.logLevels = levels;
269
- }
270
- /**
271
- * Set logger context
272
- * @param context context
273
- */
274
- setContext(context) {
275
- this.context = context;
276
- }
277
- /**
278
- * Resets the logger context to the value that was passed in the constructor.
279
- */
280
- resetContext() {
281
- this.context = this.originalContext;
282
- }
283
- isLevelEnabled(level) {
284
- const logLevels = this.options?.logLevels;
285
- return isLogLevelEnabled(level, logLevels);
286
- }
287
- getTimestamp() {
288
- return dateTimeFormatter.format(Date.now());
289
- }
290
- printMessages(messages, context = "", logLevel = "log", requestId, writeStreamType, errorStack) {
291
- messages.forEach((message) => {
292
- if (this.options.json) {
293
- this.printAsJson(message, {
294
- context,
295
- logLevel,
296
- writeStreamType,
297
- errorStack,
298
- requestId
299
- });
300
- return;
301
- }
302
- const pidMessage = this.formatPid(process.pid);
303
- const contextMessage = this.formatContext(context);
304
- const timestampDiff = this.updateAndGetTimestampDiff();
305
- const formattedLogLevel = logLevel.toUpperCase().padStart(7, " ");
306
- const formattedMessage = this.formatMessage(
307
- logLevel,
308
- message,
309
- pidMessage,
310
- formattedLogLevel,
311
- contextMessage,
312
- timestampDiff,
313
- requestId
314
- );
315
- process[writeStreamType ?? "stdout"].write(formattedMessage);
316
- });
317
- }
318
- printAsJson(message, options) {
319
- const logObject = {
320
- level: options.logLevel,
321
- pid: process.pid,
322
- timestamp: Date.now(),
323
- message
324
- };
325
- if (options.context) {
326
- logObject.context = options.context;
327
- }
328
- if (options.errorStack) {
329
- logObject.stack = options.errorStack;
330
- }
331
- if (this.options.requestId && options.requestId) {
332
- logObject.requestId = options.requestId;
333
- }
334
- const formattedMessage = !this.options.colors && this.inspectOptions.compact === true ? JSON.stringify(logObject, this.stringifyReplacer) : inspect(logObject, this.inspectOptions);
335
- process[options.writeStreamType ?? "stdout"].write(`${formattedMessage}
336
- `);
337
- }
338
- formatPid(pid) {
339
- return `[${this.options.prefix}] ${pid} - `;
340
- }
341
- formatContext(context) {
342
- if (!context) {
343
- return "";
344
- }
345
- context = `[${context}] `;
346
- return this.options.colors ? yellow(context) : context;
347
- }
348
- formatMessage(logLevel, message, pidMessage, formattedLogLevel, contextMessage, timestampDiff, requestId) {
349
- const output = this.stringifyMessage(message, logLevel);
350
- pidMessage = this.colorize(pidMessage, logLevel);
351
- formattedLogLevel = this.colorize(formattedLogLevel, logLevel);
352
- return `${pidMessage}${this.getRequestId(requestId)}${this.getTimestamp()} ${formattedLogLevel} ${contextMessage}${output}${timestampDiff}
353
- `;
354
- }
355
- getRequestId(requestId) {
356
- if (this.options.requestId && requestId) {
357
- return `(${this.colorize(requestId, "log")}) `;
358
- }
359
- return "";
360
- }
361
- stringifyMessage(message, logLevel) {
362
- if (isFunction(message)) {
363
- const messageAsStr = Function.prototype.toString.call(message);
364
- const isClass = messageAsStr.startsWith("class ");
365
- if (isClass) {
366
- return this.stringifyMessage(message.name, logLevel);
367
- }
368
- return this.stringifyMessage(message(), logLevel);
369
- }
370
- if (typeof message === "string") {
371
- return this.colorize(message, logLevel);
372
- }
373
- const outputText = inspect(message, this.inspectOptions);
374
- if (isPlainObject(message)) {
375
- return `Object(${Object.keys(message).length}) ${outputText}`;
376
- }
377
- if (Array.isArray(message)) {
378
- return `Array(${message.length}) ${outputText}`;
379
- }
380
- return outputText;
381
- }
382
- colorize(message, logLevel) {
383
- if (!this.options.colors || this.options.json) {
384
- return message;
385
- }
386
- const color = this.getColorByLogLevel(logLevel);
387
- return color(message);
388
- }
389
- printStackTrace(stack) {
390
- if (!stack || this.options.json) {
391
- return;
392
- }
393
- process.stderr.write(`${stack}
394
- `);
395
- }
396
- updateAndGetTimestampDiff() {
397
- const includeTimestamp = this.lastTimestampAt && this.options?.timestamp;
398
- const result = includeTimestamp ? this.formatTimestampDiff(Date.now() - this.lastTimestampAt) : "";
399
- this.lastTimestampAt = Date.now();
400
- return result;
401
- }
402
- formatTimestampDiff(timestampDiff) {
403
- const formattedDiff = ` +${timestampDiff}ms`;
404
- return this.options.colors ? yellow(formattedDiff) : formattedDiff;
405
- }
406
- getInspectOptions() {
407
- let breakLength = this.options.breakLength;
408
- if (typeof breakLength === "undefined") {
409
- breakLength = this.options.colors ? this.options.compact ? Infinity : void 0 : this.options.compact === false ? void 0 : Infinity;
410
- }
411
- const inspectOptions = {
412
- depth: this.options.depth ?? DEFAULT_DEPTH,
413
- sorted: this.options.sorted,
414
- showHidden: this.options.showHidden,
415
- compact: this.options.compact ?? (this.options.json ? true : false),
416
- colors: this.options.colors,
417
- breakLength
418
- };
419
- if (this.options.maxArrayLength) {
420
- inspectOptions.maxArrayLength = this.options.maxArrayLength;
421
- }
422
- if (this.options.maxStringLength) {
423
- inspectOptions.maxStringLength = this.options.maxStringLength;
424
- }
425
- return inspectOptions;
426
- }
427
- stringifyReplacer(key, value) {
428
- if (typeof value === "bigint") {
429
- return value.toString();
430
- }
431
- if (typeof value === "symbol") {
432
- return value.toString();
433
- }
434
- if (value instanceof Map || value instanceof Set || value instanceof Error) {
435
- return `${inspect(value, this.inspectOptions)}`;
436
- }
437
- return value;
438
- }
439
- getContextAndMessagesToPrint(args) {
440
- if (args?.length <= 1) {
441
- return { messages: args, context: this.context };
442
- }
443
- const lastElement = args[args.length - 1];
444
- const isContext = isString(lastElement);
445
- if (!isContext) {
446
- return { messages: args, context: this.context };
447
- }
448
- return {
449
- context: lastElement,
450
- messages: args.slice(0, args.length - 1)
451
- };
452
- }
453
- getContextAndStackAndMessagesToPrint(args) {
454
- if (args.length === 2) {
455
- return this.isStackFormat(args[1]) ? {
456
- messages: [args[0]],
457
- stack: args[1],
458
- context: this.context
459
- } : {
460
- messages: [args[0]],
461
- context: args[1]
462
- };
463
- }
464
- const { messages, context } = this.getContextAndMessagesToPrint(args);
465
- if (messages?.length <= 1) {
466
- return { messages, context };
467
- }
468
- const lastElement = messages[messages.length - 1];
469
- const isStack = isString(lastElement);
470
- if (!isStack && !isUndefined(lastElement)) {
471
- return { messages, context };
472
- }
473
- return {
474
- stack: lastElement,
475
- messages: messages.slice(0, messages.length - 1),
476
- context
477
- };
478
- }
479
- isStackFormat(stack) {
480
- if (!isString(stack) && !isUndefined(stack)) {
481
- return false;
482
- }
483
- return /^(.)+\n\s+at .+:\d+:\d+/.test(stack);
484
- }
485
- getColorByLogLevel(level) {
486
- switch (level) {
487
- case "debug":
488
- return clc.magentaBright;
489
- case "warn":
490
- return clc.yellow;
491
- case "error":
492
- return clc.red;
493
- case "verbose":
494
- return clc.cyanBright;
495
- case "fatal":
496
- return clc.bold;
497
- default:
498
- return clc.green;
499
- }
500
- }
501
- };
502
- _init = __decoratorStart();
503
- ConsoleLogger = __decorateElement(_init, 0, "ConsoleLogger", _ConsoleLogger_decorators, ConsoleLogger);
504
- __runInitializers(_init, 1, ConsoleLogger);
505
- var _LoggerInstance_decorators, _init2;
506
- _LoggerInstance_decorators = [Injectable({
507
- token: Logger
508
- })];
509
- var LoggerInstance = class {
510
- localInstance = inject(LoggerOutput);
511
- context;
512
- constructor(config = {}) {
513
- this.context = config.context;
514
- }
515
- error(message, ...optionalParams) {
516
- optionalParams = this.context ? (optionalParams.length ? optionalParams : [void 0]).concat(
517
- this.context
518
- ) : optionalParams;
519
- this.localInstance?.error(message, ...optionalParams);
520
- }
521
- log(message, ...optionalParams) {
522
- optionalParams = this.context ? optionalParams.concat(this.context) : optionalParams;
523
- this.localInstance?.log(message, ...optionalParams);
524
- }
525
- warn(message, ...optionalParams) {
526
- optionalParams = this.context ? optionalParams.concat(this.context) : optionalParams;
527
- this.localInstance?.warn(message, ...optionalParams);
528
- }
529
- debug(message, ...optionalParams) {
530
- optionalParams = this.context ? optionalParams.concat(this.context) : optionalParams;
531
- this.localInstance?.debug?.(message, ...optionalParams);
532
- }
533
- verbose(message, ...optionalParams) {
534
- optionalParams = this.context ? optionalParams.concat(this.context) : optionalParams;
535
- this.localInstance?.verbose?.(message, ...optionalParams);
536
- }
537
- fatal(message, ...optionalParams) {
538
- optionalParams = this.context ? optionalParams.concat(this.context) : optionalParams;
539
- this.localInstance?.fatal?.(message, ...optionalParams);
540
- }
541
- };
542
- _init2 = __decoratorStart();
543
- LoggerInstance = __decorateElement(_init2, 0, "LoggerInstance", _LoggerInstance_decorators, LoggerInstance);
544
- __runInitializers(_init2, 1, LoggerInstance);
545
-
546
- // src/config/config.service.mts
547
- var ConfigServiceOptionsSchema = z$1.record(z$1.string(), z$1.unknown());
548
- var ConfigServiceToken = InjectionToken.create(/* @__PURE__ */ Symbol.for("ConfigService"), ConfigServiceOptionsSchema);
549
- var _ConfigService_decorators, _init3;
550
- _ConfigService_decorators = [Injectable({
551
- token: ConfigServiceToken
552
- })];
553
- var _ConfigService = class _ConfigService {
554
- constructor(config = {}) {
555
- this.config = config;
556
- }
557
- logger = inject(Logger, {
558
- context: _ConfigService.name
559
- });
560
- getConfig() {
561
- return this.config;
562
- }
563
- get(key) {
564
- try {
565
- const parts = String(key).split(".");
566
- let value = this.config;
567
- for (const part of parts) {
568
- if (value === null || value === void 0 || typeof value !== "object") {
569
- return null;
570
- }
571
- value = value[part];
572
- }
573
- return value ?? null;
574
- } catch (error) {
575
- this.logger.debug?.(
576
- `Failed to get config value for key ${String(key)}`,
577
- error
578
- );
579
- return null;
580
- }
581
- }
582
- getOrDefault(key, defaultValue) {
583
- const value = this.get(key);
584
- return value !== null ? value : defaultValue;
585
- }
586
- getOrThrow(key, errorMessage) {
587
- const value = this.get(key);
588
- if (value === null) {
589
- const message = errorMessage || `Configuration value for key "${String(key)}" is not defined`;
590
- this.logger.error(message);
591
- throw new NaviosException(message);
592
- }
593
- return value;
594
- }
595
- };
596
- _init3 = __decoratorStart();
597
- _ConfigService = __decorateElement(_init3, 0, "ConfigService", _ConfigService_decorators, _ConfigService);
598
- __runInitializers(_init3, 1, _ConfigService);
599
- var ConfigService = _ConfigService;
600
-
601
- // src/config/config.provider.mts
602
- var ConfigProviderOptions = z$1.object({
603
- load: z$1.function({ output: ConfigServiceOptionsSchema })
604
- });
605
- function provideConfig(options) {
606
- return InjectionToken.factory(ConfigServiceToken, async () => options.load());
607
- }
608
- var EnvConfigProvider = InjectionToken.bound(ConfigServiceToken, {
609
- ...env
610
- });
611
-
612
- // src/metadata/handler.metadata.mts
613
- var EndpointMetadataKey = /* @__PURE__ */ Symbol("EndpointMetadataKey");
614
- function getAllEndpointMetadata(context) {
615
- if (context.metadata) {
616
- const metadata = context.metadata[EndpointMetadataKey];
617
- if (metadata) {
618
- return metadata;
619
- } else {
620
- context.metadata[EndpointMetadataKey] = /* @__PURE__ */ new Set();
621
- return context.metadata[EndpointMetadataKey];
622
- }
623
- }
624
- throw new Error("[Navios] Wrong environment.");
625
- }
626
- function getEndpointMetadata(target, context) {
627
- if (context.metadata) {
628
- const metadata = getAllEndpointMetadata(context);
629
- if (metadata) {
630
- const endpointMetadata = Array.from(metadata).find(
631
- (item) => item.classMethod === target.name
632
- );
633
- if (endpointMetadata) {
634
- return endpointMetadata;
635
- } else {
636
- const newMetadata = {
637
- classMethod: target.name,
638
- url: "",
639
- successStatusCode: 200,
640
- adapterToken: null,
641
- headers: {},
642
- httpMethod: "GET",
643
- // @ts-expect-error We are using a generic type here
644
- config: null,
645
- guards: /* @__PURE__ */ new Set(),
646
- customAttributes: /* @__PURE__ */ new Map()
647
- };
648
- metadata.add(newMetadata);
649
- return newMetadata;
650
- }
651
- }
652
- }
653
- throw new Error("[Navios] Wrong environment.");
654
- }
655
-
656
- // src/metadata/controller.metadata.mts
657
- var ControllerMetadataKey = /* @__PURE__ */ Symbol("ControllerMetadataKey");
658
- function getControllerMetadata(target, context) {
659
- if (context.metadata) {
660
- const metadata = context.metadata[ControllerMetadataKey];
661
- if (metadata) {
662
- return metadata;
663
- } else {
664
- const endpointsMetadata = getAllEndpointMetadata(context);
665
- const newMetadata = {
666
- endpoints: endpointsMetadata,
667
- guards: /* @__PURE__ */ new Set(),
668
- customAttributes: /* @__PURE__ */ new Map()
669
- };
670
- context.metadata[ControllerMetadataKey] = newMetadata;
671
- target[ControllerMetadataKey] = newMetadata;
672
- return newMetadata;
673
- }
674
- }
675
- throw new Error("[Navios] Wrong environment.");
676
- }
677
- function extractControllerMetadata(target) {
678
- const metadata = target[ControllerMetadataKey];
679
- if (!metadata) {
680
- throw new Error(
681
- "[Navios] Controller metadata not found. Make sure to use @Controller decorator."
682
- );
683
- }
684
- return metadata;
685
- }
686
- function hasControllerMetadata(target) {
687
- const metadata = target[ControllerMetadataKey];
688
- return !!metadata;
689
- }
690
-
691
- // src/metadata/module.metadata.mts
692
- var ModuleMetadataKey = /* @__PURE__ */ Symbol("ControllerMetadataKey");
693
- function getModuleMetadata(target, context) {
694
- if (context.metadata) {
695
- const metadata = context.metadata[ModuleMetadataKey];
696
- if (metadata) {
697
- return metadata;
698
- } else {
699
- const newMetadata = {
700
- controllers: /* @__PURE__ */ new Set(),
701
- imports: /* @__PURE__ */ new Set(),
702
- guards: /* @__PURE__ */ new Set(),
703
- customAttributes: /* @__PURE__ */ new Map()
704
- };
705
- context.metadata[ModuleMetadataKey] = newMetadata;
706
- target[ModuleMetadataKey] = newMetadata;
707
- return newMetadata;
708
- }
709
- }
710
- throw new Error("[Navios] Wrong environment.");
711
- }
712
- function extractModuleMetadata(target) {
713
- const metadata = target[ModuleMetadataKey];
714
- if (!metadata) {
715
- throw new Error(
716
- `[Navios] Module metadata not found for ${target.name}. Make sure to use @Module decorator.`
717
- );
718
- }
719
- return metadata;
720
- }
721
- function hasModuleMetadata(target) {
722
- return !!target[ModuleMetadataKey];
723
- }
724
-
725
- // src/decorators/controller.decorator.mts
726
- function Controller({ guards } = {}) {
727
- return function(target, context) {
728
- if (context.kind !== "class") {
729
- throw new Error(
730
- "[Navios] @Controller decorator can only be used on classes."
731
- );
732
- }
733
- const token = InjectionToken.create(target);
734
- if (context.metadata) {
735
- const controllerMetadata = getControllerMetadata(target, context);
736
- if (guards) {
737
- for (const guard of Array.from(guards).reverse()) {
738
- controllerMetadata.guards.add(guard);
739
- }
740
- }
741
- }
742
- return Injectable({
743
- token,
744
- scope: InjectableScope.Request
745
- })(target, context);
746
- };
747
- }
748
- var EndpointAdapterToken = InjectionToken.create(
749
- "EndpointAdapterToken"
750
- );
751
- var ExecutionContextInjectionToken = "ExecutionContextInjectionToken";
752
- var ExecutionContext = InjectionToken.create(
753
- ExecutionContextInjectionToken
754
- );
755
- var HttpAdapterToken = InjectionToken.create(
756
- "HttpAdapterToken"
757
- );
758
- var MultipartAdapterToken = InjectionToken.create(
759
- "MultipartAdapterToken"
760
- );
761
- var Reply = InjectionToken.create("ReplyToken");
762
- var Request = InjectionToken.create("RequestToken");
763
- var StreamAdapterToken = InjectionToken.create(
764
- "StreamAdapterToken"
765
- );
766
- var XmlStreamAdapterToken = InjectionToken.create(
767
- "XmlStreamAdapterToken"
768
- );
769
-
770
- // src/decorators/endpoint.decorator.mts
771
- function Endpoint(endpoint) {
772
- return (target, context) => {
773
- if (context.kind !== "method") {
774
- throw new Error(
775
- "[Navios] Endpoint decorator can only be used on methods."
776
- );
777
- }
778
- const config = endpoint.config;
779
- if (context.metadata) {
780
- let endpointMetadata = getEndpointMetadata(
781
- target,
782
- context
783
- );
784
- if (endpointMetadata.config && endpointMetadata.config.url) {
785
- throw new Error(
786
- `[Navios] Endpoint ${config.method} ${config.url} already exists. Please use a different method or url.`
787
- );
788
- }
789
- endpointMetadata.config = config;
790
- endpointMetadata.adapterToken = EndpointAdapterToken;
791
- endpointMetadata.classMethod = target.name;
792
- endpointMetadata.httpMethod = config.method;
793
- endpointMetadata.url = config.url;
794
- }
795
- return target;
796
- };
797
- }
798
-
799
- // src/decorators/header.decorator.mts
800
- function Header(name, value) {
801
- return (target, context) => {
802
- if (context.kind !== "method") {
803
- throw new Error("[Navios] Header decorator can only be used on methods.");
804
- }
805
- const metadata = getEndpointMetadata(target, context);
806
- metadata.headers[name] = value;
807
- return target;
808
- };
809
- }
810
-
811
- // src/decorators/http-code.decorator.mts
812
- function HttpCode(code) {
813
- return (target, context) => {
814
- if (context.kind !== "method") {
815
- throw new Error(
816
- "[Navios] HttpCode decorator can only be used on methods."
817
- );
818
- }
819
- const metadata = getEndpointMetadata(target, context);
820
- metadata.successStatusCode = code;
821
- return target;
822
- };
823
- }
824
- function Module({ controllers = [], imports = [], guards = [] } = {
825
- controllers: [],
826
- imports: [],
827
- guards: []
828
- }) {
829
- return (target, context) => {
830
- if (context.kind !== "class") {
831
- throw new Error("[Navios] @Module decorator can only be used on classes.");
832
- }
833
- const token = InjectionToken.create(target);
834
- const moduleMetadata = getModuleMetadata(target, context);
835
- for (const controller of controllers) {
836
- moduleMetadata.controllers.add(controller);
837
- }
838
- for (const importedModule of imports) {
839
- moduleMetadata.imports.add(importedModule);
840
- }
841
- for (const guard of Array.from(guards).reverse()) {
842
- moduleMetadata.guards.add(guard);
843
- }
844
- return Injectable({
845
- token,
846
- scope: InjectableScope.Singleton
847
- })(target, context);
848
- };
849
- }
850
- function Multipart(endpoint) {
851
- return (target, context) => {
852
- if (typeof target !== "function") {
853
- throw new Error(
854
- "[Navios] Endpoint decorator can only be used on functions."
855
- );
856
- }
857
- if (context.kind !== "method") {
858
- throw new Error(
859
- "[Navios] Endpoint decorator can only be used on methods."
860
- );
861
- }
862
- const config = endpoint.config;
863
- if (context.metadata) {
864
- let endpointMetadata = getEndpointMetadata(
865
- target,
866
- context
867
- );
868
- if (endpointMetadata.config && endpointMetadata.config.url) {
869
- throw new Error(
870
- `[Navios] Endpoint ${config.method} ${config.url} already exists. Please use a different method or url.`
871
- );
872
- }
873
- endpointMetadata.config = config;
874
- endpointMetadata.adapterToken = MultipartAdapterToken;
875
- endpointMetadata.classMethod = target.name;
876
- endpointMetadata.httpMethod = config.method;
877
- endpointMetadata.url = config.url;
878
- }
879
- return target;
880
- };
881
- }
882
-
883
- // src/decorators/stream.decorator.mts
884
- function Stream(endpoint) {
885
- return (target, context) => {
886
- if (typeof target !== "function") {
887
- throw new Error(
888
- "[Navios] Endpoint decorator can only be used on functions."
889
- );
890
- }
891
- if (context.kind !== "method") {
892
- throw new Error(
893
- "[Navios] Endpoint decorator can only be used on methods."
894
- );
895
- }
896
- const config = endpoint.config;
897
- if (context.metadata) {
898
- let endpointMetadata = getEndpointMetadata(
899
- target,
900
- context
901
- );
902
- if (endpointMetadata.config && endpointMetadata.config.url) {
903
- throw new Error(
904
- `[Navios] Endpoint ${config.method} ${config.url} already exists. Please use a different method or url.`
905
- );
906
- }
907
- endpointMetadata.config = config;
908
- endpointMetadata.adapterToken = StreamAdapterToken;
909
- endpointMetadata.classMethod = target.name;
910
- endpointMetadata.httpMethod = config.method;
911
- endpointMetadata.url = config.url;
912
- }
913
- return target;
914
- };
915
- }
916
-
917
- // src/decorators/use-guards.decorator.mts
918
- function UseGuards(...guards) {
919
- return function(target, context) {
920
- if (context.kind === "class") {
921
- const controllerMetadata = getControllerMetadata(
922
- target,
923
- context
924
- );
925
- for (const guard of guards.reverse()) {
926
- controllerMetadata.guards.add(guard);
927
- }
928
- } else if (context.kind === "method") {
929
- const endpointMetadata = getEndpointMetadata(target, context);
930
- for (const guard of guards.reverse()) {
931
- endpointMetadata.guards.add(guard);
932
- }
933
- } else {
934
- throw new Error(
935
- "[Navios] @UseGuards decorator can only be used on classes or methods."
936
- );
937
- }
938
- return target;
939
- };
940
- }
941
-
942
- // src/exceptions/http.exception.mts
943
- var HttpException = class {
944
- constructor(statusCode, response, error) {
945
- this.statusCode = statusCode;
946
- this.response = response;
947
- this.error = error;
948
- }
949
- };
950
-
951
- // src/exceptions/bad-request.exception.mts
952
- var BadRequestException = class extends HttpException {
953
- constructor(message) {
954
- super(400, message);
955
- }
956
- };
957
-
958
- // src/exceptions/forbidden.exception.mts
959
- var ForbiddenException = class extends HttpException {
960
- constructor(message) {
961
- super(403, message);
962
- }
963
- };
964
-
965
- // src/exceptions/internal-server-error.exception.mts
966
- var InternalServerErrorException = class extends HttpException {
967
- constructor(message, error) {
968
- super(500, message, error);
969
- }
970
- };
971
-
972
- // src/exceptions/not-found.exception.mts
973
- var NotFoundException = class extends HttpException {
974
- constructor(response, error) {
975
- super(404, response, error);
976
- this.response = response;
977
- this.error = error;
978
- }
979
- };
980
-
981
- // src/exceptions/unauthorized.exception.mts
982
- var UnauthorizedException = class extends HttpException {
983
- constructor(message, error) {
984
- super(401, message, error);
985
- }
986
- };
987
-
988
- // src/exceptions/conflict.exception.mts
989
- var ConflictException = class extends HttpException {
990
- constructor(message, error) {
991
- super(409, message, error);
992
- }
993
- };
994
- var _GuardRunnerService_decorators, _init4;
995
- _GuardRunnerService_decorators = [Injectable()];
996
- var GuardRunnerService = class {
997
- container = inject(Container);
998
- async runGuards(allGuards, executionContext) {
999
- let canActivate = true;
1000
- for (const guard of Array.from(allGuards).reverse()) {
1001
- const guardInstance = await this.container.get(
1002
- guard
1003
- );
1004
- if (!guardInstance.canActivate) {
1005
- throw new Error(
1006
- `[Navios] Guard ${guard.name} does not implement canActivate()`
1007
- );
1008
- }
1009
- try {
1010
- canActivate = await guardInstance.canActivate(executionContext);
1011
- if (!canActivate) {
1012
- break;
1013
- }
1014
- } catch (error) {
1015
- if (error instanceof HttpException) {
1016
- executionContext.getReply().status(error.statusCode).send(error.response);
1017
- return false;
1018
- } else {
1019
- executionContext.getReply().status(500).send({
1020
- message: "Internal server error",
1021
- error: error.message
1022
- });
1023
- return false;
1024
- }
1025
- }
1026
- }
1027
- if (!canActivate) {
1028
- executionContext.getReply().status(403).send({
1029
- message: "Forbidden"
1030
- });
1031
- return false;
1032
- }
1033
- return canActivate;
1034
- }
1035
- makeContext(moduleMetadata, controllerMetadata, endpoint) {
1036
- const guards = /* @__PURE__ */ new Set();
1037
- const endpointGuards = endpoint.guards;
1038
- const controllerGuards = controllerMetadata.guards;
1039
- const moduleGuards = moduleMetadata.guards;
1040
- if (endpointGuards.size > 0) {
1041
- for (const guard of endpointGuards) {
1042
- guards.add(guard);
1043
- }
1044
- }
1045
- if (controllerGuards.size > 0) {
1046
- for (const guard of controllerGuards) {
1047
- guards.add(guard);
1048
- }
1049
- }
1050
- if (moduleGuards.size > 0) {
1051
- for (const guard of moduleGuards) {
1052
- guards.add(guard);
1053
- }
1054
- }
1055
- return guards;
1056
- }
1057
- };
1058
- _init4 = __decoratorStart();
1059
- GuardRunnerService = __decorateElement(_init4, 0, "GuardRunnerService", _GuardRunnerService_decorators, GuardRunnerService);
1060
- __runInitializers(_init4, 1, GuardRunnerService);
1061
- var _ModuleLoaderService_decorators, _init5;
1062
- _ModuleLoaderService_decorators = [Injectable()];
1063
- var _ModuleLoaderService = class _ModuleLoaderService {
1064
- logger = inject(Logger, {
1065
- context: _ModuleLoaderService.name
1066
- });
1067
- container = inject(Container);
1068
- modulesMetadata = /* @__PURE__ */ new Map();
1069
- loadedModules = /* @__PURE__ */ new Map();
1070
- initialized = false;
1071
- async loadModules(appModule) {
1072
- if (this.initialized) {
1073
- return;
1074
- }
1075
- await this.traverseModules(appModule);
1076
- this.initialized = true;
1077
- }
1078
- async traverseModules(module, parentMetadata) {
1079
- const metadata = extractModuleMetadata(module);
1080
- if (parentMetadata) {
1081
- this.mergeMetadata(metadata, parentMetadata);
1082
- }
1083
- const moduleName = module.name;
1084
- if (this.modulesMetadata.has(moduleName)) {
1085
- return;
1086
- }
1087
- this.modulesMetadata.set(moduleName, metadata);
1088
- const imports = metadata.imports ?? /* @__PURE__ */ new Set();
1089
- const loadingPromises = Array.from(imports).map(
1090
- async (importedModule) => this.traverseModules(importedModule, metadata)
1091
- );
1092
- await Promise.all(loadingPromises);
1093
- const instance = await this.container.get(module);
1094
- if (instance.onModuleInit) {
1095
- await instance.onModuleInit();
1096
- }
1097
- this.logger.debug(`Module ${moduleName} loaded`);
1098
- this.loadedModules.set(moduleName, instance);
1099
- }
1100
- mergeMetadata(metadata, parentMetadata) {
1101
- if (parentMetadata.guards) {
1102
- for (const guard of parentMetadata.guards) {
1103
- metadata.guards.add(guard);
1104
- }
1105
- }
1106
- if (parentMetadata.customAttributes) {
1107
- for (const [key, value] of parentMetadata.customAttributes) {
1108
- if (metadata.customAttributes.has(key)) {
1109
- continue;
1110
- }
1111
- metadata.customAttributes.set(key, value);
1112
- }
1113
- }
1114
- }
1115
- getAllModules() {
1116
- return this.modulesMetadata;
1117
- }
1118
- dispose() {
1119
- this.modulesMetadata.clear();
1120
- this.loadedModules.clear();
1121
- this.initialized = false;
1122
- }
1123
- };
1124
- _init5 = __decoratorStart();
1125
- _ModuleLoaderService = __decorateElement(_init5, 0, "ModuleLoaderService", _ModuleLoaderService_decorators, _ModuleLoaderService);
1126
- __runInitializers(_init5, 1, _ModuleLoaderService);
1127
- var ModuleLoaderService = _ModuleLoaderService;
1128
-
1129
- // src/attribute.factory.mts
1130
- var AttributeFactory = class {
1131
- static createAttribute(token, schema) {
1132
- const res = (value) => (target, context) => {
1133
- if (context.kind !== "class" && context.kind !== "method") {
1134
- throw new Error(
1135
- "[Navios] Attribute can only be applied to classes or methods"
1136
- );
1137
- }
1138
- const isController = context.kind === "class" && hasControllerMetadata(target);
1139
- const isModule = context.kind === "class" && hasModuleMetadata(target);
1140
- if (context.kind === "class" && !isController && !isModule) {
1141
- throw new Error(
1142
- "[Navios] Attribute can only be applied to classes with @Controller or @Module decorators"
1143
- );
1144
- }
1145
- let metadata = context.kind === "class" ? isController ? getControllerMetadata(target, context) : getModuleMetadata(target, context) : getEndpointMetadata(target, context);
1146
- if (schema) {
1147
- const validatedValue = schema.safeParse(value);
1148
- if (!validatedValue.success) {
1149
- throw new Error(
1150
- `[Navios] Invalid value for attribute ${token.toString()}: ${validatedValue.error}`
1151
- );
1152
- }
1153
- metadata.customAttributes.set(token, validatedValue.data);
1154
- } else {
1155
- metadata.customAttributes.set(token, true);
1156
- }
1157
- return target;
1158
- };
1159
- res.token = token;
1160
- if (schema) {
1161
- res.schema = schema;
1162
- }
1163
- return res;
1164
- }
1165
- static get(attribute, target) {
1166
- return target.customAttributes.get(attribute.token) ?? null;
1167
- }
1168
- static getAll(attribute, target) {
1169
- const values = Array.from(target.customAttributes.entries()).filter(([key]) => key === attribute.token).map(([, value]) => value);
1170
- return values.length > 0 ? values : null;
1171
- }
1172
- static getLast(attribute, target) {
1173
- for (let i = target.length - 1; i >= 0; i--) {
1174
- const value = target[i].customAttributes.get(attribute.token);
1175
- if (value) {
1176
- return value;
1177
- }
1178
- }
1179
- return null;
1180
- }
1181
- static has(attribute, target) {
1182
- return target.customAttributes.has(attribute.token);
1183
- }
1184
- };
1185
- var _NaviosEnvironment_decorators, _init6;
1186
- _NaviosEnvironment_decorators = [Injectable()];
1187
- var NaviosEnvironment = class {
1188
- httpTokens = /* @__PURE__ */ new Map();
1189
- setupHttpEnvironment(tokens) {
1190
- this.httpTokens = tokens;
1191
- }
1192
- getHttpToken(token) {
1193
- return this.httpTokens.get(token);
1194
- }
1195
- hasHttpSetup() {
1196
- return this.httpTokens.size > 0;
1197
- }
1198
- };
1199
- _init6 = __decoratorStart();
1200
- NaviosEnvironment = __decorateElement(_init6, 0, "NaviosEnvironment", _NaviosEnvironment_decorators, NaviosEnvironment);
1201
- __runInitializers(_init6, 1, NaviosEnvironment);
1202
-
1203
- // src/factories/endpoint-adapter.factory.mts
1204
- var _EndpointAdapterFactory_decorators, _init7;
1205
- _EndpointAdapterFactory_decorators = [Factory({
1206
- token: EndpointAdapterToken
1207
- })];
1208
- var EndpointAdapterFactory = class {
1209
- environment = inject(NaviosEnvironment);
1210
- create(ctx) {
1211
- const service = this.environment.getHttpToken(EndpointAdapterToken);
1212
- if (!service) {
1213
- throw new Error("EndpointAdapterToken service not found in environment");
1214
- }
1215
- return ctx.inject(service);
1216
- }
1217
- };
1218
- _init7 = __decoratorStart();
1219
- EndpointAdapterFactory = __decorateElement(_init7, 0, "EndpointAdapterFactory", _EndpointAdapterFactory_decorators, EndpointAdapterFactory);
1220
- __runInitializers(_init7, 1, EndpointAdapterFactory);
1221
- var _HttpAdapterFactory_decorators, _init8;
1222
- _HttpAdapterFactory_decorators = [Factory({
1223
- token: HttpAdapterToken
1224
- })];
1225
- var HttpAdapterFactory = class {
1226
- environment = inject(NaviosEnvironment);
1227
- create(ctx) {
1228
- const service = this.environment.getHttpToken(HttpAdapterToken);
1229
- if (!service) {
1230
- throw new Error("HttpAdapterToken service not found in environment");
1231
- }
1232
- return ctx.inject(service);
1233
- }
1234
- };
1235
- _init8 = __decoratorStart();
1236
- HttpAdapterFactory = __decorateElement(_init8, 0, "HttpAdapterFactory", _HttpAdapterFactory_decorators, HttpAdapterFactory);
1237
- __runInitializers(_init8, 1, HttpAdapterFactory);
1238
- var _MultipartAdapterFactory_decorators, _init9;
1239
- _MultipartAdapterFactory_decorators = [Factory({
1240
- token: MultipartAdapterToken
1241
- })];
1242
- var MultipartAdapterFactory = class {
1243
- environment = inject(NaviosEnvironment);
1244
- create(ctx) {
1245
- const service = this.environment.getHttpToken(MultipartAdapterToken);
1246
- if (!service) {
1247
- throw new Error("MultipartAdapterToken service not found in environment");
1248
- }
1249
- return ctx.inject(service);
1250
- }
1251
- };
1252
- _init9 = __decoratorStart();
1253
- MultipartAdapterFactory = __decorateElement(_init9, 0, "MultipartAdapterFactory", _MultipartAdapterFactory_decorators, MultipartAdapterFactory);
1254
- __runInitializers(_init9, 1, MultipartAdapterFactory);
1255
- var _RequestFactory_decorators, _init10;
1256
- _RequestFactory_decorators = [Factory({
1257
- token: Request,
1258
- scope: InjectableScope.Request
1259
- })];
1260
- var RequestFactory = class {
1261
- environment = inject(NaviosEnvironment);
1262
- create(ctx) {
1263
- const service = this.environment.getHttpToken(Request);
1264
- if (!service) {
1265
- throw new Error("RequestToken service not found in environment");
1266
- }
1267
- return ctx.inject(service);
1268
- }
1269
- };
1270
- _init10 = __decoratorStart();
1271
- RequestFactory = __decorateElement(_init10, 0, "RequestFactory", _RequestFactory_decorators, RequestFactory);
1272
- __runInitializers(_init10, 1, RequestFactory);
1273
- var _ReplyFactory_decorators, _init11;
1274
- _ReplyFactory_decorators = [Factory({
1275
- token: Reply,
1276
- scope: InjectableScope.Request
1277
- })];
1278
- var ReplyFactory = class {
1279
- environment = inject(NaviosEnvironment);
1280
- create(ctx) {
1281
- const service = this.environment.getHttpToken(Reply);
1282
- if (!service) {
1283
- throw new Error("ReplyToken service not found in environment");
1284
- }
1285
- return ctx.inject(service);
1286
- }
1287
- };
1288
- _init11 = __decoratorStart();
1289
- ReplyFactory = __decorateElement(_init11, 0, "ReplyFactory", _ReplyFactory_decorators, ReplyFactory);
1290
- __runInitializers(_init11, 1, ReplyFactory);
1291
- var _StreamAdapterFactory_decorators, _init12;
1292
- _StreamAdapterFactory_decorators = [Factory({
1293
- token: StreamAdapterToken
1294
- })];
1295
- var StreamAdapterFactory = class {
1296
- environment = inject(NaviosEnvironment);
1297
- create(ctx) {
1298
- const service = this.environment.getHttpToken(StreamAdapterToken);
1299
- if (!service) {
1300
- throw new Error("StreamAdapterToken service not found in environment");
1301
- }
1302
- return ctx.inject(service);
1303
- }
1304
- };
1305
- _init12 = __decoratorStart();
1306
- StreamAdapterFactory = __decorateElement(_init12, 0, "StreamAdapterFactory", _StreamAdapterFactory_decorators, StreamAdapterFactory);
1307
- __runInitializers(_init12, 1, StreamAdapterFactory);
1308
- var _XmlStreamAdapterFactory_decorators, _init13;
1309
- _XmlStreamAdapterFactory_decorators = [Factory({
1310
- token: XmlStreamAdapterToken
1311
- })];
1312
- var XmlStreamAdapterFactory = class {
1313
- environment = inject(NaviosEnvironment);
1314
- create(ctx) {
1315
- const service = this.environment.getHttpToken(XmlStreamAdapterToken);
1316
- if (!service) {
1317
- throw new Error("XmlStreamAdapterToken service not found in environment");
1318
- }
1319
- return ctx.inject(service);
1320
- }
1321
- };
1322
- _init13 = __decoratorStart();
1323
- XmlStreamAdapterFactory = __decorateElement(_init13, 0, "XmlStreamAdapterFactory", _XmlStreamAdapterFactory_decorators, XmlStreamAdapterFactory);
1324
- __runInitializers(_init13, 1, XmlStreamAdapterFactory);
1325
- var _NaviosApplication_decorators, _init14;
1326
- _NaviosApplication_decorators = [Injectable()];
1327
- var _NaviosApplication = class _NaviosApplication {
1328
- environment = inject(NaviosEnvironment);
1329
- moduleLoader = inject(ModuleLoaderService);
1330
- httpApplication = null;
1331
- logger = inject(Logger, {
1332
- context: _NaviosApplication.name
1333
- });
1334
- container = inject(Container);
1335
- appModule = null;
1336
- options = {
1337
- adapter: []
1338
- };
1339
- isInitialized = false;
1340
- async setup(appModule, options = {
1341
- adapter: []
1342
- }) {
1343
- this.appModule = appModule;
1344
- this.options = options;
1345
- if (this.environment.hasHttpSetup()) {
1346
- this.httpApplication = await this.container.get(HttpAdapterToken);
1347
- }
1348
- }
1349
- getContainer() {
1350
- return this.container;
1351
- }
1352
- async init() {
1353
- if (!this.appModule) {
1354
- throw new Error("App module is not set. Call setAppModule() first.");
1355
- }
1356
- await this.moduleLoader.loadModules(this.appModule);
1357
- if (this.environment.hasHttpSetup()) {
1358
- await this.httpApplication?.setupHttpServer(this.options);
1359
- }
1360
- await this.initModules();
1361
- if (this.environment.hasHttpSetup()) {
1362
- await this.httpApplication?.ready();
1363
- }
1364
- this.isInitialized = true;
1365
- this.logger.debug("Navios application initialized");
1366
- }
1367
- async initModules() {
1368
- const modules = this.moduleLoader.getAllModules();
1369
- await this.httpApplication?.onModulesInit(modules);
1370
- }
1371
- enableCors(options) {
1372
- if (!this.httpApplication) {
1373
- throw new Error("HTTP application is not set");
1374
- }
1375
- this.httpApplication.enableCors(options);
1376
- }
1377
- enableMultipart(options) {
1378
- if (!this.httpApplication) {
1379
- throw new Error("HTTP application is not set");
1380
- }
1381
- this.httpApplication.enableMultipart(options);
1382
- }
1383
- setGlobalPrefix(prefix) {
1384
- if (!this.httpApplication) {
1385
- throw new Error("HTTP application is not set");
1386
- }
1387
- this.httpApplication.setGlobalPrefix(prefix);
1388
- }
1389
- getServer() {
1390
- if (!this.httpApplication) {
1391
- throw new Error("HTTP application is not set");
1392
- }
1393
- return this.httpApplication.getServer();
1394
- }
1395
- async listen(options) {
1396
- if (!this.httpApplication) {
1397
- throw new Error("HTTP application is not set");
1398
- }
1399
- await this.httpApplication.listen(options);
1400
- }
1401
- async dispose() {
1402
- if (this.httpApplication) {
1403
- await this.httpApplication.dispose();
1404
- }
1405
- if (this.moduleLoader) {
1406
- this.moduleLoader.dispose();
1407
- }
1408
- }
1409
- async close() {
1410
- await this.dispose();
1411
- }
1412
- };
1413
- _init14 = __decoratorStart();
1414
- _NaviosApplication = __decorateElement(_init14, 0, "NaviosApplication", _NaviosApplication_decorators, _NaviosApplication);
1415
- __runInitializers(_init14, 1, _NaviosApplication);
1416
- var NaviosApplication = _NaviosApplication;
1417
- var NaviosFactory = class {
1418
- static async create(appModule, options = {
1419
- adapter: []
1420
- }) {
1421
- const container = new Container();
1422
- await this.registerLoggerConfiguration(container, options);
1423
- const adapters = Array.isArray(options.adapter) ? options.adapter : [options.adapter];
1424
- for (const adapter of adapters) {
1425
- await this.registerEnvironment(container, adapter);
1426
- }
1427
- const app = await container.get(NaviosApplication);
1428
- await app.setup(appModule, options);
1429
- return app;
1430
- }
1431
- static async registerEnvironment(container, environment = {}) {
1432
- const naviosEnvironment = await container.get(NaviosEnvironment);
1433
- const { httpTokens } = environment;
1434
- if (httpTokens) {
1435
- naviosEnvironment.setupHttpEnvironment(httpTokens);
1436
- }
1437
- }
1438
- static async registerLoggerConfiguration(container, options) {
1439
- const { logger } = options;
1440
- if (Array.isArray(logger) || isNil(logger)) {
1441
- const loggerInstance = await container.get(
1442
- LoggerOutput
1443
- );
1444
- loggerInstance?.setup({
1445
- logLevels: logger
1446
- });
1447
- }
1448
- if (logger !== true && !isNil(logger)) {
1449
- container.getServiceLocator().getManager().storeCreatedHolder(
1450
- LoggerOutput.toString(),
1451
- logger,
1452
- InjectableType.Class,
1453
- InjectableScope.Singleton
1454
- );
1455
- }
1456
- }
1457
- };
1458
-
1459
- export { AttributeFactory, BadRequestException, ConfigProviderOptions, ConfigService, ConfigServiceOptionsSchema, ConfigServiceToken, ConflictException, ConsoleLogger, Controller, ControllerMetadataKey, Endpoint, EndpointAdapterFactory, EndpointAdapterToken, EndpointMetadataKey, EnvConfigProvider, ExecutionContext, ExecutionContextInjectionToken, ForbiddenException, GuardRunnerService, Header, HttpAdapterFactory, HttpAdapterToken, HttpCode, HttpException, InternalServerErrorException, LOG_LEVELS, Logger, LoggerInstance, LoggerOutput, Module, ModuleLoaderService, ModuleMetadataKey, Multipart, MultipartAdapterFactory, MultipartAdapterToken, NaviosApplication, NaviosFactory, NotFoundException, Reply, ReplyFactory, Request, RequestFactory, Stream, StreamAdapterFactory, StreamAdapterToken, UnauthorizedException, UseGuards, XmlStreamAdapterFactory, XmlStreamAdapterToken, addLeadingSlash, clc, envInt, envString, extractControllerMetadata, extractModuleMetadata, filterLogLevels, getAllEndpointMetadata, getControllerMetadata, getEndpointMetadata, getModuleMetadata, hasControllerMetadata, hasModuleMetadata, isConstructor, isEmpty, isFunction, isLogLevel, isLogLevelEnabled, isNil, isNumber, isObject, isPlainObject, isString, isSymbol, isUndefined, loggerOptionsSchema, normalizePath, provideConfig, stripEndSlash, yellow };
1460
- //# sourceMappingURL=index.mjs.map
1461
- //# sourceMappingURL=index.mjs.map
6
+ export { AttributeFactory, BadRequestException, ConfigProviderOptions, _ConfigService as ConfigService, ConfigServiceOptionsSchema, ConfigServiceToken, ConflictException, _ConsoleLogger as ConsoleLogger, Controller, ControllerMetadataKey, Endpoint, _EndpointAdapterFactory as EndpointAdapterFactory, EndpointAdapterToken, EndpointMetadataKey, EnvConfigProvider, ExecutionContext, ExecutionContextInjectionToken, ForbiddenException, _GuardRunnerService as GuardRunnerService, Header, _HttpAdapterFactory as HttpAdapterFactory, HttpAdapterToken, HttpCode, HttpException, InternalServerErrorException, LOG_LEVELS, Logger, _LoggerInstance as LoggerInstance, LoggerOutput, Module, _ModuleLoaderService as ModuleLoaderService, ModuleMetadataKey, Multipart, _MultipartAdapterFactory as MultipartAdapterFactory, MultipartAdapterToken, _NaviosApplication as NaviosApplication, NaviosFactory, NotFoundException, Reply, _ReplyFactory as ReplyFactory, Request, _RequestFactory as RequestFactory, Stream, _StreamAdapterFactory as StreamAdapterFactory, StreamAdapterToken, UnauthorizedException, UseGuards, _XmlStreamAdapterFactory as XmlStreamAdapterFactory, XmlStreamAdapterToken, addLeadingSlash, clc, envInt, envString, extractControllerMetadata, extractModuleMetadata, filterLogLevels, getAllEndpointMetadata, getControllerMetadata, getEndpointMetadata, getModuleMetadata, getRequestId, hasControllerMetadata, hasModuleMetadata, isConstructor, isEmpty, isFunction, isLogLevel, isLogLevelEnabled, isNil, isNumber, isObject, isPlainObject, isString, isSymbol, isUndefined, loggerOptionsSchema, normalizePath, provideConfig, requestIdStore, runWithRequestId, stripEndSlash, yellow };