@navios/core 0.1.12 → 0.1.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -92,7 +92,7 @@ __export(src_exports, {
92
92
  EndpointType: () => EndpointType,
93
93
  ErrorsEnum: () => ErrorsEnum,
94
94
  EventEmitter: () => EventEmitter,
95
- ExecutionContext: () => ExecutionContext2,
95
+ ExecutionContext: () => ExecutionContext,
96
96
  ExecutionContextInjectionToken: () => ExecutionContextInjectionToken,
97
97
  ExecutionContextToken: () => ExecutionContextToken,
98
98
  FactoryInjectionToken: () => FactoryInjectionToken,
@@ -188,7 +188,7 @@ function envString(key, defaultValue) {
188
188
  }
189
189
 
190
190
  // packages/core/src/config/config.provider.mts
191
- var import_zod3 = require("zod");
191
+ var import_zod4 = require("zod");
192
192
 
193
193
  // packages/core/src/logger/utils/cli-colors.util.mts
194
194
  var isColorAllowed = () => !process.env.NO_COLOR;
@@ -597,6 +597,7 @@ var ServiceLocator = class {
597
597
  destroyPromise: null,
598
598
  creationPromise: null
599
599
  });
600
+ this.eventBus.emit(instanceName, "create");
600
601
  }
601
602
  removeInstance(token) {
602
603
  const instanceName = this.getInstanceIdentifier(token, void 0);
@@ -1172,362 +1173,639 @@ function override(token, target) {
1172
1173
  };
1173
1174
  }
1174
1175
 
1175
- // packages/core/src/logger/console-logger.service.mts
1176
- var DEFAULT_DEPTH = 5;
1177
- var DEFAULT_LOG_LEVELS = [
1178
- "log",
1179
- "error",
1180
- "warn",
1181
- "debug",
1182
- "verbose",
1183
- "fatal"
1184
- ];
1185
- var dateTimeFormatter = new Intl.DateTimeFormat(void 0, {
1186
- year: "numeric",
1187
- hour: "numeric",
1188
- minute: "numeric",
1189
- second: "numeric",
1190
- day: "2-digit",
1191
- month: "2-digit"
1192
- });
1193
- var _ConsoleLogger_decorators, _init;
1194
- _ConsoleLogger_decorators = [Injectable()];
1195
- var _ConsoleLogger = class _ConsoleLogger {
1196
- /**
1197
- * The options of the logger.
1198
- */
1199
- options;
1200
- /**
1201
- * The context of the logger (can be set manually or automatically inferred).
1202
- */
1203
- context;
1204
- /**
1205
- * The original context of the logger (set in the constructor).
1206
- */
1207
- originalContext;
1208
- /**
1209
- * The options used for the "inspect" method.
1210
- */
1211
- inspectOptions;
1212
- /**
1213
- * The last timestamp at which the log message was printed.
1214
- */
1215
- static lastTimestampAt;
1216
- constructor(contextOrOptions, options) {
1217
- let [context, opts] = isString(contextOrOptions) ? [contextOrOptions, options] : options ? [void 0, options] : [contextOrOptions == null ? void 0 : contextOrOptions.context, contextOrOptions];
1218
- opts = opts ?? {};
1219
- opts.logLevels ??= DEFAULT_LOG_LEVELS;
1220
- opts.colors ??= opts.colors ?? (opts.json ? false : true);
1221
- opts.prefix ??= "Navios";
1222
- this.options = opts;
1223
- this.inspectOptions = this.getInspectOptions();
1224
- if (context) {
1225
- this.context = context;
1226
- this.originalContext = context;
1176
+ // packages/core/src/tokens/application.token.mts
1177
+ var ApplicationInjectionToken = "ApplicationInjectionToken";
1178
+ var Application = InjectionToken.create(
1179
+ ApplicationInjectionToken
1180
+ );
1181
+
1182
+ // packages/core/src/services/controller-adapter.service.mts
1183
+ var import_common3 = require("@navios/common");
1184
+ var import_zod2 = require("zod");
1185
+
1186
+ // packages/core/src/metadata/endpoint.metadata.mts
1187
+ var EndpointMetadataKey = Symbol("EndpointMetadataKey");
1188
+ var EndpointType = /* @__PURE__ */ ((EndpointType2) => {
1189
+ EndpointType2["Unknown"] = "unknown";
1190
+ EndpointType2["Endpoint"] = "endpoint";
1191
+ EndpointType2["Stream"] = "stream";
1192
+ EndpointType2["Multipart"] = "multipart";
1193
+ EndpointType2["Handler"] = "handler";
1194
+ return EndpointType2;
1195
+ })(EndpointType || {});
1196
+ function getAllEndpointMetadata(context) {
1197
+ if (context.metadata) {
1198
+ const metadata = context.metadata[EndpointMetadataKey];
1199
+ if (metadata) {
1200
+ return metadata;
1201
+ } else {
1202
+ context.metadata[EndpointMetadataKey] = /* @__PURE__ */ new Set();
1203
+ return context.metadata[EndpointMetadataKey];
1227
1204
  }
1228
1205
  }
1229
- log(message, ...optionalParams) {
1230
- if (!this.isLevelEnabled("log")) {
1231
- return;
1206
+ throw new Error("[Navios] Wrong environment.");
1207
+ }
1208
+ function getEndpointMetadata(target, context) {
1209
+ if (context.metadata) {
1210
+ const metadata = getAllEndpointMetadata(context);
1211
+ if (metadata) {
1212
+ const endpointMetadata = Array.from(metadata).find(
1213
+ (item) => item.classMethod === target.name
1214
+ );
1215
+ if (endpointMetadata) {
1216
+ return endpointMetadata;
1217
+ } else {
1218
+ const newMetadata = {
1219
+ classMethod: target.name,
1220
+ url: "",
1221
+ successStatusCode: 200,
1222
+ headers: {},
1223
+ type: "unknown" /* Unknown */,
1224
+ httpMethod: "GET",
1225
+ config: null,
1226
+ guards: /* @__PURE__ */ new Set(),
1227
+ customAttributes: /* @__PURE__ */ new Map()
1228
+ };
1229
+ metadata.add(newMetadata);
1230
+ return newMetadata;
1231
+ }
1232
1232
  }
1233
- const { messages, context } = this.getContextAndMessagesToPrint([
1234
- message,
1235
- ...optionalParams
1236
- ]);
1237
- this.printMessages(messages, context, "log");
1238
1233
  }
1239
- error(message, ...optionalParams) {
1240
- if (!this.isLevelEnabled("error")) {
1241
- return;
1234
+ throw new Error("[Navios] Wrong environment.");
1235
+ }
1236
+
1237
+ // packages/core/src/metadata/controller.metadata.mts
1238
+ var ControllerMetadataKey = Symbol("ControllerMetadataKey");
1239
+ function getControllerMetadata(target, context) {
1240
+ if (context.metadata) {
1241
+ const metadata = context.metadata[ControllerMetadataKey];
1242
+ if (metadata) {
1243
+ return metadata;
1244
+ } else {
1245
+ const endpointsMetadata = getAllEndpointMetadata(context);
1246
+ const newMetadata = {
1247
+ endpoints: endpointsMetadata,
1248
+ guards: /* @__PURE__ */ new Set(),
1249
+ customAttributes: /* @__PURE__ */ new Map()
1250
+ };
1251
+ context.metadata[ControllerMetadataKey] = newMetadata;
1252
+ target[ControllerMetadataKey] = newMetadata;
1253
+ return newMetadata;
1242
1254
  }
1243
- const { messages, context, stack } = this.getContextAndStackAndMessagesToPrint([message, ...optionalParams]);
1244
- this.printMessages(messages, context, "error", "stderr", stack);
1245
- this.printStackTrace(stack);
1246
1255
  }
1247
- warn(message, ...optionalParams) {
1248
- if (!this.isLevelEnabled("warn")) {
1249
- return;
1250
- }
1251
- const { messages, context } = this.getContextAndMessagesToPrint([
1252
- message,
1253
- ...optionalParams
1254
- ]);
1255
- this.printMessages(messages, context, "warn");
1256
+ throw new Error("[Navios] Wrong environment.");
1257
+ }
1258
+ function extractControllerMetadata(target) {
1259
+ const metadata = target[ControllerMetadataKey];
1260
+ if (!metadata) {
1261
+ throw new Error(
1262
+ "[Navios] Controller metadata not found. Make sure to use @Controller decorator."
1263
+ );
1256
1264
  }
1257
- debug(message, ...optionalParams) {
1258
- if (!this.isLevelEnabled("debug")) {
1259
- return;
1265
+ return metadata;
1266
+ }
1267
+ function hasControllerMetadata(target) {
1268
+ const metadata = target[ControllerMetadataKey];
1269
+ return !!metadata;
1270
+ }
1271
+
1272
+ // packages/core/src/metadata/module.metadata.mts
1273
+ var ModuleMetadataKey = Symbol("ControllerMetadataKey");
1274
+ function getModuleMetadata(target, context) {
1275
+ if (context.metadata) {
1276
+ const metadata = context.metadata[ModuleMetadataKey];
1277
+ if (metadata) {
1278
+ return metadata;
1279
+ } else {
1280
+ const newMetadata = {
1281
+ controllers: /* @__PURE__ */ new Set(),
1282
+ imports: /* @__PURE__ */ new Set(),
1283
+ guards: /* @__PURE__ */ new Set(),
1284
+ customAttributes: /* @__PURE__ */ new Map()
1285
+ };
1286
+ context.metadata[ModuleMetadataKey] = newMetadata;
1287
+ target[ModuleMetadataKey] = newMetadata;
1288
+ return newMetadata;
1260
1289
  }
1261
- const { messages, context } = this.getContextAndMessagesToPrint([
1262
- message,
1263
- ...optionalParams
1264
- ]);
1265
- this.printMessages(messages, context, "debug");
1266
1290
  }
1267
- verbose(message, ...optionalParams) {
1268
- if (!this.isLevelEnabled("verbose")) {
1269
- return;
1270
- }
1271
- const { messages, context } = this.getContextAndMessagesToPrint([
1272
- message,
1273
- ...optionalParams
1274
- ]);
1275
- this.printMessages(messages, context, "verbose");
1291
+ throw new Error("[Navios] Wrong environment.");
1292
+ }
1293
+ function extractModuleMetadata(target) {
1294
+ const metadata = target[ModuleMetadataKey];
1295
+ if (!metadata) {
1296
+ throw new Error(
1297
+ `[Navios] Module metadata not found for ${target.name}. Make sure to use @Module decorator.`
1298
+ );
1276
1299
  }
1277
- fatal(message, ...optionalParams) {
1278
- if (!this.isLevelEnabled("fatal")) {
1279
- return;
1280
- }
1281
- const { messages, context } = this.getContextAndMessagesToPrint([
1282
- message,
1283
- ...optionalParams
1284
- ]);
1285
- this.printMessages(messages, context, "fatal");
1300
+ return metadata;
1301
+ }
1302
+ function hasModuleMetadata(target) {
1303
+ return !!target[ModuleMetadataKey];
1304
+ }
1305
+
1306
+ // packages/core/src/services/execution-context.mts
1307
+ var ExecutionContext = class {
1308
+ constructor(module2, controller, handler) {
1309
+ this.module = module2;
1310
+ this.controller = controller;
1311
+ this.handler = handler;
1286
1312
  }
1287
- /**
1288
- * Set log levels
1289
- * @param levels log levels
1290
- */
1291
- setLogLevels(levels) {
1292
- if (!this.options) {
1293
- this.options = {};
1294
- }
1295
- this.options.logLevels = levels;
1313
+ request;
1314
+ reply;
1315
+ getModule() {
1316
+ return this.module;
1296
1317
  }
1297
- /**
1298
- * Set logger context
1299
- * @param context context
1300
- */
1301
- setContext(context) {
1302
- this.context = context;
1318
+ getController() {
1319
+ return this.controller;
1303
1320
  }
1304
- /**
1305
- * Resets the logger context to the value that was passed in the constructor.
1306
- */
1307
- resetContext() {
1308
- this.context = this.originalContext;
1321
+ getHandler() {
1322
+ return this.handler;
1309
1323
  }
1310
- isLevelEnabled(level) {
1311
- var _a;
1312
- const logLevels = (_a = this.options) == null ? void 0 : _a.logLevels;
1313
- return isLogLevelEnabled(level, logLevels);
1314
- }
1315
- getTimestamp() {
1316
- return dateTimeFormatter.format(Date.now());
1317
- }
1318
- printMessages(messages, context = "", logLevel = "log", writeStreamType, errorStack) {
1319
- messages.forEach((message) => {
1320
- if (this.options.json) {
1321
- this.printAsJson(message, {
1322
- context,
1323
- logLevel,
1324
- writeStreamType,
1325
- errorStack
1326
- });
1327
- return;
1328
- }
1329
- const pidMessage = this.formatPid(process.pid);
1330
- const contextMessage = this.formatContext(context);
1331
- const timestampDiff = this.updateAndGetTimestampDiff();
1332
- const formattedLogLevel = logLevel.toUpperCase().padStart(7, " ");
1333
- const formattedMessage = this.formatMessage(
1334
- logLevel,
1335
- message,
1336
- pidMessage,
1337
- formattedLogLevel,
1338
- contextMessage,
1339
- timestampDiff
1324
+ getRequest() {
1325
+ if (!this.request) {
1326
+ throw new Error(
1327
+ "[Navios] Request is not set. Make sure to set it before using it."
1340
1328
  );
1341
- process[writeStreamType ?? "stdout"].write(formattedMessage);
1342
- });
1343
- }
1344
- printAsJson(message, options) {
1345
- const logObject = {
1346
- level: options.logLevel,
1347
- pid: process.pid,
1348
- timestamp: Date.now(),
1349
- message
1350
- };
1351
- if (options.context) {
1352
- logObject.context = options.context;
1353
1329
  }
1354
- if (options.errorStack) {
1355
- logObject.stack = options.errorStack;
1330
+ return this.request;
1331
+ }
1332
+ getReply() {
1333
+ if (!this.reply) {
1334
+ throw new Error(
1335
+ "[Navios] Reply is not set. Make sure to set it before using it."
1336
+ );
1356
1337
  }
1357
- const formattedMessage = !this.options.colors && this.inspectOptions.compact === true ? JSON.stringify(logObject, this.stringifyReplacer) : (0, import_util.inspect)(logObject, this.inspectOptions);
1358
- process[options.writeStreamType ?? "stdout"].write(`${formattedMessage}
1359
- `);
1338
+ return this.reply;
1360
1339
  }
1361
- formatPid(pid) {
1362
- return `[${this.options.prefix}] ${pid} - `;
1340
+ provideRequest(request) {
1341
+ this.request = request;
1363
1342
  }
1364
- formatContext(context) {
1365
- if (!context) {
1366
- return "";
1367
- }
1368
- context = `[${context}] `;
1369
- return this.options.colors ? yellow(context) : context;
1343
+ provideReply(reply) {
1344
+ this.reply = reply;
1370
1345
  }
1371
- formatMessage(logLevel, message, pidMessage, formattedLogLevel, contextMessage, timestampDiff) {
1372
- const output = this.stringifyMessage(message, logLevel);
1373
- pidMessage = this.colorize(pidMessage, logLevel);
1374
- formattedLogLevel = this.colorize(formattedLogLevel, logLevel);
1375
- return `${pidMessage}${this.getTimestamp()} ${formattedLogLevel} ${contextMessage}${output}${timestampDiff}
1376
- `;
1346
+ };
1347
+
1348
+ // packages/core/src/exceptions/http.exception.mts
1349
+ var HttpException = class {
1350
+ constructor(statusCode, response, error) {
1351
+ this.statusCode = statusCode;
1352
+ this.response = response;
1353
+ this.error = error;
1377
1354
  }
1378
- stringifyMessage(message, logLevel) {
1379
- if (isFunction(message)) {
1380
- const messageAsStr = Function.prototype.toString.call(message);
1381
- const isClass = messageAsStr.startsWith("class ");
1382
- if (isClass) {
1383
- return this.stringifyMessage(message.name, logLevel);
1384
- }
1385
- return this.stringifyMessage(message(), logLevel);
1386
- }
1387
- if (typeof message === "string") {
1388
- return this.colorize(message, logLevel);
1389
- }
1390
- const outputText = (0, import_util.inspect)(message, this.inspectOptions);
1391
- if (isPlainObject(message)) {
1392
- return `Object(${Object.keys(message).length}) ${outputText}`;
1393
- }
1394
- if (Array.isArray(message)) {
1395
- return `Array(${message.length}) ${outputText}`;
1396
- }
1397
- return outputText;
1355
+ };
1356
+
1357
+ // packages/core/src/exceptions/bad-request.exception.mts
1358
+ var BadRequestException = class extends HttpException {
1359
+ constructor(message) {
1360
+ super(400, message);
1398
1361
  }
1399
- colorize(message, logLevel) {
1400
- if (!this.options.colors || this.options.json) {
1401
- return message;
1402
- }
1403
- const color = this.getColorByLogLevel(logLevel);
1404
- return color(message);
1362
+ };
1363
+
1364
+ // packages/core/src/exceptions/forbidden.exception.mts
1365
+ var ForbiddenException = class extends HttpException {
1366
+ constructor(message) {
1367
+ super(403, message);
1405
1368
  }
1406
- printStackTrace(stack) {
1407
- if (!stack || this.options.json) {
1408
- return;
1409
- }
1410
- process.stderr.write(`${stack}
1411
- `);
1369
+ };
1370
+
1371
+ // packages/core/src/exceptions/internal-server-error.exception.mts
1372
+ var InternalServerErrorException = class extends HttpException {
1373
+ constructor(message, error) {
1374
+ super(500, message, error);
1412
1375
  }
1413
- updateAndGetTimestampDiff() {
1414
- var _a;
1415
- const includeTimestamp = _ConsoleLogger.lastTimestampAt && ((_a = this.options) == null ? void 0 : _a.timestamp);
1416
- const result = includeTimestamp ? this.formatTimestampDiff(Date.now() - _ConsoleLogger.lastTimestampAt) : "";
1417
- _ConsoleLogger.lastTimestampAt = Date.now();
1418
- return result;
1376
+ };
1377
+
1378
+ // packages/core/src/exceptions/not-found.exception.mts
1379
+ var NotFoundException = class extends HttpException {
1380
+ constructor(response, error) {
1381
+ super(404, response, error);
1382
+ this.response = response;
1383
+ this.error = error;
1419
1384
  }
1420
- formatTimestampDiff(timestampDiff) {
1421
- const formattedDiff = ` +${timestampDiff}ms`;
1422
- return this.options.colors ? yellow(formattedDiff) : formattedDiff;
1385
+ };
1386
+
1387
+ // packages/core/src/exceptions/unauthorized.exception.mts
1388
+ var UnauthorizedException = class extends HttpException {
1389
+ constructor(message, error) {
1390
+ super(401, message, error);
1423
1391
  }
1424
- getInspectOptions() {
1425
- let breakLength = this.options.breakLength;
1426
- if (typeof breakLength === "undefined") {
1427
- breakLength = this.options.colors ? this.options.compact ? Infinity : void 0 : this.options.compact === false ? void 0 : Infinity;
1428
- }
1429
- const inspectOptions = {
1430
- depth: this.options.depth ?? DEFAULT_DEPTH,
1431
- sorted: this.options.sorted,
1432
- showHidden: this.options.showHidden,
1433
- compact: this.options.compact ?? (this.options.json ? true : false),
1434
- colors: this.options.colors,
1435
- breakLength
1436
- };
1437
- if (this.options.maxArrayLength) {
1438
- inspectOptions.maxArrayLength = this.options.maxArrayLength;
1392
+ };
1393
+
1394
+ // packages/core/src/exceptions/conflict.exception.mts
1395
+ var ConflictException = class extends HttpException {
1396
+ constructor(message, error) {
1397
+ super(409, message, error);
1398
+ }
1399
+ };
1400
+
1401
+ // packages/core/src/services/guard-runner.service.mts
1402
+ var _GuardRunnerService_decorators, _init;
1403
+ _GuardRunnerService_decorators = [Injectable()];
1404
+ var GuardRunnerService = class {
1405
+ async runGuards(allGuards, executionContext) {
1406
+ let canActivate = true;
1407
+ for (const guard of Array.from(allGuards).reverse()) {
1408
+ const guardInstance = await inject(
1409
+ guard
1410
+ );
1411
+ if (!guardInstance.canActivate) {
1412
+ throw new Error(
1413
+ `[Navios] Guard ${guard.name} does not implement canActivate()`
1414
+ );
1415
+ }
1416
+ try {
1417
+ canActivate = await guardInstance.canActivate(executionContext);
1418
+ if (!canActivate) {
1419
+ break;
1420
+ }
1421
+ } catch (error) {
1422
+ if (error instanceof HttpException) {
1423
+ executionContext.getReply().status(error.statusCode).send(error.response);
1424
+ return false;
1425
+ } else {
1426
+ executionContext.getReply().status(500).send({
1427
+ message: "Internal server error",
1428
+ error: error.message
1429
+ });
1430
+ return false;
1431
+ }
1432
+ }
1439
1433
  }
1440
- if (this.options.maxStringLength) {
1441
- inspectOptions.maxStringLength = this.options.maxStringLength;
1434
+ if (!canActivate) {
1435
+ executionContext.getReply().status(403).send({
1436
+ message: "Forbidden"
1437
+ });
1438
+ return false;
1442
1439
  }
1443
- return inspectOptions;
1440
+ return canActivate;
1444
1441
  }
1445
- stringifyReplacer(key, value) {
1446
- if (typeof value === "bigint") {
1447
- return value.toString();
1442
+ makeContext(executionContext) {
1443
+ const guards = /* @__PURE__ */ new Set();
1444
+ const endpointGuards = executionContext.getHandler().guards;
1445
+ const controllerGuards = executionContext.getController().guards;
1446
+ const moduleGuards = executionContext.getModule().guards;
1447
+ if (endpointGuards.size > 0) {
1448
+ for (const guard of endpointGuards) {
1449
+ guards.add(guard);
1450
+ }
1448
1451
  }
1449
- if (typeof value === "symbol") {
1450
- return value.toString();
1452
+ if (controllerGuards.size > 0) {
1453
+ for (const guard of controllerGuards) {
1454
+ guards.add(guard);
1455
+ }
1451
1456
  }
1452
- if (value instanceof Map || value instanceof Set || value instanceof Error) {
1453
- return `${(0, import_util.inspect)(value, this.inspectOptions)}`;
1457
+ if (moduleGuards.size > 0) {
1458
+ for (const guard of moduleGuards) {
1459
+ guards.add(guard);
1460
+ }
1454
1461
  }
1455
- return value;
1462
+ return guards;
1456
1463
  }
1457
- getContextAndMessagesToPrint(args) {
1458
- if ((args == null ? void 0 : args.length) <= 1) {
1459
- return { messages: args, context: this.context };
1460
- }
1461
- const lastElement = args[args.length - 1];
1462
- const isContext = isString(lastElement);
1463
- if (!isContext) {
1464
- return { messages: args, context: this.context };
1465
- }
1466
- return {
1467
- context: lastElement,
1468
- messages: args.slice(0, args.length - 1)
1469
- };
1464
+ };
1465
+ _init = __decoratorStart(null);
1466
+ GuardRunnerService = __decorateElement(_init, 0, "GuardRunnerService", _GuardRunnerService_decorators, GuardRunnerService);
1467
+ __runInitializers(_init, 1, GuardRunnerService);
1468
+
1469
+ // packages/core/src/services/controller-adapter.service.mts
1470
+ var _ControllerAdapterService_decorators, _init2;
1471
+ _ControllerAdapterService_decorators = [Injectable()];
1472
+ var _ControllerAdapterService = class _ControllerAdapterService {
1473
+ guardRunner = syncInject(GuardRunnerService);
1474
+ logger = syncInject(Logger, {
1475
+ context: _ControllerAdapterService.name
1476
+ });
1477
+ setupController(controller, instance, moduleMetadata) {
1478
+ const controllerMetadata = extractControllerMetadata(controller);
1479
+ for (const endpoint of controllerMetadata.endpoints) {
1480
+ const { classMethod, url, httpMethod } = endpoint;
1481
+ if (!url) {
1482
+ throw new Error(
1483
+ `[Navios] Malformed Endpoint ${controller.name}:${classMethod}`
1484
+ );
1485
+ }
1486
+ const executionContext = new ExecutionContext(
1487
+ moduleMetadata,
1488
+ controllerMetadata,
1489
+ endpoint
1490
+ );
1491
+ instance.withTypeProvider().route({
1492
+ method: httpMethod,
1493
+ url: url.replaceAll("$", ":"),
1494
+ schema: this.provideSchemaForConfig(endpoint),
1495
+ preHandler: this.providePreHandler(executionContext),
1496
+ handler: this.provideHandler(controller, executionContext, endpoint)
1497
+ });
1498
+ this.logger.debug(
1499
+ `Registered ${httpMethod} ${url} for ${controller.name}:${classMethod}`
1500
+ );
1501
+ }
1470
1502
  }
1471
- getContextAndStackAndMessagesToPrint(args) {
1472
- if (args.length === 2) {
1473
- return this.isStackFormat(args[1]) ? {
1474
- messages: [args[0]],
1475
- stack: args[1],
1476
- context: this.context
1477
- } : {
1478
- messages: [args[0]],
1479
- context: args[1]
1480
- };
1503
+ providePreHandler(executionContext) {
1504
+ const guards = this.guardRunner.makeContext(executionContext);
1505
+ return guards.size > 0 ? async (request, reply) => {
1506
+ getServiceLocator().registerInstance(Request, request);
1507
+ getServiceLocator().registerInstance(Reply, reply);
1508
+ getServiceLocator().registerInstance(
1509
+ ExecutionContextToken,
1510
+ executionContext
1511
+ );
1512
+ executionContext.provideRequest(request);
1513
+ executionContext.provideReply(reply);
1514
+ let canActivate = true;
1515
+ try {
1516
+ canActivate = await this.guardRunner.runGuards(
1517
+ guards,
1518
+ executionContext
1519
+ );
1520
+ } finally {
1521
+ getServiceLocator().removeInstance(Request);
1522
+ getServiceLocator().removeInstance(Reply);
1523
+ getServiceLocator().removeInstance(ExecutionContextToken);
1524
+ }
1525
+ if (!canActivate) {
1526
+ return reply;
1527
+ }
1528
+ } : void 0;
1529
+ }
1530
+ provideSchemaForConfig(endpointMetadata) {
1531
+ if (!endpointMetadata.config) {
1532
+ this.logger.warn(`No config found for endpoint ${endpointMetadata.url}`);
1533
+ return {};
1481
1534
  }
1482
- const { messages, context } = this.getContextAndMessagesToPrint(args);
1483
- if ((messages == null ? void 0 : messages.length) <= 1) {
1484
- return { messages, context };
1535
+ const { querySchema, requestSchema, responseSchema } = endpointMetadata.config;
1536
+ const schema = {};
1537
+ if (querySchema) {
1538
+ schema.querystring = querySchema;
1485
1539
  }
1486
- const lastElement = messages[messages.length - 1];
1487
- const isStack = isString(lastElement);
1488
- if (!isStack && !isUndefined(lastElement)) {
1489
- return { messages, context };
1540
+ if (requestSchema && endpointMetadata.type !== "multipart" /* Multipart */) {
1541
+ schema.body = requestSchema;
1490
1542
  }
1491
- return {
1492
- stack: lastElement,
1493
- messages: messages.slice(0, messages.length - 1),
1494
- context
1543
+ if (responseSchema) {
1544
+ schema.response = {
1545
+ 200: responseSchema
1546
+ };
1547
+ }
1548
+ return schema;
1549
+ }
1550
+ provideHandler(controller, executionContext, endpointMetadata) {
1551
+ switch (endpointMetadata.type) {
1552
+ case "unknown" /* Unknown */:
1553
+ this.logger.error(
1554
+ `Unknown endpoint type ${endpointMetadata.type} for ${controller.name}:${endpointMetadata.classMethod}`
1555
+ );
1556
+ throw new import_common3.NaviosException("Unknown endpoint type");
1557
+ case "endpoint" /* Endpoint */:
1558
+ return this.provideHandlerForConfig(
1559
+ controller,
1560
+ executionContext,
1561
+ endpointMetadata
1562
+ );
1563
+ case "stream" /* Stream */:
1564
+ return this.provideHandlerForStream(
1565
+ controller,
1566
+ executionContext,
1567
+ endpointMetadata
1568
+ );
1569
+ case "multipart" /* Multipart */:
1570
+ return this.provideHandlerForMultipart(
1571
+ controller,
1572
+ executionContext,
1573
+ endpointMetadata
1574
+ );
1575
+ case "handler" /* Handler */:
1576
+ this.logger.error("Not implemented yet");
1577
+ throw new import_common3.NaviosException("Not implemented yet");
1578
+ }
1579
+ }
1580
+ provideHandlerForConfig(controller, executionContext, endpointMetadata) {
1581
+ return async (request, reply) => {
1582
+ getServiceLocator().registerInstance(Request, request);
1583
+ getServiceLocator().registerInstance(Reply, reply);
1584
+ getServiceLocator().registerInstance(
1585
+ ExecutionContextToken,
1586
+ executionContext
1587
+ );
1588
+ executionContext.provideRequest(request);
1589
+ executionContext.provideReply(reply);
1590
+ const controllerInstance = await inject(controller);
1591
+ try {
1592
+ const { query, params, body } = request;
1593
+ const argument = {};
1594
+ if (query && Object.keys(query).length > 0) {
1595
+ argument.params = query;
1596
+ }
1597
+ if (params && Object.keys(params).length > 0) {
1598
+ argument.urlParams = params;
1599
+ }
1600
+ if (body) {
1601
+ argument.data = body;
1602
+ }
1603
+ const result = await controllerInstance[endpointMetadata.classMethod](argument);
1604
+ reply.status(endpointMetadata.successStatusCode).headers(endpointMetadata.headers).send(result);
1605
+ } finally {
1606
+ getServiceLocator().removeInstance(Request);
1607
+ getServiceLocator().removeInstance(Reply);
1608
+ getServiceLocator().removeInstance(ExecutionContextToken);
1609
+ }
1495
1610
  };
1496
1611
  }
1497
- isStackFormat(stack) {
1498
- if (!isString(stack) && !isUndefined(stack)) {
1499
- return false;
1612
+ provideHandlerForStream(controller, executionContext, endpointMetadata) {
1613
+ return async (request, reply) => {
1614
+ getServiceLocator().registerInstance(Request, request);
1615
+ getServiceLocator().registerInstance(Reply, reply);
1616
+ getServiceLocator().registerInstance(
1617
+ ExecutionContextToken,
1618
+ executionContext
1619
+ );
1620
+ executionContext.provideRequest(request);
1621
+ executionContext.provideReply(reply);
1622
+ const controllerInstance = await inject(controller);
1623
+ try {
1624
+ const { query, params, body } = request;
1625
+ const argument = {};
1626
+ if (query && Object.keys(query).length > 0) {
1627
+ argument.params = query;
1628
+ }
1629
+ if (params && Object.keys(params).length > 0) {
1630
+ argument.urlParams = params;
1631
+ }
1632
+ if (body) {
1633
+ argument.data = body;
1634
+ }
1635
+ await controllerInstance[endpointMetadata.classMethod](argument, reply);
1636
+ } finally {
1637
+ getServiceLocator().removeInstance(Request);
1638
+ getServiceLocator().removeInstance(Reply);
1639
+ getServiceLocator().removeInstance(ExecutionContextToken);
1640
+ }
1641
+ };
1642
+ }
1643
+ provideHandlerForMultipart(controller, executionContext, endpointMetadata) {
1644
+ const config = endpointMetadata.config;
1645
+ const requestSchema = config.requestSchema;
1646
+ const shape = requestSchema._def.shape();
1647
+ return async (request, reply) => {
1648
+ getServiceLocator().registerInstance(Request, request);
1649
+ getServiceLocator().registerInstance(Reply, reply);
1650
+ getServiceLocator().registerInstance(
1651
+ ExecutionContextToken,
1652
+ executionContext
1653
+ );
1654
+ executionContext.provideRequest(request);
1655
+ executionContext.provideReply(reply);
1656
+ const controllerInstance = await inject(controller);
1657
+ try {
1658
+ const parts = request.parts();
1659
+ const { query, params } = request;
1660
+ const argument = {};
1661
+ if (query && Object.keys(query).length > 0) {
1662
+ argument.params = query;
1663
+ }
1664
+ if (params && Object.keys(params).length > 0) {
1665
+ argument.urlParams = params;
1666
+ }
1667
+ const req = {};
1668
+ for await (const part of parts) {
1669
+ if (!shape[part.fieldname]) {
1670
+ throw new import_common3.NaviosException(
1671
+ `Invalid field name ${part.fieldname} for multipart request`
1672
+ );
1673
+ }
1674
+ const schema = shape[part.fieldname];
1675
+ if (part.type === "file") {
1676
+ const file = new File([await part.toBuffer()], part.filename, {
1677
+ type: part.mimetype
1678
+ });
1679
+ if (schema instanceof import_zod2.ZodArray) {
1680
+ if (!req[part.fieldname]) {
1681
+ req[part.fieldname] = [];
1682
+ }
1683
+ req[part.fieldname].push(file);
1684
+ } else {
1685
+ req[part.fieldname] = file;
1686
+ }
1687
+ } else {
1688
+ if (schema instanceof import_zod2.ZodArray) {
1689
+ if (!req[part.fieldname]) {
1690
+ req[part.fieldname] = [];
1691
+ }
1692
+ req[part.fieldname].push(part.value);
1693
+ } else {
1694
+ req[part.fieldname] = part.value;
1695
+ }
1696
+ }
1697
+ }
1698
+ argument.data = requestSchema.parse(req);
1699
+ const result = await controllerInstance[endpointMetadata.classMethod](argument);
1700
+ reply.status(endpointMetadata.successStatusCode).headers(endpointMetadata.headers).send(result);
1701
+ } finally {
1702
+ getServiceLocator().removeInstance(Request);
1703
+ getServiceLocator().removeInstance(Reply);
1704
+ getServiceLocator().removeInstance(ExecutionContextToken);
1705
+ }
1706
+ };
1707
+ }
1708
+ };
1709
+ _init2 = __decoratorStart(null);
1710
+ _ControllerAdapterService = __decorateElement(_init2, 0, "ControllerAdapterService", _ControllerAdapterService_decorators, _ControllerAdapterService);
1711
+ __runInitializers(_init2, 1, _ControllerAdapterService);
1712
+ var ControllerAdapterService = _ControllerAdapterService;
1713
+
1714
+ // packages/core/src/services/module-loader.service.mts
1715
+ var _ModuleLoaderService_decorators, _init3;
1716
+ _ModuleLoaderService_decorators = [Injectable()];
1717
+ var _ModuleLoaderService = class _ModuleLoaderService {
1718
+ logger = syncInject(Logger, {
1719
+ context: _ModuleLoaderService.name
1720
+ });
1721
+ modulesMetadata = /* @__PURE__ */ new Map();
1722
+ loadedModules = /* @__PURE__ */ new Map();
1723
+ initialized = false;
1724
+ async loadModules(appModule) {
1725
+ if (this.initialized) {
1726
+ return;
1500
1727
  }
1501
- return /^(.)+\n\s+at .+:\d+:\d+/.test(stack);
1728
+ await this.traverseModules(appModule);
1729
+ this.initialized = true;
1502
1730
  }
1503
- getColorByLogLevel(level) {
1504
- switch (level) {
1505
- case "debug":
1506
- return clc.magentaBright;
1507
- case "warn":
1508
- return clc.yellow;
1509
- case "error":
1510
- return clc.red;
1511
- case "verbose":
1512
- return clc.cyanBright;
1513
- case "fatal":
1514
- return clc.bold;
1515
- default:
1516
- return clc.green;
1731
+ async traverseModules(module2, parentMetadata) {
1732
+ const metadata = extractModuleMetadata(module2);
1733
+ if (parentMetadata) {
1734
+ this.mergeMetadata(metadata, parentMetadata);
1735
+ }
1736
+ const moduleName = module2.name;
1737
+ if (this.modulesMetadata.has(moduleName)) {
1738
+ return;
1517
1739
  }
1740
+ this.modulesMetadata.set(moduleName, metadata);
1741
+ const imports = metadata.imports ?? /* @__PURE__ */ new Set();
1742
+ const loadingPromises = Array.from(imports).map(
1743
+ async (importedModule) => this.traverseModules(importedModule, metadata)
1744
+ );
1745
+ await Promise.all(loadingPromises);
1746
+ const instance = await inject(module2);
1747
+ if (instance.onModuleInit) {
1748
+ await instance.onModuleInit();
1749
+ }
1750
+ this.logger.debug(`Module ${moduleName} loaded`);
1751
+ this.loadedModules.set(moduleName, instance);
1752
+ }
1753
+ mergeMetadata(metadata, parentMetadata) {
1754
+ if (parentMetadata.guards) {
1755
+ for (const guard of parentMetadata.guards) {
1756
+ metadata.guards.add(guard);
1757
+ }
1758
+ }
1759
+ if (parentMetadata.customAttributes) {
1760
+ for (const [key, value] of parentMetadata.customAttributes) {
1761
+ if (metadata.customAttributes.has(key)) {
1762
+ continue;
1763
+ }
1764
+ metadata.customAttributes.set(key, value);
1765
+ }
1766
+ }
1767
+ }
1768
+ getAllModules() {
1769
+ return this.modulesMetadata;
1770
+ }
1771
+ dispose() {
1772
+ this.modulesMetadata.clear();
1773
+ this.loadedModules.clear();
1774
+ this.initialized = false;
1518
1775
  }
1519
1776
  };
1520
- _init = __decoratorStart(null);
1521
- _ConsoleLogger = __decorateElement(_init, 0, "ConsoleLogger", _ConsoleLogger_decorators, _ConsoleLogger);
1522
- __runInitializers(_init, 1, _ConsoleLogger);
1523
- var ConsoleLogger = _ConsoleLogger;
1777
+ _init3 = __decoratorStart(null);
1778
+ _ModuleLoaderService = __decorateElement(_init3, 0, "ModuleLoaderService", _ModuleLoaderService_decorators, _ModuleLoaderService);
1779
+ __runInitializers(_init3, 1, _ModuleLoaderService);
1780
+ var ModuleLoaderService = _ModuleLoaderService;
1524
1781
 
1525
- // packages/core/src/logger/logger.factory.mts
1526
- var import_zod2 = require("zod");
1782
+ // packages/core/src/tokens/execution-context.token.mts
1783
+ var ExecutionContextInjectionToken = "ExecutionContextInjectionToken";
1784
+ var ExecutionContextToken = InjectionToken.create(
1785
+ ExecutionContextInjectionToken
1786
+ );
1527
1787
 
1528
- // packages/core/src/logger/logger.service.mts
1529
- var DEFAULT_LOGGER = new ConsoleLogger();
1530
- var dateTimeFormatter2 = new Intl.DateTimeFormat(void 0, {
1788
+ // packages/core/src/tokens/reply.token.mts
1789
+ var ReplyInjectionToken = "ReplyInjectionToken";
1790
+ var Reply = InjectionToken.create(ReplyInjectionToken);
1791
+
1792
+ // packages/core/src/tokens/request.token.mts
1793
+ var RequestInjectionToken = "RequestInjectionToken";
1794
+ var Request = InjectionToken.create(
1795
+ RequestInjectionToken
1796
+ );
1797
+
1798
+ // packages/core/src/logger/console-logger.service.mts
1799
+ var DEFAULT_DEPTH = 5;
1800
+ var DEFAULT_LOG_LEVELS = [
1801
+ "log",
1802
+ "error",
1803
+ "warn",
1804
+ "debug",
1805
+ "verbose",
1806
+ "fatal"
1807
+ ];
1808
+ var dateTimeFormatter = new Intl.DateTimeFormat(void 0, {
1531
1809
  year: "numeric",
1532
1810
  hour: "numeric",
1533
1811
  minute: "numeric",
@@ -1535,1106 +1813,856 @@ var dateTimeFormatter2 = new Intl.DateTimeFormat(void 0, {
1535
1813
  day: "2-digit",
1536
1814
  month: "2-digit"
1537
1815
  });
1538
- var _LoggerInstance_decorators, _init2;
1539
- _LoggerInstance_decorators = [Injectable()];
1540
- var _LoggerInstance = class _LoggerInstance {
1541
- constructor(context, options = {}) {
1542
- this.context = context;
1543
- this.options = options;
1544
- }
1545
- static staticInstanceRef = DEFAULT_LOGGER;
1546
- static logLevels;
1547
- localInstanceRef;
1548
- get localInstance() {
1549
- if (_LoggerInstance.staticInstanceRef === DEFAULT_LOGGER) {
1550
- return this.registerLocalInstanceRef();
1551
- } else if (_LoggerInstance.staticInstanceRef instanceof _LoggerInstance) {
1552
- const prototype = Object.getPrototypeOf(_LoggerInstance.staticInstanceRef);
1553
- if (prototype.constructor === _LoggerInstance) {
1554
- return this.registerLocalInstanceRef();
1555
- }
1556
- }
1557
- return _LoggerInstance.staticInstanceRef;
1558
- }
1559
- error(message, ...optionalParams) {
1560
- var _a;
1561
- optionalParams = this.context ? (optionalParams.length ? optionalParams : [void 0]).concat(
1562
- this.context
1563
- ) : optionalParams;
1564
- (_a = this.localInstance) == null ? void 0 : _a.error(message, ...optionalParams);
1565
- }
1566
- log(message, ...optionalParams) {
1567
- var _a;
1568
- optionalParams = this.context ? optionalParams.concat(this.context) : optionalParams;
1569
- (_a = this.localInstance) == null ? void 0 : _a.log(message, ...optionalParams);
1570
- }
1571
- warn(message, ...optionalParams) {
1572
- var _a;
1573
- optionalParams = this.context ? optionalParams.concat(this.context) : optionalParams;
1574
- (_a = this.localInstance) == null ? void 0 : _a.warn(message, ...optionalParams);
1575
- }
1576
- debug(message, ...optionalParams) {
1577
- var _a, _b;
1578
- optionalParams = this.context ? optionalParams.concat(this.context) : optionalParams;
1579
- (_b = (_a = this.localInstance) == null ? void 0 : _a.debug) == null ? void 0 : _b.call(_a, message, ...optionalParams);
1580
- }
1581
- verbose(message, ...optionalParams) {
1582
- var _a, _b;
1583
- optionalParams = this.context ? optionalParams.concat(this.context) : optionalParams;
1584
- (_b = (_a = this.localInstance) == null ? void 0 : _a.verbose) == null ? void 0 : _b.call(_a, message, ...optionalParams);
1585
- }
1586
- fatal(message, ...optionalParams) {
1587
- var _a, _b;
1588
- optionalParams = this.context ? optionalParams.concat(this.context) : optionalParams;
1589
- (_b = (_a = this.localInstance) == null ? void 0 : _a.fatal) == null ? void 0 : _b.call(_a, message, ...optionalParams);
1590
- }
1591
- static error(message, ...optionalParams) {
1592
- var _a;
1593
- (_a = this.staticInstanceRef) == null ? void 0 : _a.error(message, ...optionalParams);
1594
- }
1595
- static log(message, ...optionalParams) {
1596
- var _a;
1597
- (_a = this.staticInstanceRef) == null ? void 0 : _a.log(message, ...optionalParams);
1598
- }
1599
- static warn(message, ...optionalParams) {
1600
- var _a;
1601
- (_a = this.staticInstanceRef) == null ? void 0 : _a.warn(message, ...optionalParams);
1602
- }
1603
- static debug(message, ...optionalParams) {
1604
- var _a, _b;
1605
- (_b = (_a = this.staticInstanceRef) == null ? void 0 : _a.debug) == null ? void 0 : _b.call(_a, message, ...optionalParams);
1606
- }
1607
- static verbose(message, ...optionalParams) {
1608
- var _a, _b;
1609
- (_b = (_a = this.staticInstanceRef) == null ? void 0 : _a.verbose) == null ? void 0 : _b.call(_a, message, ...optionalParams);
1610
- }
1611
- static fatal(message, ...optionalParams) {
1612
- var _a, _b;
1613
- (_b = (_a = this.staticInstanceRef) == null ? void 0 : _a.fatal) == null ? void 0 : _b.call(_a, message, ...optionalParams);
1614
- }
1615
- static getTimestamp() {
1616
- return dateTimeFormatter2.format(Date.now());
1617
- }
1618
- static overrideLogger(logger) {
1619
- var _a, _b;
1620
- if (Array.isArray(logger)) {
1621
- _LoggerInstance.logLevels = logger;
1622
- return (_b = (_a = this.staticInstanceRef) == null ? void 0 : _a.setLogLevels) == null ? void 0 : _b.call(_a, logger);
1623
- }
1624
- if (isObject(logger)) {
1625
- this.staticInstanceRef = logger;
1626
- } else {
1627
- this.staticInstanceRef = void 0;
1816
+ var _ConsoleLogger_decorators, _init4;
1817
+ _ConsoleLogger_decorators = [Injectable()];
1818
+ var _ConsoleLogger = class _ConsoleLogger {
1819
+ /**
1820
+ * The options of the logger.
1821
+ */
1822
+ options;
1823
+ /**
1824
+ * The context of the logger (can be set manually or automatically inferred).
1825
+ */
1826
+ context;
1827
+ /**
1828
+ * Request ID (if enabled).
1829
+ */
1830
+ requestId = null;
1831
+ /**
1832
+ * The original context of the logger (set in the constructor).
1833
+ */
1834
+ originalContext;
1835
+ /**
1836
+ * The options used for the "inspect" method.
1837
+ */
1838
+ inspectOptions;
1839
+ /**
1840
+ * The last timestamp at which the log message was printed.
1841
+ */
1842
+ static lastTimestampAt;
1843
+ constructor(contextOrOptions, options) {
1844
+ let [context, opts] = isString(contextOrOptions) ? [contextOrOptions, options] : options ? [void 0, options] : [contextOrOptions == null ? void 0 : contextOrOptions.context, contextOrOptions];
1845
+ opts = opts ?? {};
1846
+ opts.logLevels ??= DEFAULT_LOG_LEVELS;
1847
+ opts.colors ??= opts.colors ?? (opts.json ? false : true);
1848
+ opts.prefix ??= "Navios";
1849
+ this.options = opts;
1850
+ this.inspectOptions = this.getInspectOptions();
1851
+ if (context) {
1852
+ this.context = context;
1853
+ this.originalContext = context;
1628
1854
  }
1629
- }
1630
- static isLevelEnabled(level) {
1631
- const logLevels = _LoggerInstance.logLevels;
1632
- return isLogLevelEnabled(level, logLevels);
1633
- }
1634
- registerLocalInstanceRef() {
1635
- var _a;
1636
- if (this.localInstanceRef) {
1637
- return this.localInstanceRef;
1855
+ if (opts == null ? void 0 : opts.requestId) {
1856
+ const locator = getServiceLocator();
1857
+ locator.getEventBus().on(locator.getInstanceIdentifier(Request, void 0), "create", () => {
1858
+ const request = locator.getSyncInstance(Request, void 0);
1859
+ this.requestId = (request == null ? void 0 : request.id) ?? null;
1860
+ });
1861
+ locator.getEventBus().on(
1862
+ locator.getInstanceIdentifier(Request, void 0),
1863
+ "destroy",
1864
+ () => {
1865
+ this.requestId = null;
1866
+ }
1867
+ );
1638
1868
  }
1639
- this.localInstanceRef = new ConsoleLogger(this.context, {
1640
- timestamp: (_a = this.options) == null ? void 0 : _a.timestamp,
1641
- logLevels: _LoggerInstance.logLevels
1642
- });
1643
- return this.localInstanceRef;
1644
- }
1645
- };
1646
- _init2 = __decoratorStart(null);
1647
- _LoggerInstance = __decorateElement(_init2, 0, "LoggerInstance", _LoggerInstance_decorators, _LoggerInstance);
1648
- __runInitializers(_init2, 1, _LoggerInstance);
1649
- var LoggerInstance = _LoggerInstance;
1650
-
1651
- // packages/core/src/logger/logger.factory.mts
1652
- var LoggerInjectionToken = "LoggerInjectionToken";
1653
- var LoggerOptions = import_zod2.z.object({
1654
- context: import_zod2.z.string().optional(),
1655
- options: import_zod2.z.object({
1656
- timestamp: import_zod2.z.boolean().optional()
1657
- }).optional()
1658
- }).optional();
1659
- var Logger = InjectionToken.create(LoggerInjectionToken, LoggerOptions);
1660
- var _LoggerFactory_decorators, _init3;
1661
- _LoggerFactory_decorators = [Injectable({
1662
- type: "Factory" /* Factory */,
1663
- token: Logger
1664
- })];
1665
- var LoggerFactory = class {
1666
- create(ctx, args) {
1667
- return new LoggerInstance(args == null ? void 0 : args.context, args == null ? void 0 : args.options);
1668
- }
1669
- };
1670
- _init3 = __decoratorStart(null);
1671
- LoggerFactory = __decorateElement(_init3, 0, "LoggerFactory", _LoggerFactory_decorators, LoggerFactory);
1672
- __runInitializers(_init3, 1, LoggerFactory);
1673
-
1674
- // packages/core/src/logger/pino-wrapper.mts
1675
- var PinoWrapper = class _PinoWrapper {
1676
- constructor(logger) {
1677
- this.logger = logger;
1678
1869
  }
1679
- fatal(message, ...optionalParams) {
1680
- if (this.logger.fatal === void 0) {
1681
- return this.error(message, ...optionalParams);
1870
+ log(message, ...optionalParams) {
1871
+ if (!this.isLevelEnabled("log")) {
1872
+ return;
1682
1873
  }
1683
- this.logger.fatal(message, ...optionalParams);
1874
+ const { messages, context } = this.getContextAndMessagesToPrint([
1875
+ message,
1876
+ ...optionalParams
1877
+ ]);
1878
+ this.printMessages(messages, context, "log");
1684
1879
  }
1685
1880
  error(message, ...optionalParams) {
1686
- this.logger.error(message, ...optionalParams);
1881
+ if (!this.isLevelEnabled("error")) {
1882
+ return;
1883
+ }
1884
+ const { messages, context, stack } = this.getContextAndStackAndMessagesToPrint([message, ...optionalParams]);
1885
+ this.printMessages(messages, context, "error", "stderr", stack);
1886
+ this.printStackTrace(stack);
1687
1887
  }
1688
1888
  warn(message, ...optionalParams) {
1689
- this.logger.warn(message, ...optionalParams);
1690
- }
1691
- info() {
1889
+ if (!this.isLevelEnabled("warn")) {
1890
+ return;
1891
+ }
1892
+ const { messages, context } = this.getContextAndMessagesToPrint([
1893
+ message,
1894
+ ...optionalParams
1895
+ ]);
1896
+ this.printMessages(messages, context, "warn");
1692
1897
  }
1693
1898
  debug(message, ...optionalParams) {
1694
- var _a, _b;
1695
- (_b = (_a = this.logger).debug) == null ? void 0 : _b.call(_a, message, ...optionalParams);
1696
- }
1697
- trace(message, ...optionalParams) {
1698
- var _a, _b;
1699
- (_b = (_a = this.logger).verbose) == null ? void 0 : _b.call(_a, message, ...optionalParams);
1700
- }
1701
- silent() {
1702
- }
1703
- child(options) {
1704
- const keys = Object.keys(options);
1705
- let newContext = this.logger["context"] ?? "";
1706
- if (keys.length > 1) {
1707
- newContext = `${this.logger["context"] ?? ""}:${JSON.stringify(options)}`;
1899
+ if (!this.isLevelEnabled("debug")) {
1900
+ return;
1708
1901
  }
1709
- return new _PinoWrapper(
1710
- // @ts-expect-error We don't need to support this in the current version
1711
- new LoggerInstance(newContext, this.logger["options"])
1712
- );
1902
+ const { messages, context } = this.getContextAndMessagesToPrint([
1903
+ message,
1904
+ ...optionalParams
1905
+ ]);
1906
+ this.printMessages(messages, context, "debug");
1713
1907
  }
1714
- get level() {
1715
- if ("level" in this.logger && this.logger.level) {
1716
- return this.logger.level;
1717
- }
1718
- const levels = LoggerInstance["logLevels"];
1719
- if (levels) {
1720
- return levels.find((level) => level !== "verbose");
1908
+ verbose(message, ...optionalParams) {
1909
+ if (!this.isLevelEnabled("verbose")) {
1910
+ return;
1721
1911
  }
1722
- return "warn";
1723
- }
1724
- };
1725
-
1726
- // packages/core/src/config/config.service.mts
1727
- var import_common3 = require("@navios/common");
1728
- var ConfigServiceInstance = class {
1729
- constructor(config = {}, logger) {
1730
- this.config = config;
1731
- this.logger = logger;
1912
+ const { messages, context } = this.getContextAndMessagesToPrint([
1913
+ message,
1914
+ ...optionalParams
1915
+ ]);
1916
+ this.printMessages(messages, context, "verbose");
1732
1917
  }
1733
- getConfig() {
1734
- return this.config;
1918
+ fatal(message, ...optionalParams) {
1919
+ if (!this.isLevelEnabled("fatal")) {
1920
+ return;
1921
+ }
1922
+ const { messages, context } = this.getContextAndMessagesToPrint([
1923
+ message,
1924
+ ...optionalParams
1925
+ ]);
1926
+ this.printMessages(messages, context, "fatal");
1735
1927
  }
1736
- get(key) {
1737
- var _a, _b;
1738
- try {
1739
- const parts = String(key).split(".");
1740
- let value = this.config;
1741
- for (const part of parts) {
1742
- if (value === null || value === void 0 || typeof value !== "object") {
1743
- return null;
1744
- }
1745
- value = value[part];
1746
- }
1747
- return value ?? null;
1748
- } catch (error) {
1749
- (_b = (_a = this.logger).debug) == null ? void 0 : _b.call(
1750
- _a,
1751
- `Failed to get config value for key ${String(key)}`,
1752
- error
1753
- );
1754
- return null;
1928
+ /**
1929
+ * Set log levels
1930
+ * @param levels log levels
1931
+ */
1932
+ setLogLevels(levels) {
1933
+ if (!this.options) {
1934
+ this.options = {};
1755
1935
  }
1936
+ this.options.logLevels = levels;
1756
1937
  }
1757
- getOrDefault(key, defaultValue) {
1758
- const value = this.get(key);
1759
- return value !== null ? value : defaultValue;
1938
+ /**
1939
+ * Set logger context
1940
+ * @param context context
1941
+ */
1942
+ setContext(context) {
1943
+ this.context = context;
1760
1944
  }
1761
- getOrThrow(key, errorMessage) {
1762
- const value = this.get(key);
1763
- if (value === null) {
1764
- const message = errorMessage || `Configuration value for key "${String(key)}" is not defined`;
1765
- this.logger.error(message);
1766
- throw new import_common3.NaviosException(message);
1767
- }
1768
- return value;
1945
+ /**
1946
+ * Resets the logger context to the value that was passed in the constructor.
1947
+ */
1948
+ resetContext() {
1949
+ this.context = this.originalContext;
1769
1950
  }
1770
- };
1771
-
1772
- // packages/core/src/config/config.provider.mts
1773
- var ConfigProviderOptions = import_zod3.z.object({
1774
- load: import_zod3.z.function()
1775
- });
1776
- var ConfigProvider = InjectionToken.create(ConfigServiceInstance, ConfigProviderOptions);
1777
- var _ConfigProviderFactory_decorators, _init4;
1778
- _ConfigProviderFactory_decorators = [Injectable({
1779
- token: ConfigProvider,
1780
- type: "Factory" /* Factory */
1781
- })];
1782
- var ConfigProviderFactory = class {
1783
- logger = syncInject(Logger, {
1784
- context: "ConfigService"
1785
- });
1786
- async create(ctx, args) {
1787
- const { load } = args;
1788
- const logger = this.logger;
1789
- try {
1790
- const config = await load();
1791
- return new ConfigServiceInstance(config, logger);
1792
- } catch (error) {
1793
- logger.error("Error loading config", error);
1794
- throw error;
1795
- }
1951
+ isLevelEnabled(level) {
1952
+ var _a;
1953
+ const logLevels = (_a = this.options) == null ? void 0 : _a.logLevels;
1954
+ return isLogLevelEnabled(level, logLevels);
1796
1955
  }
1797
- };
1798
- _init4 = __decoratorStart(null);
1799
- ConfigProviderFactory = __decorateElement(_init4, 0, "ConfigProviderFactory", _ConfigProviderFactory_decorators, ConfigProviderFactory);
1800
- __runInitializers(_init4, 1, ConfigProviderFactory);
1801
- function provideConfig(options) {
1802
- return InjectionToken.bound(ConfigProvider, options);
1803
- }
1804
-
1805
- // packages/core/src/metadata/endpoint.metadata.mts
1806
- var EndpointMetadataKey = Symbol("EndpointMetadataKey");
1807
- var EndpointType = /* @__PURE__ */ ((EndpointType2) => {
1808
- EndpointType2["Unknown"] = "unknown";
1809
- EndpointType2["Endpoint"] = "endpoint";
1810
- EndpointType2["Stream"] = "stream";
1811
- EndpointType2["Multipart"] = "multipart";
1812
- EndpointType2["Handler"] = "handler";
1813
- return EndpointType2;
1814
- })(EndpointType || {});
1815
- function getAllEndpointMetadata(context) {
1816
- if (context.metadata) {
1817
- const metadata = context.metadata[EndpointMetadataKey];
1818
- if (metadata) {
1819
- return metadata;
1820
- } else {
1821
- context.metadata[EndpointMetadataKey] = /* @__PURE__ */ new Set();
1822
- return context.metadata[EndpointMetadataKey];
1823
- }
1956
+ getTimestamp() {
1957
+ return dateTimeFormatter.format(Date.now());
1824
1958
  }
1825
- throw new Error("[Navios] Wrong environment.");
1826
- }
1827
- function getEndpointMetadata(target, context) {
1828
- if (context.metadata) {
1829
- const metadata = getAllEndpointMetadata(context);
1830
- if (metadata) {
1831
- const endpointMetadata = Array.from(metadata).find(
1832
- (item) => item.classMethod === target.name
1833
- );
1834
- if (endpointMetadata) {
1835
- return endpointMetadata;
1836
- } else {
1837
- const newMetadata = {
1838
- classMethod: target.name,
1839
- url: "",
1840
- successStatusCode: 200,
1841
- headers: {},
1842
- type: "unknown" /* Unknown */,
1843
- httpMethod: "GET",
1844
- config: null,
1845
- guards: /* @__PURE__ */ new Set(),
1846
- customAttributes: /* @__PURE__ */ new Map()
1847
- };
1848
- metadata.add(newMetadata);
1849
- return newMetadata;
1959
+ printMessages(messages, context = "", logLevel = "log", writeStreamType, errorStack) {
1960
+ messages.forEach((message) => {
1961
+ if (this.options.json) {
1962
+ this.printAsJson(message, {
1963
+ context,
1964
+ logLevel,
1965
+ writeStreamType,
1966
+ errorStack
1967
+ });
1968
+ return;
1850
1969
  }
1851
- }
1970
+ const pidMessage = this.formatPid(process.pid);
1971
+ const contextMessage = this.formatContext(context);
1972
+ const timestampDiff = this.updateAndGetTimestampDiff();
1973
+ const formattedLogLevel = logLevel.toUpperCase().padStart(7, " ");
1974
+ const formattedMessage = this.formatMessage(
1975
+ logLevel,
1976
+ message,
1977
+ pidMessage,
1978
+ formattedLogLevel,
1979
+ contextMessage,
1980
+ timestampDiff
1981
+ );
1982
+ process[writeStreamType ?? "stdout"].write(formattedMessage);
1983
+ });
1852
1984
  }
1853
- throw new Error("[Navios] Wrong environment.");
1854
- }
1855
-
1856
- // packages/core/src/metadata/controller.metadata.mts
1857
- var ControllerMetadataKey = Symbol("ControllerMetadataKey");
1858
- function getControllerMetadata(target, context) {
1859
- if (context.metadata) {
1860
- const metadata = context.metadata[ControllerMetadataKey];
1861
- if (metadata) {
1862
- return metadata;
1863
- } else {
1864
- const endpointsMetadata = getAllEndpointMetadata(context);
1865
- const newMetadata = {
1866
- endpoints: endpointsMetadata,
1867
- guards: /* @__PURE__ */ new Set(),
1868
- customAttributes: /* @__PURE__ */ new Map()
1869
- };
1870
- context.metadata[ControllerMetadataKey] = newMetadata;
1871
- target[ControllerMetadataKey] = newMetadata;
1872
- return newMetadata;
1985
+ printAsJson(message, options) {
1986
+ const logObject = {
1987
+ level: options.logLevel,
1988
+ pid: process.pid,
1989
+ timestamp: Date.now(),
1990
+ message
1991
+ };
1992
+ if (options.context) {
1993
+ logObject.context = options.context;
1873
1994
  }
1995
+ if (options.errorStack) {
1996
+ logObject.stack = options.errorStack;
1997
+ }
1998
+ if (this.options.requestId && this.requestId) {
1999
+ logObject.requestId = this.requestId;
2000
+ }
2001
+ const formattedMessage = !this.options.colors && this.inspectOptions.compact === true ? JSON.stringify(logObject, this.stringifyReplacer) : (0, import_util.inspect)(logObject, this.inspectOptions);
2002
+ process[options.writeStreamType ?? "stdout"].write(`${formattedMessage}
2003
+ `);
1874
2004
  }
1875
- throw new Error("[Navios] Wrong environment.");
1876
- }
1877
- function extractControllerMetadata(target) {
1878
- const metadata = target[ControllerMetadataKey];
1879
- if (!metadata) {
1880
- throw new Error(
1881
- "[Navios] Controller metadata not found. Make sure to use @Controller decorator."
1882
- );
2005
+ formatPid(pid) {
2006
+ return `[${this.options.prefix}] ${pid} - `;
1883
2007
  }
1884
- return metadata;
1885
- }
1886
- function hasControllerMetadata(target) {
1887
- const metadata = target[ControllerMetadataKey];
1888
- return !!metadata;
1889
- }
1890
-
1891
- // packages/core/src/metadata/module.metadata.mts
1892
- var ModuleMetadataKey = Symbol("ControllerMetadataKey");
1893
- function getModuleMetadata(target, context) {
1894
- if (context.metadata) {
1895
- const metadata = context.metadata[ModuleMetadataKey];
1896
- if (metadata) {
1897
- return metadata;
1898
- } else {
1899
- const newMetadata = {
1900
- controllers: /* @__PURE__ */ new Set(),
1901
- imports: /* @__PURE__ */ new Set(),
1902
- guards: /* @__PURE__ */ new Set(),
1903
- customAttributes: /* @__PURE__ */ new Map()
1904
- };
1905
- context.metadata[ModuleMetadataKey] = newMetadata;
1906
- target[ModuleMetadataKey] = newMetadata;
1907
- return newMetadata;
2008
+ formatContext(context) {
2009
+ if (!context) {
2010
+ return "";
1908
2011
  }
2012
+ context = `[${context}] `;
2013
+ return this.options.colors ? yellow(context) : context;
1909
2014
  }
1910
- throw new Error("[Navios] Wrong environment.");
1911
- }
1912
- function extractModuleMetadata(target) {
1913
- const metadata = target[ModuleMetadataKey];
1914
- if (!metadata) {
1915
- throw new Error(
1916
- `[Navios] Module metadata not found for ${target.name}. Make sure to use @Module decorator.`
1917
- );
2015
+ formatMessage(logLevel, message, pidMessage, formattedLogLevel, contextMessage, timestampDiff) {
2016
+ const output = this.stringifyMessage(message, logLevel);
2017
+ pidMessage = this.colorize(pidMessage, logLevel);
2018
+ formattedLogLevel = this.colorize(formattedLogLevel, logLevel);
2019
+ return `${pidMessage}${this.getRequestId()}${this.getTimestamp()} ${formattedLogLevel} ${contextMessage}${output}${timestampDiff}
2020
+ `;
1918
2021
  }
1919
- return metadata;
1920
- }
1921
- function hasModuleMetadata(target) {
1922
- return !!target[ModuleMetadataKey];
1923
- }
1924
-
1925
- // packages/core/src/decorators/controller.decorator.mts
1926
- function Controller({ guards } = {}) {
1927
- return function(target, context) {
1928
- if (context.kind !== "class") {
1929
- throw new Error(
1930
- "[Navios] @Controller decorator can only be used on classes."
1931
- );
2022
+ getRequestId() {
2023
+ if (this.options.requestId && this.requestId) {
2024
+ return `(${this.colorize(this.requestId, "log")}) `;
1932
2025
  }
1933
- const token = InjectionToken.create(target);
1934
- if (context.metadata) {
1935
- const controllerMetadata = getControllerMetadata(target, context);
1936
- if (guards) {
1937
- for (const guard of Array.from(guards).reverse()) {
1938
- controllerMetadata.guards.add(guard);
1939
- }
2026
+ return "";
2027
+ }
2028
+ stringifyMessage(message, logLevel) {
2029
+ if (isFunction(message)) {
2030
+ const messageAsStr = Function.prototype.toString.call(message);
2031
+ const isClass = messageAsStr.startsWith("class ");
2032
+ if (isClass) {
2033
+ return this.stringifyMessage(message.name, logLevel);
1940
2034
  }
2035
+ return this.stringifyMessage(message(), logLevel);
1941
2036
  }
1942
- return Injectable({
1943
- token,
1944
- type: "Class" /* Class */,
1945
- scope: "Instance" /* Instance */
1946
- })(target, context);
1947
- };
1948
- }
1949
-
1950
- // packages/core/src/decorators/endpoint.decorator.mts
1951
- var import_zod4 = require("zod");
1952
- function Endpoint(endpoint) {
1953
- return (target, context) => {
1954
- if (typeof target !== "function") {
1955
- throw new Error(
1956
- "[Navios] Endpoint decorator can only be used on functions."
1957
- );
2037
+ if (typeof message === "string") {
2038
+ return this.colorize(message, logLevel);
1958
2039
  }
1959
- if (context.kind !== "method") {
1960
- throw new Error(
1961
- "[Navios] Endpoint decorator can only be used on methods."
1962
- );
2040
+ const outputText = (0, import_util.inspect)(message, this.inspectOptions);
2041
+ if (isPlainObject(message)) {
2042
+ return `Object(${Object.keys(message).length}) ${outputText}`;
1963
2043
  }
1964
- const config = endpoint.config;
1965
- if (context.metadata) {
1966
- let endpointMetadata = getEndpointMetadata(target, context);
1967
- if (endpointMetadata.config && endpointMetadata.config.url) {
1968
- throw new Error(
1969
- `[Navios] Endpoint ${config.method} ${config.url} already exists. Please use a different method or url.`
1970
- );
1971
- }
1972
- endpointMetadata.config = config;
1973
- endpointMetadata.type = "endpoint" /* Endpoint */;
1974
- endpointMetadata.classMethod = target.name;
1975
- endpointMetadata.httpMethod = config.method;
1976
- endpointMetadata.url = config.url;
2044
+ if (Array.isArray(message)) {
2045
+ return `Array(${message.length}) ${outputText}`;
1977
2046
  }
1978
- return target;
1979
- };
1980
- }
1981
-
1982
- // packages/core/src/decorators/header.decorator.mts
1983
- function Header(name2, value) {
1984
- return (target, context) => {
1985
- if (context.kind !== "method") {
1986
- throw new Error("[Navios] Header decorator can only be used on methods.");
2047
+ return outputText;
2048
+ }
2049
+ colorize(message, logLevel) {
2050
+ if (!this.options.colors || this.options.json) {
2051
+ return message;
1987
2052
  }
1988
- const metadata = getEndpointMetadata(target, context);
1989
- if (metadata.type === "stream" /* Stream */) {
1990
- throw new Error(
1991
- "[Navios] HttpCode decorator cannot be used on stream endpoints."
1992
- );
2053
+ const color = this.getColorByLogLevel(logLevel);
2054
+ return color(message);
2055
+ }
2056
+ printStackTrace(stack) {
2057
+ if (!stack || this.options.json) {
2058
+ return;
1993
2059
  }
1994
- metadata.headers[name2] = value;
1995
- return target;
1996
- };
1997
- }
1998
-
1999
- // packages/core/src/decorators/http-code.decorator.mts
2000
- function HttpCode(code) {
2001
- return (target, context) => {
2002
- if (context.kind !== "method") {
2003
- throw new Error(
2004
- "[Navios] HttpCode decorator can only be used on methods."
2005
- );
2060
+ process.stderr.write(`${stack}
2061
+ `);
2062
+ }
2063
+ updateAndGetTimestampDiff() {
2064
+ var _a;
2065
+ const includeTimestamp = _ConsoleLogger.lastTimestampAt && ((_a = this.options) == null ? void 0 : _a.timestamp);
2066
+ const result = includeTimestamp ? this.formatTimestampDiff(Date.now() - _ConsoleLogger.lastTimestampAt) : "";
2067
+ _ConsoleLogger.lastTimestampAt = Date.now();
2068
+ return result;
2069
+ }
2070
+ formatTimestampDiff(timestampDiff) {
2071
+ const formattedDiff = ` +${timestampDiff}ms`;
2072
+ return this.options.colors ? yellow(formattedDiff) : formattedDiff;
2073
+ }
2074
+ getInspectOptions() {
2075
+ let breakLength = this.options.breakLength;
2076
+ if (typeof breakLength === "undefined") {
2077
+ breakLength = this.options.colors ? this.options.compact ? Infinity : void 0 : this.options.compact === false ? void 0 : Infinity;
2006
2078
  }
2007
- const metadata = getEndpointMetadata(target, context);
2008
- if (metadata.type === "stream" /* Stream */) {
2009
- throw new Error(
2010
- "[Navios] HttpCode decorator cannot be used on stream endpoints."
2011
- );
2079
+ const inspectOptions = {
2080
+ depth: this.options.depth ?? DEFAULT_DEPTH,
2081
+ sorted: this.options.sorted,
2082
+ showHidden: this.options.showHidden,
2083
+ compact: this.options.compact ?? (this.options.json ? true : false),
2084
+ colors: this.options.colors,
2085
+ breakLength
2086
+ };
2087
+ if (this.options.maxArrayLength) {
2088
+ inspectOptions.maxArrayLength = this.options.maxArrayLength;
2012
2089
  }
2013
- metadata.successStatusCode = code;
2014
- return target;
2015
- };
2016
- }
2017
-
2018
- // packages/core/src/decorators/module.decorator.mts
2019
- function Module(metadata) {
2020
- return (target, context) => {
2021
- if (context.kind !== "class") {
2022
- throw new Error("[Navios] @Module decorator can only be used on classes.");
2090
+ if (this.options.maxStringLength) {
2091
+ inspectOptions.maxStringLength = this.options.maxStringLength;
2023
2092
  }
2024
- const token = InjectionToken.create(target);
2025
- const moduleMetadata = getModuleMetadata(target, context);
2026
- if (metadata.controllers) {
2027
- for (const controller of metadata.controllers) {
2028
- moduleMetadata.controllers.add(controller);
2029
- }
2093
+ return inspectOptions;
2094
+ }
2095
+ stringifyReplacer(key, value) {
2096
+ if (typeof value === "bigint") {
2097
+ return value.toString();
2030
2098
  }
2031
- if (metadata.imports) {
2032
- for (const importedModule of metadata.imports) {
2033
- moduleMetadata.imports.add(importedModule);
2034
- }
2099
+ if (typeof value === "symbol") {
2100
+ return value.toString();
2035
2101
  }
2036
- if (metadata.guards) {
2037
- for (const guard of Array.from(metadata.guards).reverse()) {
2038
- moduleMetadata.guards.add(guard);
2039
- }
2102
+ if (value instanceof Map || value instanceof Set || value instanceof Error) {
2103
+ return `${(0, import_util.inspect)(value, this.inspectOptions)}`;
2040
2104
  }
2041
- return Injectable({
2042
- token,
2043
- type: "Class" /* Class */,
2044
- scope: "Singleton" /* Singleton */
2045
- })(target, context);
2046
- };
2047
- }
2048
-
2049
- // packages/core/src/decorators/multipart.decorator.mts
2050
- var import_zod5 = require("zod");
2051
- function Multipart(endpoint) {
2052
- return (target, context) => {
2053
- if (typeof target !== "function") {
2054
- throw new Error(
2055
- "[Navios] Endpoint decorator can only be used on functions."
2056
- );
2105
+ return value;
2106
+ }
2107
+ getContextAndMessagesToPrint(args) {
2108
+ if ((args == null ? void 0 : args.length) <= 1) {
2109
+ return { messages: args, context: this.context };
2057
2110
  }
2058
- if (context.kind !== "method") {
2059
- throw new Error(
2060
- "[Navios] Endpoint decorator can only be used on methods."
2061
- );
2111
+ const lastElement = args[args.length - 1];
2112
+ const isContext = isString(lastElement);
2113
+ if (!isContext) {
2114
+ return { messages: args, context: this.context };
2062
2115
  }
2063
- const config = endpoint.config;
2064
- if (context.metadata) {
2065
- let endpointMetadata = getEndpointMetadata(target, context);
2066
- if (endpointMetadata.config && endpointMetadata.config.url) {
2067
- throw new Error(
2068
- `[Navios] Endpoint ${config.method} ${config.url} already exists. Please use a different method or url.`
2069
- );
2070
- }
2071
- endpointMetadata.config = config;
2072
- endpointMetadata.type = "multipart" /* Multipart */;
2073
- endpointMetadata.classMethod = target.name;
2074
- endpointMetadata.httpMethod = config.method;
2075
- endpointMetadata.url = config.url;
2116
+ return {
2117
+ context: lastElement,
2118
+ messages: args.slice(0, args.length - 1)
2119
+ };
2120
+ }
2121
+ getContextAndStackAndMessagesToPrint(args) {
2122
+ if (args.length === 2) {
2123
+ return this.isStackFormat(args[1]) ? {
2124
+ messages: [args[0]],
2125
+ stack: args[1],
2126
+ context: this.context
2127
+ } : {
2128
+ messages: [args[0]],
2129
+ context: args[1]
2130
+ };
2076
2131
  }
2077
- return target;
2078
- };
2079
- }
2080
-
2081
- // packages/core/src/decorators/stream.decorator.mts
2082
- function Stream(endpoint) {
2083
- return (target, context) => {
2084
- if (typeof target !== "function") {
2085
- throw new Error(
2086
- "[Navios] Endpoint decorator can only be used on functions."
2087
- );
2132
+ const { messages, context } = this.getContextAndMessagesToPrint(args);
2133
+ if ((messages == null ? void 0 : messages.length) <= 1) {
2134
+ return { messages, context };
2088
2135
  }
2089
- if (context.kind !== "method") {
2090
- throw new Error(
2091
- "[Navios] Endpoint decorator can only be used on methods."
2092
- );
2136
+ const lastElement = messages[messages.length - 1];
2137
+ const isStack = isString(lastElement);
2138
+ if (!isStack && !isUndefined(lastElement)) {
2139
+ return { messages, context };
2093
2140
  }
2094
- const config = endpoint.config;
2095
- if (context.metadata) {
2096
- let endpointMetadata = getEndpointMetadata(target, context);
2097
- if (endpointMetadata.config && endpointMetadata.config.url) {
2098
- throw new Error(
2099
- `[Navios] Endpoint ${config.method} ${config.url} already exists. Please use a different method or url.`
2100
- );
2101
- }
2102
- endpointMetadata.config = config;
2103
- endpointMetadata.type = "stream" /* Stream */;
2104
- endpointMetadata.classMethod = target.name;
2105
- endpointMetadata.httpMethod = config.method;
2106
- endpointMetadata.url = config.url;
2141
+ return {
2142
+ stack: lastElement,
2143
+ messages: messages.slice(0, messages.length - 1),
2144
+ context
2145
+ };
2146
+ }
2147
+ isStackFormat(stack) {
2148
+ if (!isString(stack) && !isUndefined(stack)) {
2149
+ return false;
2107
2150
  }
2108
- return target;
2109
- };
2110
- }
2151
+ return /^(.)+\n\s+at .+:\d+:\d+/.test(stack);
2152
+ }
2153
+ getColorByLogLevel(level) {
2154
+ switch (level) {
2155
+ case "debug":
2156
+ return clc.magentaBright;
2157
+ case "warn":
2158
+ return clc.yellow;
2159
+ case "error":
2160
+ return clc.red;
2161
+ case "verbose":
2162
+ return clc.cyanBright;
2163
+ case "fatal":
2164
+ return clc.bold;
2165
+ default:
2166
+ return clc.green;
2167
+ }
2168
+ }
2169
+ };
2170
+ _init4 = __decoratorStart(null);
2171
+ _ConsoleLogger = __decorateElement(_init4, 0, "ConsoleLogger", _ConsoleLogger_decorators, _ConsoleLogger);
2172
+ __runInitializers(_init4, 1, _ConsoleLogger);
2173
+ var ConsoleLogger = _ConsoleLogger;
2111
2174
 
2112
- // packages/core/src/decorators/use-guards.decorator.mts
2113
- function UseGuards(...guards) {
2114
- return function(target, context) {
2115
- if (context.kind === "class") {
2116
- const controllerMetadata = getControllerMetadata(
2117
- target,
2118
- context
2119
- );
2120
- for (const guard of guards.reverse()) {
2121
- controllerMetadata.guards.add(guard);
2122
- }
2123
- } else if (context.kind === "method") {
2124
- const endpointMetadata = getEndpointMetadata(target, context);
2125
- for (const guard of guards.reverse()) {
2126
- endpointMetadata.guards.add(guard);
2175
+ // packages/core/src/logger/logger.factory.mts
2176
+ var import_zod3 = require("zod");
2177
+
2178
+ // packages/core/src/logger/logger.service.mts
2179
+ var DEFAULT_LOGGER = new ConsoleLogger();
2180
+ var dateTimeFormatter2 = new Intl.DateTimeFormat(void 0, {
2181
+ year: "numeric",
2182
+ hour: "numeric",
2183
+ minute: "numeric",
2184
+ second: "numeric",
2185
+ day: "2-digit",
2186
+ month: "2-digit"
2187
+ });
2188
+ var _LoggerInstance_decorators, _init5;
2189
+ _LoggerInstance_decorators = [Injectable()];
2190
+ var _LoggerInstance = class _LoggerInstance {
2191
+ constructor(context, options = {}) {
2192
+ this.context = context;
2193
+ this.options = options;
2194
+ }
2195
+ static staticInstanceRef = DEFAULT_LOGGER;
2196
+ static logLevels;
2197
+ localInstanceRef;
2198
+ get localInstance() {
2199
+ if (_LoggerInstance.staticInstanceRef === DEFAULT_LOGGER) {
2200
+ return this.registerLocalInstanceRef();
2201
+ } else if (_LoggerInstance.staticInstanceRef instanceof _LoggerInstance) {
2202
+ const prototype = Object.getPrototypeOf(_LoggerInstance.staticInstanceRef);
2203
+ if (prototype.constructor === _LoggerInstance) {
2204
+ return this.registerLocalInstanceRef();
2127
2205
  }
2206
+ }
2207
+ return _LoggerInstance.staticInstanceRef;
2208
+ }
2209
+ error(message, ...optionalParams) {
2210
+ var _a;
2211
+ optionalParams = this.context ? (optionalParams.length ? optionalParams : [void 0]).concat(
2212
+ this.context
2213
+ ) : optionalParams;
2214
+ (_a = this.localInstance) == null ? void 0 : _a.error(message, ...optionalParams);
2215
+ }
2216
+ log(message, ...optionalParams) {
2217
+ var _a;
2218
+ optionalParams = this.context ? optionalParams.concat(this.context) : optionalParams;
2219
+ (_a = this.localInstance) == null ? void 0 : _a.log(message, ...optionalParams);
2220
+ }
2221
+ warn(message, ...optionalParams) {
2222
+ var _a;
2223
+ optionalParams = this.context ? optionalParams.concat(this.context) : optionalParams;
2224
+ (_a = this.localInstance) == null ? void 0 : _a.warn(message, ...optionalParams);
2225
+ }
2226
+ debug(message, ...optionalParams) {
2227
+ var _a, _b;
2228
+ optionalParams = this.context ? optionalParams.concat(this.context) : optionalParams;
2229
+ (_b = (_a = this.localInstance) == null ? void 0 : _a.debug) == null ? void 0 : _b.call(_a, message, ...optionalParams);
2230
+ }
2231
+ verbose(message, ...optionalParams) {
2232
+ var _a, _b;
2233
+ optionalParams = this.context ? optionalParams.concat(this.context) : optionalParams;
2234
+ (_b = (_a = this.localInstance) == null ? void 0 : _a.verbose) == null ? void 0 : _b.call(_a, message, ...optionalParams);
2235
+ }
2236
+ fatal(message, ...optionalParams) {
2237
+ var _a, _b;
2238
+ optionalParams = this.context ? optionalParams.concat(this.context) : optionalParams;
2239
+ (_b = (_a = this.localInstance) == null ? void 0 : _a.fatal) == null ? void 0 : _b.call(_a, message, ...optionalParams);
2240
+ }
2241
+ static error(message, ...optionalParams) {
2242
+ var _a;
2243
+ (_a = this.staticInstanceRef) == null ? void 0 : _a.error(message, ...optionalParams);
2244
+ }
2245
+ static log(message, ...optionalParams) {
2246
+ var _a;
2247
+ (_a = this.staticInstanceRef) == null ? void 0 : _a.log(message, ...optionalParams);
2248
+ }
2249
+ static warn(message, ...optionalParams) {
2250
+ var _a;
2251
+ (_a = this.staticInstanceRef) == null ? void 0 : _a.warn(message, ...optionalParams);
2252
+ }
2253
+ static debug(message, ...optionalParams) {
2254
+ var _a, _b;
2255
+ (_b = (_a = this.staticInstanceRef) == null ? void 0 : _a.debug) == null ? void 0 : _b.call(_a, message, ...optionalParams);
2256
+ }
2257
+ static verbose(message, ...optionalParams) {
2258
+ var _a, _b;
2259
+ (_b = (_a = this.staticInstanceRef) == null ? void 0 : _a.verbose) == null ? void 0 : _b.call(_a, message, ...optionalParams);
2260
+ }
2261
+ static fatal(message, ...optionalParams) {
2262
+ var _a, _b;
2263
+ (_b = (_a = this.staticInstanceRef) == null ? void 0 : _a.fatal) == null ? void 0 : _b.call(_a, message, ...optionalParams);
2264
+ }
2265
+ static getTimestamp() {
2266
+ return dateTimeFormatter2.format(Date.now());
2267
+ }
2268
+ static overrideLogger(logger) {
2269
+ var _a, _b;
2270
+ if (Array.isArray(logger)) {
2271
+ _LoggerInstance.logLevels = logger;
2272
+ return (_b = (_a = this.staticInstanceRef) == null ? void 0 : _a.setLogLevels) == null ? void 0 : _b.call(_a, logger);
2273
+ }
2274
+ if (isObject(logger)) {
2275
+ this.staticInstanceRef = logger;
2128
2276
  } else {
2129
- throw new Error(
2130
- "[Navios] @UseGuards decorator can only be used on classes or methods."
2131
- );
2277
+ this.staticInstanceRef = void 0;
2132
2278
  }
2133
- return target;
2134
- };
2135
- }
2136
-
2137
- // packages/core/src/exceptions/http.exception.mts
2138
- var HttpException = class {
2139
- constructor(statusCode, response, error) {
2140
- this.statusCode = statusCode;
2141
- this.response = response;
2142
- this.error = error;
2143
2279
  }
2144
- };
2145
-
2146
- // packages/core/src/exceptions/bad-request.exception.mts
2147
- var BadRequestException = class extends HttpException {
2148
- constructor(message) {
2149
- super(400, message);
2280
+ static isLevelEnabled(level) {
2281
+ const logLevels = _LoggerInstance.logLevels;
2282
+ return isLogLevelEnabled(level, logLevels);
2150
2283
  }
2151
- };
2152
-
2153
- // packages/core/src/exceptions/forbidden.exception.mts
2154
- var ForbiddenException = class extends HttpException {
2155
- constructor(message) {
2156
- super(403, message);
2284
+ registerLocalInstanceRef() {
2285
+ var _a;
2286
+ if (this.localInstanceRef) {
2287
+ return this.localInstanceRef;
2288
+ }
2289
+ this.localInstanceRef = new ConsoleLogger(this.context, {
2290
+ timestamp: (_a = this.options) == null ? void 0 : _a.timestamp,
2291
+ logLevels: _LoggerInstance.logLevels
2292
+ });
2293
+ return this.localInstanceRef;
2157
2294
  }
2158
2295
  };
2296
+ _init5 = __decoratorStart(null);
2297
+ _LoggerInstance = __decorateElement(_init5, 0, "LoggerInstance", _LoggerInstance_decorators, _LoggerInstance);
2298
+ __runInitializers(_init5, 1, _LoggerInstance);
2299
+ var LoggerInstance = _LoggerInstance;
2159
2300
 
2160
- // packages/core/src/exceptions/internal-server-error.exception.mts
2161
- var InternalServerErrorException = class extends HttpException {
2162
- constructor(message, error) {
2163
- super(500, message, error);
2301
+ // packages/core/src/logger/logger.factory.mts
2302
+ var LoggerInjectionToken = "LoggerInjectionToken";
2303
+ var LoggerOptions = import_zod3.z.object({
2304
+ context: import_zod3.z.string().optional(),
2305
+ options: import_zod3.z.object({
2306
+ timestamp: import_zod3.z.boolean().optional()
2307
+ }).optional()
2308
+ }).optional();
2309
+ var Logger = InjectionToken.create(LoggerInjectionToken, LoggerOptions);
2310
+ var _LoggerFactory_decorators, _init6;
2311
+ _LoggerFactory_decorators = [Injectable({
2312
+ type: "Factory" /* Factory */,
2313
+ token: Logger
2314
+ })];
2315
+ var LoggerFactory = class {
2316
+ create(ctx, args) {
2317
+ return new LoggerInstance(args == null ? void 0 : args.context, args == null ? void 0 : args.options);
2164
2318
  }
2165
2319
  };
2320
+ _init6 = __decoratorStart(null);
2321
+ LoggerFactory = __decorateElement(_init6, 0, "LoggerFactory", _LoggerFactory_decorators, LoggerFactory);
2322
+ __runInitializers(_init6, 1, LoggerFactory);
2166
2323
 
2167
- // packages/core/src/exceptions/not-found.exception.mts
2168
- var NotFoundException = class extends HttpException {
2169
- constructor(response, error) {
2170
- super(404, response, error);
2171
- this.response = response;
2172
- this.error = error;
2324
+ // packages/core/src/logger/pino-wrapper.mts
2325
+ var PinoWrapper = class _PinoWrapper {
2326
+ constructor(logger) {
2327
+ this.logger = logger;
2173
2328
  }
2174
- };
2175
-
2176
- // packages/core/src/exceptions/unauthorized.exception.mts
2177
- var UnauthorizedException = class extends HttpException {
2178
- constructor(message, error) {
2179
- super(401, message, error);
2329
+ fatal(message, ...optionalParams) {
2330
+ if (this.logger.fatal === void 0) {
2331
+ return this.error(message, ...optionalParams);
2332
+ }
2333
+ this.logger.fatal(message, ...optionalParams);
2180
2334
  }
2181
- };
2182
-
2183
- // packages/core/src/exceptions/conflict.exception.mts
2184
- var ConflictException = class extends HttpException {
2185
- constructor(message, error) {
2186
- super(409, message, error);
2335
+ error(message, ...optionalParams) {
2336
+ this.logger.error(message, ...optionalParams);
2187
2337
  }
2188
- };
2189
-
2190
- // packages/core/src/services/controller-adapter.service.mts
2191
- var import_common4 = require("@navios/common");
2192
- var import_zod6 = require("zod");
2193
-
2194
- // packages/core/src/tokens/application.token.mts
2195
- var ApplicationInjectionToken = "ApplicationInjectionToken";
2196
- var Application = InjectionToken.create(
2197
- ApplicationInjectionToken
2198
- );
2199
-
2200
- // packages/core/src/tokens/execution-context.token.mts
2201
- var ExecutionContextInjectionToken = "ExecutionContextInjectionToken";
2202
- var ExecutionContextToken = InjectionToken.create(
2203
- ExecutionContextInjectionToken
2204
- );
2205
-
2206
- // packages/core/src/tokens/reply.token.mts
2207
- var ReplyInjectionToken = "ReplyInjectionToken";
2208
- var Reply = InjectionToken.create(ReplyInjectionToken);
2209
-
2210
- // packages/core/src/tokens/request.token.mts
2211
- var RequestInjectionToken = "RequestInjectionToken";
2212
- var Request = InjectionToken.create(
2213
- RequestInjectionToken
2214
- );
2215
-
2216
- // packages/core/src/services/execution-context.mts
2217
- var ExecutionContext2 = class {
2218
- constructor(module2, controller, handler) {
2219
- this.module = module2;
2220
- this.controller = controller;
2221
- this.handler = handler;
2338
+ warn(message, ...optionalParams) {
2339
+ this.logger.warn(message, ...optionalParams);
2222
2340
  }
2223
- request;
2224
- reply;
2225
- getModule() {
2226
- return this.module;
2341
+ info() {
2227
2342
  }
2228
- getController() {
2229
- return this.controller;
2343
+ debug(message, ...optionalParams) {
2344
+ var _a, _b;
2345
+ (_b = (_a = this.logger).debug) == null ? void 0 : _b.call(_a, message, ...optionalParams);
2230
2346
  }
2231
- getHandler() {
2232
- return this.handler;
2347
+ trace(message, ...optionalParams) {
2348
+ var _a, _b;
2349
+ (_b = (_a = this.logger).verbose) == null ? void 0 : _b.call(_a, message, ...optionalParams);
2233
2350
  }
2234
- getRequest() {
2235
- if (!this.request) {
2236
- throw new Error(
2237
- "[Navios] Request is not set. Make sure to set it before using it."
2238
- );
2239
- }
2240
- return this.request;
2351
+ silent() {
2241
2352
  }
2242
- getReply() {
2243
- if (!this.reply) {
2244
- throw new Error(
2245
- "[Navios] Reply is not set. Make sure to set it before using it."
2246
- );
2353
+ child(options) {
2354
+ const keys = Object.keys(options);
2355
+ let newContext = this.logger["context"] ?? "";
2356
+ if (keys.length > 1) {
2357
+ newContext = `${this.logger["context"] ?? ""}:${JSON.stringify(options)}`;
2247
2358
  }
2248
- return this.reply;
2249
- }
2250
- provideRequest(request) {
2251
- this.request = request;
2359
+ return new _PinoWrapper(
2360
+ // @ts-expect-error We don't need to support this in the current version
2361
+ new LoggerInstance(newContext, this.logger["options"])
2362
+ );
2252
2363
  }
2253
- provideReply(reply) {
2254
- this.reply = reply;
2364
+ get level() {
2365
+ if ("level" in this.logger && this.logger.level) {
2366
+ return this.logger.level;
2367
+ }
2368
+ const levels = LoggerInstance["logLevels"];
2369
+ if (levels) {
2370
+ return levels.find((level) => level !== "verbose");
2371
+ }
2372
+ return "warn";
2255
2373
  }
2256
2374
  };
2257
2375
 
2258
- // packages/core/src/services/guard-runner.service.mts
2259
- var _GuardRunnerService_decorators, _init5;
2260
- _GuardRunnerService_decorators = [Injectable()];
2261
- var GuardRunnerService = class {
2262
- async runGuards(allGuards, executionContext) {
2263
- let canActivate = true;
2264
- for (const guard of Array.from(allGuards).reverse()) {
2265
- const guardInstance = await inject(
2266
- guard
2267
- );
2268
- if (!guardInstance.canActivate) {
2269
- throw new Error(
2270
- `[Navios] Guard ${guard.name} does not implement canActivate()`
2271
- );
2272
- }
2273
- try {
2274
- canActivate = await guardInstance.canActivate(executionContext);
2275
- if (!canActivate) {
2276
- break;
2277
- }
2278
- } catch (error) {
2279
- if (error instanceof HttpException) {
2280
- executionContext.getReply().status(error.statusCode).send(error.response);
2281
- return false;
2282
- } else {
2283
- executionContext.getReply().status(500).send({
2284
- message: "Internal server error",
2285
- error: error.message
2286
- });
2287
- return false;
2288
- }
2289
- }
2290
- }
2291
- if (!canActivate) {
2292
- executionContext.getReply().status(403).send({
2293
- message: "Forbidden"
2294
- });
2295
- return false;
2296
- }
2297
- return canActivate;
2376
+ // packages/core/src/config/config.service.mts
2377
+ var import_common4 = require("@navios/common");
2378
+ var ConfigServiceInstance = class {
2379
+ constructor(config = {}, logger) {
2380
+ this.config = config;
2381
+ this.logger = logger;
2298
2382
  }
2299
- makeContext(executionContext) {
2300
- const guards = /* @__PURE__ */ new Set();
2301
- const endpointGuards = executionContext.getHandler().guards;
2302
- const controllerGuards = executionContext.getController().guards;
2303
- const moduleGuards = executionContext.getModule().guards;
2304
- if (endpointGuards.size > 0) {
2305
- for (const guard of endpointGuards) {
2306
- guards.add(guard);
2307
- }
2308
- }
2309
- if (controllerGuards.size > 0) {
2310
- for (const guard of controllerGuards) {
2311
- guards.add(guard);
2312
- }
2313
- }
2314
- if (moduleGuards.size > 0) {
2315
- for (const guard of moduleGuards) {
2316
- guards.add(guard);
2383
+ getConfig() {
2384
+ return this.config;
2385
+ }
2386
+ get(key) {
2387
+ var _a, _b;
2388
+ try {
2389
+ const parts = String(key).split(".");
2390
+ let value = this.config;
2391
+ for (const part of parts) {
2392
+ if (value === null || value === void 0 || typeof value !== "object") {
2393
+ return null;
2394
+ }
2395
+ value = value[part];
2317
2396
  }
2397
+ return value ?? null;
2398
+ } catch (error) {
2399
+ (_b = (_a = this.logger).debug) == null ? void 0 : _b.call(
2400
+ _a,
2401
+ `Failed to get config value for key ${String(key)}`,
2402
+ error
2403
+ );
2404
+ return null;
2318
2405
  }
2319
- return guards;
2406
+ }
2407
+ getOrDefault(key, defaultValue) {
2408
+ const value = this.get(key);
2409
+ return value !== null ? value : defaultValue;
2410
+ }
2411
+ getOrThrow(key, errorMessage) {
2412
+ const value = this.get(key);
2413
+ if (value === null) {
2414
+ const message = errorMessage || `Configuration value for key "${String(key)}" is not defined`;
2415
+ this.logger.error(message);
2416
+ throw new import_common4.NaviosException(message);
2417
+ }
2418
+ return value;
2320
2419
  }
2321
2420
  };
2322
- _init5 = __decoratorStart(null);
2323
- GuardRunnerService = __decorateElement(_init5, 0, "GuardRunnerService", _GuardRunnerService_decorators, GuardRunnerService);
2324
- __runInitializers(_init5, 1, GuardRunnerService);
2325
2421
 
2326
- // packages/core/src/services/controller-adapter.service.mts
2327
- var _ControllerAdapterService_decorators, _init6;
2328
- _ControllerAdapterService_decorators = [Injectable()];
2329
- var _ControllerAdapterService = class _ControllerAdapterService {
2330
- guardRunner = syncInject(GuardRunnerService);
2422
+ // packages/core/src/config/config.provider.mts
2423
+ var ConfigProviderOptions = import_zod4.z.object({
2424
+ load: import_zod4.z.function()
2425
+ });
2426
+ var ConfigProvider = InjectionToken.create(ConfigServiceInstance, ConfigProviderOptions);
2427
+ var _ConfigProviderFactory_decorators, _init7;
2428
+ _ConfigProviderFactory_decorators = [Injectable({
2429
+ token: ConfigProvider,
2430
+ type: "Factory" /* Factory */
2431
+ })];
2432
+ var ConfigProviderFactory = class {
2331
2433
  logger = syncInject(Logger, {
2332
- context: _ControllerAdapterService.name
2434
+ context: "ConfigService"
2333
2435
  });
2334
- setupController(controller, instance, moduleMetadata) {
2335
- const controllerMetadata = extractControllerMetadata(controller);
2336
- for (const endpoint of controllerMetadata.endpoints) {
2337
- const { classMethod, url, httpMethod } = endpoint;
2338
- if (!url) {
2339
- throw new Error(
2340
- `[Navios] Malformed Endpoint ${controller.name}:${classMethod}`
2341
- );
2342
- }
2343
- const executionContext = new ExecutionContext2(
2344
- moduleMetadata,
2345
- controllerMetadata,
2346
- endpoint
2347
- );
2348
- instance.withTypeProvider().route({
2349
- method: httpMethod,
2350
- url: url.replaceAll("$", ":"),
2351
- schema: this.provideSchemaForConfig(endpoint),
2352
- preHandler: this.providePreHandler(executionContext),
2353
- handler: this.provideHandler(controller, executionContext, endpoint)
2354
- });
2355
- this.logger.debug(
2356
- `Registered ${httpMethod} ${url} for ${controller.name}:${classMethod}`
2357
- );
2436
+ async create(ctx, args) {
2437
+ const { load } = args;
2438
+ const logger = this.logger;
2439
+ try {
2440
+ const config = await load();
2441
+ return new ConfigServiceInstance(config, logger);
2442
+ } catch (error) {
2443
+ logger.error("Error loading config", error);
2444
+ throw error;
2358
2445
  }
2359
2446
  }
2360
- providePreHandler(executionContext) {
2361
- const guards = this.guardRunner.makeContext(executionContext);
2362
- return guards.size > 0 ? async (request, reply) => {
2363
- getServiceLocator().registerInstance(Request, request);
2364
- getServiceLocator().registerInstance(Reply, reply);
2365
- getServiceLocator().registerInstance(
2366
- ExecutionContextToken,
2367
- executionContext
2447
+ };
2448
+ _init7 = __decoratorStart(null);
2449
+ ConfigProviderFactory = __decorateElement(_init7, 0, "ConfigProviderFactory", _ConfigProviderFactory_decorators, ConfigProviderFactory);
2450
+ __runInitializers(_init7, 1, ConfigProviderFactory);
2451
+ function provideConfig(options) {
2452
+ return InjectionToken.bound(ConfigProvider, options);
2453
+ }
2454
+
2455
+ // packages/core/src/decorators/controller.decorator.mts
2456
+ function Controller({ guards } = {}) {
2457
+ return function(target, context) {
2458
+ if (context.kind !== "class") {
2459
+ throw new Error(
2460
+ "[Navios] @Controller decorator can only be used on classes."
2368
2461
  );
2369
- executionContext.provideRequest(request);
2370
- executionContext.provideReply(reply);
2371
- let canActivate = true;
2372
- try {
2373
- canActivate = await this.guardRunner.runGuards(
2374
- guards,
2375
- executionContext
2376
- );
2377
- } finally {
2378
- getServiceLocator().removeInstance(Request);
2379
- getServiceLocator().removeInstance(Reply);
2380
- getServiceLocator().removeInstance(ExecutionContextToken);
2381
- }
2382
- if (!canActivate) {
2383
- return reply;
2384
- }
2385
- } : void 0;
2386
- }
2387
- provideSchemaForConfig(endpointMetadata) {
2388
- if (!endpointMetadata.config) {
2389
- this.logger.warn(`No config found for endpoint ${endpointMetadata.url}`);
2390
- return {};
2391
2462
  }
2392
- const { querySchema, requestSchema, responseSchema } = endpointMetadata.config;
2393
- const schema = {};
2394
- if (querySchema) {
2395
- schema.querystring = querySchema;
2463
+ const token = InjectionToken.create(target);
2464
+ if (context.metadata) {
2465
+ const controllerMetadata = getControllerMetadata(target, context);
2466
+ if (guards) {
2467
+ for (const guard of Array.from(guards).reverse()) {
2468
+ controllerMetadata.guards.add(guard);
2469
+ }
2470
+ }
2396
2471
  }
2397
- if (requestSchema && endpointMetadata.type !== "multipart" /* Multipart */) {
2398
- schema.body = requestSchema;
2472
+ return Injectable({
2473
+ token,
2474
+ type: "Class" /* Class */,
2475
+ scope: "Instance" /* Instance */
2476
+ })(target, context);
2477
+ };
2478
+ }
2479
+
2480
+ // packages/core/src/decorators/endpoint.decorator.mts
2481
+ var import_zod5 = require("zod");
2482
+ function Endpoint(endpoint) {
2483
+ return (target, context) => {
2484
+ if (typeof target !== "function") {
2485
+ throw new Error(
2486
+ "[Navios] Endpoint decorator can only be used on functions."
2487
+ );
2399
2488
  }
2400
- if (responseSchema) {
2401
- schema.response = {
2402
- 200: responseSchema
2403
- };
2489
+ if (context.kind !== "method") {
2490
+ throw new Error(
2491
+ "[Navios] Endpoint decorator can only be used on methods."
2492
+ );
2404
2493
  }
2405
- return schema;
2406
- }
2407
- provideHandler(controller, executionContext, endpointMetadata) {
2408
- switch (endpointMetadata.type) {
2409
- case "unknown" /* Unknown */:
2410
- this.logger.error(
2411
- `Unknown endpoint type ${endpointMetadata.type} for ${controller.name}:${endpointMetadata.classMethod}`
2412
- );
2413
- throw new import_common4.NaviosException("Unknown endpoint type");
2414
- case "endpoint" /* Endpoint */:
2415
- return this.provideHandlerForConfig(
2416
- controller,
2417
- executionContext,
2418
- endpointMetadata
2419
- );
2420
- case "stream" /* Stream */:
2421
- return this.provideHandlerForStream(
2422
- controller,
2423
- executionContext,
2424
- endpointMetadata
2425
- );
2426
- case "multipart" /* Multipart */:
2427
- return this.provideHandlerForMultipart(
2428
- controller,
2429
- executionContext,
2430
- endpointMetadata
2494
+ const config = endpoint.config;
2495
+ if (context.metadata) {
2496
+ let endpointMetadata = getEndpointMetadata(target, context);
2497
+ if (endpointMetadata.config && endpointMetadata.config.url) {
2498
+ throw new Error(
2499
+ `[Navios] Endpoint ${config.method} ${config.url} already exists. Please use a different method or url.`
2431
2500
  );
2432
- case "handler" /* Handler */:
2433
- this.logger.error("Not implemented yet");
2434
- throw new import_common4.NaviosException("Not implemented yet");
2501
+ }
2502
+ endpointMetadata.config = config;
2503
+ endpointMetadata.type = "endpoint" /* Endpoint */;
2504
+ endpointMetadata.classMethod = target.name;
2505
+ endpointMetadata.httpMethod = config.method;
2506
+ endpointMetadata.url = config.url;
2435
2507
  }
2436
- }
2437
- provideHandlerForConfig(controller, executionContext, endpointMetadata) {
2438
- return async (request, reply) => {
2439
- getServiceLocator().registerInstance(Request, request);
2440
- getServiceLocator().registerInstance(Reply, reply);
2441
- getServiceLocator().registerInstance(
2442
- ExecutionContextToken,
2443
- executionContext
2508
+ return target;
2509
+ };
2510
+ }
2511
+
2512
+ // packages/core/src/decorators/header.decorator.mts
2513
+ function Header(name2, value) {
2514
+ return (target, context) => {
2515
+ if (context.kind !== "method") {
2516
+ throw new Error("[Navios] Header decorator can only be used on methods.");
2517
+ }
2518
+ const metadata = getEndpointMetadata(target, context);
2519
+ if (metadata.type === "stream" /* Stream */) {
2520
+ throw new Error(
2521
+ "[Navios] HttpCode decorator cannot be used on stream endpoints."
2444
2522
  );
2445
- executionContext.provideRequest(request);
2446
- executionContext.provideReply(reply);
2447
- const controllerInstance = await inject(controller);
2448
- try {
2449
- const { query, params, body } = request;
2450
- const argument = {};
2451
- if (query && Object.keys(query).length > 0) {
2452
- argument.params = query;
2453
- }
2454
- if (params && Object.keys(params).length > 0) {
2455
- argument.urlParams = params;
2456
- }
2457
- if (body) {
2458
- argument.data = body;
2459
- }
2460
- const result = await controllerInstance[endpointMetadata.classMethod](argument);
2461
- reply.status(endpointMetadata.successStatusCode).headers(endpointMetadata.headers).send(result);
2462
- } finally {
2463
- getServiceLocator().removeInstance(Request);
2464
- getServiceLocator().removeInstance(Reply);
2465
- getServiceLocator().removeInstance(ExecutionContextToken);
2466
- }
2467
- };
2468
- }
2469
- provideHandlerForStream(controller, executionContext, endpointMetadata) {
2470
- return async (request, reply) => {
2471
- getServiceLocator().registerInstance(Request, request);
2472
- getServiceLocator().registerInstance(Reply, reply);
2473
- getServiceLocator().registerInstance(
2474
- ExecutionContextToken,
2475
- executionContext
2523
+ }
2524
+ metadata.headers[name2] = value;
2525
+ return target;
2526
+ };
2527
+ }
2528
+
2529
+ // packages/core/src/decorators/http-code.decorator.mts
2530
+ function HttpCode(code) {
2531
+ return (target, context) => {
2532
+ if (context.kind !== "method") {
2533
+ throw new Error(
2534
+ "[Navios] HttpCode decorator can only be used on methods."
2535
+ );
2536
+ }
2537
+ const metadata = getEndpointMetadata(target, context);
2538
+ if (metadata.type === "stream" /* Stream */) {
2539
+ throw new Error(
2540
+ "[Navios] HttpCode decorator cannot be used on stream endpoints."
2476
2541
  );
2477
- executionContext.provideRequest(request);
2478
- executionContext.provideReply(reply);
2479
- const controllerInstance = await inject(controller);
2480
- try {
2481
- const { query, params, body } = request;
2482
- const argument = {};
2483
- if (query && Object.keys(query).length > 0) {
2484
- argument.params = query;
2485
- }
2486
- if (params && Object.keys(params).length > 0) {
2487
- argument.urlParams = params;
2488
- }
2489
- if (body) {
2490
- argument.data = body;
2491
- }
2492
- await controllerInstance[endpointMetadata.classMethod](argument, reply);
2493
- } finally {
2494
- getServiceLocator().removeInstance(Request);
2495
- getServiceLocator().removeInstance(Reply);
2496
- getServiceLocator().removeInstance(ExecutionContextToken);
2542
+ }
2543
+ metadata.successStatusCode = code;
2544
+ return target;
2545
+ };
2546
+ }
2547
+
2548
+ // packages/core/src/decorators/module.decorator.mts
2549
+ function Module(metadata) {
2550
+ return (target, context) => {
2551
+ if (context.kind !== "class") {
2552
+ throw new Error("[Navios] @Module decorator can only be used on classes.");
2553
+ }
2554
+ const token = InjectionToken.create(target);
2555
+ const moduleMetadata = getModuleMetadata(target, context);
2556
+ if (metadata.controllers) {
2557
+ for (const controller of metadata.controllers) {
2558
+ moduleMetadata.controllers.add(controller);
2497
2559
  }
2498
- };
2499
- }
2500
- provideHandlerForMultipart(controller, executionContext, endpointMetadata) {
2501
- const config = endpointMetadata.config;
2502
- const requestSchema = config.requestSchema;
2503
- const shape = requestSchema._def.shape();
2504
- return async (request, reply) => {
2505
- getServiceLocator().registerInstance(Request, request);
2506
- getServiceLocator().registerInstance(Reply, reply);
2507
- getServiceLocator().registerInstance(
2508
- ExecutionContextToken,
2509
- executionContext
2510
- );
2511
- executionContext.provideRequest(request);
2512
- executionContext.provideReply(reply);
2513
- const controllerInstance = await inject(controller);
2514
- try {
2515
- const parts = request.parts();
2516
- const { query, params } = request;
2517
- const argument = {};
2518
- if (query && Object.keys(query).length > 0) {
2519
- argument.params = query;
2520
- }
2521
- if (params && Object.keys(params).length > 0) {
2522
- argument.urlParams = params;
2523
- }
2524
- const req = {};
2525
- for await (const part of parts) {
2526
- if (!shape[part.fieldname]) {
2527
- throw new import_common4.NaviosException(
2528
- `Invalid field name ${part.fieldname} for multipart request`
2529
- );
2530
- }
2531
- const schema = shape[part.fieldname];
2532
- if (part.type === "file") {
2533
- const file = new File([await part.toBuffer()], part.filename, {
2534
- type: part.mimetype
2535
- });
2536
- if (schema instanceof import_zod6.ZodArray) {
2537
- if (!req[part.fieldname]) {
2538
- req[part.fieldname] = [];
2539
- }
2540
- req[part.fieldname].push(file);
2541
- } else {
2542
- req[part.fieldname] = file;
2543
- }
2544
- } else {
2545
- if (schema instanceof import_zod6.ZodArray) {
2546
- if (!req[part.fieldname]) {
2547
- req[part.fieldname] = [];
2548
- }
2549
- req[part.fieldname].push(part.value);
2550
- } else {
2551
- req[part.fieldname] = part.value;
2552
- }
2553
- }
2554
- }
2555
- argument.body = requestSchema.parse(req);
2556
- const result = await controllerInstance[endpointMetadata.classMethod](argument);
2557
- reply.status(endpointMetadata.successStatusCode).headers(endpointMetadata.headers).send(result);
2558
- } finally {
2559
- getServiceLocator().removeInstance(Request);
2560
- getServiceLocator().removeInstance(Reply);
2561
- getServiceLocator().removeInstance(ExecutionContextToken);
2560
+ }
2561
+ if (metadata.imports) {
2562
+ for (const importedModule of metadata.imports) {
2563
+ moduleMetadata.imports.add(importedModule);
2562
2564
  }
2563
- };
2564
- }
2565
- };
2566
- _init6 = __decoratorStart(null);
2567
- _ControllerAdapterService = __decorateElement(_init6, 0, "ControllerAdapterService", _ControllerAdapterService_decorators, _ControllerAdapterService);
2568
- __runInitializers(_init6, 1, _ControllerAdapterService);
2569
- var ControllerAdapterService = _ControllerAdapterService;
2565
+ }
2566
+ if (metadata.guards) {
2567
+ for (const guard of Array.from(metadata.guards).reverse()) {
2568
+ moduleMetadata.guards.add(guard);
2569
+ }
2570
+ }
2571
+ return Injectable({
2572
+ token,
2573
+ type: "Class" /* Class */,
2574
+ scope: "Singleton" /* Singleton */
2575
+ })(target, context);
2576
+ };
2577
+ }
2570
2578
 
2571
- // packages/core/src/services/module-loader.service.mts
2572
- var _ModuleLoaderService_decorators, _init7;
2573
- _ModuleLoaderService_decorators = [Injectable()];
2574
- var _ModuleLoaderService = class _ModuleLoaderService {
2575
- logger = syncInject(Logger, {
2576
- context: _ModuleLoaderService.name
2577
- });
2578
- modulesMetadata = /* @__PURE__ */ new Map();
2579
- loadedModules = /* @__PURE__ */ new Map();
2580
- initialized = false;
2581
- async loadModules(appModule) {
2582
- if (this.initialized) {
2583
- return;
2579
+ // packages/core/src/decorators/multipart.decorator.mts
2580
+ var import_zod6 = require("zod");
2581
+ function Multipart(endpoint) {
2582
+ return (target, context) => {
2583
+ if (typeof target !== "function") {
2584
+ throw new Error(
2585
+ "[Navios] Endpoint decorator can only be used on functions."
2586
+ );
2584
2587
  }
2585
- await this.traverseModules(appModule);
2586
- this.initialized = true;
2587
- }
2588
- async traverseModules(module2, parentMetadata) {
2589
- const metadata = extractModuleMetadata(module2);
2590
- if (parentMetadata) {
2591
- this.mergeMetadata(metadata, parentMetadata);
2588
+ if (context.kind !== "method") {
2589
+ throw new Error(
2590
+ "[Navios] Endpoint decorator can only be used on methods."
2591
+ );
2592
2592
  }
2593
- const moduleName = module2.name;
2594
- if (this.modulesMetadata.has(moduleName)) {
2595
- return;
2593
+ const config = endpoint.config;
2594
+ if (context.metadata) {
2595
+ let endpointMetadata = getEndpointMetadata(target, context);
2596
+ if (endpointMetadata.config && endpointMetadata.config.url) {
2597
+ throw new Error(
2598
+ `[Navios] Endpoint ${config.method} ${config.url} already exists. Please use a different method or url.`
2599
+ );
2600
+ }
2601
+ endpointMetadata.config = config;
2602
+ endpointMetadata.type = "multipart" /* Multipart */;
2603
+ endpointMetadata.classMethod = target.name;
2604
+ endpointMetadata.httpMethod = config.method;
2605
+ endpointMetadata.url = config.url;
2596
2606
  }
2597
- this.modulesMetadata.set(moduleName, metadata);
2598
- const imports = metadata.imports ?? /* @__PURE__ */ new Set();
2599
- const loadingPromises = Array.from(imports).map(
2600
- async (importedModule) => this.traverseModules(importedModule, metadata)
2601
- );
2602
- await Promise.all(loadingPromises);
2603
- const instance = await inject(module2);
2604
- if (instance.onModuleInit) {
2605
- await instance.onModuleInit();
2607
+ return target;
2608
+ };
2609
+ }
2610
+
2611
+ // packages/core/src/decorators/stream.decorator.mts
2612
+ function Stream(endpoint) {
2613
+ return (target, context) => {
2614
+ if (typeof target !== "function") {
2615
+ throw new Error(
2616
+ "[Navios] Endpoint decorator can only be used on functions."
2617
+ );
2606
2618
  }
2607
- this.logger.debug(`Module ${moduleName} loaded`);
2608
- this.loadedModules.set(moduleName, instance);
2609
- }
2610
- mergeMetadata(metadata, parentMetadata) {
2611
- if (parentMetadata.guards) {
2612
- for (const guard of parentMetadata.guards) {
2613
- metadata.guards.add(guard);
2619
+ if (context.kind !== "method") {
2620
+ throw new Error(
2621
+ "[Navios] Endpoint decorator can only be used on methods."
2622
+ );
2623
+ }
2624
+ const config = endpoint.config;
2625
+ if (context.metadata) {
2626
+ let endpointMetadata = getEndpointMetadata(target, context);
2627
+ if (endpointMetadata.config && endpointMetadata.config.url) {
2628
+ throw new Error(
2629
+ `[Navios] Endpoint ${config.method} ${config.url} already exists. Please use a different method or url.`
2630
+ );
2614
2631
  }
2632
+ endpointMetadata.config = config;
2633
+ endpointMetadata.type = "stream" /* Stream */;
2634
+ endpointMetadata.classMethod = target.name;
2635
+ endpointMetadata.httpMethod = config.method;
2636
+ endpointMetadata.url = config.url;
2615
2637
  }
2616
- if (parentMetadata.customAttributes) {
2617
- for (const [key, value] of parentMetadata.customAttributes) {
2618
- if (metadata.customAttributes.has(key)) {
2619
- continue;
2620
- }
2621
- metadata.customAttributes.set(key, value);
2638
+ return target;
2639
+ };
2640
+ }
2641
+
2642
+ // packages/core/src/decorators/use-guards.decorator.mts
2643
+ function UseGuards(...guards) {
2644
+ return function(target, context) {
2645
+ if (context.kind === "class") {
2646
+ const controllerMetadata = getControllerMetadata(
2647
+ target,
2648
+ context
2649
+ );
2650
+ for (const guard of guards.reverse()) {
2651
+ controllerMetadata.guards.add(guard);
2622
2652
  }
2653
+ } else if (context.kind === "method") {
2654
+ const endpointMetadata = getEndpointMetadata(target, context);
2655
+ for (const guard of guards.reverse()) {
2656
+ endpointMetadata.guards.add(guard);
2657
+ }
2658
+ } else {
2659
+ throw new Error(
2660
+ "[Navios] @UseGuards decorator can only be used on classes or methods."
2661
+ );
2623
2662
  }
2624
- }
2625
- getAllModules() {
2626
- return this.modulesMetadata;
2627
- }
2628
- dispose() {
2629
- this.modulesMetadata.clear();
2630
- this.loadedModules.clear();
2631
- this.initialized = false;
2632
- }
2633
- };
2634
- _init7 = __decoratorStart(null);
2635
- _ModuleLoaderService = __decorateElement(_init7, 0, "ModuleLoaderService", _ModuleLoaderService_decorators, _ModuleLoaderService);
2636
- __runInitializers(_init7, 1, _ModuleLoaderService);
2637
- var ModuleLoaderService = _ModuleLoaderService;
2663
+ return target;
2664
+ };
2665
+ }
2638
2666
 
2639
2667
  // packages/core/src/attribute.factory.mts
2640
2668
  var AttributeFactory = class {