@xeno-js/core 1.1.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -57,8 +57,10 @@ var init_container_utils = __esm({
57
57
  * @throws Error If the service is not a scoped service.
58
58
  */
59
59
  async runExecute(res, req, container, action) {
60
+ const adapter = container.resolve("HTTP_ADAPTER");
61
+ const { request, response } = adapter.adapt(req, res);
60
62
  const middleware = container.resolve(TOKENS.MIDDLEWARE);
61
- return await middleware.execute(req, res, async () => {
63
+ return await middleware.execute(request, response, async () => {
62
64
  return await action();
63
65
  });
64
66
  }
@@ -1254,466 +1256,189 @@ var init_application = __esm({
1254
1256
  }
1255
1257
  });
1256
1258
 
1257
- // src/infrastructure/loggers/console.logger.ts
1258
- var console_logger_exports = {};
1259
- __export(console_logger_exports, {
1260
- ConsoleLogger: () => ConsoleLogger
1259
+ // src/infrastructure/factories/service-scope.factory.ts
1260
+ var service_scope_factory_exports = {};
1261
+ __export(service_scope_factory_exports, {
1262
+ ServiceScopeFactory: () => ServiceScopeFactory
1261
1263
  });
1262
- import { Guards as Guards15, LOG_LEVEL } from "@xeno-js/shared";
1263
- var ConsoleLogger;
1264
- var init_console_logger = __esm({
1265
- "src/infrastructure/loggers/console.logger.ts"() {
1264
+ var ServiceScopeFactory;
1265
+ var init_service_scope_factory = __esm({
1266
+ "src/infrastructure/factories/service-scope.factory.ts"() {
1266
1267
  "use strict";
1267
- ConsoleLogger = class {
1268
- /**
1269
- * Constructs a new instance of the ConsoleLogger class, which takes an optional minimum log level. The minimum log level determines the threshold for logging messages, where messages with a log level below the specified minimum will be ignored.
1270
- * @param _minLevel The minimum log level for logging messages. Messages with a log level below this threshold will not be logged. Default is LOG_LEVEL.DEBUG.
1271
-
1272
- *
1273
- * @author Xeno
1274
- * @version 1.0.0
1275
- * @since 2025-09-30
1276
- * @link https://github.com/xeno-js/xeno-js
1277
- */
1278
- constructor(_minLevel = LOG_LEVEL.DEBUG) {
1279
- this._minLevel = _minLevel;
1268
+ ServiceScopeFactory = class {
1269
+ constructor(_container) {
1270
+ this._container = _container;
1280
1271
  }
1281
- _minLevel;
1282
- track(level, message, context, error = void 0) {
1283
- if (level < this._minLevel) return;
1284
- const logMessage = `[${level}] ${message}`;
1285
- const payload = Guards15.isDefined(error) ? { ...context, error } : context;
1286
- switch (level) {
1287
- case LOG_LEVEL.ERROR:
1288
- console.error(logMessage, payload ?? {});
1289
- break;
1290
- case LOG_LEVEL.WARN:
1291
- console.warn(logMessage, payload ?? {});
1292
- break;
1293
- case LOG_LEVEL.DEBUG:
1294
- console.debug(logMessage, payload ?? {});
1295
- break;
1296
- default:
1297
- console.info(logMessage, payload ?? {});
1298
- break;
1299
- }
1272
+ _container;
1273
+ create() {
1274
+ return this._container.createScope();
1300
1275
  }
1301
1276
  };
1302
1277
  }
1303
1278
  });
1304
1279
 
1305
- // src/infrastructure/loggers/sentry.logger.ts
1306
- import { Guards as Guards16, LOG_LEVEL as LOG_LEVEL2 } from "@xeno-js/shared";
1307
- var SentryLogger;
1308
- var init_sentry_logger = __esm({
1309
- "src/infrastructure/loggers/sentry.logger.ts"() {
1280
+ // src/infrastructure/context/request-context.ts
1281
+ import { Guards as Guards15 } from "@xeno-js/shared";
1282
+ var NodeRequestContext;
1283
+ var init_request_context = __esm({
1284
+ "src/infrastructure/context/request-context.ts"() {
1310
1285
  "use strict";
1311
- SentryLogger = class {
1312
- constructor(_client, _minLevel) {
1313
- this._client = _client;
1314
- this._minLevel = _minLevel;
1286
+ NodeRequestContext = class {
1287
+ /**
1288
+ * @description Constructs a new instance of the NodeRequestContext class, which requires an instance of AsyncLocalStorage to manage the request context. The AsyncLocalStorage instance is used to create and access the context for each request, allowing for the storage of identity information and other relevant data that needs to be accessible across asynchronous operations. This constructor initializes the NodeRequestContext with the provided AsyncLocalStorage, enabling it to implement the methods defined in the IRequestContext interface for managing request-specific context data.
1289
+ * @param _storage An instance of AsyncLocalStorage that is used to manage the request context, allowing for the storage and retrieval of identity information and other relevant data across asynchronous operations.
1290
+ * @param _factoryScope An instance of IFactory that is used to create a new IServiceScope for managing service dependencies during the execution of the request. This allows for proper scoping and disposal of services after the request is processed, ensuring that resources are managed efficiently and preventing memory leaks.
1291
+ *
1292
+ * @author Xeno
1293
+ * @version 1.0.0
1294
+ * @since 2025-09-30
1295
+ * @link https://github.com/xeno-js/xeno-js
1296
+ */
1297
+ constructor(_storage, _factoryScope) {
1298
+ this._storage = _storage;
1299
+ this._factoryScope = _factoryScope;
1315
1300
  }
1316
- _client;
1317
- _minLevel;
1318
- track(level, message, context = void 0, error = void 0) {
1319
- if (level < this._minLevel) return;
1320
- if (level === LOG_LEVEL2.ERROR || level === LOG_LEVEL2.WARN) {
1321
- this._client.withScope((scope) => {
1322
- if (Guards16.isDefined(context)) scope.setExtras(context);
1323
- if (Guards16.isDefined(error)) {
1324
- this._client.captureException(error);
1325
- } else {
1326
- this._client.captureMessage(message, "warning");
1327
- }
1301
+ _storage;
1302
+ _factoryScope;
1303
+ async runAsync(context, fn) {
1304
+ const scope = this._factoryScope.create();
1305
+ try {
1306
+ return await this._storage.run({ context, scope }, fn);
1307
+ } finally {
1308
+ await scope.dispose();
1309
+ }
1310
+ }
1311
+ updateIdentity(identity) {
1312
+ const store = this._storage.getStore();
1313
+ if (Guards15.isDefined(store) && Guards15.isDefined(store.context)) {
1314
+ store.context = Object.freeze({
1315
+ ...store.context,
1316
+ identity: Object.freeze(identity)
1328
1317
  });
1329
1318
  }
1330
1319
  }
1320
+ getContext() {
1321
+ const store = this._storage.getStore();
1322
+ if (!Guards15.isDefined(store)) return void 0;
1323
+ const context = store.context;
1324
+ return Object.freeze(context);
1325
+ }
1326
+ getIdentity() {
1327
+ const store = this._storage.getStore();
1328
+ if (!Guards15.isDefined(store)) return void 0;
1329
+ return Object.freeze(store.context?.identity);
1330
+ }
1331
+ getScope() {
1332
+ const store = this._storage.getStore();
1333
+ if (!Guards15.isDefined(store)) return void 0;
1334
+ return store.scope;
1335
+ }
1336
+ getNetworkContext() {
1337
+ const store = this._storage.getStore();
1338
+ if (!Guards15.isDefined(store)) return void 0;
1339
+ return Object.freeze(store.context?.network);
1340
+ }
1331
1341
  };
1332
1342
  }
1333
1343
  });
1334
1344
 
1335
- // src/infrastructure/factories/sentry-logger.factory.ts
1336
- var sentry_logger_factory_exports = {};
1337
- __export(sentry_logger_factory_exports, {
1338
- SentryLoggerFactory: () => SentryLoggerFactory
1345
+ // src/infrastructure/factories/request-context.factory.ts
1346
+ var request_context_factory_exports = {};
1347
+ __export(request_context_factory_exports, {
1348
+ NodeRequestContextFactory: () => NodeRequestContextFactory
1339
1349
  });
1340
- import * as Sentry from "@sentry/node";
1341
- import { Guards as Guards17, LOG_LEVEL as LOG_LEVEL3 } from "@xeno-js/shared";
1342
- var SentryLoggerFactory;
1343
- var init_sentry_logger_factory = __esm({
1344
- "src/infrastructure/factories/sentry-logger.factory.ts"() {
1350
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
1351
+ var NodeRequestContextFactory;
1352
+ var init_request_context_factory = __esm({
1353
+ "src/infrastructure/factories/request-context.factory.ts"() {
1345
1354
  "use strict";
1346
- init_sentry_logger();
1347
- SentryLoggerFactory = class {
1348
- create(config) {
1349
- const level = config.level ?? LOG_LEVEL3.WARN;
1350
- const sentryConfig = config.sentry?.config;
1351
- const env = sentryConfig?.environment ?? process.env.NODE_ENV ?? "development";
1352
- if (!Guards17.isDefined(sentryConfig))
1353
- throw new Error("Sentry configuration is required when Sentry logging is enabled.");
1354
- if (!Guards17.isDefined(sentryConfig.dsn))
1355
- throw new Error("Sentry DSN is required when Sentry logging is enabled.");
1356
- Sentry.init({
1357
- dsn: sentryConfig.dsn,
1358
- environment: env,
1359
- tracesSampleRate: env === "production" ? 0.1 : 1,
1360
- integrations: [Sentry.httpIntegration()],
1361
- beforeSend(event, hint) {
1362
- const error = hint.originalException;
1363
- if (error instanceof Error && error.name === "ZodError") {
1364
- return null;
1365
- }
1366
- return event;
1367
- }
1368
- });
1369
- return new SentryLogger(Sentry, level);
1355
+ init_request_context();
1356
+ NodeRequestContextFactory = class {
1357
+ constructor(_factoryScope) {
1358
+ this._factoryScope = _factoryScope;
1359
+ }
1360
+ _factoryScope;
1361
+ _store = new AsyncLocalStorage2();
1362
+ create() {
1363
+ return new NodeRequestContext(this._store, this._factoryScope);
1370
1364
  }
1371
1365
  };
1372
1366
  }
1373
1367
  });
1374
1368
 
1375
- // src/infrastructure/loggers/pino.logger.ts
1376
- import { Guards as Guards18, LOG_LEVEL as LOG_LEVEL4 } from "@xeno-js/shared";
1377
- var PinoLogger;
1378
- var init_pino_logger = __esm({
1379
- "src/infrastructure/loggers/pino.logger.ts"() {
1369
+ // src/infrastructure/factories/user-context.factory.ts
1370
+ var user_context_factory_exports = {};
1371
+ __export(user_context_factory_exports, {
1372
+ UserContextFactory: () => UserContextFactory
1373
+ });
1374
+ import { Guards as Guards16 } from "@xeno-js/shared";
1375
+ var UserContextFactory;
1376
+ var init_user_context_factory = __esm({
1377
+ "src/infrastructure/factories/user-context.factory.ts"() {
1380
1378
  "use strict";
1381
- PinoLogger = class {
1379
+ UserContextFactory = class {
1382
1380
  /**
1383
- * Constructs a new instance of the PinoTransport class, which takes an optional minimum log level and an optional instance of the Pino logger. If no logger instance is provided, it initializes a new Pino logger with default settings. The minimum log level determines the threshold for logging messages, where messages with a log level below the specified minimum will be ignored.
1384
- * @param _logger The Pino logger instance used for logging messages.
1385
- * @param _minLevel The minimum log level for logging messages. Messages with a log level below this threshold will not be logged. Default is LOG_LEVEL.DEBUG.
1386
-
1387
- *
1381
+ * @description Constructs an instance of UserContextFactory.
1382
+ * @param _identityFactory - An instance of IIdentityAccessor that provides access to the current identity. This factory is used to retrieve the identity details when creating a UserContext instance.
1383
+ *
1388
1384
  * @author Xeno
1389
1385
  * @version 1.0.0
1390
1386
  * @since 2025-09-30
1391
- * @link https://github.com/xeno-js/xeno-js
1387
+ * @link https://github.com/xeno-js/xeno-js
1392
1388
  */
1393
- constructor(_logger, _minLevel = LOG_LEVEL4.DEBUG) {
1394
- this._logger = _logger;
1395
- this._minLevel = _minLevel;
1389
+ constructor(_identityFactory) {
1390
+ this._identityFactory = _identityFactory;
1396
1391
  }
1397
- _logger;
1398
- _minLevel;
1399
- track(level, message, context, error = void 0) {
1400
- if (level < this._minLevel) return;
1401
- const payload = Guards18.isDefined(error) ? { ...context, error } : context;
1402
- switch (level) {
1403
- case LOG_LEVEL4.ERROR:
1404
- this._logger.error(payload ?? {}, message);
1405
- break;
1406
- case LOG_LEVEL4.WARN:
1407
- this._logger.warn(payload ?? {}, message);
1408
- break;
1409
- case LOG_LEVEL4.DEBUG:
1410
- this._logger.debug(payload ?? {}, message);
1411
- break;
1412
- default:
1413
- this._logger.info(payload ?? {}, message);
1414
- break;
1392
+ _identityFactory;
1393
+ create() {
1394
+ const output = {
1395
+ userId: void 0,
1396
+ tenantId: void 0
1397
+ };
1398
+ const identity = this._identityFactory.getIdentity();
1399
+ if (Guards16.isDefined(identity)) {
1400
+ output.userId = identity.userId;
1401
+ output.tenantId = identity.tenantId;
1415
1402
  }
1403
+ return output;
1416
1404
  }
1417
1405
  };
1418
1406
  }
1419
1407
  });
1420
1408
 
1421
- // src/infrastructure/factories/pino-logger.factory.ts
1422
- var pino_logger_factory_exports = {};
1423
- __export(pino_logger_factory_exports, {
1424
- PinoLoggerFactory: () => PinoLoggerFactory
1409
+ // src/infrastructure/modules/context.module.ts
1410
+ var context_module_exports = {};
1411
+ __export(context_module_exports, {
1412
+ ContextModule: () => ContextModule
1425
1413
  });
1426
- import { LOG_LEVEL as LOG_LEVEL5 } from "@xeno-js/shared";
1427
- import pino from "pino";
1428
- var PinoLoggerFactory;
1429
- var init_pino_logger_factory = __esm({
1430
- "src/infrastructure/factories/pino-logger.factory.ts"() {
1414
+ var ContextModule;
1415
+ var init_context_module = __esm({
1416
+ "src/infrastructure/modules/context.module.ts"() {
1431
1417
  "use strict";
1432
- init_pino_logger();
1433
- PinoLoggerFactory = class {
1434
- create(config) {
1435
- const level = config.level ?? LOG_LEVEL5.DEBUG;
1436
- const env = config.pino.config?.env ?? process.env.NODE_ENV ?? "development";
1437
- const destinationType = config.pino.config?.destination ?? "stdout";
1438
- const filePath = config.pino.config?.filePath ?? "logs/app.log";
1439
- const prettyPrint = config.pino.config?.prettyPrint ?? env === "development";
1440
- const options = {
1441
- level: "trace",
1442
- serializers: {
1443
- err: pino.stdSerializers.err
1444
- },
1445
- timestamp: pino.stdTimeFunctions.isoTime,
1446
- redact: {
1447
- paths: ["password", "token", "secret", "authorization", "headers.authorization"],
1448
- censor: "***"
1449
- }
1450
- };
1451
- if (prettyPrint) {
1452
- return new PinoLogger(
1453
- pino({
1454
- ...options,
1455
- transport: {
1456
- target: "pino-pretty",
1457
- options: {
1458
- colorize: true,
1459
- ignore: "pid,hostname",
1460
- translateTime: "SYS:standard"
1461
- }
1462
- }
1463
- }),
1464
- level
1465
- );
1466
- }
1467
- if (destinationType === "file") {
1468
- const destination = pino.destination({ dest: filePath, sync: false });
1469
- return new PinoLogger(pino(options, destination), level);
1470
- } else {
1471
- const stream = pino.destination({ dest: 1, sync: false });
1472
- return new PinoLogger(pino(options, stream), level);
1473
- }
1474
- }
1475
- };
1476
- }
1477
- });
1478
-
1479
- // src/infrastructure/modules/utils/logger.utils.ts
1480
- var logger_utils_exports = {};
1481
- __export(logger_utils_exports, {
1482
- LoggerUtils: () => LoggerUtils
1483
- });
1484
- var LoggerUtils;
1485
- var init_logger_utils = __esm({
1486
- "src/infrastructure/modules/utils/logger.utils.ts"() {
1487
- "use strict";
1488
- LoggerUtils = Object.freeze({
1489
- /**
1490
- * @description Configures and registers the logging services in the dependency injection container based on the provided LoggerConfig options. It dynamically imports the necessary logger implementations (e.g., ConsoleLogger, SentryLogger, PinoLogger) and registers them with the container, allowing for flexible and modular logging configuration in the application.
1491
- *
1492
- * @param container - The service container to register logging services with.
1493
- * @param opts - The LoggerConfig options to determine which loggers to enable and their configurations.
1494
-
1495
- *
1496
- * @author Xeno
1497
- * @version 1.0.0
1498
- * @since 2025-09-30
1499
- * @link https://github.com/xeno-js/xeno-js
1500
- */
1501
- async addLogger(container, opts) {
1502
- const loggerDependencies = [];
1503
- const { Guards: Guards47, LOG_LEVEL: LOG_LEVEL7, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
1504
- if (!Guards47.isDefined(opts) || opts.console) {
1505
- const { ConsoleLogger: ConsoleLogger2 } = await Promise.resolve().then(() => (init_console_logger(), console_logger_exports));
1506
- loggerDependencies.push(new ConsoleLogger2(opts?.level));
1507
- }
1508
- if (Guards47.isDefined(opts)) {
1509
- if (Guards47.isDefined(opts.sentry.config)) {
1510
- const { SentryLoggerFactory: SentryLoggerFactory2 } = await Promise.resolve().then(() => (init_sentry_logger_factory(), sentry_logger_factory_exports));
1511
- loggerDependencies.push(new SentryLoggerFactory2().create(opts));
1512
- }
1513
- if (Guards47.isDefined(opts.pino.config)) {
1514
- const { PinoLoggerFactory: PinoLoggerFactory2 } = await Promise.resolve().then(() => (init_pino_logger_factory(), pino_logger_factory_exports));
1515
- loggerDependencies.push(new PinoLoggerFactory2().create(opts));
1516
- }
1517
- if (!Guards47.isNullOrEmpty(opts.customLoggers)) {
1518
- const customLoggers = opts.customLoggers;
1519
- customLoggers.forEach((fn) => {
1520
- if (Guards47.isDefined(fn)) loggerDependencies.push(fn(container));
1521
- });
1522
- }
1523
- }
1524
- const { BaseLogger } = await import("@xeno-js/shared");
1525
- container.addSingleton(TOKENS5.LOGGER, (c) => {
1526
- const context = c.resolve(TOKENS5.CONTEXT_ACCESSOR);
1527
- return new BaseLogger(context, opts?.level ?? LOG_LEVEL7.DEBUG, loggerDependencies);
1528
- });
1529
- }
1530
- });
1531
- }
1532
- });
1533
-
1534
- // src/infrastructure/cache/inmemory.cache.ts
1535
- var inmemory_cache_exports = {};
1536
- __export(inmemory_cache_exports, {
1537
- InMemoryCacheExtended: () => InMemoryCacheExtended
1538
- });
1539
- import { Guards as Guards19, InMemoryCache } from "@xeno-js/shared";
1540
- var InMemoryCacheExtended;
1541
- var init_inmemory_cache = __esm({
1542
- "src/infrastructure/cache/inmemory.cache.ts"() {
1543
- "use strict";
1544
- InMemoryCacheExtended = class extends InMemoryCache {
1545
- async increment(key, ttlSeconds) {
1546
- const current = await this.get(key) ?? 0;
1547
- const next = Number(current) + 1;
1548
- const ttl = Guards19.isDefined(ttlSeconds) ? Number(ttlSeconds) : 60;
1549
- await this.set(key, next, ttl);
1550
- return next;
1551
- }
1552
- };
1553
- }
1554
- });
1555
-
1556
- // src/infrastructure/cache/redis.cache.ts
1557
- import { Guards as Guards20, StringHelper } from "@xeno-js/shared";
1558
- var RedisCache;
1559
- var init_redis_cache = __esm({
1560
- "src/infrastructure/cache/redis.cache.ts"() {
1561
- "use strict";
1562
- RedisCache = class {
1563
- /**
1564
- * @description Constructs a new instance of the RedisCache class, which takes an instance of the Redis client as a parameter. This client is used to perform caching operations such as setting, getting, and removing values from the Redis database. The constructor initializes the RedisCache with the provided Redis client, allowing it to interact with the Redis server for all caching operations defined in the ICache interface.
1565
- * @param _redisClient An instance of the Redis client from the ioredis library, used to perform caching operations in the Redis database.
1566
-
1567
- *
1568
- * @author Xeno
1569
- * @version 1.0.0
1570
- * @since 2025-09-30
1571
- * @link https://github.com/xeno-js/xeno-js
1572
- */
1573
- constructor(_redisClient) {
1574
- this._redisClient = _redisClient;
1575
- }
1576
- _redisClient;
1577
- async increment(key, ttlSeconds) {
1578
- const multi = this._redisClient.multi();
1579
- multi.incr(key);
1580
- multi.expire(key, ttlSeconds ?? 60);
1581
- const results = await multi.exec();
1582
- return results?.[0]?.[1] ?? 1;
1583
- }
1584
- async get(key) {
1585
- const value = await this._redisClient.get(key);
1586
- if (!Guards20.isDefined(value)) {
1587
- return void 0;
1588
- }
1589
- return JSON.parse(value);
1590
- }
1591
- async set(key, value, ttl) {
1592
- const stringValue = StringHelper.safeStringify(value);
1593
- const ttlOption = Guards20.isDefined(ttl) ? ttl : 86400;
1594
- await this._redisClient.set(key, stringValue, "EX", ttlOption);
1595
- }
1596
- async setIfAbsent(key, value, ttl) {
1597
- const stringValue = StringHelper.safeStringify(value);
1598
- const ttlOption = Guards20.isDefined(ttl) ? ttl : 300;
1599
- const result = await this._redisClient.set(key, stringValue, "EX", ttlOption, "NX");
1600
- return result === "OK";
1601
- }
1602
- async remove(key) {
1603
- await this._redisClient.del(key);
1604
- }
1605
- async has(key) {
1606
- const exists = await this._redisClient.exists(key);
1607
- return exists === 1;
1608
- }
1609
- async clear() {
1610
- await this._redisClient.flushdb();
1611
- }
1612
- };
1613
- }
1614
- });
1615
-
1616
- // src/infrastructure/factories/redis-cache.factory.ts
1617
- var redis_cache_factory_exports = {};
1618
- __export(redis_cache_factory_exports, {
1619
- RedisCacheFactory: () => RedisCacheFactory
1620
- });
1621
- import { Guards as Guards21 } from "@xeno-js/shared";
1622
- import { Redis } from "ioredis";
1623
- var RedisCacheFactory;
1624
- var init_redis_cache_factory = __esm({
1625
- "src/infrastructure/factories/redis-cache.factory.ts"() {
1626
- "use strict";
1627
- init_redis_cache();
1628
- RedisCacheFactory = class {
1629
- create(config) {
1630
- const host = config?.host ?? "localhost";
1631
- const port = config?.port ?? 6379;
1632
- const password = config?.password;
1633
- const username = config?.username;
1634
- const useTls = config?.tls ?? false;
1635
- const maxRetries = config?.maxRetriesPerRequest ?? 3;
1636
- const redisOptions = {
1637
- host,
1638
- port,
1639
- maxRetriesPerRequest: maxRetries,
1640
- // Strategia di riconnessione esponenziale per garantire resilienza
1641
- retryStrategy(times) {
1642
- const delay = Math.min(times * 50, 2e3);
1643
- return delay;
1644
- }
1645
- };
1646
- if (Guards21.isDefined(password)) {
1647
- redisOptions.password = password;
1648
- }
1649
- if (Guards21.isDefined(username)) {
1650
- redisOptions.username = username;
1651
- }
1652
- if (useTls) {
1653
- redisOptions.tls = {};
1654
- }
1655
- const nativeRedisInstance = new Redis(redisOptions);
1656
- nativeRedisInstance.on("error", (err) => {
1657
- console.error("\u274C [Redis Error]:", err.message);
1418
+ ContextModule = class {
1419
+ async configure(container) {
1420
+ const { TOKENS: TOKENS5 } = await import("@xeno-js/shared");
1421
+ const { ServiceScopeFactory: ServiceScopeFactory2 } = await Promise.resolve().then(() => (init_service_scope_factory(), service_scope_factory_exports));
1422
+ const { NodeRequestContextFactory: NodeRequestContextFactory2 } = await Promise.resolve().then(() => (init_request_context_factory(), request_context_factory_exports));
1423
+ const requestContext = new NodeRequestContextFactory2(
1424
+ new ServiceScopeFactory2(container)
1425
+ ).create();
1426
+ container.addSingleton(TOKENS5.REQUEST_CONTEXT, () => requestContext);
1427
+ container.addSingleton(TOKENS5.CONTEXT_ACCESSOR, () => requestContext);
1428
+ container.addSingleton(TOKENS5.IDENTITY_ACCESSOR, () => requestContext);
1429
+ container.addSingleton(TOKENS5.SERVICE_SCOPE_ACCESSOR, () => requestContext);
1430
+ container.addSingleton(TOKENS5.NETWORK_CONTEXT_ACCESSOR, () => requestContext);
1431
+ const { UserContextFactory: UserContextFactory2 } = await Promise.resolve().then(() => (init_user_context_factory(), user_context_factory_exports));
1432
+ container.addSingleton("USER_CONTEXT_FACTORY", () => {
1433
+ return new UserContextFactory2(requestContext);
1658
1434
  });
1659
- return new RedisCache(nativeRedisInstance);
1660
1435
  }
1661
1436
  };
1662
1437
  }
1663
1438
  });
1664
1439
 
1665
- // src/infrastructure/modules/utils/cache.utils.ts
1666
- var cache_utils_exports = {};
1667
- __export(cache_utils_exports, {
1668
- CacheUtils: () => CacheUtils
1669
- });
1670
- var CacheUtils;
1671
- var init_cache_utils = __esm({
1672
- "src/infrastructure/modules/utils/cache.utils.ts"() {
1673
- "use strict";
1674
- CacheUtils = Object.freeze({
1675
- /**
1676
- * @description Checks if the provided cache configuration requires any cache strategies.
1677
- * @param container The service container to which the cache strategies will be added.
1678
- * @param opts The cache configuration options.
1679
- * @returns True if any cache strategies are required, false otherwise.
1680
- *
1681
- * @author Xeno
1682
- * @version 1.0.0
1683
- * @since 2025-09-30
1684
- * @link https://github.com/xeno-js/xeno-js
1685
- */
1686
- async addCache(container, opts) {
1687
- const { Guards: Guards47, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
1688
- if (!opts.inMemory && !Guards47.isDefined(opts.redis)) {
1689
- throw new Error(
1690
- "No cache strategies are configured. Please provide at least one cache strategy."
1691
- );
1692
- }
1693
- const { CacheKeyBuilder } = await import("@xeno-js/shared");
1694
- container.addSingleton(
1695
- TOKENS5.CACHE_KEY_BUILDER,
1696
- (c) => new CacheKeyBuilder(c.resolve(TOKENS5.IDENTITY_ACCESSOR))
1697
- );
1698
- if (opts.inMemory || !Guards47.isDefined(opts.redis)) {
1699
- const { InMemoryCacheExtended: InMemoryCacheExtended2 } = await Promise.resolve().then(() => (init_inmemory_cache(), inmemory_cache_exports));
1700
- container.addSingleton(TOKENS5.CACHE, () => new InMemoryCacheExtended2());
1701
- return;
1702
- }
1703
- if (Guards47.isDefined(opts.redis)) {
1704
- const { RedisCacheFactory: RedisCacheFactory2 } = await Promise.resolve().then(() => (init_redis_cache_factory(), redis_cache_factory_exports));
1705
- container.addSingleton(TOKENS5.CACHE, () => {
1706
- const config = opts.redis;
1707
- return new RedisCacheFactory2().create(config);
1708
- });
1709
- }
1710
- }
1711
- });
1712
- }
1713
- });
1714
-
1715
1440
  // src/infrastructure/services/allow_methods/allow-method.service.ts
1716
- import { Guards as Guards22 } from "@xeno-js/shared";
1441
+ import { Guards as Guards17 } from "@xeno-js/shared";
1717
1442
  var AllowMethodRegistry;
1718
1443
  var init_allow_method_service = __esm({
1719
1444
  "src/infrastructure/services/allow_methods/allow-method.service.ts"() {
@@ -1733,7 +1458,7 @@ var init_allow_method_service = __esm({
1733
1458
  check(path, method) {
1734
1459
  const cleanPath = this.normalizePath(path.split("?")[0].split("#")[0]);
1735
1460
  const staticMethods = this._staticRoutes.get(cleanPath);
1736
- if (Guards22.isDefined(staticMethods)) return staticMethods.includes(method);
1461
+ if (Guards17.isDefined(staticMethods)) return staticMethods.includes(method);
1737
1462
  for (const route of this._dynamicRoutes) {
1738
1463
  if (route.pattern.test(cleanPath)) return route.methods.includes(method);
1739
1464
  }
@@ -1742,11 +1467,11 @@ var init_allow_method_service = __esm({
1742
1467
  getMethods(path) {
1743
1468
  const cleanPath = this.normalizePath(path.split("?")[0].split("#")[0]);
1744
1469
  const methods = this.findMethods(cleanPath);
1745
- return Guards22.isDefined(methods) ? methods.join(", ").toUpperCase() : "";
1470
+ return Guards17.isDefined(methods) ? methods.join(", ").toUpperCase() : "";
1746
1471
  }
1747
1472
  findMethods(cleanPath) {
1748
1473
  const staticMethods = this._staticRoutes.get(cleanPath);
1749
- if (Guards22.isDefined(staticMethods)) return staticMethods;
1474
+ if (Guards17.isDefined(staticMethods)) return staticMethods;
1750
1475
  for (const route of this._dynamicRoutes) if (route.pattern.test(cleanPath)) return route.methods;
1751
1476
  return void 0;
1752
1477
  }
@@ -1781,7 +1506,7 @@ var init_allow_methods = __esm({
1781
1506
  });
1782
1507
 
1783
1508
  // src/infrastructure/services/allow_origins/allow-origin.http.ts
1784
- import { Guards as Guards23 } from "@xeno-js/shared";
1509
+ import { Guards as Guards18 } from "@xeno-js/shared";
1785
1510
  var AllowOrigin;
1786
1511
  var init_allow_origin_http = __esm({
1787
1512
  "src/infrastructure/services/allow_origins/allow-origin.http.ts"() {
@@ -1792,7 +1517,7 @@ var init_allow_origin_http = __esm({
1792
1517
  }
1793
1518
  _list;
1794
1519
  isAllowed(origin) {
1795
- if (Guards23.isNullOrEmpty(origin)) return true;
1520
+ if (Guards18.isNullOrEmpty(origin)) return true;
1796
1521
  const cleanOrigin = origin.trim().toLowerCase();
1797
1522
  for (const pattern of this._list) {
1798
1523
  const cleanPattern = pattern.trim().toLowerCase();
@@ -1802,7 +1527,7 @@ var init_allow_origin_http = __esm({
1802
1527
  const domainSuffix = cleanPattern.substring(1);
1803
1528
  if (cleanOrigin.endsWith(domainSuffix)) {
1804
1529
  const prefix = cleanOrigin.slice(0, cleanOrigin.length - domainSuffix.length);
1805
- if (!Guards23.isNullOrEmpty(prefix) && !prefix.includes(".")) return true;
1530
+ if (!Guards18.isNullOrEmpty(prefix) && !prefix.includes(".")) return true;
1806
1531
  }
1807
1532
  }
1808
1533
  }
@@ -1849,7 +1574,7 @@ var init_concurrency = __esm({
1849
1574
  });
1850
1575
 
1851
1576
  // src/infrastructure/services/cookies/cookies.service.ts
1852
- import { Guards as Guards24 } from "@xeno-js/shared";
1577
+ import { Guards as Guards19 } from "@xeno-js/shared";
1853
1578
  var CookieHandler;
1854
1579
  var init_cookies_service = __esm({
1855
1580
  "src/infrastructure/services/cookies/cookies.service.ts"() {
@@ -1866,7 +1591,7 @@ var init_cookies_service = __esm({
1866
1591
  getAll() {
1867
1592
  const network = this.contextAccessor.getNetworkContext();
1868
1593
  const req = network?.transport?.req;
1869
- if (!Guards24.isDefined(req) || Guards24.isNullOrEmpty(req.headers.get("cookie"))) return [];
1594
+ if (!Guards19.isDefined(req) || Guards19.isNullOrEmpty(req.headers.get("cookie"))) return [];
1870
1595
  return req.headers.get("cookie")?.split(";").map((cookie) => {
1871
1596
  const [name, ...rest] = cookie.split("=");
1872
1597
  return { name: name.trim(), value: rest.join("=") };
@@ -1875,7 +1600,7 @@ var init_cookies_service = __esm({
1875
1600
  setAll(cookies) {
1876
1601
  const network = this.contextAccessor.getNetworkContext();
1877
1602
  const res = network?.transport?.res;
1878
- if (!Guards24.isDefined(res)) return;
1603
+ if (!Guards19.isDefined(res)) return;
1879
1604
  const serializedCookies = cookies.map((c) => this.serialize(c));
1880
1605
  const existingSetCookie = res.headers.getSetCookie();
1881
1606
  res.headers.delete("Set-Cookie");
@@ -1896,9 +1621,9 @@ var init_cookies_service = __esm({
1896
1621
  };
1897
1622
  const opts = { ...defaultOptions, ...cookie.options ?? {} };
1898
1623
  str += `; Path=${opts.path}`;
1899
- if (Guards24.isDefined(opts.maxAge)) str += `; Max-Age=${opts.maxAge}`;
1900
- if (Guards24.isDefined(opts.domain)) str += `; Domain=${opts.domain}`;
1901
- if (Guards24.isDefined(opts.sameSite)) str += `; SameSite=${opts.sameSite}`;
1624
+ if (Guards19.isDefined(opts.maxAge)) str += `; Max-Age=${opts.maxAge}`;
1625
+ if (Guards19.isDefined(opts.domain)) str += `; Domain=${opts.domain}`;
1626
+ if (Guards19.isDefined(opts.sameSite)) str += `; SameSite=${opts.sameSite}`;
1902
1627
  if (opts.secure) str += `; Secure`;
1903
1628
  if (opts.httpOnly) str += `; HttpOnly`;
1904
1629
  return str;
@@ -1963,7 +1688,7 @@ var init_crypto = __esm({
1963
1688
  });
1964
1689
 
1965
1690
  // src/infrastructure/services/csrf/csrf-token.service.ts
1966
- import { Guards as Guards25 } from "@xeno-js/shared";
1691
+ import { Guards as Guards20 } from "@xeno-js/shared";
1967
1692
  var CsrfTokenService;
1968
1693
  var init_csrf_token_service = __esm({
1969
1694
  "src/infrastructure/services/csrf/csrf-token.service.ts"() {
@@ -1986,7 +1711,7 @@ var init_csrf_token_service = __esm({
1986
1711
  if (separatorIndex <= 0) return false;
1987
1712
  const nonce = token.slice(0, separatorIndex);
1988
1713
  const signature = token.slice(separatorIndex + 1);
1989
- if (Guards25.isNullOrEmpty(nonce) || Guards25.isNullOrEmpty(signature)) return false;
1714
+ if (Guards20.isNullOrEmpty(nonce) || Guards20.isNullOrEmpty(signature)) return false;
1990
1715
  const expected = await this._cryptoService.hmacSha256(this._secret, `${subject}.${nonce}`);
1991
1716
  const encoder = new TextEncoder();
1992
1717
  const actualBuffer = encoder.encode(signature);
@@ -2007,7 +1732,7 @@ var init_csrf = __esm({
2007
1732
  });
2008
1733
 
2009
1734
  // src/infrastructure/services/extractors/extract-bearer.extractor.ts
2010
- import { Guards as Guards26 } from "@xeno-js/shared";
1735
+ import { Guards as Guards21 } from "@xeno-js/shared";
2011
1736
  var BearerTokenExtractor;
2012
1737
  var init_extract_bearer_extractor = __esm({
2013
1738
  "src/infrastructure/services/extractors/extract-bearer.extractor.ts"() {
@@ -2019,14 +1744,14 @@ var init_extract_bearer_extractor = __esm({
2019
1744
  _cookiePrefix;
2020
1745
  extract(headers) {
2021
1746
  const authHeader = headers.get("Authorization");
2022
- if (Guards26.isDefined(authHeader) && authHeader.toLowerCase().startsWith("bearer ")) {
1747
+ if (Guards21.isDefined(authHeader) && authHeader.toLowerCase().startsWith("bearer ")) {
2023
1748
  return authHeader.substring(7);
2024
1749
  }
2025
1750
  const cookieHeader = headers.get("cookie");
2026
- if (Guards26.isDefined(cookieHeader)) {
1751
+ if (Guards21.isDefined(cookieHeader)) {
2027
1752
  const regex = new RegExp(`${this._cookiePrefix}=([^;]+)`);
2028
1753
  const match = regex.exec(cookieHeader);
2029
- if (!Guards26.isNullOrEmpty(match) && Guards26.isDefined(match[1])) {
1754
+ if (!Guards21.isNullOrEmpty(match) && Guards21.isDefined(match[1])) {
2030
1755
  return match[1].trim();
2031
1756
  }
2032
1757
  }
@@ -2037,7 +1762,7 @@ var init_extract_bearer_extractor = __esm({
2037
1762
  });
2038
1763
 
2039
1764
  // src/infrastructure/services/extractors/extract-ssr-bearer.extractor.ts
2040
- import { Guards as Guards27, StringHelper as StringHelper2 } from "@xeno-js/shared";
1765
+ import { Guards as Guards22, StringHelper } from "@xeno-js/shared";
2041
1766
  var SupabaseSsrTokenExtractor;
2042
1767
  var init_extract_ssr_bearer_extractor = __esm({
2043
1768
  "src/infrastructure/services/extractors/extract-ssr-bearer.extractor.ts"() {
@@ -2045,36 +1770,36 @@ var init_extract_ssr_bearer_extractor = __esm({
2045
1770
  SupabaseSsrTokenExtractor = class {
2046
1771
  extract(headers) {
2047
1772
  const authHeader = headers.get("authorization");
2048
- if (Guards27.isDefined(authHeader) && authHeader.toLowerCase().startsWith("bearer ")) {
1773
+ if (Guards22.isDefined(authHeader) && authHeader.toLowerCase().startsWith("bearer ")) {
2049
1774
  return authHeader.substring(7);
2050
1775
  }
2051
1776
  const cookieHeader = headers.get("cookie");
2052
- if (Guards27.isNullOrEmpty(cookieHeader)) return void 0;
1777
+ if (Guards22.isNullOrEmpty(cookieHeader)) return void 0;
2053
1778
  const cookies = cookieHeader.split(";").map((c) => c.trim());
2054
1779
  const tokenChunks = {};
2055
1780
  let unchunkedToken;
2056
1781
  for (const cookie of cookies) {
2057
1782
  const [name, ...rest] = cookie.split("=");
2058
- if (!Guards27.isDefined(name) || Guards27.isNullOrEmpty(rest)) continue;
1783
+ if (!Guards22.isDefined(name) || Guards22.isNullOrEmpty(rest)) continue;
2059
1784
  const value = decodeURIComponent(rest.join("="));
2060
- if (Guards27.isDefined(/^sb-[a-z0-9]+-auth-token$/.exec(name))) {
1785
+ if (Guards22.isDefined(/^sb-[a-z0-9]+-auth-token$/.exec(name))) {
2061
1786
  unchunkedToken = value;
2062
1787
  } else {
2063
1788
  const match = /^sb-[a-z0-9]+-auth-token\.(\d+)$/.exec(name);
2064
- if (Guards27.isDefined(match)) tokenChunks[parseInt(match[1], 10)] = value;
1789
+ if (Guards22.isDefined(match)) tokenChunks[parseInt(match[1], 10)] = value;
2065
1790
  }
2066
1791
  }
2067
1792
  let fullTokenString = unchunkedToken;
2068
- if (!Guards27.isDefined(fullTokenString) && Object.keys(tokenChunks).length > 0) {
1793
+ if (!Guards22.isDefined(fullTokenString) && Object.keys(tokenChunks).length > 0) {
2069
1794
  const indices = Object.keys(tokenChunks).map(Number).sort((a, b) => a - b);
2070
1795
  fullTokenString = indices.map((i) => tokenChunks[i]).join("");
2071
1796
  }
2072
- if (Guards27.isNullOrEmpty(fullTokenString)) return void 0;
1797
+ if (Guards22.isNullOrEmpty(fullTokenString)) return void 0;
2073
1798
  try {
2074
- const parsed = StringHelper2.safeParse(fullTokenString);
2075
- if (Guards27.isDefined(parsed) && Guards27.isObject(parsed) && "access_token" in parsed) {
1799
+ const parsed = StringHelper.safeParse(fullTokenString);
1800
+ if (Guards22.isDefined(parsed) && Guards22.isObject(parsed) && "access_token" in parsed) {
2076
1801
  const accessToken = parsed["access_token"];
2077
- if (Guards27.isString(accessToken)) return accessToken;
1802
+ if (Guards22.isString(accessToken)) return accessToken;
2078
1803
  }
2079
1804
  } catch {
2080
1805
  return void 0;
@@ -2085,14 +1810,14 @@ var init_extract_ssr_bearer_extractor = __esm({
2085
1810
  });
2086
1811
 
2087
1812
  // src/infrastructure/services/extractors/http-cookie.extractor.ts
2088
- import { Guards as Guards28 } from "@xeno-js/shared";
1813
+ import { Guards as Guards23 } from "@xeno-js/shared";
2089
1814
  var HttpCookieExtractor;
2090
1815
  var init_http_cookie_extractor = __esm({
2091
1816
  "src/infrastructure/services/extractors/http-cookie.extractor.ts"() {
2092
1817
  "use strict";
2093
1818
  HttpCookieExtractor = class {
2094
1819
  extract(cookie) {
2095
- if (!Guards28.isDefined(cookie.header)) return void 0;
1820
+ if (!Guards23.isDefined(cookie.header)) return void 0;
2096
1821
  for (const rawCookie of cookie.header.split(";")) {
2097
1822
  const separatorIndex = rawCookie.indexOf("=");
2098
1823
  if (separatorIndex <= 0) continue;
@@ -2112,7 +1837,7 @@ var init_http_cookie_extractor = __esm({
2112
1837
  });
2113
1838
 
2114
1839
  // src/infrastructure/services/extractors/http-header.extractor.ts
2115
- import { Guards as Guards29, GuidHelper as GuidHelper4, HttpHelper, MathHelper } from "@xeno-js/shared";
1840
+ import { Guards as Guards24, GuidHelper as GuidHelper4, HttpHelper, MathHelper } from "@xeno-js/shared";
2116
1841
  var HttpHeaderExtractor;
2117
1842
  var init_http_header_extractor = __esm({
2118
1843
  "src/infrastructure/services/extractors/http-header.extractor.ts"() {
@@ -2180,10 +1905,10 @@ var init_http_header_extractor = __esm({
2180
1905
  referer: cleanReferer,
2181
1906
  sequence: {
2182
1907
  sequenceId,
2183
- position: Guards29.isDefined(position) ? MathHelper.toNumber(position) : void 0,
2184
- size: Guards29.isDefined(size) ? MathHelper.toNumber(size) : void 0
1908
+ position: Guards24.isDefined(position) ? MathHelper.toNumber(position) : void 0,
1909
+ size: Guards24.isDefined(size) ? MathHelper.toNumber(size) : void 0
2185
1910
  },
2186
- expiration: Guards29.isDefined(expiration) ? MathHelper.toNumber(expiration) : void 0
1911
+ expiration: Guards24.isDefined(expiration) ? MathHelper.toNumber(expiration) : void 0
2187
1912
  };
2188
1913
  return metadata;
2189
1914
  }
@@ -2230,7 +1955,7 @@ var init_resiliences = __esm({
2230
1955
  });
2231
1956
 
2232
1957
  // src/infrastructure/services/resolver/utils/socket.utils.ts
2233
- import { Guards as Guards30 } from "@xeno-js/shared";
1958
+ import { Guards as Guards25 } from "@xeno-js/shared";
2234
1959
  var SocketIpExtractor;
2235
1960
  var init_socket_utils = __esm({
2236
1961
  "src/infrastructure/services/resolver/utils/socket.utils.ts"() {
@@ -2242,7 +1967,7 @@ var init_socket_utils = __esm({
2242
1967
  * @returns The IP address of the remote socket, or undefined if not available.
2243
1968
  */
2244
1969
  extract(req) {
2245
- if (Guards30.isDefined(req) && Guards30.isObject(req)) {
1970
+ if (Guards25.isDefined(req) && Guards25.isObject(req)) {
2246
1971
  const candidate = req;
2247
1972
  return candidate.socket?.remoteAddress ?? candidate.connection?.remoteAddress;
2248
1973
  }
@@ -2261,7 +1986,7 @@ var init_utils = __esm({
2261
1986
  });
2262
1987
 
2263
1988
  // src/infrastructure/services/resolver/client-ip.resolver.ts
2264
- import { Guards as Guards31 } from "@xeno-js/shared";
1989
+ import { Guards as Guards26 } from "@xeno-js/shared";
2265
1990
  var ClientIpResolver;
2266
1991
  var init_client_ip_resolver = __esm({
2267
1992
  "src/infrastructure/services/resolver/client-ip.resolver.ts"() {
@@ -2274,11 +1999,11 @@ var init_client_ip_resolver = __esm({
2274
1999
  _trustedProxies;
2275
2000
  resolve(req, clientIp) {
2276
2001
  const socketIp = SocketIpExtractor.extract(req);
2277
- if (!Guards31.isDefined(socketIp))
2278
- return !Guards31.isNullOrEmpty(clientIp) ? clientIp.split(",")[0].trim() : void 0;
2002
+ if (!Guards26.isDefined(socketIp))
2003
+ return !Guards26.isNullOrEmpty(clientIp) ? clientIp.split(",")[0].trim() : void 0;
2279
2004
  const isTrustedProxy = this._trustedProxies.includes(socketIp);
2280
2005
  if (!isTrustedProxy) return socketIp;
2281
- if (Guards31.isDefined(clientIp)) return clientIp.split(",")[0].trim();
2006
+ if (Guards26.isDefined(clientIp)) return clientIp.split(",")[0].trim();
2282
2007
  return socketIp;
2283
2008
  }
2284
2009
  };
@@ -2383,7 +2108,7 @@ var init_axios_factory = __esm({
2383
2108
  });
2384
2109
 
2385
2110
  // src/infrastructure/factories/cockatiel-resilience.factory.ts
2386
- import { AppError as AppError13, Guards as Guards32, RESILIENCE_DEFAULTS } from "@xeno-js/shared";
2111
+ import { AppError as AppError13, Guards as Guards27, RESILIENCE_DEFAULTS } from "@xeno-js/shared";
2387
2112
  import {
2388
2113
  bulkhead,
2389
2114
  circuitBreaker,
@@ -2460,13 +2185,13 @@ var init_cockatiel_resilience_factory = __esm({
2460
2185
  return new ServiceResilience(wrap(bulkheadPolicy, circuitBreakerPolicy, retryPolicy));
2461
2186
  }
2462
2187
  isTransientError(error) {
2463
- if (!Guards32.isDefined(error) || !Guards32.isObject(error)) return false;
2188
+ if (!Guards27.isDefined(error) || !Guards27.isObject(error)) return false;
2464
2189
  let status;
2465
2190
  let isNetworkError = false;
2466
2191
  if (error instanceof AppError13) {
2467
2192
  status = error.status;
2468
2193
  const cause = error.cause;
2469
- if (Guards32.isDefined(cause) && Guards32.isString(cause.code)) {
2194
+ if (Guards27.isDefined(cause) && Guards27.isString(cause.code)) {
2470
2195
  isNetworkError = [
2471
2196
  "ECONNABORTED",
2472
2197
  "ECONNRESET",
@@ -2478,7 +2203,7 @@ var init_cockatiel_resilience_factory = __esm({
2478
2203
  } else {
2479
2204
  const err = error;
2480
2205
  status = err.status;
2481
- if (Guards32.isString(err.code)) {
2206
+ if (Guards27.isString(err.code)) {
2482
2207
  isNetworkError = [
2483
2208
  "ECONNABORTED",
2484
2209
  "ECONNRESET",
@@ -2489,7 +2214,7 @@ var init_cockatiel_resilience_factory = __esm({
2489
2214
  }
2490
2215
  }
2491
2216
  if (isNetworkError) return true;
2492
- if (Guards32.isDefined(status)) return status === 408 || status >= 500 && status < 600;
2217
+ if (Guards27.isDefined(status)) return status === 408 || status >= 500 && status < 600;
2493
2218
  return false;
2494
2219
  }
2495
2220
  isTransientAndIdempotent(error) {
@@ -2497,22 +2222,22 @@ var init_cockatiel_resilience_factory = __esm({
2497
2222
  let method;
2498
2223
  if (error instanceof AppError13) {
2499
2224
  const cause = error.cause;
2500
- if (Guards32.isDefined(cause) && Guards32.isDefined(cause.config) && Guards32.isString(cause.config.method)) {
2225
+ if (Guards27.isDefined(cause) && Guards27.isDefined(cause.config) && Guards27.isString(cause.config.method)) {
2501
2226
  method = cause.config.method.toUpperCase();
2502
2227
  }
2503
2228
  } else {
2504
2229
  const err = error;
2505
- if (Guards32.isDefined(err.config) && Guards32.isString(err.config.method)) {
2230
+ if (Guards27.isDefined(err.config) && Guards27.isString(err.config.method)) {
2506
2231
  method = err.config.method.toUpperCase();
2507
2232
  }
2508
2233
  }
2509
- if (Guards32.isNullOrEmpty(method)) return false;
2234
+ if (Guards27.isNullOrEmpty(method)) return false;
2510
2235
  const idempotentMethods = ["GET", "PUT", "DELETE", "HEAD", "OPTIONS"];
2511
2236
  return idempotentMethods.includes(method);
2512
2237
  }
2513
2238
  checkConfigValue(value, defaultValue, message) {
2514
- if (Guards32.isDefined(value)) {
2515
- Guards32.throwIfNegative(value, message);
2239
+ if (Guards27.isDefined(value)) {
2240
+ Guards27.throwIfNegative(value, message);
2516
2241
  return value;
2517
2242
  }
2518
2243
  return defaultValue;
@@ -2543,111 +2268,284 @@ var init_db_client_factory = __esm({
2543
2268
  }
2544
2269
  });
2545
2270
 
2546
- // src/infrastructure/context/request-context.ts
2547
- import { Guards as Guards33 } from "@xeno-js/shared";
2548
- var NodeRequestContext;
2549
- var init_request_context = __esm({
2550
- "src/infrastructure/context/request-context.ts"() {
2271
+ // src/infrastructure/loggers/pino.logger.ts
2272
+ import { Guards as Guards28, LOG_LEVEL } from "@xeno-js/shared";
2273
+ var PinoLogger;
2274
+ var init_pino_logger = __esm({
2275
+ "src/infrastructure/loggers/pino.logger.ts"() {
2551
2276
  "use strict";
2552
- NodeRequestContext = class {
2277
+ PinoLogger = class {
2553
2278
  /**
2554
- * @description Constructs a new instance of the NodeRequestContext class, which requires an instance of AsyncLocalStorage to manage the request context. The AsyncLocalStorage instance is used to create and access the context for each request, allowing for the storage of identity information and other relevant data that needs to be accessible across asynchronous operations. This constructor initializes the NodeRequestContext with the provided AsyncLocalStorage, enabling it to implement the methods defined in the IRequestContext interface for managing request-specific context data.
2555
- * @param _storage An instance of AsyncLocalStorage that is used to manage the request context, allowing for the storage and retrieval of identity information and other relevant data across asynchronous operations.
2556
- * @param _factoryScope An instance of IFactory that is used to create a new IServiceScope for managing service dependencies during the execution of the request. This allows for proper scoping and disposal of services after the request is processed, ensuring that resources are managed efficiently and preventing memory leaks.
2557
- *
2279
+ * Constructs a new instance of the PinoTransport class, which takes an optional minimum log level and an optional instance of the Pino logger. If no logger instance is provided, it initializes a new Pino logger with default settings. The minimum log level determines the threshold for logging messages, where messages with a log level below the specified minimum will be ignored.
2280
+ * @param _logger The Pino logger instance used for logging messages.
2281
+ * @param _minLevel The minimum log level for logging messages. Messages with a log level below this threshold will not be logged. Default is LOG_LEVEL.DEBUG.
2282
+
2283
+ *
2558
2284
  * @author Xeno
2559
2285
  * @version 1.0.0
2560
2286
  * @since 2025-09-30
2561
- * @link https://github.com/xeno-js/xeno-js
2287
+ * @link https://github.com/xeno-js/xeno-js
2562
2288
  */
2563
- constructor(_storage, _factoryScope) {
2564
- this._storage = _storage;
2565
- this._factoryScope = _factoryScope;
2289
+ constructor(_logger, _minLevel = LOG_LEVEL.DEBUG) {
2290
+ this._logger = _logger;
2291
+ this._minLevel = _minLevel;
2566
2292
  }
2567
- _storage;
2568
- _factoryScope;
2569
- async runAsync(context, fn) {
2570
- const scope = this._factoryScope.create();
2571
- try {
2572
- return await this._storage.run({ context, scope }, fn);
2573
- } finally {
2574
- await scope.dispose();
2293
+ _logger;
2294
+ _minLevel;
2295
+ track(level, message, context, error = void 0) {
2296
+ if (level < this._minLevel) return;
2297
+ const payload = Guards28.isDefined(error) ? { ...context, error } : context;
2298
+ switch (level) {
2299
+ case LOG_LEVEL.ERROR:
2300
+ this._logger.error(payload ?? {}, message);
2301
+ break;
2302
+ case LOG_LEVEL.WARN:
2303
+ this._logger.warn(payload ?? {}, message);
2304
+ break;
2305
+ case LOG_LEVEL.DEBUG:
2306
+ this._logger.debug(payload ?? {}, message);
2307
+ break;
2308
+ default:
2309
+ this._logger.info(payload ?? {}, message);
2310
+ break;
2575
2311
  }
2576
2312
  }
2577
- updateIdentity(identity) {
2578
- const store = this._storage.getStore();
2579
- if (Guards33.isDefined(store) && Guards33.isDefined(store.context)) {
2580
- store.context = Object.freeze({
2581
- ...store.context,
2582
- identity: Object.freeze(identity)
2583
- });
2313
+ };
2314
+ }
2315
+ });
2316
+
2317
+ // src/infrastructure/factories/pino-logger.factory.ts
2318
+ var pino_logger_factory_exports = {};
2319
+ __export(pino_logger_factory_exports, {
2320
+ PinoLoggerFactory: () => PinoLoggerFactory
2321
+ });
2322
+ import { LOG_LEVEL as LOG_LEVEL2 } from "@xeno-js/shared";
2323
+ import pino from "pino";
2324
+ var PinoLoggerFactory;
2325
+ var init_pino_logger_factory = __esm({
2326
+ "src/infrastructure/factories/pino-logger.factory.ts"() {
2327
+ "use strict";
2328
+ init_pino_logger();
2329
+ PinoLoggerFactory = class {
2330
+ create(config) {
2331
+ const level = config.level ?? LOG_LEVEL2.DEBUG;
2332
+ const env = config.pino.config?.env ?? process.env.NODE_ENV ?? "development";
2333
+ const destinationType = config.pino.config?.destination ?? "stdout";
2334
+ const filePath = config.pino.config?.filePath ?? "logs/app.log";
2335
+ const prettyPrint = config.pino.config?.prettyPrint ?? env === "development";
2336
+ const options = {
2337
+ level: "trace",
2338
+ serializers: {
2339
+ err: pino.stdSerializers.err
2340
+ },
2341
+ timestamp: pino.stdTimeFunctions.isoTime,
2342
+ redact: {
2343
+ paths: ["password", "token", "secret", "authorization", "headers.authorization"],
2344
+ censor: "***"
2345
+ }
2346
+ };
2347
+ if (prettyPrint) {
2348
+ return new PinoLogger(
2349
+ pino({
2350
+ ...options,
2351
+ transport: {
2352
+ target: "pino-pretty",
2353
+ options: {
2354
+ colorize: true,
2355
+ ignore: "pid,hostname",
2356
+ translateTime: "SYS:standard"
2357
+ }
2358
+ }
2359
+ }),
2360
+ level
2361
+ );
2362
+ }
2363
+ if (destinationType === "file") {
2364
+ const destination = pino.destination({ dest: filePath, sync: false });
2365
+ return new PinoLogger(pino(options, destination), level);
2366
+ } else {
2367
+ const stream = pino.destination({ dest: 1, sync: false });
2368
+ return new PinoLogger(pino(options, stream), level);
2584
2369
  }
2585
2370
  }
2586
- getContext() {
2587
- const store = this._storage.getStore();
2588
- if (!Guards33.isDefined(store)) return void 0;
2589
- const context = store.context;
2590
- return Object.freeze(context);
2371
+ };
2372
+ }
2373
+ });
2374
+
2375
+ // src/infrastructure/cache/redis.cache.ts
2376
+ import { Guards as Guards29, StringHelper as StringHelper2 } from "@xeno-js/shared";
2377
+ var RedisCache;
2378
+ var init_redis_cache = __esm({
2379
+ "src/infrastructure/cache/redis.cache.ts"() {
2380
+ "use strict";
2381
+ RedisCache = class {
2382
+ /**
2383
+ * @description Constructs a new instance of the RedisCache class, which takes an instance of the Redis client as a parameter. This client is used to perform caching operations such as setting, getting, and removing values from the Redis database. The constructor initializes the RedisCache with the provided Redis client, allowing it to interact with the Redis server for all caching operations defined in the ICache interface.
2384
+ * @param _redisClient An instance of the Redis client from the ioredis library, used to perform caching operations in the Redis database.
2385
+
2386
+ *
2387
+ * @author Xeno
2388
+ * @version 1.0.0
2389
+ * @since 2025-09-30
2390
+ * @link https://github.com/xeno-js/xeno-js
2391
+ */
2392
+ constructor(_redisClient) {
2393
+ this._redisClient = _redisClient;
2591
2394
  }
2592
- getIdentity() {
2593
- const store = this._storage.getStore();
2594
- if (!Guards33.isDefined(store)) return void 0;
2595
- return Object.freeze(store.context?.identity);
2395
+ _redisClient;
2396
+ async increment(key, ttlSeconds) {
2397
+ const multi = this._redisClient.multi();
2398
+ multi.incr(key);
2399
+ multi.expire(key, ttlSeconds ?? 60);
2400
+ const results = await multi.exec();
2401
+ return results?.[0]?.[1] ?? 1;
2596
2402
  }
2597
- getScope() {
2598
- const store = this._storage.getStore();
2599
- if (!Guards33.isDefined(store)) return void 0;
2600
- return store.scope;
2403
+ async get(key) {
2404
+ const value = await this._redisClient.get(key);
2405
+ if (!Guards29.isDefined(value)) {
2406
+ return void 0;
2407
+ }
2408
+ return JSON.parse(value);
2601
2409
  }
2602
- getNetworkContext() {
2603
- const store = this._storage.getStore();
2604
- if (!Guards33.isDefined(store)) return void 0;
2605
- return Object.freeze(store.context?.network);
2410
+ async set(key, value, ttl) {
2411
+ const stringValue = StringHelper2.safeStringify(value);
2412
+ const ttlOption = Guards29.isDefined(ttl) ? ttl : 86400;
2413
+ await this._redisClient.set(key, stringValue, "EX", ttlOption);
2414
+ }
2415
+ async setIfAbsent(key, value, ttl) {
2416
+ const stringValue = StringHelper2.safeStringify(value);
2417
+ const ttlOption = Guards29.isDefined(ttl) ? ttl : 300;
2418
+ const result = await this._redisClient.set(key, stringValue, "EX", ttlOption, "NX");
2419
+ return result === "OK";
2420
+ }
2421
+ async remove(key) {
2422
+ await this._redisClient.del(key);
2423
+ }
2424
+ async has(key) {
2425
+ const exists = await this._redisClient.exists(key);
2426
+ return exists === 1;
2427
+ }
2428
+ async clear() {
2429
+ await this._redisClient.flushdb();
2606
2430
  }
2607
2431
  };
2608
2432
  }
2609
2433
  });
2610
2434
 
2611
- // src/infrastructure/factories/request-context.factory.ts
2612
- var request_context_factory_exports = {};
2613
- __export(request_context_factory_exports, {
2614
- NodeRequestContextFactory: () => NodeRequestContextFactory
2435
+ // src/infrastructure/factories/redis-cache.factory.ts
2436
+ var redis_cache_factory_exports = {};
2437
+ __export(redis_cache_factory_exports, {
2438
+ RedisCacheFactory: () => RedisCacheFactory
2615
2439
  });
2616
- import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
2617
- var NodeRequestContextFactory;
2618
- var init_request_context_factory = __esm({
2619
- "src/infrastructure/factories/request-context.factory.ts"() {
2440
+ import { Guards as Guards30 } from "@xeno-js/shared";
2441
+ import { Redis } from "ioredis";
2442
+ var RedisCacheFactory;
2443
+ var init_redis_cache_factory = __esm({
2444
+ "src/infrastructure/factories/redis-cache.factory.ts"() {
2620
2445
  "use strict";
2621
- init_request_context();
2622
- NodeRequestContextFactory = class {
2623
- constructor(_factoryScope) {
2624
- this._factoryScope = _factoryScope;
2446
+ init_redis_cache();
2447
+ RedisCacheFactory = class {
2448
+ create(config) {
2449
+ const host = config?.host ?? "localhost";
2450
+ const port = config?.port ?? 6379;
2451
+ const password = config?.password;
2452
+ const username = config?.username;
2453
+ const useTls = config?.tls ?? false;
2454
+ const maxRetries = config?.maxRetriesPerRequest ?? 3;
2455
+ const redisOptions = {
2456
+ host,
2457
+ port,
2458
+ maxRetriesPerRequest: maxRetries,
2459
+ // Strategia di riconnessione esponenziale per garantire resilienza
2460
+ retryStrategy(times) {
2461
+ const delay = Math.min(times * 50, 2e3);
2462
+ return delay;
2463
+ }
2464
+ };
2465
+ if (Guards30.isDefined(password)) {
2466
+ redisOptions.password = password;
2467
+ }
2468
+ if (Guards30.isDefined(username)) {
2469
+ redisOptions.username = username;
2470
+ }
2471
+ if (useTls) {
2472
+ redisOptions.tls = {};
2473
+ }
2474
+ const nativeRedisInstance = new Redis(redisOptions);
2475
+ nativeRedisInstance.on("error", (err) => {
2476
+ console.error("\u274C [Redis Error]:", err.message);
2477
+ });
2478
+ return new RedisCache(nativeRedisInstance);
2625
2479
  }
2626
- _factoryScope;
2627
- _store = new AsyncLocalStorage2();
2628
- create() {
2629
- return new NodeRequestContext(this._store, this._factoryScope);
2480
+ };
2481
+ }
2482
+ });
2483
+
2484
+ // src/infrastructure/loggers/sentry.logger.ts
2485
+ import { Guards as Guards31, LOG_LEVEL as LOG_LEVEL3 } from "@xeno-js/shared";
2486
+ var SentryLogger;
2487
+ var init_sentry_logger = __esm({
2488
+ "src/infrastructure/loggers/sentry.logger.ts"() {
2489
+ "use strict";
2490
+ SentryLogger = class {
2491
+ constructor(_client, _minLevel) {
2492
+ this._client = _client;
2493
+ this._minLevel = _minLevel;
2494
+ }
2495
+ _client;
2496
+ _minLevel;
2497
+ track(level, message, context = void 0, error = void 0) {
2498
+ if (level < this._minLevel) return;
2499
+ if (level === LOG_LEVEL3.ERROR || level === LOG_LEVEL3.WARN) {
2500
+ this._client.withScope((scope) => {
2501
+ if (Guards31.isDefined(context)) scope.setExtras(context);
2502
+ if (Guards31.isDefined(error)) {
2503
+ this._client.captureException(error);
2504
+ } else {
2505
+ this._client.captureMessage(message, "warning");
2506
+ }
2507
+ });
2508
+ }
2630
2509
  }
2631
2510
  };
2632
2511
  }
2633
2512
  });
2634
2513
 
2635
- // src/infrastructure/factories/service-scope.factory.ts
2636
- var service_scope_factory_exports = {};
2637
- __export(service_scope_factory_exports, {
2638
- ServiceScopeFactory: () => ServiceScopeFactory
2514
+ // src/infrastructure/factories/sentry-logger.factory.ts
2515
+ var sentry_logger_factory_exports = {};
2516
+ __export(sentry_logger_factory_exports, {
2517
+ SentryLoggerFactory: () => SentryLoggerFactory
2639
2518
  });
2640
- var ServiceScopeFactory;
2641
- var init_service_scope_factory = __esm({
2642
- "src/infrastructure/factories/service-scope.factory.ts"() {
2519
+ import * as Sentry from "@sentry/node";
2520
+ import { Guards as Guards32, LOG_LEVEL as LOG_LEVEL4 } from "@xeno-js/shared";
2521
+ var SentryLoggerFactory;
2522
+ var init_sentry_logger_factory = __esm({
2523
+ "src/infrastructure/factories/sentry-logger.factory.ts"() {
2643
2524
  "use strict";
2644
- ServiceScopeFactory = class {
2645
- constructor(_container) {
2646
- this._container = _container;
2647
- }
2648
- _container;
2649
- create() {
2650
- return this._container.createScope();
2525
+ init_sentry_logger();
2526
+ SentryLoggerFactory = class {
2527
+ create(config) {
2528
+ const level = config.level ?? LOG_LEVEL4.WARN;
2529
+ const sentryConfig = config.sentry?.config;
2530
+ const env = sentryConfig?.environment ?? process.env.NODE_ENV ?? "development";
2531
+ if (!Guards32.isDefined(sentryConfig))
2532
+ throw new Error("Sentry configuration is required when Sentry logging is enabled.");
2533
+ if (!Guards32.isDefined(sentryConfig.dsn))
2534
+ throw new Error("Sentry DSN is required when Sentry logging is enabled.");
2535
+ Sentry.init({
2536
+ dsn: sentryConfig.dsn,
2537
+ environment: env,
2538
+ tracesSampleRate: env === "production" ? 0.1 : 1,
2539
+ integrations: [Sentry.httpIntegration()],
2540
+ beforeSend(event, hint) {
2541
+ const error = hint.originalException;
2542
+ if (error instanceof Error && error.name === "ZodError") {
2543
+ return null;
2544
+ }
2545
+ return event;
2546
+ }
2547
+ });
2548
+ return new SentryLogger(Sentry, level);
2651
2549
  }
2652
2550
  };
2653
2551
  }
@@ -2676,7 +2574,7 @@ var init_sql_light_db_client_factory = __esm({
2676
2574
  // src/infrastructure/factories/supabase.factory.ts
2677
2575
  import { createServerClient } from "@supabase/ssr";
2678
2576
  import {
2679
- Guards as Guards34,
2577
+ Guards as Guards33,
2680
2578
  SupabaseAuthService,
2681
2579
  SupabaseClaimsMapper,
2682
2580
  SupabaseSessionMapper,
@@ -2702,7 +2600,7 @@ var init_supabase_factory = __esm({
2702
2600
  return new SupabaseAuthService(client, mapper, sessionMapper, config);
2703
2601
  }
2704
2602
  _getCookieSsr(ssrOpts, container, config) {
2705
- if (Guards34.isDefined(ssrOpts)) {
2603
+ if (Guards33.isDefined(ssrOpts)) {
2706
2604
  return ssrOpts(container);
2707
2605
  } else {
2708
2606
  return new CookieHandler(
@@ -2716,46 +2614,6 @@ var init_supabase_factory = __esm({
2716
2614
  }
2717
2615
  });
2718
2616
 
2719
- // src/infrastructure/factories/user-context.factory.ts
2720
- var user_context_factory_exports = {};
2721
- __export(user_context_factory_exports, {
2722
- UserContextFactory: () => UserContextFactory
2723
- });
2724
- import { Guards as Guards35 } from "@xeno-js/shared";
2725
- var UserContextFactory;
2726
- var init_user_context_factory = __esm({
2727
- "src/infrastructure/factories/user-context.factory.ts"() {
2728
- "use strict";
2729
- UserContextFactory = class {
2730
- /**
2731
- * @description Constructs an instance of UserContextFactory.
2732
- * @param _identityFactory - An instance of IIdentityAccessor that provides access to the current identity. This factory is used to retrieve the identity details when creating a UserContext instance.
2733
- *
2734
- * @author Xeno
2735
- * @version 1.0.0
2736
- * @since 2025-09-30
2737
- * @link https://github.com/xeno-js/xeno-js
2738
- */
2739
- constructor(_identityFactory) {
2740
- this._identityFactory = _identityFactory;
2741
- }
2742
- _identityFactory;
2743
- create() {
2744
- const output = {
2745
- userId: void 0,
2746
- tenantId: void 0
2747
- };
2748
- const identity = this._identityFactory.getIdentity();
2749
- if (Guards35.isDefined(identity)) {
2750
- output.userId = identity.userId;
2751
- output.tenantId = identity.tenantId;
2752
- }
2753
- return output;
2754
- }
2755
- };
2756
- }
2757
- });
2758
-
2759
2617
  // src/infrastructure/factories/zod-validator.factory.ts
2760
2618
  import { ZodValidatorService } from "@xeno-js/shared";
2761
2619
  var ZodValidatorFactory;
@@ -2829,99 +2687,351 @@ var init_auth_utils = __esm({
2829
2687
  * @author Xeno
2830
2688
  * @version 1.0.0
2831
2689
  * @since 2025-09-30
2832
- * @link https://github.com/xeno-js/xeno-js
2690
+ * @link https://github.com/xeno-js/xeno-js
2691
+ */
2692
+ async addAuthZ(container, opts) {
2693
+ const { TOKENS: TOKENS5 } = await import("@xeno-js/shared");
2694
+ const strategies = [];
2695
+ const { Guards: Guards49 } = await import("@xeno-js/shared");
2696
+ if (Guards49.isDefined(opts.policies)) {
2697
+ const { PolicyRegistry: PolicyRegistry2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2698
+ const policyRegistry = opts.policies;
2699
+ const registryInstance = new PolicyRegistry2();
2700
+ const ctxAccessor = container.resolve(TOKENS5.CONTEXT_ACCESSOR);
2701
+ const Policies = /* @__PURE__ */ new Set();
2702
+ for (const [intent, policy] of Object.entries(policyRegistry)) {
2703
+ const intentLower = intent.toLowerCase();
2704
+ registryInstance.addPolicy(intentLower, policy);
2705
+ if (!Guards49.isNullOrEmpty(policy.roles)) {
2706
+ Policies.add("roles");
2707
+ }
2708
+ if (!Guards49.isNullOrEmpty(policy.permissions)) {
2709
+ Policies.add("permissions");
2710
+ }
2711
+ if (!Guards49.isNullOrEmpty(policy.userId)) {
2712
+ Policies.add("userId");
2713
+ }
2714
+ if (!Guards49.isNullOrEmpty(policy.tenantId)) {
2715
+ Policies.add("tenantId");
2716
+ }
2717
+ }
2718
+ if (Policies.has("roles")) {
2719
+ const { RoleAuthorizationStrategy: RoleAuthorizationStrategy2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2720
+ strategies.push(new RoleAuthorizationStrategy2(registryInstance, ctxAccessor));
2721
+ }
2722
+ if (Policies.has("permissions")) {
2723
+ const { PermissionAuthorizationStrategy: PermissionAuthorizationStrategy2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2724
+ strategies.push(new PermissionAuthorizationStrategy2(registryInstance, ctxAccessor));
2725
+ }
2726
+ if (Policies.has("userId")) {
2727
+ const { UserAuthorizationStrategy: UserAuthorizationStrategy2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2728
+ strategies.push(new UserAuthorizationStrategy2(registryInstance, ctxAccessor));
2729
+ }
2730
+ if (Policies.has("tenantId")) {
2731
+ const { TenantAuthorizationStrategy: TenantAuthorizationStrategy2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2732
+ strategies.push(new TenantAuthorizationStrategy2(registryInstance, ctxAccessor));
2733
+ }
2734
+ }
2735
+ if (!Guards49.isNullOrEmpty(opts.customAuthorizationStrategy)) {
2736
+ const customStrategies = opts.customAuthorizationStrategy;
2737
+ customStrategies.forEach((strategyToken) => {
2738
+ if (Guards49.isDefined(strategyToken)) {
2739
+ strategies.push(strategyToken(container));
2740
+ }
2741
+ });
2742
+ }
2743
+ const { AuthorizationPipeline: AuthorizationPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2744
+ return new AuthorizationPipeline2(strategies);
2745
+ },
2746
+ /**
2747
+ * @description Configures the authentication service and gatekeeper in the service container.
2748
+ * @param container The service container to configure.
2749
+ * @param opts The authentication configuration options.
2750
+
2751
+ *
2752
+ * @author Xeno
2753
+ * @version 1.0.0
2754
+ * @since 2025-09-30
2755
+ * @link https://github.com/xeno-js/xeno-js
2756
+ */
2757
+ async addAuthN(container, opts) {
2758
+ const { Guards: Guards49, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
2759
+ if (Guards49.isDefined(opts.customAuth)) {
2760
+ const authService = opts.customAuth.authExtendedService();
2761
+ container.addScoped(TOKENS5.AUTH_SERVICE, () => {
2762
+ return authService;
2763
+ });
2764
+ container.addSingleton(TOKENS5.BASE_AUTH_SERVICE, () => {
2765
+ return authService;
2766
+ });
2767
+ } else {
2768
+ const { SupabaseServerAuthFactory: SupabaseServerAuthFactory2 } = await Promise.resolve().then(() => (init_factories(), factories_exports));
2769
+ const factory = new SupabaseServerAuthFactory2();
2770
+ const supabase = factory.create({ config: opts, container });
2771
+ container.addScoped(TOKENS5.AUTH_SERVICE, () => {
2772
+ return supabase;
2773
+ });
2774
+ container.addSingleton(TOKENS5.BASE_AUTH_SERVICE, () => {
2775
+ return supabase;
2776
+ });
2777
+ }
2778
+ }
2779
+ });
2780
+ }
2781
+ });
2782
+
2783
+ // src/infrastructure/modules/utils/validation.utils.ts
2784
+ var validation_utils_exports = {};
2785
+ __export(validation_utils_exports, {
2786
+ ValidationUtils: () => ValidationUtils
2787
+ });
2788
+ var ValidationUtils;
2789
+ var init_validation_utils = __esm({
2790
+ "src/infrastructure/modules/utils/validation.utils.ts"() {
2791
+ "use strict";
2792
+ ValidationUtils = Object.freeze({
2793
+ /**
2794
+ * @description Checks if the provided validation configuration requires any validation strategies.
2795
+ * @param validationConfig The validation configuration to check.
2796
+ * @returns True if any validation strategies are required, false otherwise.
2797
+ *
2798
+ * @author Xeno
2799
+ * @version 1.0.0
2800
+ * @since 2025-09-30
2801
+ * @link https://github.com/xeno-js/xeno-js
2802
+ */
2803
+ async addValidation(container, opts, logger) {
2804
+ const { Guards: Guards49, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
2805
+ if (!Guards49.isDefined(opts.zod) && Guards49.isNullOrEmpty(opts.customValidationStrategy)) {
2806
+ return;
2807
+ }
2808
+ const validationStrategies = [];
2809
+ if (Guards49.isDefined(opts.zod)) {
2810
+ const config = opts.zod;
2811
+ const { ZodValidatorFactory: ZodValidatorFactory2 } = await Promise.resolve().then(() => (init_factories(), factories_exports));
2812
+ const { SchemaValidationStrategy: SchemaValidationStrategy2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2813
+ const validatorService = new ZodValidatorFactory2().create({ ...config, logger });
2814
+ container.addSingleton(TOKENS5.VALIDATOR_SERVICE, () => validatorService);
2815
+ validationStrategies.push(new SchemaValidationStrategy2(validatorService));
2816
+ }
2817
+ if (!Guards49.isNullOrEmpty(opts.customValidationStrategy)) {
2818
+ for (const strategyToken of opts.customValidationStrategy) {
2819
+ if (Guards49.isDefined(strategyToken)) validationStrategies.push(strategyToken(container));
2820
+ }
2821
+ }
2822
+ const { ValidationPipeline: ValidationPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2823
+ return new ValidationPipeline2(validationStrategies);
2824
+ }
2825
+ });
2826
+ }
2827
+ });
2828
+
2829
+ // src/infrastructure/idempotency/idempotency-store.ts
2830
+ import { IDEMPOTENCY_CONSTANTS as IDEMPOTENCY_CONSTANTS2 } from "@xeno-js/shared";
2831
+ var IdempotencyStore;
2832
+ var init_idempotency_store = __esm({
2833
+ "src/infrastructure/idempotency/idempotency-store.ts"() {
2834
+ "use strict";
2835
+ IdempotencyStore = class {
2836
+ /**
2837
+ * @description Constructs a new instance of IdempotencyStore, accepting an instance of ICache for accessing the caching system and an instance of IIdentityAccessor for obtaining the user's identity context. The IdempotencyStore uses the caching system to manage locks and results of idempotent commands, ensuring that commands with the same ID are processed only once. The identity context is used to build contextual keys, allowing for more granular management of idempotent commands in multi-tenant scenarios.
2838
+ * @param _cache An instance of ICache that provides methods to interact with the underlying caching system, used to store locks and results of idempotent commands.
2839
+ * @param _identityAccessor An instance of IIdentityAccessor that allows access to the user's identity context, used to build contextual keys for idempotent commands, supporting multi-tenant scenarios.
2840
+
2841
+ *
2842
+ * @author Xeno
2843
+ * @version 1.0.0
2844
+ * @since 2025-09-30
2845
+ * @link https://github.com/xeno-js/xeno-js
2846
+ */
2847
+ constructor(_cache, _cacheKeyBuilder) {
2848
+ this._cache = _cache;
2849
+ this._cacheKeyBuilder = _cacheKeyBuilder;
2850
+ }
2851
+ _cache;
2852
+ _cacheKeyBuilder;
2853
+ async acquireLock(requestId, ttlSeconds) {
2854
+ const key = this._cacheKeyBuilder.buildContextualKey(`command:${requestId}`);
2855
+ return await this._cache.setIfAbsent(
2856
+ `${IDEMPOTENCY_CONSTANTS2.LOCK_KEY_PREFIX}${key}`,
2857
+ IDEMPOTENCY_CONSTANTS2.LOCKED_VALUE,
2858
+ ttlSeconds
2859
+ );
2860
+ }
2861
+ async hasBeenProcessed(commandId) {
2862
+ const key = this._cacheKeyBuilder.buildContextualKey(`command:${commandId}`);
2863
+ return await this._cache.has(`${IDEMPOTENCY_CONSTANTS2.PROCESSED_KEY_PREFIX}${key}`);
2864
+ }
2865
+ async markAsProcessed(commandId, payload, ttlSeconds) {
2866
+ const key = this._cacheKeyBuilder.buildContextualKey(`command:${commandId}`);
2867
+ await this._cache.set(
2868
+ `${IDEMPOTENCY_CONSTANTS2.PROCESSED_KEY_PREFIX}${key}`,
2869
+ payload,
2870
+ ttlSeconds
2871
+ );
2872
+ }
2873
+ async getPayload(commandId) {
2874
+ const key = this._cacheKeyBuilder.buildContextualKey(`command:${commandId}`);
2875
+ const payload = await this._cache.get(`${IDEMPOTENCY_CONSTANTS2.PROCESSED_KEY_PREFIX}${key}`);
2876
+ return payload;
2877
+ }
2878
+ async releaseLock(commandId) {
2879
+ const key = this._cacheKeyBuilder.buildContextualKey(`command:${commandId}`);
2880
+ await this._cache.remove(`${IDEMPOTENCY_CONSTANTS2.LOCK_KEY_PREFIX}${key}`);
2881
+ }
2882
+ };
2883
+ }
2884
+ });
2885
+
2886
+ // src/infrastructure/idempotency/index.ts
2887
+ var idempotency_exports = {};
2888
+ __export(idempotency_exports, {
2889
+ IdempotencyStore: () => IdempotencyStore
2890
+ });
2891
+ var init_idempotency = __esm({
2892
+ "src/infrastructure/idempotency/index.ts"() {
2893
+ "use strict";
2894
+ init_idempotency_store();
2895
+ }
2896
+ });
2897
+
2898
+ // src/infrastructure/modules/utils/pipeline.utils.ts
2899
+ var pipeline_utils_exports = {};
2900
+ __export(pipeline_utils_exports, {
2901
+ PipelineUtils: () => PipelineUtils
2902
+ });
2903
+ var PipelineUtils;
2904
+ var init_pipeline_utils = __esm({
2905
+ "src/infrastructure/modules/utils/pipeline.utils.ts"() {
2906
+ "use strict";
2907
+ PipelineUtils = Object.freeze({
2908
+ /**
2909
+ * @description Checks if the provided command configuration requires any command strategies.
2910
+ * @param commandConfig The command configuration to check.
2911
+ * @returns True if any command strategies are required, false otherwise.
2912
+ *
2913
+ * @author Xeno
2914
+ * @version 1.0.0
2915
+ * @since 2025-09-30
2916
+ * @link https://github.com/xeno-js/xeno-js
2833
2917
  */
2834
- async addAuthZ(container, opts) {
2835
- const { TOKENS: TOKENS5 } = await import("@xeno-js/shared");
2836
- const strategies = [];
2837
- const { Guards: Guards47 } = await import("@xeno-js/shared");
2838
- if (Guards47.isDefined(opts.policies)) {
2839
- const { PolicyRegistry: PolicyRegistry2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2840
- const policyRegistry = opts.policies;
2841
- const registryInstance = new PolicyRegistry2();
2842
- const ctxAccessor = container.resolve(TOKENS5.CONTEXT_ACCESSOR);
2843
- const Policies = /* @__PURE__ */ new Set();
2844
- for (const [intent, policy] of Object.entries(policyRegistry)) {
2845
- const intentLower = intent.toLowerCase();
2846
- registryInstance.addPolicy(intentLower, policy);
2847
- if (!Guards47.isNullOrEmpty(policy.roles)) {
2848
- Policies.add("roles");
2849
- }
2850
- if (!Guards47.isNullOrEmpty(policy.permissions)) {
2851
- Policies.add("permissions");
2852
- }
2853
- if (!Guards47.isNullOrEmpty(policy.userId)) {
2854
- Policies.add("userId");
2855
- }
2856
- if (!Guards47.isNullOrEmpty(policy.tenantId)) {
2857
- Policies.add("tenantId");
2858
- }
2859
- }
2860
- if (Policies.has("roles")) {
2861
- const { RoleAuthorizationStrategy: RoleAuthorizationStrategy2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2862
- strategies.push(new RoleAuthorizationStrategy2(registryInstance, ctxAccessor));
2863
- }
2864
- if (Policies.has("permissions")) {
2865
- const { PermissionAuthorizationStrategy: PermissionAuthorizationStrategy2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2866
- strategies.push(new PermissionAuthorizationStrategy2(registryInstance, ctxAccessor));
2867
- }
2868
- if (Policies.has("userId")) {
2869
- const { UserAuthorizationStrategy: UserAuthorizationStrategy2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2870
- strategies.push(new UserAuthorizationStrategy2(registryInstance, ctxAccessor));
2871
- }
2872
- if (Policies.has("tenantId")) {
2873
- const { TenantAuthorizationStrategy: TenantAuthorizationStrategy2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2874
- strategies.push(new TenantAuthorizationStrategy2(registryInstance, ctxAccessor));
2875
- }
2918
+ async addCommand(container, opts) {
2919
+ const { Guards: Guards49, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
2920
+ const pipelines = [];
2921
+ if (Guards49.isDefined(opts.idempotency)) {
2922
+ const { IdempotencyStore: IdempotencyStore2 } = await Promise.resolve().then(() => (init_idempotency(), idempotency_exports));
2923
+ const imdStore = new IdempotencyStore2(
2924
+ container.resolve(TOKENS5.CACHE),
2925
+ container.resolve(TOKENS5.CACHE_KEY_BUILDER)
2926
+ );
2927
+ const { IdempotencyPipeline: IdempotencyPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2928
+ const requestContext = container.resolve(TOKENS5.NETWORK_CONTEXT_ACCESSOR);
2929
+ const config = opts.idempotency;
2930
+ pipelines.push(
2931
+ new IdempotencyPipeline2(
2932
+ requestContext,
2933
+ imdStore,
2934
+ config?.lockTtlSeconds,
2935
+ config?.processedTtlSeconds
2936
+ )
2937
+ );
2876
2938
  }
2877
- if (!Guards47.isNullOrEmpty(opts.customAuthorizationStrategy)) {
2878
- const customStrategies = opts.customAuthorizationStrategy;
2879
- customStrategies.forEach((strategyToken) => {
2880
- if (Guards47.isDefined(strategyToken)) {
2881
- strategies.push(strategyToken(container));
2882
- }
2883
- });
2939
+ if (Guards49.isDefined(opts.concurrency)) {
2940
+ const { ConcurrencyRetryPipeline: ConcurrencyRetryPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2941
+ const config = opts.concurrency;
2942
+ pipelines.push(new ConcurrencyRetryPipeline2(config?.maxRetries, config?.delayConfig));
2884
2943
  }
2885
- const { AuthorizationPipeline: AuthorizationPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2886
- return new AuthorizationPipeline2(strategies);
2944
+ return pipelines;
2887
2945
  },
2888
2946
  /**
2889
- * @description Configures the authentication service and gatekeeper in the service container.
2890
- * @param container The service container to configure.
2891
- * @param opts The authentication configuration options.
2892
-
2893
- *
2947
+ * @description Checks if the provided query configuration requires any query strategies.
2948
+ * @param queryConfig The query configuration to check.
2949
+ * @returns True if any query strategies are required, false otherwise.
2950
+ *
2894
2951
  * @author Xeno
2895
2952
  * @version 1.0.0
2896
2953
  * @since 2025-09-30
2897
- * @link https://github.com/xeno-js/xeno-js
2954
+ * @link https://github.com/xeno-js/xeno-js
2898
2955
  */
2899
- async addAuthN(container, opts) {
2900
- const { Guards: Guards47, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
2901
- if (Guards47.isDefined(opts.customAuth)) {
2902
- const authService = opts.customAuth.authExtendedService();
2903
- container.addScoped(TOKENS5.AUTH_SERVICE, () => {
2904
- return authService;
2905
- });
2906
- container.addSingleton(TOKENS5.BASE_AUTH_SERVICE, () => {
2907
- return authService;
2908
- });
2909
- } else {
2910
- const { SupabaseServerAuthFactory: SupabaseServerAuthFactory2 } = await Promise.resolve().then(() => (init_factories(), factories_exports));
2911
- const factory = new SupabaseServerAuthFactory2();
2912
- const supabase = factory.create({ config: opts, container });
2913
- container.addScoped(TOKENS5.AUTH_SERVICE, () => {
2914
- return supabase;
2915
- });
2916
- container.addSingleton(TOKENS5.BASE_AUTH_SERVICE, () => {
2917
- return supabase;
2918
- });
2919
- }
2956
+ async addQuery(container) {
2957
+ const { TOKENS: TOKENS5 } = await import("@xeno-js/shared");
2958
+ const { QueryCachingPipeline: QueryCachingPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2959
+ return new QueryCachingPipeline2(
2960
+ container.resolve(TOKENS5.CACHE),
2961
+ container.resolve(TOKENS5.CACHE_KEY_BUILDER),
2962
+ container.resolve(TOKENS5.LOGGER)
2963
+ );
2920
2964
  }
2921
2965
  });
2922
2966
  }
2923
2967
  });
2924
2968
 
2969
+ // src/infrastructure/modules/cqrs.module.ts
2970
+ var cqrs_module_exports = {};
2971
+ __export(cqrs_module_exports, {
2972
+ CqrsModule: () => CqrsModule
2973
+ });
2974
+ var CqrsModule;
2975
+ var init_cqrs_module = __esm({
2976
+ "src/infrastructure/modules/cqrs.module.ts"() {
2977
+ "use strict";
2978
+ CqrsModule = class {
2979
+ async configure(container, opts) {
2980
+ const { TOKENS: TOKENS5 } = await import("@xeno-js/shared");
2981
+ const logger = container.resolve(TOKENS5.LOGGER);
2982
+ const { Mediator: Mediator2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2983
+ container.addSingleton(TOKENS5.MEDIATOR, (c) => {
2984
+ const serviceScopeAccessor = c.resolve(TOKENS5.SERVICE_SCOPE_ACCESSOR);
2985
+ return new Mediator2(serviceScopeAccessor);
2986
+ });
2987
+ const { ExceptionPipeline: ExceptionPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2988
+ const { LoggingPipeline: LoggingPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2989
+ const { PerformancePipeline: PerformancePipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2990
+ const thresholdMs = opts.performance?.thresholdMs;
2991
+ const pipelines = [
2992
+ new ExceptionPipeline2(),
2993
+ new LoggingPipeline2(logger),
2994
+ new PerformancePipeline2(logger, thresholdMs)
2995
+ ];
2996
+ const { Guards: Guards49 } = await import("@xeno-js/shared");
2997
+ if (Guards49.isDefined(opts.authorization.policies) || Guards49.isDefined(opts.authorization.customAuthorizationStrategy)) {
2998
+ const { AuthUtils: AuthUtils2 } = await Promise.resolve().then(() => (init_auth_utils(), auth_utils_exports));
2999
+ const authPipelines = await AuthUtils2.addAuthZ(container, opts.authorization);
3000
+ pipelines.push(authPipelines);
3001
+ }
3002
+ if (Guards49.isDefined(opts.validation.zod) || Guards49.isDefined(opts.validation.customValidationStrategy)) {
3003
+ const { ValidationUtils: ValidationUtils2 } = await Promise.resolve().then(() => (init_validation_utils(), validation_utils_exports));
3004
+ const validationPipelines = await ValidationUtils2.addValidation(
3005
+ container,
3006
+ opts.validation,
3007
+ logger
3008
+ );
3009
+ if (Guards49.isDefined(validationPipelines)) pipelines.push(validationPipelines);
3010
+ }
3011
+ const commandPipelines = [...pipelines];
3012
+ const queryPipelines = [...pipelines];
3013
+ if (Guards49.isDefined(opts.commandBus.idempotency) || Guards49.isDefined(opts.commandBus.concurrency)) {
3014
+ const { PipelineUtils: PipelineUtils2 } = await Promise.resolve().then(() => (init_pipeline_utils(), pipeline_utils_exports));
3015
+ const newCommandPipelines = await PipelineUtils2.addCommand(container, opts.commandBus);
3016
+ commandPipelines.push(...newCommandPipelines);
3017
+ }
3018
+ if (opts.queryBus.isEnabled) {
3019
+ const { PipelineUtils: PipelineUtils2 } = await Promise.resolve().then(() => (init_pipeline_utils(), pipeline_utils_exports));
3020
+ const newQueryPipelines = await PipelineUtils2.addQuery(container);
3021
+ queryPipelines.push(newQueryPipelines);
3022
+ }
3023
+ const { CompositePipeline: CompositePipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
3024
+ container.addSingleton(TOKENS5.COMMAND_PIPELINES_BEHAVIOR, () => {
3025
+ return new CompositePipeline2(commandPipelines);
3026
+ });
3027
+ container.addSingleton(TOKENS5.QUERY_PIPELINES_BEHAVIOR, () => {
3028
+ return new CompositePipeline2(queryPipelines);
3029
+ });
3030
+ }
3031
+ };
3032
+ }
3033
+ });
3034
+
2925
3035
  // src/infrastructure/modules/utils/db.utils.ts
2926
3036
  var db_utils_exports = {};
2927
3037
  __export(db_utils_exports, {
@@ -3009,7 +3119,7 @@ __export(unit_of_work_exports, {
3009
3119
  UnitOfWork: () => UnitOfWork
3010
3120
  });
3011
3121
  import { AppError as AppError14 } from "@xeno-js/shared";
3012
- import { Guards as Guards36 } from "@xeno-js/shared";
3122
+ import { Guards as Guards34 } from "@xeno-js/shared";
3013
3123
  var UnitOfWork;
3014
3124
  var init_unit_of_work = __esm({
3015
3125
  "src/infrastructure/transaction/unit-of-work.ts"() {
@@ -3044,9 +3154,9 @@ var init_unit_of_work = __esm({
3044
3154
  });
3045
3155
  }
3046
3156
  async dispose() {
3047
- if (Guards36.isDefined(this._ttx.state)) {
3157
+ if (Guards34.isDefined(this._ttx.state)) {
3048
3158
  try {
3049
- if (Guards36.hasMethod(this._ttx.state, "rollback")) {
3159
+ if (Guards34.hasMethod(this._ttx.state, "rollback")) {
3050
3160
  await this._ttx.state.rollback();
3051
3161
  }
3052
3162
  } finally {
@@ -3069,7 +3179,7 @@ var init_db_module = __esm({
3069
3179
  "use strict";
3070
3180
  DbModule = class {
3071
3181
  async configure(container, opts) {
3072
- const { Guards: Guards47, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
3182
+ const { Guards: Guards49, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
3073
3183
  const { DbUtils: DbUtils2 } = await Promise.resolve().then(() => (init_db_utils(), db_utils_exports));
3074
3184
  const db = opts.enableSqlLite ? await DbUtils2.addSqlLite(opts) : await DbUtils2.addDbClient(opts);
3075
3185
  const { TransactionState: TransactionState2 } = await Promise.resolve().then(() => (init_transaction_state(), transaction_state_exports));
@@ -3082,351 +3192,290 @@ var init_db_module = __esm({
3082
3192
  return new UnitOfWork2(db, ttx);
3083
3193
  });
3084
3194
  container.addScoped(TOKENS5.DB_CONTEXT, (c) => {
3085
- const ttx = c.resolve("TRANSACTION_STATE");
3086
- return new Proxy(db, {
3087
- get(_target, prop, receiver) {
3088
- const activeState = ttx.state;
3089
- if (Guards47.isDefined(activeState)) {
3090
- if (prop === "transaction") {
3091
- return activeState.transaction.bind(activeState);
3092
- }
3093
- return Reflect.get(activeState, prop, receiver);
3094
- }
3095
- return Reflect.get(db, prop, receiver);
3096
- }
3097
- });
3098
- });
3099
- }
3100
- };
3101
- }
3102
- });
3103
-
3104
- // src/infrastructure/modules/utils/http.utils.ts
3105
- var http_utils_exports = {};
3106
- __export(http_utils_exports, {
3107
- HttpUtils: () => HttpUtils
3108
- });
3109
- var HttpUtils;
3110
- var init_http_utils = __esm({
3111
- "src/infrastructure/modules/utils/http.utils.ts"() {
3112
- "use strict";
3113
- HttpUtils = Object.freeze({
3114
- /**
3115
- * @description Utility function to create a query string from an object of query parameters. It takes an object where the keys are the parameter names and the values are the parameter values, and returns a properly encoded query string that can be appended to a URL for making HTTP requests.
3116
- * @param params - An object containing the query parameters as key-value pairs. The keys represent the parameter names, and the values represent the parameter values.
3117
- * @returns A string representing the encoded query string that can be appended to a URL for making HTTP requests.
3118
- *
3119
- * @author Xeno
3120
- * @version 1.0.0
3121
- * @since 2025-09-30
3122
- * @link https://github.com/xeno-js/xeno-js
3123
- */
3124
- async addAxios(container, opts) {
3125
- const { NodeAxiosFactory: NodeAxiosFactory2 } = await Promise.resolve().then(() => (init_factories(), factories_exports));
3126
- const { Guards: Guards47 } = await import("@xeno-js/shared");
3127
- if (!Guards47.isDefined(opts.token)) {
3128
- throw new Error("HttpConfig.token is required and must be defined.");
3129
- }
3130
- container.addSingleton(opts.token, () => {
3131
- const factory = new NodeAxiosFactory2();
3132
- const instance = factory.create(opts.client);
3133
- if (!Guards47.hasMethod(instance, "get") || !Guards47.hasMethod(instance, "post") || !Guards47.hasMethod(instance, "put") || !Guards47.hasMethod(instance, "patch") || !Guards47.hasMethod(instance, "delete")) {
3134
- throw new Error(
3135
- "The created HTTP client instance does not implement the required methods of IHttpClient."
3136
- );
3137
- }
3138
- return instance;
3139
- });
3140
- },
3141
- /**
3142
- * @description Utility function to add resilience features to the service container. It takes a ResilienceConfig object that specifies whether resilience features are enabled and provides the necessary settings for implementing resilience strategies such as retries, circuit breakers, and timeouts. If resilience is enabled, it registers a singleton factory in the service container that creates an instance of the resilience client based on the provided configuration.
3143
- * @param container - The service container to register the resilience client with.
3144
- * @param opts - The ResilienceConfig options that determine whether resilience features are enabled and provide the necessary settings for implementing resilience strategies.
3145
- *
3146
- * @author Xeno
3147
- * @version 1.0.0
3148
- * @since 2025-09-30
3149
- * @link https://github.com/xeno-js/xeno-js
3150
- */
3151
- async addResilience(container, opts) {
3152
- const { TOKENS: TOKENS5 } = await import("@xeno-js/shared");
3153
- const { CockatielResilienceFactory: CockatielResilienceFactory2 } = await Promise.resolve().then(() => (init_factories(), factories_exports));
3154
- container.addSingleton(TOKENS5.RESILIENCE_CLIENT, () => {
3155
- const factory = new CockatielResilienceFactory2();
3156
- return factory.create(opts);
3157
- });
3158
- }
3159
- });
3160
- }
3161
- });
3162
-
3163
- // src/infrastructure/modules/http-core.module.ts
3164
- var http_core_module_exports = {};
3165
- __export(http_core_module_exports, {
3166
- HttpCoreModule: () => HttpCoreModule
3167
- });
3168
- var HttpCoreModule;
3169
- var init_http_core_module = __esm({
3170
- "src/infrastructure/modules/http-core.module.ts"() {
3171
- "use strict";
3172
- HttpCoreModule = class {
3173
- async configure(container, opts) {
3174
- const { HttpUtils: HttpUtils2 } = await Promise.resolve().then(() => (init_http_utils(), http_utils_exports));
3175
- await HttpUtils2.addAxios(container, opts.http);
3176
- await HttpUtils2.addResilience(container, opts.resilience);
3195
+ const ttx = c.resolve("TRANSACTION_STATE");
3196
+ return new Proxy(db, {
3197
+ get(_target, prop, receiver) {
3198
+ const activeState = ttx.state;
3199
+ if (Guards49.isDefined(activeState)) {
3200
+ if (prop === "transaction") {
3201
+ return activeState.transaction.bind(activeState);
3202
+ }
3203
+ return Reflect.get(activeState, prop, receiver);
3204
+ }
3205
+ return Reflect.get(db, prop, receiver);
3206
+ }
3207
+ });
3208
+ });
3177
3209
  }
3178
3210
  };
3179
3211
  }
3180
3212
  });
3181
3213
 
3182
- // src/infrastructure/modules/utils/validation.utils.ts
3183
- var validation_utils_exports = {};
3184
- __export(validation_utils_exports, {
3185
- ValidationUtils: () => ValidationUtils
3186
- });
3187
- var ValidationUtils;
3188
- var init_validation_utils = __esm({
3189
- "src/infrastructure/modules/utils/validation.utils.ts"() {
3214
+ // src/infrastructure/http/base.http-adapter.ts
3215
+ import { Guards as Guards35, StringHelper as StringHelper3 } from "@xeno-js/shared";
3216
+ var BaseHttpAdapter;
3217
+ var init_base_http_adapter = __esm({
3218
+ "src/infrastructure/http/base.http-adapter.ts"() {
3190
3219
  "use strict";
3191
- ValidationUtils = Object.freeze({
3220
+ BaseHttpAdapter = class {
3192
3221
  /**
3193
- * @description Checks if the provided validation configuration requires any validation strategies.
3194
- * @param validationConfig The validation configuration to check.
3195
- * @returns True if any validation strategies are required, false otherwise.
3196
- *
3197
- * @author Xeno
3198
- * @version 1.0.0
3199
- * @since 2025-09-30
3200
- * @link https://github.com/xeno-js/xeno-js
3222
+ * @description Parse the URL from the request.
3223
+ * @param rawUrl The raw URL.
3224
+ * @param headers The headers.
3225
+ * @param queryParams The query parameters.
3226
+ * @returns The parsed URL.
3201
3227
  */
3202
- async addValidation(container, opts, logger) {
3203
- const { Guards: Guards47, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
3204
- if (!Guards47.isDefined(opts.zod) && Guards47.isNullOrEmpty(opts.customValidationStrategy)) {
3205
- return;
3206
- }
3207
- const validationStrategies = [];
3208
- if (Guards47.isDefined(opts.zod)) {
3209
- const config = opts.zod;
3210
- const { ZodValidatorFactory: ZodValidatorFactory2 } = await Promise.resolve().then(() => (init_factories(), factories_exports));
3211
- const { SchemaValidationStrategy: SchemaValidationStrategy2 } = await Promise.resolve().then(() => (init_application(), application_exports));
3212
- const validatorService = new ZodValidatorFactory2().create({ ...config, logger });
3213
- container.addSingleton(TOKENS5.VALIDATOR_SERVICE, () => validatorService);
3214
- validationStrategies.push(new SchemaValidationStrategy2(validatorService));
3215
- }
3216
- if (!Guards47.isNullOrEmpty(opts.customValidationStrategy)) {
3217
- for (const strategyToken of opts.customValidationStrategy) {
3218
- if (Guards47.isDefined(strategyToken)) validationStrategies.push(strategyToken(container));
3228
+ parseUrl(rawUrl = "/", headers, queryParams) {
3229
+ const protocol = StringHelper3.getSingleValue(headers["x-forwarded-proto"]) ?? "https";
3230
+ const host = StringHelper3.safeStringify(headers["host"]) ?? "localhost";
3231
+ const url = new URL(rawUrl, `${protocol}://${host}`);
3232
+ if (!Guards35.isNullOrEmpty(queryParams)) {
3233
+ for (const [key, value] of Object.entries(queryParams)) {
3234
+ if (Guards35.isArray(value)) {
3235
+ value.forEach((v) => url.searchParams.append(key, String(v)));
3236
+ } else if (Guards35.isDefined(value)) {
3237
+ url.searchParams.set(key, String(value));
3238
+ }
3219
3239
  }
3220
3240
  }
3221
- const { ValidationPipeline: ValidationPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
3222
- return new ValidationPipeline2(validationStrategies);
3241
+ return url;
3223
3242
  }
3224
- });
3225
- }
3226
- });
3227
-
3228
- // src/infrastructure/idempotency/idempotency-store.ts
3229
- import { IDEMPOTENCY_CONSTANTS as IDEMPOTENCY_CONSTANTS2 } from "@xeno-js/shared";
3230
- var IdempotencyStore;
3231
- var init_idempotency_store = __esm({
3232
- "src/infrastructure/idempotency/idempotency-store.ts"() {
3233
- "use strict";
3234
- IdempotencyStore = class {
3235
3243
  /**
3236
- * @description Constructs a new instance of IdempotencyStore, accepting an instance of ICache for accessing the caching system and an instance of IIdentityAccessor for obtaining the user's identity context. The IdempotencyStore uses the caching system to manage locks and results of idempotent commands, ensuring that commands with the same ID are processed only once. The identity context is used to build contextual keys, allowing for more granular management of idempotent commands in multi-tenant scenarios.
3237
- * @param _cache An instance of ICache that provides methods to interact with the underlying caching system, used to store locks and results of idempotent commands.
3238
- * @param _identityAccessor An instance of IIdentityAccessor that allows access to the user's identity context, used to build contextual keys for idempotent commands, supporting multi-tenant scenarios.
3239
-
3240
- *
3241
- * @author Xeno
3242
- * @version 1.0.0
3243
- * @since 2025-09-30
3244
- * @link https://github.com/xeno-js/xeno-js
3244
+ * @description Parses the headers.
3245
+ * @param rawHeaders The raw headers.
3246
+ * @returns The parsed headers.
3245
3247
  */
3246
- constructor(_cache, _cacheKeyBuilder) {
3247
- this._cache = _cache;
3248
- this._cacheKeyBuilder = _cacheKeyBuilder;
3248
+ parseHeaders(rawHeaders) {
3249
+ const headers = new Headers();
3250
+ for (const [key, value] of Object.entries(rawHeaders)) {
3251
+ if (Guards35.isDefined(value)) {
3252
+ if (Guards35.isArray(value)) {
3253
+ value.forEach((v) => headers.append(key, String(v)));
3254
+ } else {
3255
+ headers.set(key, String(value));
3256
+ }
3257
+ }
3258
+ }
3259
+ return headers;
3249
3260
  }
3250
- _cache;
3251
- _cacheKeyBuilder;
3252
- async acquireLock(requestId, ttlSeconds) {
3253
- const key = this._cacheKeyBuilder.buildContextualKey(`command:${requestId}`);
3254
- return await this._cache.setIfAbsent(
3255
- `${IDEMPOTENCY_CONSTANTS2.LOCK_KEY_PREFIX}${key}`,
3256
- IDEMPOTENCY_CONSTANTS2.LOCKED_VALUE,
3257
- ttlSeconds
3258
- );
3261
+ /**
3262
+ * @description Parses the body.
3263
+ * @param method The method.
3264
+ * @param rawBody The raw body.
3265
+ * @returns The parsed body.
3266
+ */
3267
+ parseBody(method, rawBody) {
3268
+ if (!Guards35.isDefined(method) || !["POST", "PUT", "PATCH", "DELETE"].includes(method.toUpperCase()) || !Guards35.isDefined(rawBody))
3269
+ return void 0;
3270
+ if (Guards35.isObject(rawBody)) return JSON.stringify(rawBody);
3271
+ if (Guards35.isString(rawBody) || rawBody instanceof Blob || rawBody instanceof ArrayBuffer || ArrayBuffer.isView(rawBody) || rawBody instanceof URLSearchParams || rawBody instanceof FormData)
3272
+ return rawBody;
3273
+ return String(rawBody);
3259
3274
  }
3260
- async hasBeenProcessed(commandId) {
3261
- const key = this._cacheKeyBuilder.buildContextualKey(`command:${commandId}`);
3262
- return await this._cache.has(`${IDEMPOTENCY_CONSTANTS2.PROCESSED_KEY_PREFIX}${key}`);
3275
+ /**
3276
+ * @description Creates the XenoWebTransport.
3277
+ * @param url The url.
3278
+ * @param method The method.
3279
+ * @param headers The headers.
3280
+ * @param body The body.
3281
+ * @returns The XenoWebTransport.
3282
+ */
3283
+ createXenoWebTransport(url, method = "GET", headers, body = void 0) {
3284
+ const init2 = {
3285
+ method: method.toUpperCase(),
3286
+ headers
3287
+ };
3288
+ const parsedBody = this.parseBody(method, body);
3289
+ if (Guards35.isDefined(parsedBody)) {
3290
+ init2.body = parsedBody;
3291
+ init2.duplex = "half";
3292
+ }
3293
+ return {
3294
+ request: {
3295
+ ...new Request(url, init2),
3296
+ path: url.pathname
3297
+ },
3298
+ response: new Response()
3299
+ };
3263
3300
  }
3264
- async markAsProcessed(commandId, payload, ttlSeconds) {
3265
- const key = this._cacheKeyBuilder.buildContextualKey(`command:${commandId}`);
3266
- await this._cache.set(
3267
- `${IDEMPOTENCY_CONSTANTS2.PROCESSED_KEY_PREFIX}${key}`,
3268
- payload,
3269
- ttlSeconds
3270
- );
3301
+ };
3302
+ }
3303
+ });
3304
+
3305
+ // src/infrastructure/http/fastify.http-adapter.ts
3306
+ var FastifyHttpAdapter;
3307
+ var init_fastify_http_adapter = __esm({
3308
+ "src/infrastructure/http/fastify.http-adapter.ts"() {
3309
+ "use strict";
3310
+ init_base_http_adapter();
3311
+ FastifyHttpAdapter = class extends BaseHttpAdapter {
3312
+ adapt(req, _res) {
3313
+ const headers = this.parseHeaders(req.headers);
3314
+ const url = this.parseUrl(req.url, req.headers, req.query);
3315
+ const body = req.body;
3316
+ return this.createXenoWebTransport(url, req.method, headers, body);
3271
3317
  }
3272
- async getPayload(commandId) {
3273
- const key = this._cacheKeyBuilder.buildContextualKey(`command:${commandId}`);
3274
- const payload = await this._cache.get(`${IDEMPOTENCY_CONSTANTS2.PROCESSED_KEY_PREFIX}${key}`);
3275
- return payload;
3318
+ };
3319
+ }
3320
+ });
3321
+
3322
+ // src/infrastructure/http/native.http-adapter.ts
3323
+ var NativeHttpAdapter;
3324
+ var init_native_http_adapter = __esm({
3325
+ "src/infrastructure/http/native.http-adapter.ts"() {
3326
+ "use strict";
3327
+ init_base_http_adapter();
3328
+ NativeHttpAdapter = class extends BaseHttpAdapter {
3329
+ adapt(req, res) {
3330
+ return {
3331
+ request: {
3332
+ ...req,
3333
+ path: new URL(req.url).pathname
3334
+ },
3335
+ response: res
3336
+ };
3276
3337
  }
3277
- async releaseLock(commandId) {
3278
- const key = this._cacheKeyBuilder.buildContextualKey(`command:${commandId}`);
3279
- await this._cache.remove(`${IDEMPOTENCY_CONSTANTS2.LOCK_KEY_PREFIX}${key}`);
3338
+ };
3339
+ }
3340
+ });
3341
+
3342
+ // src/infrastructure/http/vercel.http-adapter.ts
3343
+ var VercelHttpAdapter;
3344
+ var init_vercel_http_adapter = __esm({
3345
+ "src/infrastructure/http/vercel.http-adapter.ts"() {
3346
+ "use strict";
3347
+ init_base_http_adapter();
3348
+ VercelHttpAdapter = class extends BaseHttpAdapter {
3349
+ adapt(req, _res) {
3350
+ const headers = this.parseHeaders(req.headers);
3351
+ const url = this.parseUrl(req.url, req.headers, req.query);
3352
+ return this.createXenoWebTransport(url, req.method, headers, req.body);
3280
3353
  }
3281
3354
  };
3282
3355
  }
3283
3356
  });
3284
3357
 
3285
- // src/infrastructure/idempotency/index.ts
3286
- var idempotency_exports = {};
3287
- __export(idempotency_exports, {
3288
- IdempotencyStore: () => IdempotencyStore
3358
+ // src/infrastructure/http/index.ts
3359
+ var http_exports = {};
3360
+ __export(http_exports, {
3361
+ BaseHttpAdapter: () => BaseHttpAdapter,
3362
+ FastifyHttpAdapter: () => FastifyHttpAdapter,
3363
+ NativeHttpAdapter: () => NativeHttpAdapter,
3364
+ VercelHttpAdapter: () => VercelHttpAdapter
3289
3365
  });
3290
- var init_idempotency = __esm({
3291
- "src/infrastructure/idempotency/index.ts"() {
3366
+ var init_http = __esm({
3367
+ "src/infrastructure/http/index.ts"() {
3292
3368
  "use strict";
3293
- init_idempotency_store();
3369
+ init_base_http_adapter();
3370
+ init_fastify_http_adapter();
3371
+ init_native_http_adapter();
3372
+ init_vercel_http_adapter();
3294
3373
  }
3295
3374
  });
3296
3375
 
3297
- // src/infrastructure/modules/utils/pipeline.utils.ts
3298
- var pipeline_utils_exports = {};
3299
- __export(pipeline_utils_exports, {
3300
- PipelineUtils: () => PipelineUtils
3301
- });
3302
- var PipelineUtils;
3303
- var init_pipeline_utils = __esm({
3304
- "src/infrastructure/modules/utils/pipeline.utils.ts"() {
3376
+ // src/infrastructure/modules/http-adapter.module.ts
3377
+ import { Guards as Guards36 } from "@xeno-js/shared";
3378
+ var HttpAdapterModule;
3379
+ var init_http_adapter_module = __esm({
3380
+ "src/infrastructure/modules/http-adapter.module.ts"() {
3305
3381
  "use strict";
3306
- PipelineUtils = Object.freeze({
3307
- /**
3308
- * @description Checks if the provided command configuration requires any command strategies.
3309
- * @param commandConfig The command configuration to check.
3310
- * @returns True if any command strategies are required, false otherwise.
3311
- *
3312
- * @author Xeno
3313
- * @version 1.0.0
3314
- * @since 2025-09-30
3315
- * @link https://github.com/xeno-js/xeno-js
3316
- */
3317
- async addCommand(container, opts) {
3318
- const { Guards: Guards47, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
3319
- const pipelines = [];
3320
- if (Guards47.isDefined(opts.idempotency)) {
3321
- const { IdempotencyStore: IdempotencyStore2 } = await Promise.resolve().then(() => (init_idempotency(), idempotency_exports));
3322
- const imdStore = new IdempotencyStore2(
3323
- container.resolve(TOKENS5.CACHE),
3324
- container.resolve(TOKENS5.CACHE_KEY_BUILDER)
3325
- );
3326
- const { IdempotencyPipeline: IdempotencyPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
3327
- const requestContext = container.resolve(TOKENS5.NETWORK_CONTEXT_ACCESSOR);
3328
- const config = opts.idempotency;
3329
- pipelines.push(
3330
- new IdempotencyPipeline2(
3331
- requestContext,
3332
- imdStore,
3333
- config?.lockTtlSeconds,
3334
- config?.processedTtlSeconds
3335
- )
3336
- );
3337
- }
3338
- if (Guards47.isDefined(opts.concurrency)) {
3339
- const { ConcurrencyRetryPipeline: ConcurrencyRetryPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
3340
- const config = opts.concurrency;
3341
- pipelines.push(new ConcurrencyRetryPipeline2(config?.maxRetries, config?.delayConfig));
3382
+ HttpAdapterModule = class {
3383
+ async configure(container, opts) {
3384
+ const adapter = await this._getAdapter(opts);
3385
+ container.addSingleton("HTTP_ADAPTER", () => adapter);
3386
+ }
3387
+ async _getAdapter(opts) {
3388
+ if (opts.vercel) {
3389
+ const { VercelHttpAdapter: VercelHttpAdapter2 } = await Promise.resolve().then(() => (init_http(), http_exports));
3390
+ return new VercelHttpAdapter2();
3391
+ } else if (opts.fastify) {
3392
+ const { FastifyHttpAdapter: FastifyHttpAdapter2 } = await Promise.resolve().then(() => (init_http(), http_exports));
3393
+ return new FastifyHttpAdapter2();
3394
+ } else if (Guards36.isDefined(opts.custom)) {
3395
+ return opts.custom();
3396
+ } else {
3397
+ const { NativeHttpAdapter: NativeHttpAdapter2 } = await Promise.resolve().then(() => (init_http(), http_exports));
3398
+ return new NativeHttpAdapter2();
3342
3399
  }
3343
- return pipelines;
3344
- },
3345
- /**
3346
- * @description Checks if the provided query configuration requires any query strategies.
3347
- * @param queryConfig The query configuration to check.
3348
- * @returns True if any query strategies are required, false otherwise.
3349
- *
3350
- * @author Xeno
3351
- * @version 1.0.0
3352
- * @since 2025-09-30
3353
- * @link https://github.com/xeno-js/xeno-js
3354
- */
3355
- async addQuery(container) {
3356
- const { TOKENS: TOKENS5 } = await import("@xeno-js/shared");
3357
- const { QueryCachingPipeline: QueryCachingPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
3358
- return new QueryCachingPipeline2(
3359
- container.resolve(TOKENS5.CACHE),
3360
- container.resolve(TOKENS5.CACHE_KEY_BUILDER),
3361
- container.resolve(TOKENS5.LOGGER)
3362
- );
3363
3400
  }
3364
- });
3401
+ };
3365
3402
  }
3366
3403
  });
3367
3404
 
3368
- // src/infrastructure/modules/cqrs.module.ts
3369
- var cqrs_module_exports = {};
3370
- __export(cqrs_module_exports, {
3371
- CqrsModule: () => CqrsModule
3405
+ // src/infrastructure/modules/utils/http.utils.ts
3406
+ var http_utils_exports = {};
3407
+ __export(http_utils_exports, {
3408
+ HttpUtils: () => HttpUtils
3372
3409
  });
3373
- var CqrsModule;
3374
- var init_cqrs_module = __esm({
3375
- "src/infrastructure/modules/cqrs.module.ts"() {
3410
+ var HttpUtils;
3411
+ var init_http_utils = __esm({
3412
+ "src/infrastructure/modules/utils/http.utils.ts"() {
3376
3413
  "use strict";
3377
- CqrsModule = class {
3378
- async configure(container, opts) {
3379
- const { TOKENS: TOKENS5 } = await import("@xeno-js/shared");
3380
- const logger = container.resolve(TOKENS5.LOGGER);
3381
- const { Mediator: Mediator2 } = await Promise.resolve().then(() => (init_application(), application_exports));
3382
- container.addSingleton(TOKENS5.MEDIATOR, (c) => {
3383
- const serviceScopeAccessor = c.resolve(TOKENS5.SERVICE_SCOPE_ACCESSOR);
3384
- return new Mediator2(serviceScopeAccessor);
3385
- });
3386
- const { ExceptionPipeline: ExceptionPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
3387
- const { LoggingPipeline: LoggingPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
3388
- const { PerformancePipeline: PerformancePipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
3389
- const thresholdMs = opts.performance?.thresholdMs;
3390
- const pipelines = [
3391
- new ExceptionPipeline2(),
3392
- new LoggingPipeline2(logger),
3393
- new PerformancePipeline2(logger, thresholdMs)
3394
- ];
3395
- const { Guards: Guards47 } = await import("@xeno-js/shared");
3396
- if (Guards47.isDefined(opts.authorization.policies) || Guards47.isDefined(opts.authorization.customAuthorizationStrategy)) {
3397
- const { AuthUtils: AuthUtils2 } = await Promise.resolve().then(() => (init_auth_utils(), auth_utils_exports));
3398
- const authPipelines = await AuthUtils2.addAuthZ(container, opts.authorization);
3399
- pipelines.push(authPipelines);
3400
- }
3401
- if (Guards47.isDefined(opts.validation.zod) || Guards47.isDefined(opts.validation.customValidationStrategy)) {
3402
- const { ValidationUtils: ValidationUtils2 } = await Promise.resolve().then(() => (init_validation_utils(), validation_utils_exports));
3403
- const validationPipelines = await ValidationUtils2.addValidation(
3404
- container,
3405
- opts.validation,
3406
- logger
3407
- );
3408
- if (Guards47.isDefined(validationPipelines)) pipelines.push(validationPipelines);
3409
- }
3410
- const commandPipelines = [...pipelines];
3411
- const queryPipelines = [...pipelines];
3412
- if (Guards47.isDefined(opts.commandBus.idempotency) || Guards47.isDefined(opts.commandBus.concurrency)) {
3413
- const { PipelineUtils: PipelineUtils2 } = await Promise.resolve().then(() => (init_pipeline_utils(), pipeline_utils_exports));
3414
- const newCommandPipelines = await PipelineUtils2.addCommand(container, opts.commandBus);
3415
- commandPipelines.push(...newCommandPipelines);
3416
- }
3417
- if (opts.queryBus.isEnabled) {
3418
- const { PipelineUtils: PipelineUtils2 } = await Promise.resolve().then(() => (init_pipeline_utils(), pipeline_utils_exports));
3419
- const newQueryPipelines = await PipelineUtils2.addQuery(container);
3420
- queryPipelines.push(newQueryPipelines);
3414
+ HttpUtils = Object.freeze({
3415
+ /**
3416
+ * @description Utility function to create a query string from an object of query parameters. It takes an object where the keys are the parameter names and the values are the parameter values, and returns a properly encoded query string that can be appended to a URL for making HTTP requests.
3417
+ * @param params - An object containing the query parameters as key-value pairs. The keys represent the parameter names, and the values represent the parameter values.
3418
+ * @returns A string representing the encoded query string that can be appended to a URL for making HTTP requests.
3419
+ *
3420
+ * @author Xeno
3421
+ * @version 1.0.0
3422
+ * @since 2025-09-30
3423
+ * @link https://github.com/xeno-js/xeno-js
3424
+ */
3425
+ async addAxios(container, opts) {
3426
+ const { NodeAxiosFactory: NodeAxiosFactory2 } = await Promise.resolve().then(() => (init_factories(), factories_exports));
3427
+ const { Guards: Guards49 } = await import("@xeno-js/shared");
3428
+ if (!Guards49.isDefined(opts.token)) {
3429
+ throw new Error("HttpConfig.token is required and must be defined.");
3421
3430
  }
3422
- const { CompositePipeline: CompositePipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
3423
- container.addSingleton(TOKENS5.COMMAND_PIPELINES_BEHAVIOR, () => {
3424
- return new CompositePipeline2(commandPipelines);
3431
+ container.addSingleton(opts.token, () => {
3432
+ const factory = new NodeAxiosFactory2();
3433
+ const instance = factory.create(opts.client);
3434
+ if (!Guards49.hasMethod(instance, "get") || !Guards49.hasMethod(instance, "post") || !Guards49.hasMethod(instance, "put") || !Guards49.hasMethod(instance, "patch") || !Guards49.hasMethod(instance, "delete")) {
3435
+ throw new Error(
3436
+ "The created HTTP client instance does not implement the required methods of IHttpClient."
3437
+ );
3438
+ }
3439
+ return instance;
3425
3440
  });
3426
- container.addSingleton(TOKENS5.QUERY_PIPELINES_BEHAVIOR, () => {
3427
- return new CompositePipeline2(queryPipelines);
3441
+ },
3442
+ /**
3443
+ * @description Utility function to add resilience features to the service container. It takes a ResilienceConfig object that specifies whether resilience features are enabled and provides the necessary settings for implementing resilience strategies such as retries, circuit breakers, and timeouts. If resilience is enabled, it registers a singleton factory in the service container that creates an instance of the resilience client based on the provided configuration.
3444
+ * @param container - The service container to register the resilience client with.
3445
+ * @param opts - The ResilienceConfig options that determine whether resilience features are enabled and provide the necessary settings for implementing resilience strategies.
3446
+ *
3447
+ * @author Xeno
3448
+ * @version 1.0.0
3449
+ * @since 2025-09-30
3450
+ * @link https://github.com/xeno-js/xeno-js
3451
+ */
3452
+ async addResilience(container, opts) {
3453
+ const { TOKENS: TOKENS5 } = await import("@xeno-js/shared");
3454
+ const { CockatielResilienceFactory: CockatielResilienceFactory2 } = await Promise.resolve().then(() => (init_factories(), factories_exports));
3455
+ container.addSingleton(TOKENS5.RESILIENCE_CLIENT, () => {
3456
+ const factory = new CockatielResilienceFactory2();
3457
+ return factory.create(opts);
3428
3458
  });
3429
3459
  }
3460
+ });
3461
+ }
3462
+ });
3463
+
3464
+ // src/infrastructure/modules/http-core.module.ts
3465
+ var http_core_module_exports = {};
3466
+ __export(http_core_module_exports, {
3467
+ HttpCoreModule: () => HttpCoreModule
3468
+ });
3469
+ var HttpCoreModule;
3470
+ var init_http_core_module = __esm({
3471
+ "src/infrastructure/modules/http-core.module.ts"() {
3472
+ "use strict";
3473
+ HttpCoreModule = class {
3474
+ async configure(container, opts) {
3475
+ const { HttpUtils: HttpUtils2 } = await Promise.resolve().then(() => (init_http_utils(), http_utils_exports));
3476
+ await HttpUtils2.addAxios(container, opts.http);
3477
+ await HttpUtils2.addResilience(container, opts.resilience);
3478
+ }
3430
3479
  };
3431
3480
  }
3432
3481
  });
@@ -4192,8 +4241,30 @@ var init_presentation = __esm({
4192
4241
  }
4193
4242
  });
4194
4243
 
4244
+ // src/infrastructure/cache/inmemory.cache.ts
4245
+ var inmemory_cache_exports = {};
4246
+ __export(inmemory_cache_exports, {
4247
+ InMemoryCacheExtended: () => InMemoryCacheExtended
4248
+ });
4249
+ import { Guards as Guards43, InMemoryCache } from "@xeno-js/shared";
4250
+ var InMemoryCacheExtended;
4251
+ var init_inmemory_cache = __esm({
4252
+ "src/infrastructure/cache/inmemory.cache.ts"() {
4253
+ "use strict";
4254
+ InMemoryCacheExtended = class extends InMemoryCache {
4255
+ async increment(key, ttlSeconds) {
4256
+ const current = await this.get(key) ?? 0;
4257
+ const next = Number(current) + 1;
4258
+ const ttl = Guards43.isDefined(ttlSeconds) ? Number(ttlSeconds) : 60;
4259
+ await this.set(key, next, ttl);
4260
+ return next;
4261
+ }
4262
+ };
4263
+ }
4264
+ });
4265
+
4195
4266
  // src/infrastructure/cache/rate-limit-key-builder.cache.ts
4196
- import { Guards as Guards43 } from "@xeno-js/shared";
4267
+ import { Guards as Guards44 } from "@xeno-js/shared";
4197
4268
  var RateLimitKeyBuilder;
4198
4269
  var init_rate_limit_key_builder_cache = __esm({
4199
4270
  "src/infrastructure/cache/rate-limit-key-builder.cache.ts"() {
@@ -4208,12 +4279,12 @@ var init_rate_limit_key_builder_cache = __esm({
4208
4279
  const tenantId = ctx?.identity?.tenantId;
4209
4280
  const userId = ctx?.identity?.userId;
4210
4281
  const clientIp = ctx?.network?.clientIp;
4211
- if (!Guards43.isNullOrEmpty(tenantId) && !Guards43.isNullOrEmpty(userId))
4282
+ if (!Guards44.isNullOrEmpty(tenantId) && !Guards44.isNullOrEmpty(userId))
4212
4283
  return `ratelimit:tenant:${tenantId}:user:${userId}:${resource}`;
4213
- if (!Guards43.isNullOrEmpty(tenantId) && !Guards43.isNullOrEmpty(clientIp))
4284
+ if (!Guards44.isNullOrEmpty(tenantId) && !Guards44.isNullOrEmpty(clientIp))
4214
4285
  return `ratelimit:tenant:${tenantId}:ip:${clientIp}:${resource}`;
4215
- if (!Guards43.isNullOrEmpty(userId)) return `ratelimit:user:${userId}:${resource}`;
4216
- if (!Guards43.isNullOrEmpty(clientIp)) return `ratelimit:ip:${clientIp}:${resource}`;
4286
+ if (!Guards44.isNullOrEmpty(userId)) return `ratelimit:user:${userId}:${resource}`;
4287
+ if (!Guards44.isNullOrEmpty(clientIp)) return `ratelimit:ip:${clientIp}:${resource}`;
4217
4288
  return void 0;
4218
4289
  }
4219
4290
  };
@@ -4247,7 +4318,7 @@ var init_middleware_module = __esm({
4247
4318
  "use strict";
4248
4319
  MiddlewareModule = class {
4249
4320
  async configure(container, opts) {
4250
- const { Guards: Guards47, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
4321
+ const { Guards: Guards49, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
4251
4322
  const { HttpCookieExtractor: HttpCookieExtractor2 } = await Promise.resolve().then(() => (init_services(), services_exports));
4252
4323
  const { HttpHeaderExtractor: HttpHeaderExtractor2 } = await Promise.resolve().then(() => (init_services(), services_exports));
4253
4324
  const tokenExtractor = await this._getTokenExtractor(
@@ -4277,7 +4348,7 @@ var init_middleware_module = __esm({
4277
4348
  logger
4278
4349
  )
4279
4350
  );
4280
- if (!Guards47.isNullOrEmpty(opts.allowOrigins)) {
4351
+ if (!Guards49.isNullOrEmpty(opts.allowOrigins)) {
4281
4352
  if (opts.withCredentials && opts.allowOrigins.includes("*"))
4282
4353
  throw new Error(
4283
4354
  "Wildcard CORS origin is not allowed when withCredentials is set to true in addHttpCore"
@@ -4303,7 +4374,7 @@ var init_middleware_module = __esm({
4303
4374
  const { CORSMiddleware: CORSMiddleware2 } = await Promise.resolve().then(() => (init_presentation(), presentation_exports));
4304
4375
  middlewares.push(new CORSMiddleware2(requestContext, withCredentials));
4305
4376
  }
4306
- if (Guards47.isDefined(opts.routeRegistry)) {
4377
+ if (Guards49.isDefined(opts.routeRegistry)) {
4307
4378
  const { MethodCheckMiddleware: MethodCheckMiddleware2 } = await Promise.resolve().then(() => (init_presentation(), presentation_exports));
4308
4379
  middlewares.push(new MethodCheckMiddleware2(requestContext, allowMethod));
4309
4380
  }
@@ -4330,13 +4401,13 @@ var init_middleware_module = __esm({
4330
4401
  )
4331
4402
  );
4332
4403
  }
4333
- if (Guards47.isDefined(opts.rateLimite.maxRequests) || Guards47.isDefined(opts.rateLimite.windowSeconds)) {
4404
+ if (Guards49.isDefined(opts.rateLimite.maxRequests) || Guards49.isDefined(opts.rateLimite.windowSeconds)) {
4334
4405
  const maxRequests = opts.rateLimite.maxRequests ?? 30;
4335
- Guards47.throwIfNegative(maxRequests, "MaxRequests must be positive");
4336
- Guards47.throwIfNotInteger(maxRequests, "MaxRequests must be an integer");
4406
+ Guards49.throwIfNegative(maxRequests, "MaxRequests must be positive");
4407
+ Guards49.throwIfNotInteger(maxRequests, "MaxRequests must be an integer");
4337
4408
  const windowSeconds = opts.rateLimite.windowSeconds ?? 30;
4338
- Guards47.throwIfNegative(windowSeconds, "WindowSeconds must be positive");
4339
- Guards47.throwIfNotInteger(windowSeconds, "WindowSeconds must be an integer");
4409
+ Guards49.throwIfNegative(windowSeconds, "WindowSeconds must be positive");
4410
+ Guards49.throwIfNotInteger(windowSeconds, "WindowSeconds must be an integer");
4340
4411
  const { RateLimitKeyBuilder: RateLimitKeyBuilder2 } = await Promise.resolve().then(() => (init_cache(), cache_exports));
4341
4412
  const { RateLimitMiddleware: RateLimitMiddleware2 } = await Promise.resolve().then(() => (init_presentation(), presentation_exports));
4342
4413
  middlewares.push(
@@ -4349,7 +4420,7 @@ var init_middleware_module = __esm({
4349
4420
  )
4350
4421
  );
4351
4422
  }
4352
- if (Guards47.isDefined(opts.csrf)) {
4423
+ if (Guards49.isDefined(opts.csrf)) {
4353
4424
  const csrf = opts.csrf;
4354
4425
  const { EdgeCryptoService: EdgeCryptoService2 } = await Promise.resolve().then(() => (init_services(), services_exports));
4355
4426
  container.addSingleton("CRYPTO_SERVICE", () => new EdgeCryptoService2());
@@ -4374,8 +4445,8 @@ var init_middleware_module = __esm({
4374
4445
  });
4375
4446
  }
4376
4447
  async _getTokenExtractor(isSSR, cookieName, customTokenExtractor) {
4377
- const { Guards: Guards47 } = await import("@xeno-js/shared");
4378
- if (Guards47.isDefined(customTokenExtractor)) return customTokenExtractor();
4448
+ const { Guards: Guards49 } = await import("@xeno-js/shared");
4449
+ if (Guards49.isDefined(customTokenExtractor)) return customTokenExtractor();
4379
4450
  if (isSSR) {
4380
4451
  const { SupabaseSsrTokenExtractor: SupabaseSsrTokenExtractor2 } = await Promise.resolve().then(() => (init_services(), services_exports));
4381
4452
  return new SupabaseSsrTokenExtractor2();
@@ -4385,8 +4456,8 @@ var init_middleware_module = __esm({
4385
4456
  }
4386
4457
  }
4387
4458
  async _getAllowMethod(configure, opts) {
4388
- const { Guards: Guards47 } = await import("@xeno-js/shared");
4389
- if (!configure || !Guards47.isDefined(opts)) return void 0;
4459
+ const { Guards: Guards49 } = await import("@xeno-js/shared");
4460
+ if (!configure || !Guards49.isDefined(opts)) return void 0;
4390
4461
  const { AllowMethodFactory: AllowMethodFactory2 } = await Promise.resolve().then(() => (init_factories(), factories_exports));
4391
4462
  return new AllowMethodFactory2().create(opts);
4392
4463
  }
@@ -4394,37 +4465,203 @@ var init_middleware_module = __esm({
4394
4465
  }
4395
4466
  });
4396
4467
 
4397
- // src/infrastructure/modules/context.module.ts
4398
- var context_module_exports = {};
4399
- __export(context_module_exports, {
4400
- ContextModule: () => ContextModule
4468
+ // src/infrastructure/modules/utils/cache.utils.ts
4469
+ var cache_utils_exports = {};
4470
+ __export(cache_utils_exports, {
4471
+ CacheUtils: () => CacheUtils
4401
4472
  });
4402
- var ContextModule;
4403
- var init_context_module = __esm({
4404
- "src/infrastructure/modules/context.module.ts"() {
4473
+ var CacheUtils;
4474
+ var init_cache_utils = __esm({
4475
+ "src/infrastructure/modules/utils/cache.utils.ts"() {
4405
4476
  "use strict";
4406
- ContextModule = class {
4407
- async configure(container) {
4408
- const { TOKENS: TOKENS5 } = await import("@xeno-js/shared");
4409
- const { ServiceScopeFactory: ServiceScopeFactory2 } = await Promise.resolve().then(() => (init_service_scope_factory(), service_scope_factory_exports));
4410
- const { NodeRequestContextFactory: NodeRequestContextFactory2 } = await Promise.resolve().then(() => (init_request_context_factory(), request_context_factory_exports));
4411
- const requestContext = new NodeRequestContextFactory2(
4412
- new ServiceScopeFactory2(container)
4413
- ).create();
4414
- container.addSingleton(TOKENS5.REQUEST_CONTEXT, () => requestContext);
4415
- container.addSingleton(TOKENS5.CONTEXT_ACCESSOR, () => requestContext);
4416
- container.addSingleton(TOKENS5.IDENTITY_ACCESSOR, () => requestContext);
4417
- container.addSingleton(TOKENS5.SERVICE_SCOPE_ACCESSOR, () => requestContext);
4418
- container.addSingleton(TOKENS5.NETWORK_CONTEXT_ACCESSOR, () => requestContext);
4419
- const { UserContextFactory: UserContextFactory2 } = await Promise.resolve().then(() => (init_user_context_factory(), user_context_factory_exports));
4420
- container.addSingleton("USER_CONTEXT_FACTORY", () => {
4421
- return new UserContextFactory2(requestContext);
4422
- });
4477
+ CacheUtils = Object.freeze({
4478
+ /**
4479
+ * @description Checks if the provided cache configuration requires any cache strategies.
4480
+ * @param container The service container to which the cache strategies will be added.
4481
+ * @param opts The cache configuration options.
4482
+ * @returns True if any cache strategies are required, false otherwise.
4483
+ *
4484
+ * @author Xeno
4485
+ * @version 1.0.0
4486
+ * @since 2025-09-30
4487
+ * @link https://github.com/xeno-js/xeno-js
4488
+ */
4489
+ async addCache(container, opts) {
4490
+ const { Guards: Guards49, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
4491
+ if (!opts.inMemory && !Guards49.isDefined(opts.redis)) {
4492
+ throw new Error(
4493
+ "No cache strategies are configured. Please provide at least one cache strategy."
4494
+ );
4495
+ }
4496
+ const { CacheKeyBuilder } = await import("@xeno-js/shared");
4497
+ container.addSingleton(
4498
+ TOKENS5.CACHE_KEY_BUILDER,
4499
+ (c) => new CacheKeyBuilder(c.resolve(TOKENS5.IDENTITY_ACCESSOR))
4500
+ );
4501
+ if (opts.inMemory || !Guards49.isDefined(opts.redis)) {
4502
+ const { InMemoryCacheExtended: InMemoryCacheExtended2 } = await Promise.resolve().then(() => (init_inmemory_cache(), inmemory_cache_exports));
4503
+ container.addSingleton(TOKENS5.CACHE, () => new InMemoryCacheExtended2());
4504
+ return;
4505
+ }
4506
+ if (Guards49.isDefined(opts.redis)) {
4507
+ const { RedisCacheFactory: RedisCacheFactory2 } = await Promise.resolve().then(() => (init_redis_cache_factory(), redis_cache_factory_exports));
4508
+ container.addSingleton(TOKENS5.CACHE, () => {
4509
+ const config = opts.redis;
4510
+ return new RedisCacheFactory2().create(config);
4511
+ });
4512
+ }
4513
+ }
4514
+ });
4515
+ }
4516
+ });
4517
+
4518
+ // src/infrastructure/loggers/console.logger.ts
4519
+ var console_logger_exports = {};
4520
+ __export(console_logger_exports, {
4521
+ ConsoleLogger: () => ConsoleLogger
4522
+ });
4523
+ import { Guards as Guards45, LOG_LEVEL as LOG_LEVEL5 } from "@xeno-js/shared";
4524
+ var ConsoleLogger;
4525
+ var init_console_logger = __esm({
4526
+ "src/infrastructure/loggers/console.logger.ts"() {
4527
+ "use strict";
4528
+ ConsoleLogger = class {
4529
+ /**
4530
+ * Constructs a new instance of the ConsoleLogger class, which takes an optional minimum log level. The minimum log level determines the threshold for logging messages, where messages with a log level below the specified minimum will be ignored.
4531
+ * @param _minLevel The minimum log level for logging messages. Messages with a log level below this threshold will not be logged. Default is LOG_LEVEL.DEBUG.
4532
+
4533
+ *
4534
+ * @author Xeno
4535
+ * @version 1.0.0
4536
+ * @since 2025-09-30
4537
+ * @link https://github.com/xeno-js/xeno-js
4538
+ */
4539
+ constructor(_minLevel = LOG_LEVEL5.DEBUG) {
4540
+ this._minLevel = _minLevel;
4541
+ }
4542
+ _minLevel;
4543
+ track(level, message, context, error = void 0) {
4544
+ if (level < this._minLevel) return;
4545
+ const logMessage = `[${level}] ${message}`;
4546
+ const payload = Guards45.isDefined(error) ? { ...context, error } : context;
4547
+ switch (level) {
4548
+ case LOG_LEVEL5.ERROR:
4549
+ console.error(logMessage, payload ?? {});
4550
+ break;
4551
+ case LOG_LEVEL5.WARN:
4552
+ console.warn(logMessage, payload ?? {});
4553
+ break;
4554
+ case LOG_LEVEL5.DEBUG:
4555
+ console.debug(logMessage, payload ?? {});
4556
+ break;
4557
+ default:
4558
+ console.info(logMessage, payload ?? {});
4559
+ break;
4560
+ }
4423
4561
  }
4424
4562
  };
4425
4563
  }
4426
4564
  });
4427
4565
 
4566
+ // src/infrastructure/modules/utils/logger.utils.ts
4567
+ var logger_utils_exports = {};
4568
+ __export(logger_utils_exports, {
4569
+ LoggerUtils: () => LoggerUtils
4570
+ });
4571
+ var LoggerUtils;
4572
+ var init_logger_utils = __esm({
4573
+ "src/infrastructure/modules/utils/logger.utils.ts"() {
4574
+ "use strict";
4575
+ LoggerUtils = Object.freeze({
4576
+ /**
4577
+ * @description Configures and registers the logging services in the dependency injection container based on the provided LoggerConfig options. It dynamically imports the necessary logger implementations (e.g., ConsoleLogger, SentryLogger, PinoLogger) and registers them with the container, allowing for flexible and modular logging configuration in the application.
4578
+ *
4579
+ * @param container - The service container to register logging services with.
4580
+ * @param opts - The LoggerConfig options to determine which loggers to enable and their configurations.
4581
+
4582
+ *
4583
+ * @author Xeno
4584
+ * @version 1.0.0
4585
+ * @since 2025-09-30
4586
+ * @link https://github.com/xeno-js/xeno-js
4587
+ */
4588
+ async addLogger(container, opts) {
4589
+ const loggerDependencies = [];
4590
+ const { Guards: Guards49, LOG_LEVEL: LOG_LEVEL7, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
4591
+ if (!Guards49.isDefined(opts) || opts.console) {
4592
+ const { ConsoleLogger: ConsoleLogger2 } = await Promise.resolve().then(() => (init_console_logger(), console_logger_exports));
4593
+ loggerDependencies.push(new ConsoleLogger2(opts?.level));
4594
+ }
4595
+ if (Guards49.isDefined(opts)) {
4596
+ if (Guards49.isDefined(opts.sentry.config)) {
4597
+ const { SentryLoggerFactory: SentryLoggerFactory2 } = await Promise.resolve().then(() => (init_sentry_logger_factory(), sentry_logger_factory_exports));
4598
+ loggerDependencies.push(new SentryLoggerFactory2().create(opts));
4599
+ }
4600
+ if (Guards49.isDefined(opts.pino.config)) {
4601
+ const { PinoLoggerFactory: PinoLoggerFactory2 } = await Promise.resolve().then(() => (init_pino_logger_factory(), pino_logger_factory_exports));
4602
+ loggerDependencies.push(new PinoLoggerFactory2().create(opts));
4603
+ }
4604
+ if (!Guards49.isNullOrEmpty(opts.customLoggers)) {
4605
+ const customLoggers = opts.customLoggers;
4606
+ customLoggers.forEach((fn) => {
4607
+ if (Guards49.isDefined(fn)) loggerDependencies.push(fn(container));
4608
+ });
4609
+ }
4610
+ }
4611
+ const { BaseLogger } = await import("@xeno-js/shared");
4612
+ container.addSingleton(TOKENS5.LOGGER, (c) => {
4613
+ const context = c.resolve(TOKENS5.CONTEXT_ACCESSOR);
4614
+ return new BaseLogger(context, opts?.level ?? LOG_LEVEL7.DEBUG, loggerDependencies);
4615
+ });
4616
+ }
4617
+ });
4618
+ }
4619
+ });
4620
+
4621
+ // src/infrastructure/modules/utils/index.ts
4622
+ var init_utils2 = __esm({
4623
+ "src/infrastructure/modules/utils/index.ts"() {
4624
+ "use strict";
4625
+ init_auth_utils();
4626
+ init_cache_utils();
4627
+ init_db_utils();
4628
+ init_http_utils();
4629
+ init_logger_utils();
4630
+ init_pipeline_utils();
4631
+ init_validation_utils();
4632
+ }
4633
+ });
4634
+
4635
+ // src/infrastructure/modules/index.ts
4636
+ var modules_exports = {};
4637
+ __export(modules_exports, {
4638
+ AuthUtils: () => AuthUtils,
4639
+ CacheUtils: () => CacheUtils,
4640
+ ContextModule: () => ContextModule,
4641
+ CqrsModule: () => CqrsModule,
4642
+ DbModule: () => DbModule,
4643
+ DbUtils: () => DbUtils,
4644
+ HttpAdapterModule: () => HttpAdapterModule,
4645
+ HttpCoreModule: () => HttpCoreModule,
4646
+ HttpUtils: () => HttpUtils,
4647
+ LoggerUtils: () => LoggerUtils,
4648
+ MiddlewareModule: () => MiddlewareModule,
4649
+ PipelineUtils: () => PipelineUtils,
4650
+ ValidationUtils: () => ValidationUtils
4651
+ });
4652
+ var init_modules = __esm({
4653
+ "src/infrastructure/modules/index.ts"() {
4654
+ "use strict";
4655
+ init_context_module();
4656
+ init_cqrs_module();
4657
+ init_db_module();
4658
+ init_http_adapter_module();
4659
+ init_http_core_module();
4660
+ init_middleware_module();
4661
+ init_utils2();
4662
+ }
4663
+ });
4664
+
4428
4665
  // src/index.ts
4429
4666
  var index_exports = {};
4430
4667
  __export(index_exports, {
@@ -4444,7 +4681,7 @@ __export(index_exports, {
4444
4681
  init_application();
4445
4682
 
4446
4683
  // src/infrastructure/builder/app.builder.ts
4447
- import { Guards as Guards44, LOG_LEVEL as LOG_LEVEL6, TOKENS as TOKENS4 } from "@xeno-js/shared";
4684
+ import { Guards as Guards46, LOG_LEVEL as LOG_LEVEL6, TOKENS as TOKENS4 } from "@xeno-js/shared";
4448
4685
 
4449
4686
  // src/infrastructure/configuration/configuration.ts
4450
4687
  import { Guards as Guards13 } from "@xeno-js/shared";
@@ -4735,6 +4972,12 @@ var AppBuilder = class {
4735
4972
  // --- Module Configurations ---
4736
4973
  _modules = [];
4737
4974
  // --- Specific Configurations ---
4975
+ _adapterConfig = {
4976
+ native: true,
4977
+ vercel: false,
4978
+ fastify: false,
4979
+ custom: void 0
4980
+ };
4738
4981
  _pipelineConfig = {
4739
4982
  performance: { thresholdMs: 500 },
4740
4983
  authorization: {
@@ -4818,9 +5061,24 @@ var AppBuilder = class {
4818
5061
  _isDbContextModuleQueued = false;
4819
5062
  _isConcurrencyServiceQueued = false;
4820
5063
  _isCacheModuleQueued = false;
5064
+ _isAdapterModuleQueued = false;
4821
5065
  // ─────────────────────────────────────────────────────────────────────────────
4822
5066
  // Application Modules Configuration
4823
5067
  // ─────────────────────────────────────────────────────────────────────────────
5068
+ addAdapter(setupAction) {
5069
+ if (this._isAdapterModuleQueued) return this;
5070
+ setupAction(this._adapterConfig, this._configuration);
5071
+ this._isAdapterModuleQueued = true;
5072
+ this._modules.push({
5073
+ priority: 50,
5074
+ name: "AdapterModule",
5075
+ action: async () => {
5076
+ const { HttpAdapterModule: HttpAdapterModule2 } = await Promise.resolve().then(() => (init_modules(), modules_exports));
5077
+ await new HttpAdapterModule2().configure(this._container, this._adapterConfig);
5078
+ }
5079
+ });
5080
+ return this;
5081
+ }
4824
5082
  /**
4825
5083
  * @description Enables the use of middlewares in the application. Middlewares can be used for cross-cutting concerns such as logging, authentication, and request/response manipulation.
4826
5084
  * @returns The current instance of AppBuilder for method chaining.
@@ -4861,7 +5119,7 @@ var AppBuilder = class {
4861
5119
  * @link https://github.com/xeno-js/xeno-js
4862
5120
  */
4863
5121
  addLogger(setupAction) {
4864
- if (Guards44.isDefined(setupAction)) setupAction(this._loggerConfig, this._configuration);
5122
+ if (Guards46.isDefined(setupAction)) setupAction(this._loggerConfig, this._configuration);
4865
5123
  if (this._isLoggerModuleQueued) return this;
4866
5124
  this._isLoggerModuleQueued = true;
4867
5125
  this._modules.push({
@@ -4886,7 +5144,7 @@ var AppBuilder = class {
4886
5144
  * @link https://github.com/xeno-js/xeno-js
4887
5145
  */
4888
5146
  addCache(setupAction) {
4889
- if (Guards44.isDefined(setupAction)) setupAction(this._config, this._configuration);
5147
+ if (Guards46.isDefined(setupAction)) setupAction(this._config, this._configuration);
4890
5148
  if (this._isCacheModuleQueued) return this;
4891
5149
  this._isCacheModuleQueued = true;
4892
5150
  this._modules.push({
@@ -4989,7 +5247,7 @@ var AppBuilder = class {
4989
5247
  * @link https://github.com/xeno-js/xeno-js
4990
5248
  */
4991
5249
  addPipeline(setupAction) {
4992
- if (Guards44.isDefined(setupAction)) {
5250
+ if (Guards46.isDefined(setupAction)) {
4993
5251
  setupAction(this._pipelineConfig, this._configuration);
4994
5252
  }
4995
5253
  this._queuePipelineModule();
@@ -5110,7 +5368,7 @@ var AppBuilder = class {
5110
5368
  console.error(`\u{1F449} Module: **${queued.name}**`);
5111
5369
  console.error(`\u{1F4DD} Reason: ${errorMessage}
5112
5370
  `);
5113
- if (error instanceof Error && Guards44.isDefined(error.stack)) {
5371
+ if (error instanceof Error && Guards46.isDefined(error.stack)) {
5114
5372
  console.error(error.stack);
5115
5373
  }
5116
5374
  throw new Error(`Bootstrap failed at [${queued.name}]: ${errorMessage}`, { cause: error });
@@ -5249,25 +5507,12 @@ init_console_logger();
5249
5507
  init_pino_logger();
5250
5508
  init_sentry_logger();
5251
5509
 
5252
- // src/infrastructure/modules/index.ts
5253
- init_context_module();
5254
- init_cqrs_module();
5255
- init_db_module();
5256
- init_http_core_module();
5257
- init_middleware_module();
5258
-
5259
- // src/infrastructure/modules/utils/index.ts
5260
- init_auth_utils();
5261
- init_cache_utils();
5262
- init_db_utils();
5263
- init_http_utils();
5264
- init_logger_utils();
5265
- init_pipeline_utils();
5266
- init_validation_utils();
5510
+ // src/infrastructure/index.ts
5511
+ init_modules();
5267
5512
 
5268
5513
  // src/infrastructure/repositories/read-dao.ts
5269
5514
  import { AppError as AppError16, Result as Result17 } from "@xeno-js/shared";
5270
- import { Guards as Guards45 } from "@xeno-js/shared";
5515
+ import { Guards as Guards47 } from "@xeno-js/shared";
5271
5516
  var ReadDao = class {
5272
5517
  /**
5273
5518
  * Constructs a new ReadDao instance.
@@ -5289,7 +5534,7 @@ var ReadDao = class {
5289
5534
  async findById(id, ctx, signal) {
5290
5535
  AppError16.throwIfAborted(signal, "ReadDao.findById");
5291
5536
  const result = await this._dataSource.findById(id, ctx, signal);
5292
- if (Guards45.isNullOrEmpty(result)) return Result17.ok();
5537
+ if (Guards47.isNullOrEmpty(result)) return Result17.ok();
5293
5538
  const entity = this._mapper.toEntity(result);
5294
5539
  return Result17.ok(entity);
5295
5540
  }
@@ -5303,7 +5548,7 @@ var ReadDao = class {
5303
5548
 
5304
5549
  // src/infrastructure/repositories/repository.ts
5305
5550
  import { AppError as AppError17, Result as Result18 } from "@xeno-js/shared";
5306
- import { Guards as Guards46 } from "@xeno-js/shared";
5551
+ import { Guards as Guards48 } from "@xeno-js/shared";
5307
5552
  var Repository = class {
5308
5553
  /**
5309
5554
  * Constructs a new Repository instance.
@@ -5325,7 +5570,7 @@ var Repository = class {
5325
5570
  async findById(id, ctx, signal) {
5326
5571
  AppError17.throwIfAborted(signal, "Repository.findById");
5327
5572
  const result = await this._dataSource.findById(id, ctx, signal);
5328
- if (Guards46.isNullOrEmpty(result)) return Result18.ok();
5573
+ if (Guards48.isNullOrEmpty(result)) return Result18.ok();
5329
5574
  const entity = this._mapper.toEntity(result);
5330
5575
  return Result18.ok(entity);
5331
5576
  }