@navios/core 0.3.0 → 0.5.0

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