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