@navios/core 0.4.0 → 0.5.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 (92) hide show
  1. package/README.md +95 -2
  2. package/docs/README.md +310 -3
  3. package/docs/adapters.md +308 -0
  4. package/docs/application-setup.md +524 -0
  5. package/docs/attributes.md +689 -0
  6. package/docs/controllers.md +373 -0
  7. package/docs/endpoints.md +444 -0
  8. package/docs/exceptions.md +316 -0
  9. package/docs/guards.md +550 -0
  10. package/docs/modules.md +377 -0
  11. package/docs/quick-start.md +295 -0
  12. package/docs/services.md +427 -0
  13. package/docs/testing.md +704 -0
  14. package/lib/_tsup-dts-rollup.d.mts +310 -239
  15. package/lib/_tsup-dts-rollup.d.ts +310 -239
  16. package/lib/index.d.mts +51 -28
  17. package/lib/index.d.ts +51 -28
  18. package/lib/index.js +633 -1072
  19. package/lib/index.js.map +1 -1
  20. package/lib/index.mjs +631 -1064
  21. package/lib/index.mjs.map +1 -1
  22. package/package.json +5 -9
  23. package/project.json +9 -1
  24. package/src/__tests__/config.service.spec.mts +11 -9
  25. package/src/__tests__/controller.spec.mts +0 -1
  26. package/src/config/config.service.mts +2 -2
  27. package/src/decorators/controller.decorator.mts +1 -1
  28. package/src/decorators/endpoint.decorator.mts +2 -2
  29. package/src/decorators/header.decorator.mts +1 -1
  30. package/src/decorators/multipart.decorator.mts +1 -2
  31. package/src/decorators/stream.decorator.mts +2 -3
  32. package/src/factories/endpoint-adapter.factory.mts +21 -0
  33. package/src/factories/http-adapter.factory.mts +20 -0
  34. package/src/factories/index.mts +6 -0
  35. package/src/factories/multipart-adapter.factory.mts +21 -0
  36. package/src/factories/reply.factory.mts +21 -0
  37. package/src/factories/request.factory.mts +21 -0
  38. package/src/factories/stream-adapter.factory.mts +20 -0
  39. package/src/index.mts +1 -1
  40. package/src/interfaces/abstract-execution-context.inteface.mts +13 -0
  41. package/src/interfaces/abstract-http-adapter.interface.mts +20 -0
  42. package/src/interfaces/abstract-http-cors-options.interface.mts +59 -0
  43. package/src/interfaces/abstract-http-handler-adapter.interface.mts +13 -0
  44. package/src/interfaces/abstract-http-listen-options.interface.mts +4 -0
  45. package/src/interfaces/can-activate.mts +4 -2
  46. package/src/interfaces/http-header.mts +18 -0
  47. package/src/interfaces/index.mts +6 -0
  48. package/src/logger/console-logger.service.mts +28 -44
  49. package/src/logger/index.mts +1 -2
  50. package/src/logger/logger.service.mts +9 -128
  51. package/src/logger/logger.tokens.mts +21 -0
  52. package/src/metadata/handler.metadata.mts +7 -5
  53. package/src/navios.application.mts +65 -172
  54. package/src/navios.environment.mts +30 -0
  55. package/src/navios.factory.mts +53 -12
  56. package/src/services/guard-runner.service.mts +19 -9
  57. package/src/services/index.mts +0 -2
  58. package/src/services/module-loader.service.mts +4 -3
  59. package/src/tokens/endpoint-adapter.token.mts +8 -0
  60. package/src/tokens/execution-context.token.mts +2 -2
  61. package/src/tokens/http-adapter.token.mts +8 -0
  62. package/src/tokens/index.mts +4 -1
  63. package/src/tokens/multipart-adapter.token.mts +8 -0
  64. package/src/tokens/reply.token.mts +1 -5
  65. package/src/tokens/request.token.mts +1 -7
  66. package/src/tokens/stream-adapter.token.mts +8 -0
  67. package/docs/recipes/prisma.md +0 -60
  68. package/e2e/endpoints/get.spec.mts +0 -97
  69. package/e2e/endpoints/post.spec.mts +0 -113
  70. package/examples/simple-test/api/index.mts +0 -64
  71. package/examples/simple-test/config/config.service.mts +0 -14
  72. package/examples/simple-test/config/configuration.mts +0 -7
  73. package/examples/simple-test/index.mts +0 -16
  74. package/examples/simple-test/src/acl/acl-modern.guard.mts +0 -15
  75. package/examples/simple-test/src/acl/acl.guard.mts +0 -14
  76. package/examples/simple-test/src/acl/app.guard.mts +0 -27
  77. package/examples/simple-test/src/acl/one-more.guard.mts +0 -15
  78. package/examples/simple-test/src/acl/public.attribute.mts +0 -21
  79. package/examples/simple-test/src/app.module.mts +0 -9
  80. package/examples/simple-test/src/user/user.controller.mts +0 -72
  81. package/examples/simple-test/src/user/user.module.mts +0 -14
  82. package/examples/simple-test/src/user/user.service.mts +0 -14
  83. package/src/adapters/endpoint-adapter.service.mts +0 -72
  84. package/src/adapters/handler-adapter.interface.mts +0 -21
  85. package/src/adapters/index.mts +0 -4
  86. package/src/adapters/multipart-adapter.service.mts +0 -135
  87. package/src/adapters/stream-adapter.service.mts +0 -91
  88. package/src/logger/logger.factory.mts +0 -36
  89. package/src/logger/pino-wrapper.mts +0 -64
  90. package/src/services/controller-adapter.service.mts +0 -124
  91. package/src/services/execution-context.mts +0 -54
  92. package/src/tokens/application.token.mts +0 -9
package/lib/index.js CHANGED
@@ -1,19 +1,14 @@
1
1
  'use strict';
2
2
 
3
3
  var di = require('@navios/di');
4
- var v4 = require('zod/v4');
5
4
  var process$1 = require('process');
5
+ var z = require('zod/v4');
6
6
  var builder = require('@navios/builder');
7
7
  var util = require('util');
8
- var cors = require('@fastify/cors');
9
- var multipart = require('@fastify/multipart');
10
- var fastify = require('fastify');
11
- var fastifyTypeProviderZod = require('fastify-type-provider-zod');
12
8
 
13
9
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
14
10
 
15
- var cors__default = /*#__PURE__*/_interopDefault(cors);
16
- var multipart__default = /*#__PURE__*/_interopDefault(multipart);
11
+ var z__default = /*#__PURE__*/_interopDefault(z);
17
12
 
18
13
  var __create = Object.create;
19
14
  var __defProp = Object.defineProperty;
@@ -24,7 +19,7 @@ var __typeError = (msg) => {
24
19
  };
25
20
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
26
21
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
27
- var __decoratorStart = (base) => [, , , __create(base?.[__knownSymbol("metadata")] ?? null)];
22
+ var __decoratorStart = (base) => [, , , __create(null)];
28
23
  var __decoratorStrings = ["class", "method", "getter", "setter", "accessor", "field", "value", "get", "set"];
29
24
  var __expectFn = (fn) => fn !== void 0 && typeof fn !== "function" ? __typeError("Function expected") : fn;
30
25
  var __decoratorContext = (kind, name, done, metadata, fns) => ({ kind: __decoratorStrings[kind], name, metadata, addInitializer: (fn) => done._ ? __typeError("Already initialized") : fns.push(__expectFn(fn || null)) });
@@ -46,223 +41,6 @@ var __decorateElement = (array, flags, name, decorators, target, extra) => {
46
41
  }
47
42
  return __decoratorMetadata(array, target), desc && __defProp(target, name, desc), p ? k ^ 4 ? extra : desc : target;
48
43
  };
49
- var StreamAdapterToken = di.InjectionToken.create(
50
- Symbol.for("StreamAdapterService")
51
- );
52
- var _StreamAdapterService_decorators, _init;
53
- _StreamAdapterService_decorators = [di.Injectable({
54
- token: StreamAdapterToken
55
- })];
56
- exports.StreamAdapterService = class StreamAdapterService {
57
- hasSchema(handlerMetadata) {
58
- const config = handlerMetadata.config;
59
- return !!config.requestSchema || !!config.querySchema;
60
- }
61
- prepareArguments(handlerMetadata) {
62
- const config = handlerMetadata.config;
63
- const getters = [];
64
- if (config.querySchema) {
65
- getters.push((target, request) => {
66
- target.params = request.query;
67
- });
68
- }
69
- if (config.requestSchema) {
70
- getters.push((target, request) => {
71
- target.data = request.body;
72
- });
73
- }
74
- if (config.url.includes("$")) {
75
- getters.push((target, request) => {
76
- target.urlParams = request.params;
77
- });
78
- }
79
- return getters;
80
- }
81
- provideHandler(controller, executionContext, handlerMetadata) {
82
- const getters = this.prepareArguments(handlerMetadata);
83
- const formatArguments = async (request) => {
84
- const argument = {};
85
- const promises = [];
86
- for (const getter of getters) {
87
- const res = getter(argument, request);
88
- if (res instanceof Promise) {
89
- promises.push(res);
90
- }
91
- }
92
- await Promise.all(promises);
93
- return argument;
94
- };
95
- return async function(request, reply) {
96
- const controllerInstance = await di.inject(controller);
97
- const argument = await formatArguments(request);
98
- await controllerInstance[handlerMetadata.classMethod](argument, reply);
99
- };
100
- }
101
- provideSchema(handlerMetadata) {
102
- const schema = {};
103
- const { querySchema, requestSchema } = handlerMetadata.config;
104
- if (querySchema) {
105
- schema.querystring = querySchema;
106
- }
107
- if (requestSchema) {
108
- schema.body = requestSchema;
109
- }
110
- return schema;
111
- }
112
- };
113
- _init = __decoratorStart(null);
114
- exports.StreamAdapterService = __decorateElement(_init, 0, "StreamAdapterService", _StreamAdapterService_decorators, exports.StreamAdapterService);
115
- __runInitializers(_init, 1, exports.StreamAdapterService);
116
-
117
- // src/adapters/endpoint-adapter.service.mts
118
- var EndpointAdapterToken = di.InjectionToken.create(
119
- Symbol.for("EndpointAdapterService")
120
- );
121
- var _EndpointAdapterService_decorators, _init2, _a;
122
- _EndpointAdapterService_decorators = [di.Injectable({
123
- token: EndpointAdapterToken
124
- })];
125
- exports.EndpointAdapterService = class EndpointAdapterService extends (_a = exports.StreamAdapterService) {
126
- hasSchema(handlerMetadata) {
127
- const config = handlerMetadata.config;
128
- return super.hasSchema(handlerMetadata) || !!config.responseSchema;
129
- }
130
- provideSchema(handlerMetadata) {
131
- const config = handlerMetadata.config;
132
- const schema = super.provideSchema(handlerMetadata);
133
- if (config.responseSchema) {
134
- schema.response = {
135
- 200: config.responseSchema
136
- };
137
- }
138
- return schema;
139
- }
140
- provideHandler(controller, executionContext, handlerMetadata) {
141
- const getters = this.prepareArguments(handlerMetadata);
142
- const formatArguments = async (request) => {
143
- const argument = {};
144
- const promises = [];
145
- for (const getter of getters) {
146
- const res = getter(argument, request);
147
- if (res instanceof Promise) {
148
- promises.push(res);
149
- }
150
- }
151
- await Promise.all(promises);
152
- return argument;
153
- };
154
- return async function(request, reply) {
155
- const controllerInstance = await di.inject(controller);
156
- const argument = await formatArguments(request);
157
- const result = await controllerInstance[handlerMetadata.classMethod](argument);
158
- reply.status(handlerMetadata.successStatusCode).headers(handlerMetadata.headers).send(result);
159
- };
160
- }
161
- };
162
- _init2 = __decoratorStart(_a);
163
- exports.EndpointAdapterService = __decorateElement(_init2, 0, "EndpointAdapterService", _EndpointAdapterService_decorators, exports.EndpointAdapterService);
164
- __runInitializers(_init2, 1, exports.EndpointAdapterService);
165
- var MultipartAdapterToken = di.InjectionToken.create(
166
- Symbol.for("MultipartAdapterService")
167
- );
168
- var _MultipartAdapterService_decorators, _init3, _a2;
169
- _MultipartAdapterService_decorators = [di.Injectable({
170
- token: MultipartAdapterToken
171
- })];
172
- exports.MultipartAdapterService = class MultipartAdapterService extends (_a2 = exports.EndpointAdapterService) {
173
- prepareArguments(handlerMetadata) {
174
- const config = handlerMetadata.config;
175
- const getters = [];
176
- if (config.querySchema) {
177
- getters.push((target, request) => {
178
- target.params = request.query;
179
- });
180
- }
181
- if (config.url.includes("$")) {
182
- getters.push((target, request) => {
183
- target.urlParams = request.params;
184
- });
185
- }
186
- const requestSchema = config.requestSchema;
187
- const shape = requestSchema._zod.def.shape;
188
- const structure = this.analyzeSchema(shape);
189
- getters.push(async (target, request) => {
190
- const req = {};
191
- for await (const part of request.parts()) {
192
- await this.populateRequest(structure, part, req);
193
- }
194
- target.data = requestSchema.parse(req);
195
- });
196
- return getters;
197
- }
198
- async populateRequest(structure, part, req) {
199
- const { isArray, isObject: isObject2 } = structure[part.fieldname] ?? {};
200
- if (isArray && !req[part.fieldname]) {
201
- req[part.fieldname] = [];
202
- }
203
- let value;
204
- if (part.type === "file") {
205
- value = new File(
206
- [await part.toBuffer()],
207
- part.filename,
208
- {
209
- type: part.mimetype
210
- }
211
- );
212
- } else {
213
- value = part.value;
214
- if (isObject2 && typeof value === "string") {
215
- value = JSON.parse(value);
216
- }
217
- }
218
- if (isArray) {
219
- req[part.fieldname].push(value);
220
- } else {
221
- req[part.fieldname] = value;
222
- }
223
- }
224
- analyzeSchema(shape) {
225
- return Object.keys(shape).reduce(
226
- (target, key) => {
227
- let schema = shape[key];
228
- const isOptional = schema instanceof v4.ZodOptional;
229
- if (isOptional) {
230
- schema = schema.unwrap();
231
- }
232
- const isArray = schema instanceof v4.ZodArray;
233
- if (isArray) {
234
- schema = schema.element;
235
- }
236
- const isObject2 = schema instanceof v4.ZodObject;
237
- return {
238
- ...target,
239
- [key]: {
240
- isArray,
241
- isOptional,
242
- isObject: isObject2
243
- }
244
- };
245
- },
246
- {}
247
- );
248
- }
249
- provideSchema(handlerMetadata) {
250
- const schema = {};
251
- const { querySchema, responseSchema } = handlerMetadata.config;
252
- if (querySchema) {
253
- schema.querystring = querySchema;
254
- }
255
- if (responseSchema) {
256
- schema.response = {
257
- 200: responseSchema
258
- };
259
- }
260
- return schema;
261
- }
262
- };
263
- _init3 = __decoratorStart(_a2);
264
- exports.MultipartAdapterService = __decorateElement(_init3, 0, "MultipartAdapterService", _MultipartAdapterService_decorators, exports.MultipartAdapterService);
265
- __runInitializers(_init3, 1, exports.MultipartAdapterService);
266
44
  function envInt(key, defaultValue) {
267
45
  const envKey = process$1.env[key] || process.env[key];
268
46
  return envKey ? parseInt(envKey, 10) : defaultValue;
@@ -309,515 +87,66 @@ function filterLogLevels(parseableString = "") {
309
87
  const logLevelIndex = LOG_LEVELS.indexOf(
310
88
  sanitizedString.substring(orEqual ? 2 : 1)
311
89
  );
312
- if (logLevelIndex === -1) {
313
- throw new Error(`parse error (unknown log level): ${sanitizedString}`);
314
- }
315
- return LOG_LEVELS.slice(orEqual ? logLevelIndex : logLevelIndex + 1);
316
- } else if (sanitizedString.includes(",")) {
317
- return sanitizedString.split(",").filter(isLogLevel);
318
- }
319
- return isLogLevel(sanitizedString) ? [sanitizedString] : LOG_LEVELS;
320
- }
321
-
322
- // src/logger/utils/is-log-level-enabled.mts
323
- var LOG_LEVEL_VALUES = {
324
- verbose: 0,
325
- debug: 1,
326
- log: 2,
327
- warn: 3,
328
- error: 4,
329
- fatal: 5
330
- };
331
- function isLogLevelEnabled(targetLevel, logLevels) {
332
- if (!logLevels || Array.isArray(logLevels) && logLevels?.length === 0) {
333
- return false;
334
- }
335
- if (logLevels.includes(targetLevel)) {
336
- return true;
337
- }
338
- const highestLogLevelValue = logLevels.map((level) => LOG_LEVEL_VALUES[level]).sort((a, b) => b - a)?.[0];
339
- const targetLevelValue = LOG_LEVEL_VALUES[targetLevel];
340
- return targetLevelValue >= highestLogLevelValue;
341
- }
342
-
343
- // src/logger/utils/shared.utils.mts
344
- var isUndefined = (obj) => typeof obj === "undefined";
345
- var isObject = (fn) => !isNil(fn) && typeof fn === "object";
346
- var isPlainObject = (fn) => {
347
- if (!isObject(fn)) {
348
- return false;
349
- }
350
- const proto = Object.getPrototypeOf(fn);
351
- if (proto === null) {
352
- return true;
353
- }
354
- const ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor;
355
- return typeof ctor === "function" && ctor instanceof ctor && Function.prototype.toString.call(ctor) === Function.prototype.toString.call(Object);
356
- };
357
- var addLeadingSlash = (path) => path && typeof path === "string" ? path.charAt(0) !== "/" && path.substring(0, 2) !== "{/" ? "/" + path : path : "";
358
- var normalizePath = (path) => path ? path.startsWith("/") ? ("/" + path.replace(/\/+$/, "")).replace(/\/+/g, "/") : "/" + path.replace(/\/+$/, "") : "/";
359
- var stripEndSlash = (path) => path[path.length - 1] === "/" ? path.slice(0, path.length - 1) : path;
360
- var isFunction = (val) => typeof val === "function";
361
- var isString = (val) => typeof val === "string";
362
- var isNumber = (val) => typeof val === "number";
363
- var isConstructor = (val) => val === "constructor";
364
- var isNil = (val) => isUndefined(val) || val === null;
365
- var isEmpty = (array) => !(array && array.length > 0);
366
- var isSymbol = (val) => typeof val === "symbol";
367
- var ApplicationInjectionToken = "ApplicationInjectionToken";
368
- var Application = di.InjectionToken.create(
369
- ApplicationInjectionToken
370
- );
371
-
372
- // src/metadata/handler.metadata.mts
373
- var EndpointMetadataKey = Symbol("EndpointMetadataKey");
374
- function getAllEndpointMetadata(context) {
375
- if (context.metadata) {
376
- const metadata = context.metadata[EndpointMetadataKey];
377
- if (metadata) {
378
- return metadata;
379
- } else {
380
- context.metadata[EndpointMetadataKey] = /* @__PURE__ */ new Set();
381
- return context.metadata[EndpointMetadataKey];
382
- }
383
- }
384
- throw new Error("[Navios] Wrong environment.");
385
- }
386
- function getEndpointMetadata(target, context) {
387
- if (context.metadata) {
388
- const metadata = getAllEndpointMetadata(context);
389
- if (metadata) {
390
- const endpointMetadata = Array.from(metadata).find(
391
- (item) => item.classMethod === target.name
392
- );
393
- if (endpointMetadata) {
394
- return endpointMetadata;
395
- } else {
396
- const newMetadata = {
397
- classMethod: target.name,
398
- url: "",
399
- successStatusCode: 200,
400
- adapterToken: null,
401
- headers: {},
402
- httpMethod: "GET",
403
- // @ts-expect-error We are using a generic type here
404
- config: null,
405
- guards: /* @__PURE__ */ new Set(),
406
- customAttributes: /* @__PURE__ */ new Map()
407
- };
408
- metadata.add(newMetadata);
409
- return newMetadata;
410
- }
411
- }
412
- }
413
- throw new Error("[Navios] Wrong environment.");
414
- }
415
-
416
- // src/metadata/controller.metadata.mts
417
- var ControllerMetadataKey = Symbol("ControllerMetadataKey");
418
- function getControllerMetadata(target, context) {
419
- if (context.metadata) {
420
- const metadata = context.metadata[ControllerMetadataKey];
421
- if (metadata) {
422
- return metadata;
423
- } else {
424
- const endpointsMetadata = getAllEndpointMetadata(context);
425
- const newMetadata = {
426
- endpoints: endpointsMetadata,
427
- guards: /* @__PURE__ */ new Set(),
428
- customAttributes: /* @__PURE__ */ new Map()
429
- };
430
- context.metadata[ControllerMetadataKey] = newMetadata;
431
- target[ControllerMetadataKey] = newMetadata;
432
- return newMetadata;
433
- }
434
- }
435
- throw new Error("[Navios] Wrong environment.");
436
- }
437
- function extractControllerMetadata(target) {
438
- const metadata = target[ControllerMetadataKey];
439
- if (!metadata) {
440
- throw new Error(
441
- "[Navios] Controller metadata not found. Make sure to use @Controller decorator."
442
- );
443
- }
444
- return metadata;
445
- }
446
- function hasControllerMetadata(target) {
447
- const metadata = target[ControllerMetadataKey];
448
- return !!metadata;
449
- }
450
-
451
- // src/metadata/module.metadata.mts
452
- var ModuleMetadataKey = Symbol("ControllerMetadataKey");
453
- function getModuleMetadata(target, context) {
454
- if (context.metadata) {
455
- const metadata = context.metadata[ModuleMetadataKey];
456
- if (metadata) {
457
- return metadata;
458
- } else {
459
- const newMetadata = {
460
- controllers: /* @__PURE__ */ new Set(),
461
- imports: /* @__PURE__ */ new Set(),
462
- guards: /* @__PURE__ */ new Set(),
463
- customAttributes: /* @__PURE__ */ new Map()
464
- };
465
- context.metadata[ModuleMetadataKey] = newMetadata;
466
- target[ModuleMetadataKey] = newMetadata;
467
- return newMetadata;
468
- }
469
- }
470
- throw new Error("[Navios] Wrong environment.");
471
- }
472
- function extractModuleMetadata(target) {
473
- const metadata = target[ModuleMetadataKey];
474
- if (!metadata) {
475
- throw new Error(
476
- `[Navios] Module metadata not found for ${target.name}. Make sure to use @Module decorator.`
477
- );
478
- }
479
- return metadata;
480
- }
481
- function hasModuleMetadata(target) {
482
- return !!target[ModuleMetadataKey];
483
- }
484
-
485
- // src/services/execution-context.mts
486
- var ExecutionContext = class {
487
- constructor(module, controller, handler) {
488
- this.module = module;
489
- this.controller = controller;
490
- this.handler = handler;
491
- }
492
- request;
493
- reply;
494
- getModule() {
495
- return this.module;
496
- }
497
- getController() {
498
- return this.controller;
499
- }
500
- getHandler() {
501
- return this.handler;
502
- }
503
- getRequest() {
504
- if (!this.request) {
505
- throw new Error(
506
- "[Navios] Request is not set. Make sure to set it before using it."
507
- );
508
- }
509
- return this.request;
510
- }
511
- getReply() {
512
- if (!this.reply) {
513
- throw new Error(
514
- "[Navios] Reply is not set. Make sure to set it before using it."
515
- );
516
- }
517
- return this.reply;
518
- }
519
- provideRequest(request) {
520
- this.request = request;
521
- }
522
- provideReply(reply) {
523
- this.reply = reply;
524
- }
525
- };
526
-
527
- // src/exceptions/http.exception.mts
528
- var HttpException = class {
529
- constructor(statusCode, response, error) {
530
- this.statusCode = statusCode;
531
- this.response = response;
532
- this.error = error;
533
- }
534
- };
535
-
536
- // src/exceptions/bad-request.exception.mts
537
- var BadRequestException = class extends HttpException {
538
- constructor(message) {
539
- super(400, message);
540
- }
541
- };
542
-
543
- // src/exceptions/forbidden.exception.mts
544
- var ForbiddenException = class extends HttpException {
545
- constructor(message) {
546
- super(403, message);
547
- }
548
- };
549
-
550
- // src/exceptions/internal-server-error.exception.mts
551
- var InternalServerErrorException = class extends HttpException {
552
- constructor(message, error) {
553
- super(500, message, error);
554
- }
555
- };
556
-
557
- // src/exceptions/not-found.exception.mts
558
- var NotFoundException = class extends HttpException {
559
- constructor(response, error) {
560
- super(404, response, error);
561
- this.response = response;
562
- this.error = error;
563
- }
564
- };
565
-
566
- // src/exceptions/unauthorized.exception.mts
567
- var UnauthorizedException = class extends HttpException {
568
- constructor(message, error) {
569
- super(401, message, error);
570
- }
571
- };
572
-
573
- // src/exceptions/conflict.exception.mts
574
- var ConflictException = class extends HttpException {
575
- constructor(message, error) {
576
- super(409, message, error);
577
- }
578
- };
579
-
580
- // src/services/guard-runner.service.mts
581
- var _GuardRunnerService_decorators, _init4;
582
- _GuardRunnerService_decorators = [di.Injectable()];
583
- exports.GuardRunnerService = class GuardRunnerService {
584
- async runGuards(allGuards, executionContext) {
585
- let canActivate = true;
586
- for (const guard of Array.from(allGuards).reverse()) {
587
- const guardInstance = await di.inject(
588
- guard
589
- );
590
- if (!guardInstance.canActivate) {
591
- throw new Error(
592
- `[Navios] Guard ${guard.name} does not implement canActivate()`
593
- );
594
- }
595
- try {
596
- canActivate = await guardInstance.canActivate(executionContext);
597
- if (!canActivate) {
598
- break;
599
- }
600
- } catch (error) {
601
- if (error instanceof HttpException) {
602
- executionContext.getReply().status(error.statusCode).send(error.response);
603
- return false;
604
- } else {
605
- executionContext.getReply().status(500).send({
606
- message: "Internal server error",
607
- error: error.message
608
- });
609
- return false;
610
- }
611
- }
612
- }
613
- if (!canActivate) {
614
- executionContext.getReply().status(403).send({
615
- message: "Forbidden"
616
- });
617
- return false;
618
- }
619
- return canActivate;
620
- }
621
- makeContext(executionContext) {
622
- const guards = /* @__PURE__ */ new Set();
623
- const endpointGuards = executionContext.getHandler().guards;
624
- const controllerGuards = executionContext.getController().guards;
625
- const moduleGuards = executionContext.getModule().guards;
626
- if (endpointGuards.size > 0) {
627
- for (const guard of endpointGuards) {
628
- guards.add(guard);
629
- }
630
- }
631
- if (controllerGuards.size > 0) {
632
- for (const guard of controllerGuards) {
633
- guards.add(guard);
634
- }
635
- }
636
- if (moduleGuards.size > 0) {
637
- for (const guard of moduleGuards) {
638
- guards.add(guard);
639
- }
640
- }
641
- return guards;
642
- }
643
- };
644
- _init4 = __decoratorStart(null);
645
- exports.GuardRunnerService = __decorateElement(_init4, 0, "GuardRunnerService", _GuardRunnerService_decorators, exports.GuardRunnerService);
646
- __runInitializers(_init4, 1, exports.GuardRunnerService);
647
-
648
- // src/services/controller-adapter.service.mts
649
- var _ControllerAdapterService_decorators, _init5;
650
- _ControllerAdapterService_decorators = [di.Injectable()];
651
- var _ControllerAdapterService = class _ControllerAdapterService {
652
- guardRunner = di.syncInject(exports.GuardRunnerService);
653
- logger = di.syncInject(Logger, {
654
- context: _ControllerAdapterService.name
655
- });
656
- async setupController(controller, instance, moduleMetadata) {
657
- const controllerMetadata = extractControllerMetadata(controller);
658
- for (const endpoint of controllerMetadata.endpoints) {
659
- const { classMethod, url, httpMethod, adapterToken } = endpoint;
660
- if (!url || !adapterToken) {
661
- throw new Error(
662
- `[Navios] Malformed Endpoint ${controller.name}:${classMethod}`
663
- );
664
- }
665
- const adapter = await di.inject(
666
- adapterToken
667
- );
668
- const executionContext = new ExecutionContext(
669
- moduleMetadata,
670
- controllerMetadata,
671
- endpoint
672
- );
673
- const hasSchema = adapter.hasSchema?.(endpoint) ?? false;
674
- if (hasSchema) {
675
- instance.withTypeProvider().route({
676
- method: httpMethod,
677
- url: url.replaceAll("$", ":"),
678
- schema: adapter.provideSchema?.(endpoint) ?? {},
679
- preHandler: this.providePreHandler(executionContext),
680
- handler: this.wrapHandler(
681
- executionContext,
682
- adapter.provideHandler(controller, executionContext, endpoint)
683
- )
684
- });
685
- } else {
686
- instance.route({
687
- method: httpMethod,
688
- url: url.replaceAll("$", ":"),
689
- preHandler: this.providePreHandler(executionContext),
690
- handler: this.wrapHandler(
691
- executionContext,
692
- adapter.provideHandler(controller, executionContext, endpoint)
693
- )
694
- });
695
- }
696
- this.logger.debug(
697
- `Registered ${httpMethod} ${url} for ${controller.name}:${classMethod}`
698
- );
699
- }
700
- }
701
- providePreHandler(executionContext) {
702
- const guards = this.guardRunner.makeContext(executionContext);
703
- return guards.size > 0 ? this.wrapHandler(
704
- executionContext,
705
- async (request, reply) => {
706
- let canActivate = true;
707
- canActivate = await this.guardRunner.runGuards(
708
- guards,
709
- executionContext
710
- );
711
- if (!canActivate) {
712
- return reply;
713
- }
714
- }
715
- ) : void 0;
716
- }
717
- wrapHandler(executionContext, handler) {
718
- const locator = di.getGlobalServiceLocator();
719
- return async (request, reply) => {
720
- locator.storeInstance(request, Request);
721
- locator.storeInstance(reply, Reply);
722
- locator.storeInstance(executionContext, ExecutionContextToken);
723
- executionContext.provideRequest(request);
724
- executionContext.provideReply(reply);
725
- try {
726
- return await handler(request, reply);
727
- } finally {
728
- Promise.all([
729
- locator.removeInstance(Request),
730
- locator.removeInstance(Reply),
731
- locator.removeInstance(ExecutionContextToken)
732
- ]).catch((err) => {
733
- this.logger.warn(`Error removing instances: ${err}`);
734
- });
735
- }
736
- };
737
- }
738
- };
739
- _init5 = __decoratorStart(null);
740
- _ControllerAdapterService = __decorateElement(_init5, 0, "ControllerAdapterService", _ControllerAdapterService_decorators, _ControllerAdapterService);
741
- __runInitializers(_init5, 1, _ControllerAdapterService);
742
- var ControllerAdapterService = _ControllerAdapterService;
743
- var _ModuleLoaderService_decorators, _init6;
744
- _ModuleLoaderService_decorators = [di.Injectable()];
745
- var _ModuleLoaderService = class _ModuleLoaderService {
746
- logger = di.syncInject(Logger, {
747
- context: _ModuleLoaderService.name
748
- });
749
- modulesMetadata = /* @__PURE__ */ new Map();
750
- loadedModules = /* @__PURE__ */ new Map();
751
- initialized = false;
752
- async loadModules(appModule) {
753
- if (this.initialized) {
754
- return;
755
- }
756
- await this.traverseModules(appModule);
757
- this.initialized = true;
758
- }
759
- async traverseModules(module, parentMetadata) {
760
- const metadata = extractModuleMetadata(module);
761
- if (parentMetadata) {
762
- this.mergeMetadata(metadata, parentMetadata);
763
- }
764
- const moduleName = module.name;
765
- if (this.modulesMetadata.has(moduleName)) {
766
- return;
767
- }
768
- this.modulesMetadata.set(moduleName, metadata);
769
- const imports = metadata.imports ?? /* @__PURE__ */ new Set();
770
- const loadingPromises = Array.from(imports).map(
771
- async (importedModule) => this.traverseModules(importedModule, metadata)
772
- );
773
- await Promise.all(loadingPromises);
774
- const instance = await di.inject(module);
775
- if (instance.onModuleInit) {
776
- await instance.onModuleInit();
90
+ if (logLevelIndex === -1) {
91
+ throw new Error(`parse error (unknown log level): ${sanitizedString}`);
777
92
  }
778
- this.logger.debug(`Module ${moduleName} loaded`);
779
- this.loadedModules.set(moduleName, instance);
93
+ return LOG_LEVELS.slice(orEqual ? logLevelIndex : logLevelIndex + 1);
94
+ } else if (sanitizedString.includes(",")) {
95
+ return sanitizedString.split(",").filter(isLogLevel);
780
96
  }
781
- mergeMetadata(metadata, parentMetadata) {
782
- if (parentMetadata.guards) {
783
- for (const guard of parentMetadata.guards) {
784
- metadata.guards.add(guard);
785
- }
786
- }
787
- if (parentMetadata.customAttributes) {
788
- for (const [key, value] of parentMetadata.customAttributes) {
789
- if (metadata.customAttributes.has(key)) {
790
- continue;
791
- }
792
- metadata.customAttributes.set(key, value);
793
- }
794
- }
97
+ return isLogLevel(sanitizedString) ? [sanitizedString] : LOG_LEVELS;
98
+ }
99
+
100
+ // src/logger/utils/is-log-level-enabled.mts
101
+ var LOG_LEVEL_VALUES = {
102
+ verbose: 0,
103
+ debug: 1,
104
+ log: 2,
105
+ warn: 3,
106
+ error: 4,
107
+ fatal: 5
108
+ };
109
+ function isLogLevelEnabled(targetLevel, logLevels) {
110
+ if (!logLevels || Array.isArray(logLevels) && logLevels?.length === 0) {
111
+ return false;
795
112
  }
796
- getAllModules() {
797
- return this.modulesMetadata;
113
+ if (logLevels.includes(targetLevel)) {
114
+ return true;
798
115
  }
799
- dispose() {
800
- this.modulesMetadata.clear();
801
- this.loadedModules.clear();
802
- this.initialized = false;
116
+ const highestLogLevelValue = logLevels.map((level) => LOG_LEVEL_VALUES[level]).sort((a, b) => b - a)?.[0];
117
+ const targetLevelValue = LOG_LEVEL_VALUES[targetLevel];
118
+ return targetLevelValue >= highestLogLevelValue;
119
+ }
120
+
121
+ // src/logger/utils/shared.utils.mts
122
+ var isUndefined = (obj) => typeof obj === "undefined";
123
+ var isObject = (fn) => !isNil(fn) && typeof fn === "object";
124
+ var isPlainObject = (fn) => {
125
+ if (!isObject(fn)) {
126
+ return false;
127
+ }
128
+ const proto = Object.getPrototypeOf(fn);
129
+ if (proto === null) {
130
+ return true;
803
131
  }
132
+ const ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor;
133
+ return typeof ctor === "function" && ctor instanceof ctor && Function.prototype.toString.call(ctor) === Function.prototype.toString.call(Object);
804
134
  };
805
- _init6 = __decoratorStart(null);
806
- _ModuleLoaderService = __decorateElement(_init6, 0, "ModuleLoaderService", _ModuleLoaderService_decorators, _ModuleLoaderService);
807
- __runInitializers(_init6, 1, _ModuleLoaderService);
808
- var ModuleLoaderService = _ModuleLoaderService;
809
-
810
- // src/tokens/execution-context.token.mts
811
- var ExecutionContextInjectionToken = "ExecutionContextInjectionToken";
812
- var ExecutionContextToken = di.InjectionToken.create(
813
- ExecutionContextInjectionToken
814
- );
815
- var ReplyInjectionToken = "ReplyInjectionToken";
816
- var Reply = di.InjectionToken.create(ReplyInjectionToken);
817
- var RequestInjectionToken = "RequestInjectionToken";
818
- var Request = di.InjectionToken.create(
819
- RequestInjectionToken
820
- );
135
+ var addLeadingSlash = (path) => path && typeof path === "string" ? path.charAt(0) !== "/" && path.substring(0, 2) !== "{/" ? "/" + path : path : "";
136
+ var normalizePath = (path) => path ? path.startsWith("/") ? ("/" + path.replace(/\/+$/, "")).replace(/\/+/g, "/") : "/" + path.replace(/\/+$/, "") : "/";
137
+ var stripEndSlash = (path) => path[path.length - 1] === "/" ? path.slice(0, path.length - 1) : path;
138
+ var isFunction = (val) => typeof val === "function";
139
+ var isString = (val) => typeof val === "string";
140
+ var isNumber = (val) => typeof val === "number";
141
+ var isConstructor = (val) => val === "constructor";
142
+ var isNil = (val) => isUndefined(val) || val === null;
143
+ var isEmpty = (array) => !(array && array.length > 0);
144
+ var isSymbol = (val) => typeof val === "symbol";
145
+ var LoggerOutput = di.InjectionToken.create("LoggerOutput");
146
+ var loggerOptionsSchema = z__default.default.object({
147
+ context: z__default.default.string().optional()
148
+ }).optional();
149
+ var Logger = di.InjectionToken.create("Logger", loggerOptionsSchema);
821
150
 
822
151
  // src/logger/console-logger.service.mts
823
152
  var DEFAULT_DEPTH = 5;
@@ -837,21 +166,19 @@ var dateTimeFormatter = new Intl.DateTimeFormat(void 0, {
837
166
  day: "2-digit",
838
167
  month: "2-digit"
839
168
  });
840
- var _ConsoleLogger_decorators, _init7;
841
- _ConsoleLogger_decorators = [di.Injectable()];
842
- var _ConsoleLogger = class _ConsoleLogger {
169
+ var _ConsoleLogger_decorators, _init;
170
+ _ConsoleLogger_decorators = [di.Injectable({
171
+ token: LoggerOutput
172
+ })];
173
+ exports.ConsoleLogger = class ConsoleLogger {
843
174
  /**
844
175
  * The options of the logger.
845
176
  */
846
- options;
177
+ options = {};
847
178
  /**
848
179
  * The context of the logger (can be set manually or automatically inferred).
849
180
  */
850
181
  context;
851
- /**
852
- * Request ID (if enabled).
853
- */
854
- requestId = null;
855
182
  /**
856
183
  * The original context of the logger (set in the constructor).
857
184
  */
@@ -859,12 +186,12 @@ var _ConsoleLogger = class _ConsoleLogger {
859
186
  /**
860
187
  * The options used for the "inspect" method.
861
188
  */
862
- inspectOptions;
189
+ inspectOptions = this.getInspectOptions();
863
190
  /**
864
191
  * The last timestamp at which the log message was printed.
865
192
  */
866
- static lastTimestampAt;
867
- constructor(contextOrOptions, options) {
193
+ lastTimestampAt;
194
+ setup(contextOrOptions, options) {
868
195
  let [context, opts] = isString(contextOrOptions) ? [contextOrOptions, options] : options ? [void 0, options] : [contextOrOptions?.context, contextOrOptions];
869
196
  opts = opts ?? {};
870
197
  opts.logLevels ??= DEFAULT_LOG_LEVELS;
@@ -876,20 +203,6 @@ var _ConsoleLogger = class _ConsoleLogger {
876
203
  this.context = context;
877
204
  this.originalContext = context;
878
205
  }
879
- if (opts?.requestId) {
880
- const locator = di.getGlobalServiceLocator();
881
- locator.getEventBus().on(locator.getInstanceIdentifier(Request, void 0), "create", () => {
882
- const request = locator.getSyncInstance(Request, void 0);
883
- this.requestId = request?.id ?? null;
884
- });
885
- locator.getEventBus().on(
886
- locator.getInstanceIdentifier(Request, void 0),
887
- "destroy",
888
- () => {
889
- this.requestId = null;
890
- }
891
- );
892
- }
893
206
  }
894
207
  log(message, ...optionalParams) {
895
208
  if (!this.isLevelEnabled("log")) {
@@ -906,7 +219,7 @@ var _ConsoleLogger = class _ConsoleLogger {
906
219
  return;
907
220
  }
908
221
  const { messages, context, stack } = this.getContextAndStackAndMessagesToPrint([message, ...optionalParams]);
909
- this.printMessages(messages, context, "error", "stderr", stack);
222
+ this.printMessages(messages, context, "error", void 0, "stderr", stack);
910
223
  this.printStackTrace(stack);
911
224
  }
912
225
  warn(message, ...optionalParams) {
@@ -979,14 +292,15 @@ var _ConsoleLogger = class _ConsoleLogger {
979
292
  getTimestamp() {
980
293
  return dateTimeFormatter.format(Date.now());
981
294
  }
982
- printMessages(messages, context = "", logLevel = "log", writeStreamType, errorStack) {
295
+ printMessages(messages, context = "", logLevel = "log", requestId, writeStreamType, errorStack) {
983
296
  messages.forEach((message) => {
984
297
  if (this.options.json) {
985
298
  this.printAsJson(message, {
986
299
  context,
987
300
  logLevel,
988
301
  writeStreamType,
989
- errorStack
302
+ errorStack,
303
+ requestId
990
304
  });
991
305
  return;
992
306
  }
@@ -1000,7 +314,8 @@ var _ConsoleLogger = class _ConsoleLogger {
1000
314
  pidMessage,
1001
315
  formattedLogLevel,
1002
316
  contextMessage,
1003
- timestampDiff
317
+ timestampDiff,
318
+ requestId
1004
319
  );
1005
320
  process[writeStreamType ?? "stdout"].write(formattedMessage);
1006
321
  });
@@ -1018,8 +333,8 @@ var _ConsoleLogger = class _ConsoleLogger {
1018
333
  if (options.errorStack) {
1019
334
  logObject.stack = options.errorStack;
1020
335
  }
1021
- if (this.options.requestId && this.requestId) {
1022
- logObject.requestId = this.requestId;
336
+ if (this.options.requestId && options.requestId) {
337
+ logObject.requestId = options.requestId;
1023
338
  }
1024
339
  const formattedMessage = !this.options.colors && this.inspectOptions.compact === true ? JSON.stringify(logObject, this.stringifyReplacer) : util.inspect(logObject, this.inspectOptions);
1025
340
  process[options.writeStreamType ?? "stdout"].write(`${formattedMessage}
@@ -1035,16 +350,16 @@ var _ConsoleLogger = class _ConsoleLogger {
1035
350
  context = `[${context}] `;
1036
351
  return this.options.colors ? yellow(context) : context;
1037
352
  }
1038
- formatMessage(logLevel, message, pidMessage, formattedLogLevel, contextMessage, timestampDiff) {
353
+ formatMessage(logLevel, message, pidMessage, formattedLogLevel, contextMessage, timestampDiff, requestId) {
1039
354
  const output = this.stringifyMessage(message, logLevel);
1040
355
  pidMessage = this.colorize(pidMessage, logLevel);
1041
356
  formattedLogLevel = this.colorize(formattedLogLevel, logLevel);
1042
- return `${pidMessage}${this.getRequestId()}${this.getTimestamp()} ${formattedLogLevel} ${contextMessage}${output}${timestampDiff}
357
+ return `${pidMessage}${this.getRequestId(requestId)}${this.getTimestamp()} ${formattedLogLevel} ${contextMessage}${output}${timestampDiff}
1043
358
  `;
1044
359
  }
1045
- getRequestId() {
1046
- if (this.options.requestId && this.requestId) {
1047
- return `(${this.colorize(this.requestId, "log")}) `;
360
+ getRequestId(requestId) {
361
+ if (this.options.requestId && requestId) {
362
+ return `(${this.colorize(requestId, "log")}) `;
1048
363
  }
1049
364
  return "";
1050
365
  }
@@ -1084,9 +399,9 @@ var _ConsoleLogger = class _ConsoleLogger {
1084
399
  `);
1085
400
  }
1086
401
  updateAndGetTimestampDiff() {
1087
- const includeTimestamp = _ConsoleLogger.lastTimestampAt && this.options?.timestamp;
1088
- const result = includeTimestamp ? this.formatTimestampDiff(Date.now() - _ConsoleLogger.lastTimestampAt) : "";
1089
- _ConsoleLogger.lastTimestampAt = Date.now();
402
+ const includeTimestamp = this.lastTimestampAt && this.options?.timestamp;
403
+ const result = includeTimestamp ? this.formatTimestampDiff(Date.now() - this.lastTimestampAt) : "";
404
+ this.lastTimestampAt = Date.now();
1090
405
  return result;
1091
406
  }
1092
407
  formatTimestampDiff(timestampDiff) {
@@ -1189,39 +504,18 @@ var _ConsoleLogger = class _ConsoleLogger {
1189
504
  }
1190
505
  }
1191
506
  };
1192
- _init7 = __decoratorStart(null);
1193
- _ConsoleLogger = __decorateElement(_init7, 0, "ConsoleLogger", _ConsoleLogger_decorators, _ConsoleLogger);
1194
- __runInitializers(_init7, 1, _ConsoleLogger);
1195
- var ConsoleLogger = _ConsoleLogger;
1196
- var DEFAULT_LOGGER = new ConsoleLogger();
1197
- var dateTimeFormatter2 = new Intl.DateTimeFormat(void 0, {
1198
- year: "numeric",
1199
- hour: "numeric",
1200
- minute: "numeric",
1201
- second: "numeric",
1202
- day: "2-digit",
1203
- month: "2-digit"
1204
- });
1205
- var _LoggerInstance_decorators, _init8;
1206
- _LoggerInstance_decorators = [di.Injectable()];
1207
- var _LoggerInstance = class _LoggerInstance {
1208
- constructor(context, options = {}) {
1209
- this.context = context;
1210
- this.options = options;
1211
- }
1212
- static staticInstanceRef = DEFAULT_LOGGER;
1213
- static logLevels;
1214
- localInstanceRef;
1215
- get localInstance() {
1216
- if (_LoggerInstance.staticInstanceRef === DEFAULT_LOGGER) {
1217
- return this.registerLocalInstanceRef();
1218
- } else if (_LoggerInstance.staticInstanceRef instanceof _LoggerInstance) {
1219
- const prototype = Object.getPrototypeOf(_LoggerInstance.staticInstanceRef);
1220
- if (prototype.constructor === _LoggerInstance) {
1221
- return this.registerLocalInstanceRef();
1222
- }
1223
- }
1224
- return _LoggerInstance.staticInstanceRef;
507
+ _init = __decoratorStart();
508
+ exports.ConsoleLogger = __decorateElement(_init, 0, "ConsoleLogger", _ConsoleLogger_decorators, exports.ConsoleLogger);
509
+ __runInitializers(_init, 1, exports.ConsoleLogger);
510
+ var _LoggerInstance_decorators, _init2;
511
+ _LoggerInstance_decorators = [di.Injectable({
512
+ token: Logger
513
+ })];
514
+ exports.LoggerInstance = class LoggerInstance {
515
+ localInstance = di.inject(LoggerOutput);
516
+ context;
517
+ constructor(config = {}) {
518
+ this.context = config.context;
1225
519
  }
1226
520
  error(message, ...optionalParams) {
1227
521
  optionalParams = this.context ? (optionalParams.length ? optionalParams : [void 0]).concat(
@@ -1249,135 +543,15 @@ var _LoggerInstance = class _LoggerInstance {
1249
543
  optionalParams = this.context ? optionalParams.concat(this.context) : optionalParams;
1250
544
  this.localInstance?.fatal?.(message, ...optionalParams);
1251
545
  }
1252
- static error(message, ...optionalParams) {
1253
- this.staticInstanceRef?.error(message, ...optionalParams);
1254
- }
1255
- static log(message, ...optionalParams) {
1256
- this.staticInstanceRef?.log(message, ...optionalParams);
1257
- }
1258
- static warn(message, ...optionalParams) {
1259
- this.staticInstanceRef?.warn(message, ...optionalParams);
1260
- }
1261
- static debug(message, ...optionalParams) {
1262
- this.staticInstanceRef?.debug?.(message, ...optionalParams);
1263
- }
1264
- static verbose(message, ...optionalParams) {
1265
- this.staticInstanceRef?.verbose?.(message, ...optionalParams);
1266
- }
1267
- static fatal(message, ...optionalParams) {
1268
- this.staticInstanceRef?.fatal?.(message, ...optionalParams);
1269
- }
1270
- static getTimestamp() {
1271
- return dateTimeFormatter2.format(Date.now());
1272
- }
1273
- static overrideLogger(logger) {
1274
- if (Array.isArray(logger)) {
1275
- _LoggerInstance.logLevels = logger;
1276
- return this.staticInstanceRef?.setLogLevels?.(logger);
1277
- }
1278
- if (isObject(logger)) {
1279
- this.staticInstanceRef = logger;
1280
- } else {
1281
- this.staticInstanceRef = void 0;
1282
- }
1283
- }
1284
- static isLevelEnabled(level) {
1285
- const logLevels = _LoggerInstance.logLevels;
1286
- return isLogLevelEnabled(level, logLevels);
1287
- }
1288
- registerLocalInstanceRef() {
1289
- if (this.localInstanceRef) {
1290
- return this.localInstanceRef;
1291
- }
1292
- this.localInstanceRef = new ConsoleLogger(this.context, {
1293
- timestamp: this.options?.timestamp,
1294
- logLevels: _LoggerInstance.logLevels
1295
- });
1296
- return this.localInstanceRef;
1297
- }
1298
- };
1299
- _init8 = __decoratorStart(null);
1300
- _LoggerInstance = __decorateElement(_init8, 0, "LoggerInstance", _LoggerInstance_decorators, _LoggerInstance);
1301
- __runInitializers(_init8, 1, _LoggerInstance);
1302
- var LoggerInstance = _LoggerInstance;
1303
-
1304
- // src/logger/logger.factory.mts
1305
- var LoggerInjectionToken = "LoggerInjectionToken";
1306
- var LoggerOptions = v4.z.object({
1307
- context: v4.z.string().optional(),
1308
- options: v4.z.object({
1309
- timestamp: v4.z.boolean().optional()
1310
- }).optional()
1311
- }).optional();
1312
- var Logger = di.InjectionToken.create(LoggerInjectionToken, LoggerOptions);
1313
- var _LoggerFactory_decorators, _init9;
1314
- _LoggerFactory_decorators = [di.Injectable({
1315
- type: di.InjectableType.Factory,
1316
- token: Logger
1317
- })];
1318
- exports.LoggerFactory = class LoggerFactory {
1319
- create(ctx, args) {
1320
- return new LoggerInstance(args?.context, args?.options);
1321
- }
1322
- };
1323
- _init9 = __decoratorStart(null);
1324
- exports.LoggerFactory = __decorateElement(_init9, 0, "LoggerFactory", _LoggerFactory_decorators, exports.LoggerFactory);
1325
- __runInitializers(_init9, 1, exports.LoggerFactory);
1326
-
1327
- // src/logger/pino-wrapper.mts
1328
- var PinoWrapper = class _PinoWrapper {
1329
- constructor(logger) {
1330
- this.logger = logger;
1331
- }
1332
- fatal(message, ...optionalParams) {
1333
- if (this.logger.fatal === void 0) {
1334
- return this.error(message, ...optionalParams);
1335
- }
1336
- this.logger.fatal(message, ...optionalParams);
1337
- }
1338
- error(message, ...optionalParams) {
1339
- this.logger.error(message, ...optionalParams);
1340
- }
1341
- warn(message, ...optionalParams) {
1342
- this.logger.warn(message, ...optionalParams);
1343
- }
1344
- info() {
1345
- }
1346
- debug(message, ...optionalParams) {
1347
- this.logger.debug?.(message, ...optionalParams);
1348
- }
1349
- trace(message, ...optionalParams) {
1350
- this.logger.verbose?.(message, ...optionalParams);
1351
- }
1352
- silent() {
1353
- }
1354
- child(options) {
1355
- const keys = Object.keys(options);
1356
- let newContext = this.logger["context"] ?? "";
1357
- if (keys.length > 1) {
1358
- newContext = `${this.logger["context"] ?? ""}:${JSON.stringify(options)}`;
1359
- }
1360
- return new _PinoWrapper(
1361
- // @ts-expect-error We don't need to support this in the current version
1362
- new LoggerInstance(newContext, this.logger["options"])
1363
- );
1364
- }
1365
- get level() {
1366
- if ("level" in this.logger && this.logger.level) {
1367
- return this.logger.level;
1368
- }
1369
- const levels = LoggerInstance["logLevels"];
1370
- if (levels) {
1371
- return levels.find((level) => level !== "verbose");
1372
- }
1373
- return "warn";
1374
- }
1375
546
  };
547
+ _init2 = __decoratorStart();
548
+ exports.LoggerInstance = __decorateElement(_init2, 0, "LoggerInstance", _LoggerInstance_decorators, exports.LoggerInstance);
549
+ __runInitializers(_init2, 1, exports.LoggerInstance);
1376
550
 
1377
551
  // src/config/config.service.mts
1378
- var ConfigServiceOptionsSchema = v4.z.record(v4.z.string(), v4.z.unknown());
552
+ var ConfigServiceOptionsSchema = z.z.record(z.z.string(), z.z.unknown());
1379
553
  var ConfigServiceToken = di.InjectionToken.create(Symbol.for("ConfigService"), ConfigServiceOptionsSchema);
1380
- var _ConfigService_decorators, _init10;
554
+ var _ConfigService_decorators, _init3;
1381
555
  _ConfigService_decorators = [di.Injectable({
1382
556
  token: ConfigServiceToken
1383
557
  })];
@@ -1385,7 +559,7 @@ var _ConfigService = class _ConfigService {
1385
559
  constructor(config = {}) {
1386
560
  this.config = config;
1387
561
  }
1388
- logger = di.syncInject(Logger, {
562
+ logger = di.inject(Logger, {
1389
563
  context: _ConfigService.name
1390
564
  });
1391
565
  getConfig() {
@@ -1424,14 +598,14 @@ var _ConfigService = class _ConfigService {
1424
598
  return value;
1425
599
  }
1426
600
  };
1427
- _init10 = __decoratorStart(null);
1428
- _ConfigService = __decorateElement(_init10, 0, "ConfigService", _ConfigService_decorators, _ConfigService);
1429
- __runInitializers(_init10, 1, _ConfigService);
601
+ _init3 = __decoratorStart();
602
+ _ConfigService = __decorateElement(_init3, 0, "ConfigService", _ConfigService_decorators, _ConfigService);
603
+ __runInitializers(_init3, 1, _ConfigService);
1430
604
  var ConfigService = _ConfigService;
1431
605
 
1432
606
  // src/config/config.provider.mts
1433
- var ConfigProviderOptions = v4.z.object({
1434
- load: v4.z.function({ output: ConfigServiceOptionsSchema })
607
+ var ConfigProviderOptions = z.z.object({
608
+ load: z.z.function({ output: ConfigServiceOptionsSchema })
1435
609
  });
1436
610
  function provideConfig(options) {
1437
611
  return di.InjectionToken.factory(ConfigServiceToken, async () => options.load());
@@ -1439,6 +613,121 @@ function provideConfig(options) {
1439
613
  var EnvConfigProvider = di.InjectionToken.bound(ConfigServiceToken, {
1440
614
  ...process$1.env
1441
615
  });
616
+
617
+ // src/metadata/handler.metadata.mts
618
+ var EndpointMetadataKey = Symbol("EndpointMetadataKey");
619
+ function getAllEndpointMetadata(context) {
620
+ if (context.metadata) {
621
+ const metadata = context.metadata[EndpointMetadataKey];
622
+ if (metadata) {
623
+ return metadata;
624
+ } else {
625
+ context.metadata[EndpointMetadataKey] = /* @__PURE__ */ new Set();
626
+ return context.metadata[EndpointMetadataKey];
627
+ }
628
+ }
629
+ throw new Error("[Navios] Wrong environment.");
630
+ }
631
+ function getEndpointMetadata(target, context) {
632
+ if (context.metadata) {
633
+ const metadata = getAllEndpointMetadata(context);
634
+ if (metadata) {
635
+ const endpointMetadata = Array.from(metadata).find(
636
+ (item) => item.classMethod === target.name
637
+ );
638
+ if (endpointMetadata) {
639
+ return endpointMetadata;
640
+ } else {
641
+ const newMetadata = {
642
+ classMethod: target.name,
643
+ url: "",
644
+ successStatusCode: 200,
645
+ adapterToken: null,
646
+ headers: {},
647
+ httpMethod: "GET",
648
+ // @ts-expect-error We are using a generic type here
649
+ config: null,
650
+ guards: /* @__PURE__ */ new Set(),
651
+ customAttributes: /* @__PURE__ */ new Map()
652
+ };
653
+ metadata.add(newMetadata);
654
+ return newMetadata;
655
+ }
656
+ }
657
+ }
658
+ throw new Error("[Navios] Wrong environment.");
659
+ }
660
+
661
+ // src/metadata/controller.metadata.mts
662
+ var ControllerMetadataKey = Symbol("ControllerMetadataKey");
663
+ function getControllerMetadata(target, context) {
664
+ if (context.metadata) {
665
+ const metadata = context.metadata[ControllerMetadataKey];
666
+ if (metadata) {
667
+ return metadata;
668
+ } else {
669
+ const endpointsMetadata = getAllEndpointMetadata(context);
670
+ const newMetadata = {
671
+ endpoints: endpointsMetadata,
672
+ guards: /* @__PURE__ */ new Set(),
673
+ customAttributes: /* @__PURE__ */ new Map()
674
+ };
675
+ context.metadata[ControllerMetadataKey] = newMetadata;
676
+ target[ControllerMetadataKey] = newMetadata;
677
+ return newMetadata;
678
+ }
679
+ }
680
+ throw new Error("[Navios] Wrong environment.");
681
+ }
682
+ function extractControllerMetadata(target) {
683
+ const metadata = target[ControllerMetadataKey];
684
+ if (!metadata) {
685
+ throw new Error(
686
+ "[Navios] Controller metadata not found. Make sure to use @Controller decorator."
687
+ );
688
+ }
689
+ return metadata;
690
+ }
691
+ function hasControllerMetadata(target) {
692
+ const metadata = target[ControllerMetadataKey];
693
+ return !!metadata;
694
+ }
695
+
696
+ // src/metadata/module.metadata.mts
697
+ var ModuleMetadataKey = Symbol("ControllerMetadataKey");
698
+ function getModuleMetadata(target, context) {
699
+ if (context.metadata) {
700
+ const metadata = context.metadata[ModuleMetadataKey];
701
+ if (metadata) {
702
+ return metadata;
703
+ } else {
704
+ const newMetadata = {
705
+ controllers: /* @__PURE__ */ new Set(),
706
+ imports: /* @__PURE__ */ new Set(),
707
+ guards: /* @__PURE__ */ new Set(),
708
+ customAttributes: /* @__PURE__ */ new Map()
709
+ };
710
+ context.metadata[ModuleMetadataKey] = newMetadata;
711
+ target[ModuleMetadataKey] = newMetadata;
712
+ return newMetadata;
713
+ }
714
+ }
715
+ throw new Error("[Navios] Wrong environment.");
716
+ }
717
+ function extractModuleMetadata(target) {
718
+ const metadata = target[ModuleMetadataKey];
719
+ if (!metadata) {
720
+ throw new Error(
721
+ `[Navios] Module metadata not found for ${target.name}. Make sure to use @Module decorator.`
722
+ );
723
+ }
724
+ return metadata;
725
+ }
726
+ function hasModuleMetadata(target) {
727
+ return !!target[ModuleMetadataKey];
728
+ }
729
+
730
+ // src/decorators/controller.decorator.mts
1442
731
  function Controller({ guards } = {}) {
1443
732
  return function(target, context) {
1444
733
  if (context.kind !== "class") {
@@ -1457,10 +746,30 @@ function Controller({ guards } = {}) {
1457
746
  }
1458
747
  return di.Injectable({
1459
748
  token,
1460
- scope: di.InjectableScope.Instance
749
+ scope: di.InjectableScope.Request
1461
750
  })(target, context);
1462
751
  };
1463
752
  }
753
+ var EndpointAdapterToken = di.InjectionToken.create(
754
+ "EndpointAdapterToken"
755
+ );
756
+ var ExecutionContextInjectionToken = "ExecutionContextInjectionToken";
757
+ var ExecutionContext = di.InjectionToken.create(
758
+ ExecutionContextInjectionToken
759
+ );
760
+ var HttpAdapterToken = di.InjectionToken.create(
761
+ "HttpAdapterToken"
762
+ );
763
+ var MultipartAdapterToken = di.InjectionToken.create(
764
+ "MultipartAdapterToken"
765
+ );
766
+ var Reply = di.InjectionToken.create("ReplyToken");
767
+ var Request = di.InjectionToken.create("RequestToken");
768
+ var StreamAdapterToken = di.InjectionToken.create(
769
+ "StreamAdapterToken"
770
+ );
771
+
772
+ // src/decorators/endpoint.decorator.mts
1464
773
  function Endpoint(endpoint) {
1465
774
  return (target, context) => {
1466
775
  if (context.kind !== "method") {
@@ -1632,6 +941,193 @@ function UseGuards(...guards) {
1632
941
  };
1633
942
  }
1634
943
 
944
+ // src/exceptions/http.exception.mts
945
+ var HttpException = class {
946
+ constructor(statusCode, response, error) {
947
+ this.statusCode = statusCode;
948
+ this.response = response;
949
+ this.error = error;
950
+ }
951
+ };
952
+
953
+ // src/exceptions/bad-request.exception.mts
954
+ var BadRequestException = class extends HttpException {
955
+ constructor(message) {
956
+ super(400, message);
957
+ }
958
+ };
959
+
960
+ // src/exceptions/forbidden.exception.mts
961
+ var ForbiddenException = class extends HttpException {
962
+ constructor(message) {
963
+ super(403, message);
964
+ }
965
+ };
966
+
967
+ // src/exceptions/internal-server-error.exception.mts
968
+ var InternalServerErrorException = class extends HttpException {
969
+ constructor(message, error) {
970
+ super(500, message, error);
971
+ }
972
+ };
973
+
974
+ // src/exceptions/not-found.exception.mts
975
+ var NotFoundException = class extends HttpException {
976
+ constructor(response, error) {
977
+ super(404, response, error);
978
+ this.response = response;
979
+ this.error = error;
980
+ }
981
+ };
982
+
983
+ // src/exceptions/unauthorized.exception.mts
984
+ var UnauthorizedException = class extends HttpException {
985
+ constructor(message, error) {
986
+ super(401, message, error);
987
+ }
988
+ };
989
+
990
+ // src/exceptions/conflict.exception.mts
991
+ var ConflictException = class extends HttpException {
992
+ constructor(message, error) {
993
+ super(409, message, error);
994
+ }
995
+ };
996
+ var _GuardRunnerService_decorators, _init4;
997
+ _GuardRunnerService_decorators = [di.Injectable()];
998
+ exports.GuardRunnerService = class GuardRunnerService {
999
+ container = di.inject(di.Container);
1000
+ async runGuards(allGuards, executionContext) {
1001
+ let canActivate = true;
1002
+ for (const guard of Array.from(allGuards).reverse()) {
1003
+ const guardInstance = await this.container.get(
1004
+ guard
1005
+ );
1006
+ if (!guardInstance.canActivate) {
1007
+ throw new Error(
1008
+ `[Navios] Guard ${guard.name} does not implement canActivate()`
1009
+ );
1010
+ }
1011
+ try {
1012
+ canActivate = await guardInstance.canActivate(executionContext);
1013
+ if (!canActivate) {
1014
+ break;
1015
+ }
1016
+ } catch (error) {
1017
+ if (error instanceof HttpException) {
1018
+ executionContext.getReply().status(error.statusCode).send(error.response);
1019
+ return false;
1020
+ } else {
1021
+ executionContext.getReply().status(500).send({
1022
+ message: "Internal server error",
1023
+ error: error.message
1024
+ });
1025
+ return false;
1026
+ }
1027
+ }
1028
+ }
1029
+ if (!canActivate) {
1030
+ executionContext.getReply().status(403).send({
1031
+ message: "Forbidden"
1032
+ });
1033
+ return false;
1034
+ }
1035
+ return canActivate;
1036
+ }
1037
+ makeContext(moduleMetadata, controllerMetadata, endpoint) {
1038
+ const guards = /* @__PURE__ */ new Set();
1039
+ const endpointGuards = endpoint.guards;
1040
+ const controllerGuards = controllerMetadata.guards;
1041
+ const moduleGuards = moduleMetadata.guards;
1042
+ if (endpointGuards.size > 0) {
1043
+ for (const guard of endpointGuards) {
1044
+ guards.add(guard);
1045
+ }
1046
+ }
1047
+ if (controllerGuards.size > 0) {
1048
+ for (const guard of controllerGuards) {
1049
+ guards.add(guard);
1050
+ }
1051
+ }
1052
+ if (moduleGuards.size > 0) {
1053
+ for (const guard of moduleGuards) {
1054
+ guards.add(guard);
1055
+ }
1056
+ }
1057
+ return guards;
1058
+ }
1059
+ };
1060
+ _init4 = __decoratorStart();
1061
+ exports.GuardRunnerService = __decorateElement(_init4, 0, "GuardRunnerService", _GuardRunnerService_decorators, exports.GuardRunnerService);
1062
+ __runInitializers(_init4, 1, exports.GuardRunnerService);
1063
+ var _ModuleLoaderService_decorators, _init5;
1064
+ _ModuleLoaderService_decorators = [di.Injectable()];
1065
+ var _ModuleLoaderService = class _ModuleLoaderService {
1066
+ logger = di.inject(Logger, {
1067
+ context: _ModuleLoaderService.name
1068
+ });
1069
+ container = di.inject(di.Container);
1070
+ modulesMetadata = /* @__PURE__ */ new Map();
1071
+ loadedModules = /* @__PURE__ */ new Map();
1072
+ initialized = false;
1073
+ async loadModules(appModule) {
1074
+ if (this.initialized) {
1075
+ return;
1076
+ }
1077
+ await this.traverseModules(appModule);
1078
+ this.initialized = true;
1079
+ }
1080
+ async traverseModules(module, parentMetadata) {
1081
+ const metadata = extractModuleMetadata(module);
1082
+ if (parentMetadata) {
1083
+ this.mergeMetadata(metadata, parentMetadata);
1084
+ }
1085
+ const moduleName = module.name;
1086
+ if (this.modulesMetadata.has(moduleName)) {
1087
+ return;
1088
+ }
1089
+ this.modulesMetadata.set(moduleName, metadata);
1090
+ const imports = metadata.imports ?? /* @__PURE__ */ new Set();
1091
+ const loadingPromises = Array.from(imports).map(
1092
+ async (importedModule) => this.traverseModules(importedModule, metadata)
1093
+ );
1094
+ await Promise.all(loadingPromises);
1095
+ const instance = await this.container.get(module);
1096
+ if (instance.onModuleInit) {
1097
+ await instance.onModuleInit();
1098
+ }
1099
+ this.logger.debug(`Module ${moduleName} loaded`);
1100
+ this.loadedModules.set(moduleName, instance);
1101
+ }
1102
+ mergeMetadata(metadata, parentMetadata) {
1103
+ if (parentMetadata.guards) {
1104
+ for (const guard of parentMetadata.guards) {
1105
+ metadata.guards.add(guard);
1106
+ }
1107
+ }
1108
+ if (parentMetadata.customAttributes) {
1109
+ for (const [key, value] of parentMetadata.customAttributes) {
1110
+ if (metadata.customAttributes.has(key)) {
1111
+ continue;
1112
+ }
1113
+ metadata.customAttributes.set(key, value);
1114
+ }
1115
+ }
1116
+ }
1117
+ getAllModules() {
1118
+ return this.modulesMetadata;
1119
+ }
1120
+ dispose() {
1121
+ this.modulesMetadata.clear();
1122
+ this.loadedModules.clear();
1123
+ this.initialized = false;
1124
+ }
1125
+ };
1126
+ _init5 = __decoratorStart();
1127
+ _ModuleLoaderService = __decorateElement(_init5, 0, "ModuleLoaderService", _ModuleLoaderService_decorators, _ModuleLoaderService);
1128
+ __runInitializers(_init5, 1, _ModuleLoaderService);
1129
+ var ModuleLoaderService = _ModuleLoaderService;
1130
+
1635
1131
  // src/attribute.factory.mts
1636
1132
  var AttributeFactory = class {
1637
1133
  static createAttribute(token, schema) {
@@ -1688,162 +1184,208 @@ var AttributeFactory = class {
1688
1184
  return target.customAttributes.has(attribute.token);
1689
1185
  }
1690
1186
  };
1691
- var _NaviosApplication_decorators, _init11;
1187
+ var _NaviosEnvironment_decorators, _init6;
1188
+ _NaviosEnvironment_decorators = [di.Injectable()];
1189
+ var NaviosEnvironment = class {
1190
+ httpTokens = /* @__PURE__ */ new Map();
1191
+ setupHttpEnvironment(tokens) {
1192
+ this.httpTokens = tokens;
1193
+ }
1194
+ getHttpToken(token) {
1195
+ return this.httpTokens.get(token);
1196
+ }
1197
+ hasHttpSetup() {
1198
+ return this.httpTokens.size > 0;
1199
+ }
1200
+ };
1201
+ _init6 = __decoratorStart();
1202
+ NaviosEnvironment = __decorateElement(_init6, 0, "NaviosEnvironment", _NaviosEnvironment_decorators, NaviosEnvironment);
1203
+ __runInitializers(_init6, 1, NaviosEnvironment);
1204
+
1205
+ // src/factories/endpoint-adapter.factory.mts
1206
+ var _EndpointAdapterFactory_decorators, _init7;
1207
+ _EndpointAdapterFactory_decorators = [di.Factory({
1208
+ token: EndpointAdapterToken
1209
+ })];
1210
+ exports.EndpointAdapterFactory = class EndpointAdapterFactory {
1211
+ environment = di.inject(NaviosEnvironment);
1212
+ create(ctx) {
1213
+ const service = this.environment.getHttpToken(EndpointAdapterToken);
1214
+ if (!service) {
1215
+ throw new Error("EndpointAdapterToken service not found in environment");
1216
+ }
1217
+ return ctx.inject(service);
1218
+ }
1219
+ };
1220
+ _init7 = __decoratorStart();
1221
+ exports.EndpointAdapterFactory = __decorateElement(_init7, 0, "EndpointAdapterFactory", _EndpointAdapterFactory_decorators, exports.EndpointAdapterFactory);
1222
+ __runInitializers(_init7, 1, exports.EndpointAdapterFactory);
1223
+ var _HttpAdapterFactory_decorators, _init8;
1224
+ _HttpAdapterFactory_decorators = [di.Factory({
1225
+ token: HttpAdapterToken
1226
+ })];
1227
+ exports.HttpAdapterFactory = class HttpAdapterFactory {
1228
+ environment = di.inject(NaviosEnvironment);
1229
+ create(ctx) {
1230
+ const service = this.environment.getHttpToken(HttpAdapterToken);
1231
+ if (!service) {
1232
+ throw new Error("HttpAdapterToken service not found in environment");
1233
+ }
1234
+ return ctx.inject(service);
1235
+ }
1236
+ };
1237
+ _init8 = __decoratorStart();
1238
+ exports.HttpAdapterFactory = __decorateElement(_init8, 0, "HttpAdapterFactory", _HttpAdapterFactory_decorators, exports.HttpAdapterFactory);
1239
+ __runInitializers(_init8, 1, exports.HttpAdapterFactory);
1240
+ var _MultipartAdapterFactory_decorators, _init9;
1241
+ _MultipartAdapterFactory_decorators = [di.Factory({
1242
+ token: MultipartAdapterToken
1243
+ })];
1244
+ exports.MultipartAdapterFactory = class MultipartAdapterFactory {
1245
+ environment = di.inject(NaviosEnvironment);
1246
+ create(ctx) {
1247
+ const service = this.environment.getHttpToken(MultipartAdapterToken);
1248
+ if (!service) {
1249
+ throw new Error("MultipartAdapterToken service not found in environment");
1250
+ }
1251
+ return ctx.inject(service);
1252
+ }
1253
+ };
1254
+ _init9 = __decoratorStart();
1255
+ exports.MultipartAdapterFactory = __decorateElement(_init9, 0, "MultipartAdapterFactory", _MultipartAdapterFactory_decorators, exports.MultipartAdapterFactory);
1256
+ __runInitializers(_init9, 1, exports.MultipartAdapterFactory);
1257
+ var _RequestFactory_decorators, _init10;
1258
+ _RequestFactory_decorators = [di.Factory({
1259
+ token: Request,
1260
+ scope: di.InjectableScope.Request
1261
+ })];
1262
+ exports.RequestFactory = class RequestFactory {
1263
+ environment = di.inject(NaviosEnvironment);
1264
+ create(ctx) {
1265
+ const service = this.environment.getHttpToken(Request);
1266
+ if (!service) {
1267
+ throw new Error("RequestToken service not found in environment");
1268
+ }
1269
+ return ctx.inject(service);
1270
+ }
1271
+ };
1272
+ _init10 = __decoratorStart();
1273
+ exports.RequestFactory = __decorateElement(_init10, 0, "RequestFactory", _RequestFactory_decorators, exports.RequestFactory);
1274
+ __runInitializers(_init10, 1, exports.RequestFactory);
1275
+ var _ReplyFactory_decorators, _init11;
1276
+ _ReplyFactory_decorators = [di.Factory({
1277
+ token: Reply,
1278
+ scope: di.InjectableScope.Request
1279
+ })];
1280
+ exports.ReplyFactory = class ReplyFactory {
1281
+ environment = di.inject(NaviosEnvironment);
1282
+ create(ctx) {
1283
+ const service = this.environment.getHttpToken(Reply);
1284
+ if (!service) {
1285
+ throw new Error("ReplyToken service not found in environment");
1286
+ }
1287
+ return ctx.inject(service);
1288
+ }
1289
+ };
1290
+ _init11 = __decoratorStart();
1291
+ exports.ReplyFactory = __decorateElement(_init11, 0, "ReplyFactory", _ReplyFactory_decorators, exports.ReplyFactory);
1292
+ __runInitializers(_init11, 1, exports.ReplyFactory);
1293
+ var _StreamAdapterFactory_decorators, _init12;
1294
+ _StreamAdapterFactory_decorators = [di.Factory({
1295
+ token: StreamAdapterToken
1296
+ })];
1297
+ exports.StreamAdapterFactory = class StreamAdapterFactory {
1298
+ environment = di.inject(NaviosEnvironment);
1299
+ create(ctx) {
1300
+ const service = this.environment.getHttpToken(StreamAdapterToken);
1301
+ if (!service) {
1302
+ throw new Error("StreamAdapterToken service not found in environment");
1303
+ }
1304
+ return ctx.inject(service);
1305
+ }
1306
+ };
1307
+ _init12 = __decoratorStart();
1308
+ exports.StreamAdapterFactory = __decorateElement(_init12, 0, "StreamAdapterFactory", _StreamAdapterFactory_decorators, exports.StreamAdapterFactory);
1309
+ __runInitializers(_init12, 1, exports.StreamAdapterFactory);
1310
+ var _NaviosApplication_decorators, _init13;
1692
1311
  _NaviosApplication_decorators = [di.Injectable()];
1693
1312
  var _NaviosApplication = class _NaviosApplication {
1694
- moduleLoader = di.syncInject(ModuleLoaderService);
1695
- controllerAdapter = di.syncInject(ControllerAdapterService);
1696
- logger = di.syncInject(Logger, {
1313
+ environment = di.inject(NaviosEnvironment);
1314
+ moduleLoader = di.inject(ModuleLoaderService);
1315
+ httpApplication = null;
1316
+ logger = di.inject(Logger, {
1697
1317
  context: _NaviosApplication.name
1698
1318
  });
1699
- server = null;
1700
- corsOptions = null;
1701
- multipartOptions = null;
1702
- globalPrefix = null;
1319
+ container = di.inject(di.Container);
1703
1320
  appModule = null;
1704
- options = {};
1321
+ options = {
1322
+ adapter: []
1323
+ };
1705
1324
  isInitialized = false;
1706
- setup(appModule, options = {}) {
1325
+ async setup(appModule, options = {
1326
+ adapter: []
1327
+ }) {
1707
1328
  this.appModule = appModule;
1708
1329
  this.options = options;
1330
+ if (this.environment.hasHttpSetup()) {
1331
+ this.httpApplication = await this.container.get(HttpAdapterToken);
1332
+ }
1333
+ }
1334
+ getContainer() {
1335
+ return this.container;
1709
1336
  }
1710
1337
  async init() {
1711
1338
  if (!this.appModule) {
1712
1339
  throw new Error("App module is not set. Call setAppModule() first.");
1713
1340
  }
1714
1341
  await this.moduleLoader.loadModules(this.appModule);
1715
- this.server = await this.getFastifyInstance(this.options);
1716
- this.configureFastifyInstance(this.server);
1717
- di.getGlobalServiceLocator().storeInstance(this.server, Application);
1718
- this.server.setValidatorCompiler(fastifyTypeProviderZod.validatorCompiler);
1719
- this.server.setSerializerCompiler(fastifyTypeProviderZod.serializerCompiler);
1720
- if (this.corsOptions) {
1721
- await this.server.register(cors__default.default, this.corsOptions);
1722
- }
1723
- if (this.multipartOptions) {
1724
- await this.configureMultipart(this.server, this.multipartOptions);
1342
+ if (this.environment.hasHttpSetup()) {
1343
+ await this.httpApplication?.setupHttpServer(this.options);
1725
1344
  }
1726
1345
  await this.initModules();
1727
- await this.server.ready();
1346
+ if (this.environment.hasHttpSetup()) {
1347
+ await this.httpApplication?.ready();
1348
+ }
1728
1349
  this.isInitialized = true;
1729
1350
  this.logger.debug("Navios application initialized");
1730
1351
  }
1731
- async getFastifyInstance(rawOptions) {
1732
- const { logger, ...options } = rawOptions;
1733
- if (logger) {
1734
- const fastifyOptions = options;
1735
- if (typeof logger === "boolean") {
1736
- if (!logger) {
1737
- fastifyOptions.logger = false;
1738
- }
1739
- } else {
1740
- fastifyOptions.loggerInstance = new PinoWrapper(
1741
- await di.inject(Logger, {
1742
- context: "FastifyAdapter"
1743
- })
1744
- );
1745
- }
1746
- return fastify.fastify(fastifyOptions);
1747
- } else {
1748
- return fastify.fastify({
1749
- ...options,
1750
- loggerInstance: new PinoWrapper(
1751
- await di.inject(Logger, {
1752
- context: "FastifyAdapter"
1753
- })
1754
- )
1755
- });
1756
- }
1757
- }
1758
- configureFastifyInstance(fastifyInstance) {
1759
- fastifyInstance.setErrorHandler((error, request, reply) => {
1760
- if (error instanceof HttpException) {
1761
- return reply.status(error.statusCode).send(error.response);
1762
- } else {
1763
- const statusCode = error.statusCode || 500;
1764
- const message = error.message || "Internal Server Error";
1765
- const response = {
1766
- statusCode,
1767
- message,
1768
- error: error.name || "InternalServerError"
1769
- };
1770
- this.logger.error(
1771
- `Error occurred: ${error.message} on ${request.url}`,
1772
- error
1773
- );
1774
- return reply.status(statusCode).send(response);
1775
- }
1776
- });
1777
- fastifyInstance.setNotFoundHandler((req, reply) => {
1778
- const response = {
1779
- statusCode: 404,
1780
- message: "Not Found",
1781
- error: "NotFound"
1782
- };
1783
- this.logger.error(`Route not found: [${req.method}] ${req.url}`);
1784
- return reply.status(404).send(response);
1785
- });
1786
- }
1787
- async configureMultipart(server, options) {
1788
- if (options) {
1789
- await server.register(
1790
- multipart__default.default,
1791
- typeof options === "object" ? options : {}
1792
- );
1793
- }
1794
- }
1795
1352
  async initModules() {
1796
1353
  const modules = this.moduleLoader.getAllModules();
1797
- const promises = [];
1798
- for (const [moduleName, moduleMetadata] of modules) {
1799
- if (!moduleMetadata.controllers || moduleMetadata.controllers.size === 0) {
1800
- continue;
1801
- }
1802
- promises.push(
1803
- this.server.register(
1804
- async (instance, opts) => {
1805
- for (const controller of moduleMetadata.controllers) {
1806
- await this.controllerAdapter.setupController(
1807
- controller,
1808
- instance,
1809
- moduleMetadata
1810
- );
1811
- }
1812
- },
1813
- {
1814
- prefix: this.globalPrefix ?? ""
1815
- }
1816
- )
1817
- );
1818
- }
1819
- await Promise.all(promises);
1354
+ await this.httpApplication?.onModulesInit(modules);
1820
1355
  }
1821
1356
  enableCors(options) {
1822
- this.corsOptions = options;
1357
+ if (!this.httpApplication) {
1358
+ throw new Error("HTTP application is not set");
1359
+ }
1360
+ this.httpApplication.enableCors(options);
1823
1361
  }
1824
1362
  enableMultipart(options) {
1825
- this.multipartOptions = options;
1363
+ if (!this.httpApplication) {
1364
+ throw new Error("HTTP application is not set");
1365
+ }
1366
+ this.httpApplication.enableMultipart(options);
1826
1367
  }
1827
1368
  setGlobalPrefix(prefix) {
1828
- this.globalPrefix = prefix;
1369
+ if (!this.httpApplication) {
1370
+ throw new Error("HTTP application is not set");
1371
+ }
1372
+ this.httpApplication.setGlobalPrefix(prefix);
1829
1373
  }
1830
1374
  getServer() {
1831
- if (!this.server) {
1832
- throw new Error("Server is not initialized. Call init() first.");
1375
+ if (!this.httpApplication) {
1376
+ throw new Error("HTTP application is not set");
1833
1377
  }
1834
- return this.server;
1378
+ return this.httpApplication.getServer();
1835
1379
  }
1836
1380
  async listen(options) {
1837
- if (!this.server) {
1838
- throw new Error("Server is not initialized. Call init() first.");
1381
+ if (!this.httpApplication) {
1382
+ throw new Error("HTTP application is not set");
1839
1383
  }
1840
- const res = await this.server.listen(options);
1841
- this.logger.debug(`Navios is listening on ${res}`);
1384
+ await this.httpApplication.listen(options);
1842
1385
  }
1843
1386
  async dispose() {
1844
- if (this.server) {
1845
- await this.server.close();
1846
- this.server = null;
1387
+ if (this.httpApplication) {
1388
+ await this.httpApplication.dispose();
1847
1389
  }
1848
1390
  if (this.moduleLoader) {
1849
1391
  this.moduleLoader.dispose();
@@ -1853,29 +1395,52 @@ var _NaviosApplication = class _NaviosApplication {
1853
1395
  await this.dispose();
1854
1396
  }
1855
1397
  };
1856
- _init11 = __decoratorStart(null);
1857
- _NaviosApplication = __decorateElement(_init11, 0, "NaviosApplication", _NaviosApplication_decorators, _NaviosApplication);
1858
- __runInitializers(_init11, 1, _NaviosApplication);
1398
+ _init13 = __decoratorStart();
1399
+ _NaviosApplication = __decorateElement(_init13, 0, "NaviosApplication", _NaviosApplication_decorators, _NaviosApplication);
1400
+ __runInitializers(_init13, 1, _NaviosApplication);
1859
1401
  var NaviosApplication = _NaviosApplication;
1860
1402
  var NaviosFactory = class {
1861
- static async create(appModule, options = {}) {
1862
- const app = await di.inject(NaviosApplication);
1863
- this.registerLoggerConfiguration(options);
1864
- app.setup(appModule, options);
1403
+ static async create(appModule, options = {
1404
+ adapter: []
1405
+ }) {
1406
+ const container = new di.Container();
1407
+ await this.registerLoggerConfiguration(container, options);
1408
+ const adapters = Array.isArray(options.adapter) ? options.adapter : [options.adapter];
1409
+ for (const adapter of adapters) {
1410
+ await this.registerEnvironment(container, adapter);
1411
+ }
1412
+ const app = await container.get(NaviosApplication);
1413
+ await app.setup(appModule, options);
1865
1414
  return app;
1866
1415
  }
1867
- static registerLoggerConfiguration(options) {
1868
- if (!options) {
1869
- return;
1416
+ static async registerEnvironment(container, environment = {}) {
1417
+ const naviosEnvironment = await container.get(NaviosEnvironment);
1418
+ const { httpTokens } = environment;
1419
+ if (httpTokens) {
1420
+ naviosEnvironment.setupHttpEnvironment(httpTokens);
1870
1421
  }
1422
+ }
1423
+ static async registerLoggerConfiguration(container, options) {
1871
1424
  const { logger } = options;
1425
+ if (Array.isArray(logger) || isNil(logger)) {
1426
+ const loggerInstance = await container.get(
1427
+ LoggerOutput
1428
+ );
1429
+ loggerInstance?.setup({
1430
+ logLevels: logger
1431
+ });
1432
+ }
1872
1433
  if (logger !== true && !isNil(logger)) {
1873
- LoggerInstance.overrideLogger(logger);
1434
+ container.getServiceLocator().getManager().storeCreatedHolder(
1435
+ LoggerOutput.toString(),
1436
+ logger,
1437
+ di.InjectableType.Class,
1438
+ di.InjectableScope.Singleton
1439
+ );
1874
1440
  }
1875
1441
  }
1876
1442
  };
1877
1443
 
1878
- exports.Application = Application;
1879
1444
  exports.AttributeFactory = AttributeFactory;
1880
1445
  exports.BadRequestException = BadRequestException;
1881
1446
  exports.ConfigProviderOptions = ConfigProviderOptions;
@@ -1883,9 +1448,7 @@ exports.ConfigService = ConfigService;
1883
1448
  exports.ConfigServiceOptionsSchema = ConfigServiceOptionsSchema;
1884
1449
  exports.ConfigServiceToken = ConfigServiceToken;
1885
1450
  exports.ConflictException = ConflictException;
1886
- exports.ConsoleLogger = ConsoleLogger;
1887
1451
  exports.Controller = Controller;
1888
- exports.ControllerAdapterService = ControllerAdapterService;
1889
1452
  exports.ControllerMetadataKey = ControllerMetadataKey;
1890
1453
  exports.Endpoint = Endpoint;
1891
1454
  exports.EndpointAdapterToken = EndpointAdapterToken;
@@ -1893,17 +1456,15 @@ exports.EndpointMetadataKey = EndpointMetadataKey;
1893
1456
  exports.EnvConfigProvider = EnvConfigProvider;
1894
1457
  exports.ExecutionContext = ExecutionContext;
1895
1458
  exports.ExecutionContextInjectionToken = ExecutionContextInjectionToken;
1896
- exports.ExecutionContextToken = ExecutionContextToken;
1897
1459
  exports.ForbiddenException = ForbiddenException;
1898
1460
  exports.Header = Header;
1461
+ exports.HttpAdapterToken = HttpAdapterToken;
1899
1462
  exports.HttpCode = HttpCode;
1900
1463
  exports.HttpException = HttpException;
1901
1464
  exports.InternalServerErrorException = InternalServerErrorException;
1902
1465
  exports.LOG_LEVELS = LOG_LEVELS;
1903
1466
  exports.Logger = Logger;
1904
- exports.LoggerInjectionToken = LoggerInjectionToken;
1905
- exports.LoggerInstance = LoggerInstance;
1906
- exports.LoggerOptions = LoggerOptions;
1467
+ exports.LoggerOutput = LoggerOutput;
1907
1468
  exports.Module = Module;
1908
1469
  exports.ModuleLoaderService = ModuleLoaderService;
1909
1470
  exports.ModuleMetadataKey = ModuleMetadataKey;
@@ -1912,7 +1473,6 @@ exports.MultipartAdapterToken = MultipartAdapterToken;
1912
1473
  exports.NaviosApplication = NaviosApplication;
1913
1474
  exports.NaviosFactory = NaviosFactory;
1914
1475
  exports.NotFoundException = NotFoundException;
1915
- exports.PinoWrapper = PinoWrapper;
1916
1476
  exports.Reply = Reply;
1917
1477
  exports.Request = Request;
1918
1478
  exports.Stream = Stream;
@@ -1944,6 +1504,7 @@ exports.isPlainObject = isPlainObject;
1944
1504
  exports.isString = isString;
1945
1505
  exports.isSymbol = isSymbol;
1946
1506
  exports.isUndefined = isUndefined;
1507
+ exports.loggerOptionsSchema = loggerOptionsSchema;
1947
1508
  exports.normalizePath = normalizePath;
1948
1509
  exports.provideConfig = provideConfig;
1949
1510
  exports.stripEndSlash = stripEndSlash;