@xeno-js/core 2.0.2 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1240,595 +1240,572 @@ var init_application = __esm({
1240
1240
  }
1241
1241
  });
1242
1242
 
1243
- // src/infrastructure/factories/service-scope.factory.ts
1244
- var service_scope_factory_exports = {};
1245
- __export(service_scope_factory_exports, {
1246
- ServiceScopeFactory: () => ServiceScopeFactory
1247
- });
1248
- var ServiceScopeFactory;
1249
- var init_service_scope_factory = __esm({
1250
- "src/infrastructure/factories/service-scope.factory.ts"() {
1251
- "use strict";
1252
- ServiceScopeFactory = class {
1253
- constructor(_container) {
1254
- this._container = _container;
1255
- }
1256
- _container;
1257
- create() {
1258
- return this._container.createScope();
1259
- }
1260
- };
1261
- }
1262
- });
1263
-
1264
- // src/infrastructure/context/request-context.ts
1265
- var import_shared33, NodeRequestContext;
1266
- var init_request_context = __esm({
1267
- "src/infrastructure/context/request-context.ts"() {
1243
+ // src/infrastructure/http/base.http-adapter.ts
1244
+ var import_shared33, BaseHttpAdapter;
1245
+ var init_base_http_adapter = __esm({
1246
+ "src/infrastructure/http/base.http-adapter.ts"() {
1268
1247
  "use strict";
1269
1248
  import_shared33 = require("@xeno-js/shared");
1270
- NodeRequestContext = class {
1249
+ BaseHttpAdapter = class {
1271
1250
  /**
1272
- * @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.
1273
- * @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.
1274
- * @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.
1275
- *
1276
- * @author Xeno
1277
- * @version 1.0.0
1278
- * @since 2025-09-30
1279
- * @link https://github.com/xeno-js/xeno-js
1251
+ * @description Parse the URL from the request.
1252
+ * @param rawUrl The raw URL.
1253
+ * @param headers The headers.
1254
+ * @param queryParams The query parameters.
1255
+ * @returns The parsed URL.
1280
1256
  */
1281
- constructor(_storage, _factoryScope) {
1282
- this._storage = _storage;
1283
- this._factoryScope = _factoryScope;
1284
- }
1285
- _storage;
1286
- _factoryScope;
1287
- async runAsync(context, fn) {
1288
- const scope = this._factoryScope.create();
1289
- try {
1290
- return await this._storage.run({ context, scope }, fn);
1291
- } finally {
1292
- await scope.dispose();
1257
+ parseUrl(rawUrl = "/", headers, queryParams) {
1258
+ const protocol = import_shared33.StringHelper.getSingleValue(headers["x-forwarded-proto"]) ?? "https";
1259
+ const host = import_shared33.StringHelper.safeStringify(headers["host"]) ?? "localhost";
1260
+ const cleanHost = host.replace(/['"]/g, "");
1261
+ const url = new URL(rawUrl, `${protocol}://${cleanHost}`);
1262
+ if (!import_shared33.Guards.isNullOrEmpty(queryParams)) {
1263
+ for (const [key, value] of Object.entries(queryParams)) {
1264
+ if (import_shared33.Guards.isArray(value)) {
1265
+ value.forEach((v) => url.searchParams.append(key, String(v)));
1266
+ } else if (import_shared33.Guards.isDefined(value)) {
1267
+ url.searchParams.set(key, String(value));
1268
+ }
1269
+ }
1293
1270
  }
1271
+ return url;
1294
1272
  }
1295
- updateIdentity(identity) {
1296
- const store = this._storage.getStore();
1297
- if (import_shared33.Guards.isDefined(store) && import_shared33.Guards.isDefined(store.context)) {
1298
- store.context = Object.freeze({
1299
- ...store.context,
1300
- identity: Object.freeze(identity)
1301
- });
1273
+ /**
1274
+ * @description Parses the headers.
1275
+ * @param rawHeaders The raw headers.
1276
+ * @returns The parsed headers.
1277
+ */
1278
+ parseHeaders(rawHeaders) {
1279
+ const headers = new Headers();
1280
+ for (const [key, value] of Object.entries(rawHeaders)) {
1281
+ if (import_shared33.Guards.isDefined(value)) {
1282
+ if (import_shared33.Guards.isArray(value)) {
1283
+ value.forEach((v) => headers.append(key, String(v)));
1284
+ } else {
1285
+ headers.set(key, String(value));
1286
+ }
1287
+ }
1302
1288
  }
1289
+ return headers;
1303
1290
  }
1304
- getContext() {
1305
- const store = this._storage.getStore();
1306
- if (!import_shared33.Guards.isDefined(store)) return void 0;
1307
- const context = store.context;
1308
- return Object.freeze(context);
1309
- }
1310
- getIdentity() {
1311
- const store = this._storage.getStore();
1312
- if (!import_shared33.Guards.isDefined(store)) return void 0;
1313
- return Object.freeze(store.context?.identity);
1314
- }
1315
- getScope() {
1316
- const store = this._storage.getStore();
1317
- if (!import_shared33.Guards.isDefined(store)) return void 0;
1318
- return store.scope;
1319
- }
1320
- getNetworkContext() {
1321
- const store = this._storage.getStore();
1322
- if (!import_shared33.Guards.isDefined(store)) return void 0;
1323
- return Object.freeze(store.context?.network);
1324
- }
1325
- };
1326
- }
1327
- });
1328
-
1329
- // src/infrastructure/factories/request-context.factory.ts
1330
- var request_context_factory_exports = {};
1331
- __export(request_context_factory_exports, {
1332
- NodeRequestContextFactory: () => NodeRequestContextFactory
1333
- });
1334
- var import_node_async_hooks2, NodeRequestContextFactory;
1335
- var init_request_context_factory = __esm({
1336
- "src/infrastructure/factories/request-context.factory.ts"() {
1337
- "use strict";
1338
- import_node_async_hooks2 = require("async_hooks");
1339
- init_request_context();
1340
- NodeRequestContextFactory = class {
1341
- constructor(_factoryScope) {
1342
- this._factoryScope = _factoryScope;
1291
+ /**
1292
+ * @description Parses the body.
1293
+ * @param method The method.
1294
+ * @param rawBody The raw body.
1295
+ * @returns The parsed body.
1296
+ */
1297
+ parseBody(method, rawBody) {
1298
+ if (!import_shared33.Guards.isDefined(method) || !["POST", "PUT", "PATCH", "DELETE"].includes(method.toUpperCase()) || !import_shared33.Guards.isDefined(rawBody))
1299
+ return void 0;
1300
+ if (import_shared33.Guards.isObject(rawBody)) return JSON.stringify(rawBody);
1301
+ if (import_shared33.Guards.isString(rawBody) || rawBody instanceof Blob || rawBody instanceof ArrayBuffer || ArrayBuffer.isView(rawBody) || rawBody instanceof URLSearchParams || rawBody instanceof FormData)
1302
+ return rawBody;
1303
+ return String(rawBody);
1343
1304
  }
1344
- _factoryScope;
1345
- _store = new import_node_async_hooks2.AsyncLocalStorage();
1346
- create() {
1347
- return new NodeRequestContext(this._store, this._factoryScope);
1305
+ /**
1306
+ * @description Creates the XenoWebTransport.
1307
+ * @param url The url.
1308
+ * @param method The method.
1309
+ * @param headers The headers.
1310
+ * @param body The body.
1311
+ * @returns The XenoWebTransport.
1312
+ */
1313
+ createXenoWebTransport(url, method = "GET", headers, body = void 0, res = void 0) {
1314
+ const init2 = {
1315
+ method: method.toUpperCase(),
1316
+ headers
1317
+ };
1318
+ const parsedBody = this.parseBody(method, body);
1319
+ if (import_shared33.Guards.isDefined(parsedBody)) {
1320
+ init2.body = parsedBody;
1321
+ init2.duplex = "half";
1322
+ }
1323
+ const extendedRequest = new Request(url, init2);
1324
+ extendedRequest.path = url.pathname;
1325
+ const webResponse = new Response();
1326
+ if (import_shared33.Guards.isDefined(res)) {
1327
+ const originalAppend = webResponse.headers.append.bind(webResponse.headers);
1328
+ const originalSet = webResponse.headers.set.bind(webResponse.headers);
1329
+ const originalDelete = webResponse.headers.delete.bind(webResponse.headers);
1330
+ webResponse.headers.append = (name, value) => {
1331
+ originalAppend(name, value);
1332
+ this.handleHeaderChange(res, name, value, "append");
1333
+ };
1334
+ webResponse.headers.set = (name, value) => {
1335
+ originalSet(name, value);
1336
+ this.handleHeaderChange(res, name, value, "set");
1337
+ };
1338
+ webResponse.headers.delete = (name) => {
1339
+ originalDelete(name);
1340
+ this.handleHeaderChange(res, name, "", "delete");
1341
+ };
1342
+ }
1343
+ return {
1344
+ request: extendedRequest,
1345
+ response: webResponse
1346
+ };
1348
1347
  }
1349
1348
  };
1350
1349
  }
1351
1350
  });
1352
1351
 
1353
- // src/infrastructure/factories/user-context.factory.ts
1354
- var user_context_factory_exports = {};
1355
- __export(user_context_factory_exports, {
1356
- UserContextFactory: () => UserContextFactory
1352
+ // src/infrastructure/http/vercel.http-adapter.ts
1353
+ var vercel_http_adapter_exports = {};
1354
+ __export(vercel_http_adapter_exports, {
1355
+ VercelHttpAdapter: () => VercelHttpAdapter
1357
1356
  });
1358
- var import_shared34, UserContextFactory;
1359
- var init_user_context_factory = __esm({
1360
- "src/infrastructure/factories/user-context.factory.ts"() {
1357
+ var import_shared34, VercelHttpAdapter;
1358
+ var init_vercel_http_adapter = __esm({
1359
+ "src/infrastructure/http/vercel.http-adapter.ts"() {
1361
1360
  "use strict";
1362
1361
  import_shared34 = require("@xeno-js/shared");
1363
- UserContextFactory = class {
1364
- /**
1365
- * @description Constructs an instance of UserContextFactory.
1366
- * @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.
1367
- *
1368
- * @author Xeno
1369
- * @version 1.0.0
1370
- * @since 2025-09-30
1371
- * @link https://github.com/xeno-js/xeno-js
1372
- */
1373
- constructor(_identityFactory) {
1374
- this._identityFactory = _identityFactory;
1362
+ init_base_http_adapter();
1363
+ VercelHttpAdapter = class extends BaseHttpAdapter {
1364
+ adapt(req, res) {
1365
+ const headers = this.parseHeaders(req.headers);
1366
+ const url = this.parseUrl(req.url, req.headers, req.query);
1367
+ return this.createXenoWebTransport(url, req.method, headers, req.body, res);
1375
1368
  }
1376
- _identityFactory;
1377
- create() {
1378
- const output = {
1379
- userId: void 0,
1380
- tenantId: void 0
1381
- };
1382
- const identity = this._identityFactory.getIdentity();
1383
- if (import_shared34.Guards.isDefined(identity)) {
1384
- output.userId = identity.userId;
1385
- output.tenantId = identity.tenantId;
1369
+ handleHeaderChange(res, name, value, action) {
1370
+ if (action === "delete") {
1371
+ res.removeHeader(name);
1372
+ return;
1373
+ }
1374
+ if (name.toLowerCase() === "set-cookie") {
1375
+ const existing = res.getHeader("Set-Cookie");
1376
+ let cookies = [];
1377
+ if (import_shared34.Guards.isArray(existing)) {
1378
+ cookies = existing;
1379
+ } else if (import_shared34.Guards.isString(existing)) {
1380
+ cookies = [existing];
1381
+ }
1382
+ if (action === "append") {
1383
+ cookies.push(value);
1384
+ } else {
1385
+ cookies = [value];
1386
+ }
1387
+ res.setHeader("Set-Cookie", cookies);
1388
+ } else {
1389
+ res.setHeader(name, value);
1386
1390
  }
1387
- return output;
1388
1391
  }
1389
1392
  };
1390
1393
  }
1391
1394
  });
1392
1395
 
1393
- // src/infrastructure/modules/context.module.ts
1394
- var context_module_exports = {};
1395
- __export(context_module_exports, {
1396
- ContextModule: () => ContextModule
1396
+ // src/infrastructure/http/fastify.http-adapter.ts
1397
+ var fastify_http_adapter_exports = {};
1398
+ __export(fastify_http_adapter_exports, {
1399
+ FastifyHttpAdapter: () => FastifyHttpAdapter
1397
1400
  });
1398
- var ContextModule;
1399
- var init_context_module = __esm({
1400
- "src/infrastructure/modules/context.module.ts"() {
1401
+ var import_shared35, FastifyHttpAdapter;
1402
+ var init_fastify_http_adapter = __esm({
1403
+ "src/infrastructure/http/fastify.http-adapter.ts"() {
1401
1404
  "use strict";
1402
- ContextModule = class {
1403
- async configure(container) {
1404
- const { TOKENS: TOKENS5 } = await import("@xeno-js/shared");
1405
- const { ServiceScopeFactory: ServiceScopeFactory2 } = await Promise.resolve().then(() => (init_service_scope_factory(), service_scope_factory_exports));
1406
- const { NodeRequestContextFactory: NodeRequestContextFactory2 } = await Promise.resolve().then(() => (init_request_context_factory(), request_context_factory_exports));
1407
- const requestContext = new NodeRequestContextFactory2(
1408
- new ServiceScopeFactory2(container)
1409
- ).create();
1410
- container.addSingleton(TOKENS5.REQUEST_CONTEXT, () => requestContext);
1411
- container.addSingleton(TOKENS5.CONTEXT_ACCESSOR, () => requestContext);
1412
- container.addSingleton(TOKENS5.IDENTITY_ACCESSOR, () => requestContext);
1413
- container.addSingleton(TOKENS5.SERVICE_SCOPE_ACCESSOR, () => requestContext);
1414
- container.addSingleton(TOKENS5.NETWORK_CONTEXT_ACCESSOR, () => requestContext);
1415
- const { UserContextFactory: UserContextFactory2 } = await Promise.resolve().then(() => (init_user_context_factory(), user_context_factory_exports));
1416
- container.addSingleton("USER_CONTEXT_FACTORY", () => {
1417
- return new UserContextFactory2(requestContext);
1418
- });
1405
+ import_shared35 = require("@xeno-js/shared");
1406
+ init_base_http_adapter();
1407
+ FastifyHttpAdapter = class extends BaseHttpAdapter {
1408
+ adapt(req, res) {
1409
+ const headers = this.parseHeaders(req.headers);
1410
+ const url = this.parseUrl(req.url, req.headers, req.query);
1411
+ const body = req.body;
1412
+ return this.createXenoWebTransport(url, req.method, headers, body, res);
1413
+ }
1414
+ handleHeaderChange(res, name, value, action) {
1415
+ if (action === "delete") {
1416
+ res.removeHeader(name);
1417
+ return;
1418
+ }
1419
+ if (name.toLowerCase() === "set-cookie") {
1420
+ const existing = res.getHeader("set-cookie");
1421
+ let cookies = [];
1422
+ if (import_shared35.Guards.isArray(existing)) {
1423
+ cookies = existing;
1424
+ } else if (import_shared35.Guards.isString(existing)) {
1425
+ cookies = [existing];
1426
+ }
1427
+ if (action === "append") {
1428
+ cookies.push(value);
1429
+ } else {
1430
+ cookies = [value];
1431
+ }
1432
+ res.header("set-cookie", cookies);
1433
+ } else {
1434
+ res.header(name, value);
1435
+ }
1419
1436
  }
1420
1437
  };
1421
1438
  }
1422
1439
  });
1423
1440
 
1424
- // src/infrastructure/services/allow_methods/allow-method.service.ts
1425
- var import_shared35, AllowMethodRegistry;
1426
- var init_allow_method_service = __esm({
1427
- "src/infrastructure/services/allow_methods/allow-method.service.ts"() {
1441
+ // src/infrastructure/http/native.http-adapter.ts
1442
+ var native_http_adapter_exports = {};
1443
+ __export(native_http_adapter_exports, {
1444
+ NativeHttpAdapter: () => NativeHttpAdapter
1445
+ });
1446
+ var NativeHttpAdapter;
1447
+ var init_native_http_adapter = __esm({
1448
+ "src/infrastructure/http/native.http-adapter.ts"() {
1428
1449
  "use strict";
1429
- import_shared35 = require("@xeno-js/shared");
1430
- AllowMethodRegistry = class {
1431
- _staticRoutes = /* @__PURE__ */ new Map();
1432
- _dynamicRoutes = [];
1433
- add(path, methods) {
1434
- const normalizedPath = this.normalizePath(path);
1435
- if (this.isDynamicPath(normalizedPath)) {
1436
- const pattern = this.createRoutePattern(normalizedPath);
1437
- this._dynamicRoutes.push({ pattern, methods });
1438
- } else {
1439
- this._staticRoutes.set(normalizedPath, methods);
1440
- }
1441
- }
1442
- check(path, method) {
1443
- const cleanPath = this.normalizePath(path.split("?")[0].split("#")[0]);
1444
- const staticMethods = this._staticRoutes.get(cleanPath);
1445
- if (import_shared35.Guards.isDefined(staticMethods)) return staticMethods.includes(method);
1446
- for (const route of this._dynamicRoutes) {
1447
- if (route.pattern.test(cleanPath)) return route.methods.includes(method);
1448
- }
1449
- return false;
1450
- }
1451
- getMethods(path) {
1452
- const cleanPath = this.normalizePath(path.split("?")[0].split("#")[0]);
1453
- const methods = this.findMethods(cleanPath);
1454
- return import_shared35.Guards.isDefined(methods) ? methods.join(", ").toUpperCase() : "";
1455
- }
1456
- findMethods(cleanPath) {
1457
- const staticMethods = this._staticRoutes.get(cleanPath);
1458
- if (import_shared35.Guards.isDefined(staticMethods)) return staticMethods;
1459
- for (const route of this._dynamicRoutes) if (route.pattern.test(cleanPath)) return route.methods;
1460
- return void 0;
1461
- }
1462
- isDynamicPath(path) {
1463
- return path.includes(":") || path.includes("{") && path.includes("}");
1464
- }
1465
- normalizePath(path) {
1466
- const trimmed = path.trim();
1467
- const withLeadingSlash = trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
1468
- if (withLeadingSlash === "/") return "/";
1469
- return withLeadingSlash.replace(/\/+$/, "");
1450
+ init_base_http_adapter();
1451
+ NativeHttpAdapter = class extends BaseHttpAdapter {
1452
+ adapt(req, res) {
1453
+ const extendedRequest = req;
1454
+ extendedRequest.path = new URL(req.url).pathname;
1455
+ return {
1456
+ request: extendedRequest,
1457
+ response: res
1458
+ };
1470
1459
  }
1471
- createRoutePattern(path) {
1472
- const segments = path.split("/").filter(Boolean);
1473
- const regexSegments = segments.map((segment) => {
1474
- if (segment.startsWith(":") || segment.startsWith("{") && segment.endsWith("}"))
1475
- return "([^/]+)";
1476
- return segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1477
- });
1478
- return new RegExp(`^\\/${regexSegments.join("\\/")}\\/?$`);
1460
+ handleHeaderChange(_res, _name, _value, _action) {
1461
+ return;
1479
1462
  }
1480
1463
  };
1481
1464
  }
1482
1465
  });
1483
1466
 
1484
- // src/infrastructure/services/allow_methods/index.ts
1485
- var init_allow_methods = __esm({
1486
- "src/infrastructure/services/allow_methods/index.ts"() {
1487
- "use strict";
1488
- init_allow_method_service();
1489
- }
1467
+ // src/infrastructure/modules/http-adapter.module.ts
1468
+ var http_adapter_module_exports = {};
1469
+ __export(http_adapter_module_exports, {
1470
+ HttpAdapterModule: () => HttpAdapterModule
1490
1471
  });
1491
-
1492
- // src/infrastructure/services/allow_origins/allow-origin.http.ts
1493
- var import_shared36, AllowOrigin;
1494
- var init_allow_origin_http = __esm({
1495
- "src/infrastructure/services/allow_origins/allow-origin.http.ts"() {
1472
+ var import_shared36, HttpAdapterModule;
1473
+ var init_http_adapter_module = __esm({
1474
+ "src/infrastructure/modules/http-adapter.module.ts"() {
1496
1475
  "use strict";
1497
1476
  import_shared36 = require("@xeno-js/shared");
1498
- AllowOrigin = class {
1499
- constructor(_list) {
1500
- this._list = _list;
1477
+ HttpAdapterModule = class {
1478
+ async configure(container, opts) {
1479
+ const adapter = await this._getAdapter(opts);
1480
+ container.addSingleton("HTTP_ADAPTER", () => adapter);
1501
1481
  }
1502
- _list;
1503
- isAllowed(origin) {
1504
- if (import_shared36.Guards.isNullOrEmpty(origin)) return true;
1505
- const cleanOrigin = origin.trim().toLowerCase();
1506
- for (const pattern of this._list) {
1507
- const cleanPattern = pattern.trim().toLowerCase();
1508
- if (cleanPattern === "*") return true;
1509
- if (cleanPattern === cleanOrigin) return true;
1510
- if (cleanPattern.startsWith("*.")) {
1511
- const domainSuffix = cleanPattern.substring(1);
1512
- if (cleanOrigin.endsWith(domainSuffix)) {
1513
- const prefix = cleanOrigin.slice(0, cleanOrigin.length - domainSuffix.length);
1514
- if (!import_shared36.Guards.isNullOrEmpty(prefix) && !prefix.includes(".")) return true;
1515
- }
1516
- }
1482
+ async _getAdapter(opts) {
1483
+ if (opts.vercel) {
1484
+ const { VercelHttpAdapter: VercelHttpAdapter2 } = await Promise.resolve().then(() => (init_vercel_http_adapter(), vercel_http_adapter_exports));
1485
+ return new VercelHttpAdapter2();
1486
+ } else if (opts.fastify) {
1487
+ const { FastifyHttpAdapter: FastifyHttpAdapter2 } = await Promise.resolve().then(() => (init_fastify_http_adapter(), fastify_http_adapter_exports));
1488
+ return new FastifyHttpAdapter2();
1489
+ } else if (import_shared36.Guards.isDefined(opts.custom)) {
1490
+ return opts.custom();
1491
+ } else {
1492
+ const { NativeHttpAdapter: NativeHttpAdapter2 } = await Promise.resolve().then(() => (init_native_http_adapter(), native_http_adapter_exports));
1493
+ return new NativeHttpAdapter2();
1517
1494
  }
1518
- return false;
1519
1495
  }
1520
1496
  };
1521
1497
  }
1522
1498
  });
1523
1499
 
1524
- // src/infrastructure/services/allow_origins/index.ts
1525
- var init_allow_origins = __esm({
1526
- "src/infrastructure/services/allow_origins/index.ts"() {
1527
- "use strict";
1528
- init_allow_origin_http();
1529
- }
1500
+ // src/infrastructure/loggers/console.logger.ts
1501
+ var console_logger_exports = {};
1502
+ __export(console_logger_exports, {
1503
+ ConsoleLogger: () => ConsoleLogger
1530
1504
  });
1531
-
1532
- // src/infrastructure/services/concurrency/p-limit.service.ts
1533
- var PLimitConcurrencyService;
1534
- var init_p_limit_service = __esm({
1535
- "src/infrastructure/services/concurrency/p-limit.service.ts"() {
1505
+ var import_shared37, ConsoleLogger;
1506
+ var init_console_logger = __esm({
1507
+ "src/infrastructure/loggers/console.logger.ts"() {
1536
1508
  "use strict";
1537
- PLimitConcurrencyService = class {
1538
- async executeInParallel(tasks, concurrencyLimit) {
1539
- const { default: pLimit } = await import("p-limit");
1540
- const limit = pLimit(concurrencyLimit);
1541
- const promises = tasks.map((task) => limit(task));
1542
- return Promise.all(promises);
1509
+ import_shared37 = require("@xeno-js/shared");
1510
+ ConsoleLogger = class {
1511
+ /**
1512
+ * 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.
1513
+ * @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.
1514
+
1515
+ *
1516
+ * @author Xeno
1517
+ * @version 1.0.0
1518
+ * @since 2025-09-30
1519
+ * @link https://github.com/xeno-js/xeno-js
1520
+ */
1521
+ constructor(_minLevel = import_shared37.LOG_LEVEL.DEBUG) {
1522
+ this._minLevel = _minLevel;
1523
+ }
1524
+ _minLevel;
1525
+ track(level, message, context, error = void 0) {
1526
+ if (level < this._minLevel) return;
1527
+ const logMessage = `[${level}] ${message}`;
1528
+ const payload = import_shared37.Guards.isDefined(error) ? { ...context, error } : context;
1529
+ switch (level) {
1530
+ case import_shared37.LOG_LEVEL.ERROR:
1531
+ console.error(logMessage, payload ?? {});
1532
+ break;
1533
+ case import_shared37.LOG_LEVEL.WARN:
1534
+ console.warn(logMessage, payload ?? {});
1535
+ break;
1536
+ case import_shared37.LOG_LEVEL.DEBUG:
1537
+ console.debug(logMessage, payload ?? {});
1538
+ break;
1539
+ default:
1540
+ console.info(logMessage, payload ?? {});
1541
+ break;
1542
+ }
1543
1543
  }
1544
1544
  };
1545
1545
  }
1546
1546
  });
1547
1547
 
1548
- // src/infrastructure/services/concurrency/index.ts
1549
- var concurrency_exports = {};
1550
- __export(concurrency_exports, {
1551
- PLimitConcurrencyService: () => PLimitConcurrencyService
1552
- });
1553
- var init_concurrency = __esm({
1554
- "src/infrastructure/services/concurrency/index.ts"() {
1548
+ // src/infrastructure/loggers/sentry.logger.ts
1549
+ var import_shared38, SentryLogger;
1550
+ var init_sentry_logger = __esm({
1551
+ "src/infrastructure/loggers/sentry.logger.ts"() {
1555
1552
  "use strict";
1556
- init_p_limit_service();
1553
+ import_shared38 = require("@xeno-js/shared");
1554
+ SentryLogger = class {
1555
+ constructor(_client, _minLevel) {
1556
+ this._client = _client;
1557
+ this._minLevel = _minLevel;
1558
+ }
1559
+ _client;
1560
+ _minLevel;
1561
+ track(level, message, context = void 0, error = void 0) {
1562
+ if (level < this._minLevel) return;
1563
+ if (level === import_shared38.LOG_LEVEL.ERROR || level === import_shared38.LOG_LEVEL.WARN) {
1564
+ this._client.withScope((scope) => {
1565
+ if (import_shared38.Guards.isDefined(context)) scope.setExtras(context);
1566
+ if (import_shared38.Guards.isDefined(error)) {
1567
+ this._client.captureException(error);
1568
+ } else {
1569
+ this._client.captureMessage(message, "warning");
1570
+ }
1571
+ });
1572
+ }
1573
+ }
1574
+ };
1557
1575
  }
1558
1576
  });
1559
1577
 
1560
- // src/infrastructure/services/cookies/cookies.service.ts
1561
- var import_shared37, CookieHandler;
1562
- var init_cookies_service = __esm({
1563
- "src/infrastructure/services/cookies/cookies.service.ts"() {
1578
+ // src/infrastructure/factories/sentry-logger.factory.ts
1579
+ var sentry_logger_factory_exports = {};
1580
+ __export(sentry_logger_factory_exports, {
1581
+ SentryLoggerFactory: () => SentryLoggerFactory
1582
+ });
1583
+ var Sentry, import_shared39, SentryLoggerFactory;
1584
+ var init_sentry_logger_factory = __esm({
1585
+ "src/infrastructure/factories/sentry-logger.factory.ts"() {
1564
1586
  "use strict";
1565
- import_shared37 = require("@xeno-js/shared");
1566
- CookieHandler = class {
1567
- constructor(contextAccessor, _config, _cookieOpts) {
1568
- this.contextAccessor = contextAccessor;
1569
- this._config = _config;
1570
- this._cookieOpts = _cookieOpts;
1571
- }
1572
- contextAccessor;
1573
- _config;
1574
- _cookieOpts;
1575
- getAll() {
1576
- const network = this.contextAccessor.getNetworkContext();
1577
- const req = network?.transport?.req;
1578
- if (!import_shared37.Guards.isDefined(req) || import_shared37.Guards.isNullOrEmpty(req.headers.get("cookie"))) return [];
1579
- return req.headers.get("cookie")?.split(";").map((cookie) => {
1580
- const [name, ...rest] = cookie.split("=");
1581
- return { name: name.trim(), value: rest.join("=") };
1582
- }) ?? [];
1583
- }
1584
- setAll(cookies) {
1585
- const network = this.contextAccessor.getNetworkContext();
1586
- const res = network?.transport?.res;
1587
- if (!import_shared37.Guards.isDefined(res)) return;
1588
- const serializedCookies = cookies.map((c) => this.serialize(c));
1589
- const existingSetCookie = res.headers.getSetCookie();
1590
- res.headers.delete("Set-Cookie");
1591
- for (const cookie of [...existingSetCookie, ...serializedCookies]) {
1592
- res.headers.append("Set-Cookie", cookie);
1593
- }
1594
- }
1595
- serialize(cookie) {
1596
- const safeName = encodeURIComponent(cookie.name);
1597
- const safeValue = encodeURIComponent(cookie.value);
1598
- let str = `${safeName}=${safeValue}`;
1599
- const isProd = this._config.get("NODE_ENV") === "production";
1600
- const defaultOptions = {
1601
- path: this._cookieOpts.path,
1602
- httpOnly: this._cookieOpts.httpOnly,
1603
- secure: this._cookieOpts.secure ?? isProd,
1604
- sameSite: this._cookieOpts.sameSite ?? "Lax"
1605
- };
1606
- const opts = { ...defaultOptions, ...cookie.options ?? {} };
1607
- str += `; Path=${opts.path}`;
1608
- if (import_shared37.Guards.isDefined(opts.maxAge)) str += `; Max-Age=${opts.maxAge}`;
1609
- if (import_shared37.Guards.isDefined(opts.domain)) str += `; Domain=${opts.domain}`;
1610
- if (import_shared37.Guards.isDefined(opts.sameSite)) str += `; SameSite=${opts.sameSite}`;
1611
- if (opts.secure) str += `; Secure`;
1612
- if (opts.httpOnly) str += `; HttpOnly`;
1613
- return str;
1587
+ Sentry = __toESM(require("@sentry/node"), 1);
1588
+ import_shared39 = require("@xeno-js/shared");
1589
+ init_sentry_logger();
1590
+ SentryLoggerFactory = class {
1591
+ create(config) {
1592
+ const level = config.level ?? import_shared39.LOG_LEVEL.WARN;
1593
+ const sentryConfig = config.sentry?.config;
1594
+ const env = sentryConfig?.environment ?? process.env.NODE_ENV ?? "development";
1595
+ if (!import_shared39.Guards.isDefined(sentryConfig))
1596
+ throw new Error("Sentry configuration is required when Sentry logging is enabled.");
1597
+ if (!import_shared39.Guards.isDefined(sentryConfig.dsn))
1598
+ throw new Error("Sentry DSN is required when Sentry logging is enabled.");
1599
+ Sentry.init({
1600
+ dsn: sentryConfig.dsn,
1601
+ environment: env,
1602
+ tracesSampleRate: env === "production" ? 0.1 : 1,
1603
+ integrations: [Sentry.httpIntegration()],
1604
+ beforeSend(event, hint) {
1605
+ const error = hint.originalException;
1606
+ if (error instanceof Error && error.name === "ZodError") {
1607
+ return null;
1608
+ }
1609
+ return event;
1610
+ }
1611
+ });
1612
+ return new SentryLogger(Sentry, level);
1614
1613
  }
1615
1614
  };
1616
1615
  }
1617
1616
  });
1618
1617
 
1619
- // src/infrastructure/services/cookies/index.ts
1620
- var init_cookies = __esm({
1621
- "src/infrastructure/services/cookies/index.ts"() {
1622
- "use strict";
1623
- init_cookies_service();
1624
- }
1625
- });
1626
-
1627
- // src/infrastructure/services/crypto/crypto.service.ts
1628
- var EdgeCryptoService;
1629
- var init_crypto_service = __esm({
1630
- "src/infrastructure/services/crypto/crypto.service.ts"() {
1618
+ // src/infrastructure/loggers/pino.logger.ts
1619
+ var import_shared40, PinoLogger;
1620
+ var init_pino_logger = __esm({
1621
+ "src/infrastructure/loggers/pino.logger.ts"() {
1631
1622
  "use strict";
1632
- EdgeCryptoService = class {
1633
- randomBytes(size) {
1634
- const buffer = new Uint8Array(size);
1635
- crypto.getRandomValues(buffer);
1636
- return buffer;
1637
- }
1638
- async hmacSha256(secret, data) {
1639
- const encoder = new TextEncoder();
1640
- const keyData = encoder.encode(secret);
1641
- const messageData = encoder.encode(data);
1642
- const cryptoKey = await crypto.subtle.importKey(
1643
- "raw",
1644
- keyData,
1645
- { name: "HMAC", hash: "SHA-256" },
1646
- false,
1647
- ["sign"]
1648
- );
1649
- const signature = await crypto.subtle.sign("HMAC", cryptoKey, messageData);
1650
- return btoa(String.fromCharCode(...new Uint8Array(signature))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
1623
+ import_shared40 = require("@xeno-js/shared");
1624
+ PinoLogger = class {
1625
+ /**
1626
+ * 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.
1627
+ * @param _logger The Pino logger instance used for logging messages.
1628
+ * @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.
1629
+
1630
+ *
1631
+ * @author Xeno
1632
+ * @version 1.0.0
1633
+ * @since 2025-09-30
1634
+ * @link https://github.com/xeno-js/xeno-js
1635
+ */
1636
+ constructor(_logger, _minLevel = import_shared40.LOG_LEVEL.DEBUG) {
1637
+ this._logger = _logger;
1638
+ this._minLevel = _minLevel;
1651
1639
  }
1652
- timingSafeEqual(a, b) {
1653
- if (a.length !== b.length) {
1654
- return false;
1655
- }
1656
- let mismatch = 0;
1657
- for (let i = 0; i < a.length; i++) {
1658
- mismatch |= a[i] ^ b[i];
1640
+ _logger;
1641
+ _minLevel;
1642
+ track(level, message, context, error = void 0) {
1643
+ if (level < this._minLevel) return;
1644
+ const payload = import_shared40.Guards.isDefined(error) ? { ...context, error } : context;
1645
+ switch (level) {
1646
+ case import_shared40.LOG_LEVEL.ERROR:
1647
+ this._logger.error(payload ?? {}, message);
1648
+ break;
1649
+ case import_shared40.LOG_LEVEL.WARN:
1650
+ this._logger.warn(payload ?? {}, message);
1651
+ break;
1652
+ case import_shared40.LOG_LEVEL.DEBUG:
1653
+ this._logger.debug(payload ?? {}, message);
1654
+ break;
1655
+ default:
1656
+ this._logger.info(payload ?? {}, message);
1657
+ break;
1659
1658
  }
1660
- return mismatch === 0;
1661
- }
1662
- };
1663
- }
1664
- });
1665
-
1666
- // src/infrastructure/services/crypto/index.ts
1667
- var init_crypto = __esm({
1668
- "src/infrastructure/services/crypto/index.ts"() {
1669
- "use strict";
1670
- init_crypto_service();
1671
- }
1672
- });
1673
-
1674
- // src/infrastructure/services/csrf/csrf-token.service.ts
1675
- var import_shared38, CsrfTokenService;
1676
- var init_csrf_token_service = __esm({
1677
- "src/infrastructure/services/csrf/csrf-token.service.ts"() {
1678
- "use strict";
1679
- import_shared38 = require("@xeno-js/shared");
1680
- CsrfTokenService = class {
1681
- constructor(_secret, _cryptoService) {
1682
- this._secret = _secret;
1683
- this._cryptoService = _cryptoService;
1684
- }
1685
- _secret;
1686
- _cryptoService;
1687
- async generate(subject) {
1688
- const randomBuffer = this._cryptoService.randomBytes(32);
1689
- const nonce = btoa(String.fromCharCode(...randomBuffer)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
1690
- const signature = await this._cryptoService.hmacSha256(this._secret, `${subject}.${nonce}`);
1691
- return `${nonce}.${signature}`;
1692
- }
1693
- async validate(token, subject) {
1694
- const separatorIndex = token.indexOf(".");
1695
- if (separatorIndex <= 0) return false;
1696
- const nonce = token.slice(0, separatorIndex);
1697
- const signature = token.slice(separatorIndex + 1);
1698
- if (import_shared38.Guards.isNullOrEmpty(nonce) || import_shared38.Guards.isNullOrEmpty(signature)) return false;
1699
- const expected = await this._cryptoService.hmacSha256(this._secret, `${subject}.${nonce}`);
1700
- const encoder = new TextEncoder();
1701
- const actualBuffer = encoder.encode(signature);
1702
- const expectedBuffer = encoder.encode(expected);
1703
- if (actualBuffer.length !== expectedBuffer.length) return false;
1704
- return this._cryptoService.timingSafeEqual(actualBuffer, expectedBuffer);
1705
1659
  }
1706
1660
  };
1707
1661
  }
1708
1662
  });
1709
1663
 
1710
- // src/infrastructure/services/csrf/index.ts
1711
- var init_csrf = __esm({
1712
- "src/infrastructure/services/csrf/index.ts"() {
1713
- "use strict";
1714
- init_csrf_token_service();
1715
- }
1664
+ // src/infrastructure/factories/pino-logger.factory.ts
1665
+ var pino_logger_factory_exports = {};
1666
+ __export(pino_logger_factory_exports, {
1667
+ PinoLoggerFactory: () => PinoLoggerFactory
1716
1668
  });
1717
-
1718
- // src/infrastructure/services/extractors/extract-bearer.extractor.ts
1719
- var import_shared39, BearerTokenExtractor;
1720
- var init_extract_bearer_extractor = __esm({
1721
- "src/infrastructure/services/extractors/extract-bearer.extractor.ts"() {
1669
+ var import_shared41, import_pino, PinoLoggerFactory;
1670
+ var init_pino_logger_factory = __esm({
1671
+ "src/infrastructure/factories/pino-logger.factory.ts"() {
1722
1672
  "use strict";
1723
- import_shared39 = require("@xeno-js/shared");
1724
- BearerTokenExtractor = class {
1725
- constructor(_cookiePrefix) {
1726
- this._cookiePrefix = _cookiePrefix;
1727
- }
1728
- _cookiePrefix;
1729
- extract(headers) {
1730
- const authHeader = headers.get("Authorization");
1731
- if (import_shared39.Guards.isDefined(authHeader) && authHeader.toLowerCase().startsWith("bearer ")) {
1732
- return authHeader.substring(7);
1733
- }
1734
- const cookieHeader = headers.get("cookie");
1735
- if (import_shared39.Guards.isDefined(cookieHeader)) {
1736
- const regex = new RegExp(`${this._cookiePrefix}=([^;]+)`);
1737
- const match = regex.exec(cookieHeader);
1738
- if (!import_shared39.Guards.isNullOrEmpty(match) && import_shared39.Guards.isDefined(match[1])) {
1739
- return match[1].trim();
1673
+ import_shared41 = require("@xeno-js/shared");
1674
+ import_pino = __toESM(require("pino"), 1);
1675
+ init_pino_logger();
1676
+ PinoLoggerFactory = class {
1677
+ create(config) {
1678
+ const level = config.level ?? import_shared41.LOG_LEVEL.DEBUG;
1679
+ const env = config.pino.config?.env ?? process.env.NODE_ENV ?? "development";
1680
+ const destinationType = config.pino.config?.destination ?? "stdout";
1681
+ const filePath = config.pino.config?.filePath ?? "logs/app.log";
1682
+ const prettyPrint = config.pino.config?.prettyPrint ?? env === "development";
1683
+ const options = {
1684
+ level: "trace",
1685
+ serializers: {
1686
+ err: import_pino.default.stdSerializers.err
1687
+ },
1688
+ timestamp: import_pino.default.stdTimeFunctions.isoTime,
1689
+ redact: {
1690
+ paths: ["password", "token", "secret", "authorization", "headers.authorization"],
1691
+ censor: "***"
1740
1692
  }
1693
+ };
1694
+ if (prettyPrint) {
1695
+ return new PinoLogger(
1696
+ (0, import_pino.default)({
1697
+ ...options,
1698
+ transport: {
1699
+ target: "pino-pretty",
1700
+ options: {
1701
+ colorize: true,
1702
+ ignore: "pid,hostname",
1703
+ translateTime: "SYS:standard"
1704
+ }
1705
+ }
1706
+ }),
1707
+ level
1708
+ );
1709
+ }
1710
+ if (destinationType === "file") {
1711
+ const destination = import_pino.default.destination({ dest: filePath, sync: false });
1712
+ return new PinoLogger((0, import_pino.default)(options, destination), level);
1713
+ } else {
1714
+ const stream = import_pino.default.destination({ dest: 1, sync: false });
1715
+ return new PinoLogger((0, import_pino.default)(options, stream), level);
1741
1716
  }
1742
- return void 0;
1743
1717
  }
1744
1718
  };
1745
1719
  }
1746
1720
  });
1747
1721
 
1748
- // src/infrastructure/services/extractors/extract-ssr-bearer.extractor.ts
1749
- var import_shared40, SupabaseSsrTokenExtractor;
1750
- var init_extract_ssr_bearer_extractor = __esm({
1751
- "src/infrastructure/services/extractors/extract-ssr-bearer.extractor.ts"() {
1722
+ // src/infrastructure/modules/utils/logger.utils.ts
1723
+ var logger_utils_exports = {};
1724
+ __export(logger_utils_exports, {
1725
+ LoggerUtils: () => LoggerUtils
1726
+ });
1727
+ var LoggerUtils;
1728
+ var init_logger_utils = __esm({
1729
+ "src/infrastructure/modules/utils/logger.utils.ts"() {
1752
1730
  "use strict";
1753
- import_shared40 = require("@xeno-js/shared");
1754
- SupabaseSsrTokenExtractor = class {
1755
- extract(headers) {
1756
- const authHeader = headers.get("authorization");
1757
- if (import_shared40.Guards.isDefined(authHeader) && authHeader.toLowerCase().startsWith("bearer ")) {
1758
- return authHeader.substring(7);
1759
- }
1760
- const cookieHeader = headers.get("cookie");
1761
- if (import_shared40.Guards.isNullOrEmpty(cookieHeader)) return void 0;
1762
- const cookies = cookieHeader.split(";").map((c) => c.trim());
1763
- const tokenChunks = {};
1764
- let unchunkedToken;
1765
- for (const cookie of cookies) {
1766
- const [name, ...rest] = cookie.split("=");
1767
- if (!import_shared40.Guards.isDefined(name) || import_shared40.Guards.isNullOrEmpty(rest)) continue;
1768
- const value = decodeURIComponent(rest.join("="));
1769
- if (import_shared40.Guards.isDefined(/^sb-[a-z0-9]+-auth-token$/.exec(name))) {
1770
- unchunkedToken = value;
1771
- } else {
1772
- const match = /^sb-[a-z0-9]+-auth-token\.(\d+)$/.exec(name);
1773
- if (import_shared40.Guards.isDefined(match)) tokenChunks[parseInt(match[1], 10)] = value;
1774
- }
1775
- }
1776
- let fullTokenString = unchunkedToken;
1777
- if (!import_shared40.Guards.isDefined(fullTokenString) && Object.keys(tokenChunks).length > 0) {
1778
- const indices = Object.keys(tokenChunks).map(Number).sort((a, b) => a - b);
1779
- fullTokenString = indices.map((i) => tokenChunks[i]).join("");
1731
+ LoggerUtils = Object.freeze({
1732
+ /**
1733
+ * @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.
1734
+ *
1735
+ * @param container - The service container to register logging services with.
1736
+ * @param opts - The LoggerConfig options to determine which loggers to enable and their configurations.
1737
+
1738
+ *
1739
+ * @author Xeno
1740
+ * @version 1.0.0
1741
+ * @since 2025-09-30
1742
+ * @link https://github.com/xeno-js/xeno-js
1743
+ */
1744
+ async addLogger(container, opts) {
1745
+ const loggerDependencies = [];
1746
+ const { Guards: Guards51, LOG_LEVEL: LOG_LEVEL7, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
1747
+ if (!Guards51.isDefined(opts) || opts.console) {
1748
+ const { ConsoleLogger: ConsoleLogger2 } = await Promise.resolve().then(() => (init_console_logger(), console_logger_exports));
1749
+ loggerDependencies.push(new ConsoleLogger2(opts?.level));
1780
1750
  }
1781
- if (import_shared40.Guards.isNullOrEmpty(fullTokenString)) return void 0;
1782
- try {
1783
- const parsed = import_shared40.StringHelper.safeParse(fullTokenString);
1784
- if (import_shared40.Guards.isDefined(parsed) && import_shared40.Guards.isObject(parsed) && "access_token" in parsed) {
1785
- const accessToken = parsed["access_token"];
1786
- if (import_shared40.Guards.isString(accessToken)) return accessToken;
1751
+ if (Guards51.isDefined(opts)) {
1752
+ if (Guards51.isDefined(opts.sentry.config)) {
1753
+ const { SentryLoggerFactory: SentryLoggerFactory2 } = await Promise.resolve().then(() => (init_sentry_logger_factory(), sentry_logger_factory_exports));
1754
+ loggerDependencies.push(new SentryLoggerFactory2().create(opts));
1755
+ }
1756
+ if (Guards51.isDefined(opts.pino.config)) {
1757
+ const { PinoLoggerFactory: PinoLoggerFactory2 } = await Promise.resolve().then(() => (init_pino_logger_factory(), pino_logger_factory_exports));
1758
+ loggerDependencies.push(new PinoLoggerFactory2().create(opts));
1759
+ }
1760
+ if (!Guards51.isNullOrEmpty(opts.customLoggers)) {
1761
+ const customLoggers = opts.customLoggers;
1762
+ customLoggers.forEach((fn) => {
1763
+ if (Guards51.isDefined(fn)) loggerDependencies.push(fn(container));
1764
+ });
1787
1765
  }
1788
- } catch {
1789
- return void 0;
1790
1766
  }
1767
+ const { BaseLogger } = await import("@xeno-js/shared");
1768
+ container.addSingleton(TOKENS5.LOGGER, (c) => {
1769
+ const context = c.resolve(TOKENS5.CONTEXT_ACCESSOR);
1770
+ return new BaseLogger(context, opts?.level ?? LOG_LEVEL7.DEBUG, loggerDependencies);
1771
+ });
1791
1772
  }
1792
- };
1773
+ });
1793
1774
  }
1794
1775
  });
1795
1776
 
1796
- // src/infrastructure/services/extractors/http-cookie.extractor.ts
1797
- var import_shared41, HttpCookieExtractor;
1798
- var init_http_cookie_extractor = __esm({
1799
- "src/infrastructure/services/extractors/http-cookie.extractor.ts"() {
1777
+ // src/infrastructure/cache/inmemory.cache.ts
1778
+ var inmemory_cache_exports = {};
1779
+ __export(inmemory_cache_exports, {
1780
+ InMemoryCacheExtended: () => InMemoryCacheExtended
1781
+ });
1782
+ var import_shared42, InMemoryCacheExtended;
1783
+ var init_inmemory_cache = __esm({
1784
+ "src/infrastructure/cache/inmemory.cache.ts"() {
1800
1785
  "use strict";
1801
- import_shared41 = require("@xeno-js/shared");
1802
- HttpCookieExtractor = class {
1803
- extract(cookie) {
1804
- if (!import_shared41.Guards.isDefined(cookie.header)) return void 0;
1805
- for (const rawCookie of cookie.header.split(";")) {
1806
- const separatorIndex = rawCookie.indexOf("=");
1807
- if (separatorIndex <= 0) continue;
1808
- const name = rawCookie.slice(0, separatorIndex).trim();
1809
- if (name !== cookie.name) continue;
1810
- const value = rawCookie.slice(separatorIndex + 1).trim();
1811
- try {
1812
- return decodeURIComponent(value);
1813
- } catch {
1814
- return void 0;
1815
- }
1816
- }
1817
- return void 0;
1786
+ import_shared42 = require("@xeno-js/shared");
1787
+ InMemoryCacheExtended = class extends import_shared42.InMemoryCache {
1788
+ async increment(key, ttlSeconds) {
1789
+ const current = await this.get(key) ?? 0;
1790
+ const next = Number(current) + 1;
1791
+ const ttl = import_shared42.Guards.isDefined(ttlSeconds) ? Number(ttlSeconds) : 60;
1792
+ await this.set(key, next, ttl);
1793
+ return next;
1818
1794
  }
1819
1795
  };
1820
1796
  }
1821
1797
  });
1822
1798
 
1823
- // src/infrastructure/services/extractors/http-header.extractor.ts
1824
- var import_shared42, HttpHeaderExtractor;
1825
- var init_http_header_extractor = __esm({
1826
- "src/infrastructure/services/extractors/http-header.extractor.ts"() {
1799
+ // src/infrastructure/cache/redis.cache.ts
1800
+ var import_shared43, RedisCache;
1801
+ var init_redis_cache = __esm({
1802
+ "src/infrastructure/cache/redis.cache.ts"() {
1827
1803
  "use strict";
1828
- import_shared42 = require("@xeno-js/shared");
1829
- HttpHeaderExtractor = class {
1804
+ import_shared43 = require("@xeno-js/shared");
1805
+ RedisCache = class {
1830
1806
  /**
1831
- * @description Constructor for HttpHeaderExtractor. It takes an instance of IServiceExtractor for extracting Bearer tokens, allowing for separation of concerns and adherence to the Single Responsibility Principle (SRP). This design enables the HttpHeaderExtractor to focus on general header extraction while delegating the specific logic of Bearer token extraction to a dedicated extractor, promoting code reusability and maintainability.
1807
+ * @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.
1808
+ * @param _redisClient An instance of the Redis client from the ioredis library, used to perform caching operations in the Redis database.
1832
1809
 
1833
1810
  *
1834
1811
  * @author Xeno
@@ -1836,1108 +1813,918 @@ var init_http_header_extractor = __esm({
1836
1813
  * @since 2025-09-30
1837
1814
  * @link https://github.com/xeno-js/xeno-js
1838
1815
  */
1839
- constructor(_bearerExtractor, _cookieExtractor, _trustedIp, _cookieName) {
1840
- this._bearerExtractor = _bearerExtractor;
1841
- this._cookieExtractor = _cookieExtractor;
1842
- this._trustedIp = _trustedIp;
1843
- this._cookieName = _cookieName;
1816
+ constructor(_redisClient) {
1817
+ this._redisClient = _redisClient;
1844
1818
  }
1845
- _bearerExtractor;
1846
- _cookieExtractor;
1847
- _trustedIp;
1848
- _cookieName;
1849
- extract(headers) {
1850
- const correlationId = import_shared42.GuidHelper.parse(headers.get("x-correlation-id") ?? void 0);
1851
- const requestId = import_shared42.GuidHelper.parse(headers.get("x-request-id") ?? void 0);
1852
- const token = this._bearerExtractor.extract(headers);
1853
- const clientIp = headers.get(this._trustedIp?.toLowerCase() ?? "x-forwarded-for") ?? headers.get("x-real-ip") ?? void 0;
1854
- const spanId = import_shared42.GuidHelper.parse(headers.get("x-span-id") ?? void 0);
1855
- const parentSpanId = headers.get("x-parent-span-id") ?? void 0;
1856
- const acceptHeader = headers.get("accept");
1857
- const contentTypeHeader = headers.get("content-type");
1858
- const userAgent = headers.get("user-agent") ?? void 0;
1859
- const returnAddress = headers.get("x-return-address") ?? void 0;
1860
- const sequenceId = headers.get("x-sequence-id") ?? void 0;
1861
- const position = headers.get("x-sequence-position");
1862
- const size = headers.get("x-sequence-size");
1863
- const expiration = headers.get("x-expiration");
1864
- const csrf = headers.get("x-csrf-token") ?? void 0;
1865
- const cookieHeader = headers.get("cookie") ?? void 0;
1866
- const csrfCookie = this._cookieExtractor.extract({
1867
- header: cookieHeader,
1868
- name: this._cookieName
1869
- });
1870
- const origin = headers.get("origin") ?? void 0;
1871
- const cleanOrigin = import_shared42.HttpHelper.sanitizeOriginUrl(origin);
1872
- const referer = headers.get("referer") ?? void 0;
1873
- const cleanReferer = import_shared42.HttpHelper.sanitizeOriginUrl(referer);
1874
- const accept = acceptHeader === "*/*" ? void 0 : acceptHeader;
1875
- const formatIndicator = accept ?? contentTypeHeader ?? "application/json";
1876
- const metadata = {
1877
- correlationId,
1878
- requestId,
1879
- token,
1880
- clientIp,
1881
- spanId,
1882
- parentSpanId,
1883
- formatIndicator,
1884
- userAgent,
1885
- returnAddress,
1886
- csrf,
1887
- csrfCookie,
1888
- origin: cleanOrigin,
1889
- referer: cleanReferer,
1890
- sequence: {
1891
- sequenceId,
1892
- position: import_shared42.Guards.isDefined(position) ? import_shared42.MathHelper.toNumber(position) : void 0,
1893
- size: import_shared42.Guards.isDefined(size) ? import_shared42.MathHelper.toNumber(size) : void 0
1894
- },
1895
- expiration: import_shared42.Guards.isDefined(expiration) ? import_shared42.MathHelper.toNumber(expiration) : void 0
1896
- };
1897
- return metadata;
1819
+ _redisClient;
1820
+ async increment(key, ttlSeconds) {
1821
+ const multi = this._redisClient.multi();
1822
+ multi.incr(key);
1823
+ multi.expire(key, ttlSeconds ?? 60);
1824
+ const results = await multi.exec();
1825
+ return results?.[0]?.[1] ?? 1;
1826
+ }
1827
+ async get(key) {
1828
+ const value = await this._redisClient.get(key);
1829
+ if (!import_shared43.Guards.isDefined(value)) {
1830
+ return void 0;
1831
+ }
1832
+ return JSON.parse(value);
1833
+ }
1834
+ async set(key, value, ttl) {
1835
+ const stringValue = import_shared43.StringHelper.safeStringify(value);
1836
+ const ttlOption = import_shared43.Guards.isDefined(ttl) ? ttl : 86400;
1837
+ await this._redisClient.set(key, stringValue, "EX", ttlOption);
1838
+ }
1839
+ async setIfAbsent(key, value, ttl) {
1840
+ const stringValue = import_shared43.StringHelper.safeStringify(value);
1841
+ const ttlOption = import_shared43.Guards.isDefined(ttl) ? ttl : 300;
1842
+ const result = await this._redisClient.set(key, stringValue, "EX", ttlOption, "NX");
1843
+ return result === "OK";
1844
+ }
1845
+ async remove(key) {
1846
+ await this._redisClient.del(key);
1847
+ }
1848
+ async has(key) {
1849
+ const exists = await this._redisClient.exists(key);
1850
+ return exists === 1;
1851
+ }
1852
+ async clear() {
1853
+ await this._redisClient.flushdb();
1898
1854
  }
1899
1855
  };
1900
1856
  }
1901
1857
  });
1902
1858
 
1903
- // src/infrastructure/services/extractors/index.ts
1904
- var init_extractors = __esm({
1905
- "src/infrastructure/services/extractors/index.ts"() {
1906
- "use strict";
1907
- init_extract_bearer_extractor();
1908
- init_extract_ssr_bearer_extractor();
1909
- init_http_cookie_extractor();
1910
- init_http_header_extractor();
1911
- }
1859
+ // src/infrastructure/factories/redis-cache.factory.ts
1860
+ var redis_cache_factory_exports = {};
1861
+ __export(redis_cache_factory_exports, {
1862
+ RedisCacheFactory: () => RedisCacheFactory
1912
1863
  });
1913
-
1914
- // src/infrastructure/services/resiliences/resilience.service.ts
1915
- var import_shared43, ServiceResilience;
1916
- var init_resilience_service = __esm({
1917
- "src/infrastructure/services/resiliences/resilience.service.ts"() {
1864
+ var import_shared44, import_ioredis, RedisCacheFactory;
1865
+ var init_redis_cache_factory = __esm({
1866
+ "src/infrastructure/factories/redis-cache.factory.ts"() {
1918
1867
  "use strict";
1919
- import_shared43 = require("@xeno-js/shared");
1920
- ServiceResilience = class {
1921
- constructor(policy) {
1922
- this.policy = policy;
1923
- }
1924
- policy;
1925
- async execute(operation, signal) {
1926
- import_shared43.AppError.throwIfAborted(signal, "ServiceResilience.execute");
1927
- return this.policy.execute(() => operation(), signal);
1868
+ import_shared44 = require("@xeno-js/shared");
1869
+ import_ioredis = require("ioredis");
1870
+ init_redis_cache();
1871
+ RedisCacheFactory = class {
1872
+ create(config) {
1873
+ const host = config?.host ?? "localhost";
1874
+ const port = config?.port ?? 6379;
1875
+ const password = config?.password;
1876
+ const username = config?.username;
1877
+ const useTls = config?.tls ?? false;
1878
+ const maxRetries = config?.maxRetriesPerRequest ?? 3;
1879
+ const redisOptions = {
1880
+ host,
1881
+ port,
1882
+ maxRetriesPerRequest: maxRetries,
1883
+ // Strategia di riconnessione esponenziale per garantire resilienza
1884
+ retryStrategy(times) {
1885
+ const delay = Math.min(times * 50, 2e3);
1886
+ return delay;
1887
+ }
1888
+ };
1889
+ if (import_shared44.Guards.isDefined(password)) {
1890
+ redisOptions.password = password;
1891
+ }
1892
+ if (import_shared44.Guards.isDefined(username)) {
1893
+ redisOptions.username = username;
1894
+ }
1895
+ if (useTls) {
1896
+ redisOptions.tls = {};
1897
+ }
1898
+ const nativeRedisInstance = new import_ioredis.Redis(redisOptions);
1899
+ nativeRedisInstance.on("error", (err) => {
1900
+ console.error("\u274C [Redis Error]:", err.message);
1901
+ });
1902
+ return new RedisCache(nativeRedisInstance);
1928
1903
  }
1929
1904
  };
1930
1905
  }
1931
1906
  });
1932
1907
 
1933
- // src/infrastructure/services/resiliences/index.ts
1934
- var init_resiliences = __esm({
1935
- "src/infrastructure/services/resiliences/index.ts"() {
1936
- "use strict";
1937
- init_resilience_service();
1938
- }
1908
+ // src/infrastructure/modules/utils/cache.utils.ts
1909
+ var cache_utils_exports = {};
1910
+ __export(cache_utils_exports, {
1911
+ CacheUtils: () => CacheUtils
1939
1912
  });
1940
-
1941
- // src/infrastructure/services/resolver/utils/socket.utils.ts
1942
- var import_shared44, SocketIpExtractor;
1943
- var init_socket_utils = __esm({
1944
- "src/infrastructure/services/resolver/utils/socket.utils.ts"() {
1913
+ var CacheUtils;
1914
+ var init_cache_utils = __esm({
1915
+ "src/infrastructure/modules/utils/cache.utils.ts"() {
1945
1916
  "use strict";
1946
- import_shared44 = require("@xeno-js/shared");
1947
- SocketIpExtractor = Object.freeze({
1917
+ CacheUtils = Object.freeze({
1948
1918
  /**
1949
- * @description Extracts the IP address of the remote socket from an incoming request.
1950
- * @param req The incoming request object.
1951
- * @returns The IP address of the remote socket, or undefined if not available.
1919
+ * @description Checks if the provided cache configuration requires any cache strategies.
1920
+ * @param container The service container to which the cache strategies will be added.
1921
+ * @param opts The cache configuration options.
1922
+ * @returns True if any cache strategies are required, false otherwise.
1923
+ *
1924
+ * @author Xeno
1925
+ * @version 1.0.0
1926
+ * @since 2025-09-30
1927
+ * @link https://github.com/xeno-js/xeno-js
1952
1928
  */
1953
- extract(req) {
1954
- if (import_shared44.Guards.isDefined(req) && import_shared44.Guards.isObject(req)) {
1955
- const candidate = req;
1956
- return candidate.socket?.remoteAddress ?? candidate.connection?.remoteAddress;
1929
+ async addCache(container, opts) {
1930
+ const { Guards: Guards51, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
1931
+ if (!opts.inMemory && !Guards51.isDefined(opts.redis)) {
1932
+ throw new Error(
1933
+ "No cache strategies are configured. Please provide at least one cache strategy."
1934
+ );
1935
+ }
1936
+ const { CacheKeyBuilder } = await import("@xeno-js/shared");
1937
+ container.addSingleton(
1938
+ TOKENS5.CACHE_KEY_BUILDER,
1939
+ (c) => new CacheKeyBuilder(c.resolve(TOKENS5.IDENTITY_ACCESSOR))
1940
+ );
1941
+ if (opts.inMemory || !Guards51.isDefined(opts.redis)) {
1942
+ const { InMemoryCacheExtended: InMemoryCacheExtended2 } = await Promise.resolve().then(() => (init_inmemory_cache(), inmemory_cache_exports));
1943
+ container.addSingleton(TOKENS5.CACHE, () => new InMemoryCacheExtended2());
1944
+ return;
1945
+ }
1946
+ if (Guards51.isDefined(opts.redis)) {
1947
+ const { RedisCacheFactory: RedisCacheFactory2 } = await Promise.resolve().then(() => (init_redis_cache_factory(), redis_cache_factory_exports));
1948
+ container.addSingleton(TOKENS5.CACHE, () => {
1949
+ const config = opts.redis;
1950
+ return new RedisCacheFactory2().create(config);
1951
+ });
1957
1952
  }
1958
- return void 0;
1959
1953
  }
1960
1954
  });
1961
1955
  }
1962
1956
  });
1963
1957
 
1964
- // src/infrastructure/services/resolver/utils/index.ts
1965
- var init_utils = __esm({
1966
- "src/infrastructure/services/resolver/utils/index.ts"() {
1967
- "use strict";
1968
- init_socket_utils();
1969
- }
1970
- });
1971
-
1972
- // src/infrastructure/services/resolver/client-ip.resolver.ts
1973
- var import_shared45, ClientIpResolver;
1974
- var init_client_ip_resolver = __esm({
1975
- "src/infrastructure/services/resolver/client-ip.resolver.ts"() {
1958
+ // src/infrastructure/services/allow_methods/allow-method.service.ts
1959
+ var import_shared45, AllowMethodRegistry;
1960
+ var init_allow_method_service = __esm({
1961
+ "src/infrastructure/services/allow_methods/allow-method.service.ts"() {
1976
1962
  "use strict";
1977
1963
  import_shared45 = require("@xeno-js/shared");
1978
- init_utils();
1979
- ClientIpResolver = class {
1980
- constructor(_trustedProxies = []) {
1981
- this._trustedProxies = _trustedProxies;
1964
+ AllowMethodRegistry = class {
1965
+ _staticRoutes = /* @__PURE__ */ new Map();
1966
+ _dynamicRoutes = [];
1967
+ add(path, methods) {
1968
+ const normalizedPath = this.normalizePath(path);
1969
+ if (this.isDynamicPath(normalizedPath)) {
1970
+ const pattern = this.createRoutePattern(normalizedPath);
1971
+ this._dynamicRoutes.push({ pattern, methods });
1972
+ } else {
1973
+ this._staticRoutes.set(normalizedPath, methods);
1974
+ }
1982
1975
  }
1983
- _trustedProxies;
1984
- resolve(req, clientIp) {
1985
- const socketIp = SocketIpExtractor.extract(req);
1986
- if (!import_shared45.Guards.isDefined(socketIp))
1987
- return !import_shared45.Guards.isNullOrEmpty(clientIp) ? clientIp.split(",")[0].trim() : void 0;
1988
- const isTrustedProxy = this._trustedProxies.includes(socketIp);
1989
- if (!isTrustedProxy) return socketIp;
1990
- if (import_shared45.Guards.isDefined(clientIp)) return clientIp.split(",")[0].trim();
1991
- return socketIp;
1976
+ check(path, method) {
1977
+ const cleanPath = this.normalizePath(path.split("?")[0].split("#")[0]);
1978
+ const staticMethods = this._staticRoutes.get(cleanPath);
1979
+ if (import_shared45.Guards.isDefined(staticMethods)) return staticMethods.includes(method);
1980
+ for (const route of this._dynamicRoutes) {
1981
+ if (route.pattern.test(cleanPath)) return route.methods.includes(method);
1982
+ }
1983
+ return false;
1992
1984
  }
1993
- };
1994
- }
1995
- });
1996
-
1997
- // src/infrastructure/services/resolver/index.ts
1998
- var init_resolver = __esm({
1999
- "src/infrastructure/services/resolver/index.ts"() {
2000
- "use strict";
2001
- init_client_ip_resolver();
2002
- }
2003
- });
2004
-
2005
- // src/infrastructure/services/index.ts
2006
- var services_exports = {};
2007
- __export(services_exports, {
2008
- AllowMethodRegistry: () => AllowMethodRegistry,
2009
- AllowOrigin: () => AllowOrigin,
2010
- BearerTokenExtractor: () => BearerTokenExtractor,
2011
- ClientIpResolver: () => ClientIpResolver,
2012
- CookieHandler: () => CookieHandler,
2013
- CsrfTokenService: () => CsrfTokenService,
2014
- EdgeCryptoService: () => EdgeCryptoService,
2015
- HttpCookieExtractor: () => HttpCookieExtractor,
2016
- HttpHeaderExtractor: () => HttpHeaderExtractor,
2017
- PLimitConcurrencyService: () => PLimitConcurrencyService,
2018
- ServiceResilience: () => ServiceResilience,
2019
- SupabaseSsrTokenExtractor: () => SupabaseSsrTokenExtractor
2020
- });
2021
- var init_services = __esm({
2022
- "src/infrastructure/services/index.ts"() {
2023
- "use strict";
2024
- init_allow_methods();
2025
- init_allow_origins();
2026
- init_concurrency();
2027
- init_cookies();
2028
- init_crypto();
2029
- init_csrf();
2030
- init_extractors();
2031
- init_resiliences();
2032
- init_resolver();
2033
- }
2034
- });
2035
-
2036
- // src/infrastructure/factories/supabase.factory.ts
2037
- var supabase_factory_exports = {};
2038
- __export(supabase_factory_exports, {
2039
- SupabaseServerAuthFactory: () => SupabaseServerAuthFactory
2040
- });
2041
- var import_ssr, import_shared46, import_supabase, SupabaseServerAuthFactory;
2042
- var init_supabase_factory = __esm({
2043
- "src/infrastructure/factories/supabase.factory.ts"() {
2044
- "use strict";
2045
- import_ssr = require("@supabase/ssr");
2046
- import_shared46 = require("@xeno-js/shared");
2047
- import_supabase = require("@xeno-js/shared/supabase");
2048
- init_services();
2049
- SupabaseServerAuthFactory = class {
2050
- create({
2051
- config,
2052
- container
2053
- }) {
2054
- const cookieService = this._getCookieSsr(config.ssrOpts, container, config.cookieOpts);
2055
- const client = (0, import_ssr.createServerClient)(config.url, config.key, {
2056
- ...config.opts,
2057
- cookies: {
2058
- getAll() {
2059
- return cookieService.getAll();
2060
- },
2061
- setAll(cookiesToSet) {
2062
- cookieService.setAll(cookiesToSet);
2063
- }
2064
- }
2065
- });
2066
- const mapper = new import_supabase.SupabaseClaimsMapper();
2067
- const sessionMapper = new import_supabase.SupabaseSessionMapper(mapper);
2068
- return new import_supabase.SupabaseAuthService(client, mapper, sessionMapper, config);
1985
+ getMethods(path) {
1986
+ const cleanPath = this.normalizePath(path.split("?")[0].split("#")[0]);
1987
+ const methods = this.findMethods(cleanPath);
1988
+ return import_shared45.Guards.isDefined(methods) ? methods.join(", ").toUpperCase() : "";
2069
1989
  }
2070
- _getCookieSsr(ssrOpts, container, config) {
2071
- if (import_shared46.Guards.isDefined(ssrOpts)) {
2072
- return ssrOpts(container);
2073
- } else {
2074
- return new CookieHandler(
2075
- container.resolve(import_shared46.TOKENS.NETWORK_CONTEXT_ACCESSOR),
2076
- container.resolve(import_shared46.TOKENS.CONFIGURATION_SERVICE),
2077
- config
2078
- );
2079
- }
1990
+ findMethods(cleanPath) {
1991
+ const staticMethods = this._staticRoutes.get(cleanPath);
1992
+ if (import_shared45.Guards.isDefined(staticMethods)) return staticMethods;
1993
+ for (const route of this._dynamicRoutes) if (route.pattern.test(cleanPath)) return route.methods;
1994
+ return void 0;
1995
+ }
1996
+ isDynamicPath(path) {
1997
+ return path.includes(":") || path.includes("{") && path.includes("}");
1998
+ }
1999
+ normalizePath(path) {
2000
+ const trimmed = path.trim();
2001
+ const withLeadingSlash = trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
2002
+ if (withLeadingSlash === "/") return "/";
2003
+ return withLeadingSlash.replace(/\/+$/, "");
2004
+ }
2005
+ createRoutePattern(path) {
2006
+ const segments = path.split("/").filter(Boolean);
2007
+ const regexSegments = segments.map((segment) => {
2008
+ if (segment.startsWith(":") || segment.startsWith("{") && segment.endsWith("}"))
2009
+ return "([^/]+)";
2010
+ return segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2011
+ });
2012
+ return new RegExp(`^\\/${regexSegments.join("\\/")}\\/?$`);
2080
2013
  }
2081
2014
  };
2082
2015
  }
2083
2016
  });
2084
2017
 
2085
- // src/infrastructure/modules/utils/auth.utils.ts
2086
- var auth_utils_exports = {};
2087
- __export(auth_utils_exports, {
2088
- AuthUtils: () => AuthUtils
2089
- });
2090
- var AuthUtils;
2091
- var init_auth_utils = __esm({
2092
- "src/infrastructure/modules/utils/auth.utils.ts"() {
2093
- "use strict";
2094
- AuthUtils = Object.freeze({
2095
- /**
2096
- * @description Checks if the provided authorization configuration requires any authorization strategies.
2097
- * @param authorizationConfig The authorization configuration to check.
2098
- * @returns True if any authorization strategies are required, false otherwise.
2099
-
2100
- *
2101
- * @author Xeno
2102
- * @version 1.0.0
2103
- * @since 2025-09-30
2104
- * @link https://github.com/xeno-js/xeno-js
2105
- */
2106
- async addAuthZ(container, opts) {
2107
- const { TOKENS: TOKENS5 } = await import("@xeno-js/shared");
2108
- const strategies = [];
2109
- const { Guards: Guards51 } = await import("@xeno-js/shared");
2110
- if (Guards51.isDefined(opts.policies)) {
2111
- const { PolicyRegistry: PolicyRegistry2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2112
- const policyRegistry = opts.policies;
2113
- const registryInstance = new PolicyRegistry2();
2114
- const ctxAccessor = container.resolve(TOKENS5.CONTEXT_ACCESSOR);
2115
- const Policies = /* @__PURE__ */ new Set();
2116
- for (const [intent, policy] of Object.entries(policyRegistry)) {
2117
- const intentLower = intent.toLowerCase();
2118
- registryInstance.addPolicy(intentLower, policy);
2119
- if (!Guards51.isNullOrEmpty(policy.roles)) {
2120
- Policies.add("roles");
2121
- }
2122
- if (!Guards51.isNullOrEmpty(policy.permissions)) {
2123
- Policies.add("permissions");
2124
- }
2125
- if (!Guards51.isNullOrEmpty(policy.userId)) {
2126
- Policies.add("userId");
2127
- }
2128
- if (!Guards51.isNullOrEmpty(policy.tenantId)) {
2129
- Policies.add("tenantId");
2130
- }
2131
- }
2132
- if (Policies.has("roles")) {
2133
- const { RoleAuthorizationStrategy: RoleAuthorizationStrategy2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2134
- strategies.push(new RoleAuthorizationStrategy2(registryInstance, ctxAccessor));
2135
- }
2136
- if (Policies.has("permissions")) {
2137
- const { PermissionAuthorizationStrategy: PermissionAuthorizationStrategy2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2138
- strategies.push(new PermissionAuthorizationStrategy2(registryInstance, ctxAccessor));
2139
- }
2140
- if (Policies.has("userId")) {
2141
- const { UserAuthorizationStrategy: UserAuthorizationStrategy2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2142
- strategies.push(new UserAuthorizationStrategy2(registryInstance, ctxAccessor));
2143
- }
2144
- if (Policies.has("tenantId")) {
2145
- const { TenantAuthorizationStrategy: TenantAuthorizationStrategy2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2146
- strategies.push(new TenantAuthorizationStrategy2(registryInstance, ctxAccessor));
2147
- }
2148
- }
2149
- if (!Guards51.isNullOrEmpty(opts.customAuthorizationStrategy)) {
2150
- const customStrategies = opts.customAuthorizationStrategy;
2151
- customStrategies.forEach((strategyToken) => {
2152
- if (Guards51.isDefined(strategyToken)) {
2153
- strategies.push(strategyToken(container));
2154
- }
2155
- });
2156
- }
2157
- const { AuthorizationPipeline: AuthorizationPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2158
- return new AuthorizationPipeline2(strategies);
2159
- },
2160
- /**
2161
- * @description Configures the authentication service and gatekeeper in the service container.
2162
- * @param container The service container to configure.
2163
- * @param opts The authentication configuration options.
2164
-
2165
- *
2166
- * @author Xeno
2167
- * @version 1.0.0
2168
- * @since 2025-09-30
2169
- * @link https://github.com/xeno-js/xeno-js
2170
- */
2171
- async addAuthN(container, opts) {
2172
- const { Guards: Guards51, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
2173
- if (Guards51.isDefined(opts.customAuth)) {
2174
- const authService = opts.customAuth.authExtendedService();
2175
- container.addScoped(TOKENS5.AUTH_SERVICE, () => {
2176
- return authService;
2177
- });
2178
- container.addSingleton(TOKENS5.BASE_AUTH_SERVICE, () => {
2179
- return authService;
2180
- });
2181
- } else {
2182
- const { SupabaseServerAuthFactory: SupabaseServerAuthFactory2 } = await Promise.resolve().then(() => (init_supabase_factory(), supabase_factory_exports));
2183
- const factory = new SupabaseServerAuthFactory2();
2184
- const supabase = factory.create({ config: opts, container });
2185
- container.addScoped(TOKENS5.AUTH_SERVICE, () => {
2186
- return supabase;
2187
- });
2188
- container.addSingleton(TOKENS5.BASE_AUTH_SERVICE, () => {
2189
- return supabase;
2190
- });
2191
- }
2192
- }
2193
- });
2018
+ // src/infrastructure/services/allow_methods/index.ts
2019
+ var init_allow_methods = __esm({
2020
+ "src/infrastructure/services/allow_methods/index.ts"() {
2021
+ "use strict";
2022
+ init_allow_method_service();
2194
2023
  }
2195
2024
  });
2196
2025
 
2197
- // src/infrastructure/factories/zod-validator.factory.ts
2198
- var zod_validator_factory_exports = {};
2199
- __export(zod_validator_factory_exports, {
2200
- ZodValidatorFactory: () => ZodValidatorFactory
2201
- });
2202
- var import_zod, ZodValidatorFactory;
2203
- var init_zod_validator_factory = __esm({
2204
- "src/infrastructure/factories/zod-validator.factory.ts"() {
2026
+ // src/infrastructure/services/allow_origins/allow-origin.http.ts
2027
+ var import_shared46, AllowOrigin;
2028
+ var init_allow_origin_http = __esm({
2029
+ "src/infrastructure/services/allow_origins/allow-origin.http.ts"() {
2205
2030
  "use strict";
2206
- import_zod = require("@xeno-js/shared/zod");
2207
- ZodValidatorFactory = class {
2208
- create(opts) {
2209
- const validatorService = new import_zod.ZodValidatorService(/* @__PURE__ */ new Map(), opts.logger);
2210
- for (const [intentKey, schema] of Object.entries(opts.schemas)) {
2211
- validatorService.addSchema(intentKey, schema);
2031
+ import_shared46 = require("@xeno-js/shared");
2032
+ AllowOrigin = class {
2033
+ constructor(_list) {
2034
+ this._list = _list;
2035
+ }
2036
+ _list;
2037
+ isAllowed(origin) {
2038
+ if (import_shared46.Guards.isNullOrEmpty(origin)) return true;
2039
+ const cleanOrigin = origin.trim().toLowerCase();
2040
+ for (const pattern of this._list) {
2041
+ const cleanPattern = pattern.trim().toLowerCase();
2042
+ if (cleanPattern === "*") return true;
2043
+ if (cleanPattern === cleanOrigin) return true;
2044
+ if (cleanPattern.startsWith("*.")) {
2045
+ const domainSuffix = cleanPattern.substring(1);
2046
+ if (cleanOrigin.endsWith(domainSuffix)) {
2047
+ const prefix = cleanOrigin.slice(0, cleanOrigin.length - domainSuffix.length);
2048
+ if (!import_shared46.Guards.isNullOrEmpty(prefix) && !prefix.includes(".")) return true;
2049
+ }
2050
+ }
2212
2051
  }
2213
- return validatorService;
2052
+ return false;
2214
2053
  }
2215
2054
  };
2216
2055
  }
2217
2056
  });
2218
2057
 
2219
- // src/infrastructure/modules/utils/validation.utils.ts
2220
- var validation_utils_exports = {};
2221
- __export(validation_utils_exports, {
2222
- ValidationUtils: () => ValidationUtils
2223
- });
2224
- var ValidationUtils;
2225
- var init_validation_utils = __esm({
2226
- "src/infrastructure/modules/utils/validation.utils.ts"() {
2058
+ // src/infrastructure/services/allow_origins/index.ts
2059
+ var init_allow_origins = __esm({
2060
+ "src/infrastructure/services/allow_origins/index.ts"() {
2227
2061
  "use strict";
2228
- ValidationUtils = Object.freeze({
2229
- /**
2230
- * @description Checks if the provided validation configuration requires any validation strategies.
2231
- * @param validationConfig The validation configuration to check.
2232
- * @returns True if any validation strategies are required, false otherwise.
2233
- *
2234
- * @author Xeno
2235
- * @version 1.0.0
2236
- * @since 2025-09-30
2237
- * @link https://github.com/xeno-js/xeno-js
2238
- */
2239
- async addValidation(container, opts, logger) {
2240
- const { Guards: Guards51, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
2241
- if (!Guards51.isDefined(opts.zod) && Guards51.isNullOrEmpty(opts.customValidationStrategy)) {
2242
- return;
2243
- }
2244
- const validationStrategies = [];
2245
- if (Guards51.isDefined(opts.zod)) {
2246
- const config = opts.zod;
2247
- const { ZodValidatorFactory: ZodValidatorFactory2 } = await Promise.resolve().then(() => (init_zod_validator_factory(), zod_validator_factory_exports));
2248
- const { SchemaValidationStrategy: SchemaValidationStrategy2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2249
- const validatorService = new ZodValidatorFactory2().create({ ...config, logger });
2250
- container.addSingleton(TOKENS5.VALIDATOR_SERVICE, () => validatorService);
2251
- validationStrategies.push(new SchemaValidationStrategy2(validatorService));
2252
- }
2253
- if (!Guards51.isNullOrEmpty(opts.customValidationStrategy)) {
2254
- for (const strategyToken of opts.customValidationStrategy) {
2255
- if (Guards51.isDefined(strategyToken)) validationStrategies.push(strategyToken(container));
2256
- }
2257
- }
2258
- const { ValidationPipeline: ValidationPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2259
- return new ValidationPipeline2(validationStrategies);
2260
- }
2261
- });
2062
+ init_allow_origin_http();
2262
2063
  }
2263
2064
  });
2264
2065
 
2265
- // src/infrastructure/idempotency/idempotency-store.ts
2266
- var import_shared47, IdempotencyStore;
2267
- var init_idempotency_store = __esm({
2268
- "src/infrastructure/idempotency/idempotency-store.ts"() {
2066
+ // src/infrastructure/services/concurrency/p-limit.service.ts
2067
+ var PLimitConcurrencyService;
2068
+ var init_p_limit_service = __esm({
2069
+ "src/infrastructure/services/concurrency/p-limit.service.ts"() {
2269
2070
  "use strict";
2270
- import_shared47 = require("@xeno-js/shared");
2271
- IdempotencyStore = class {
2272
- /**
2273
- * @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.
2274
- * @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.
2275
- * @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.
2276
-
2277
- *
2278
- * @author Xeno
2279
- * @version 1.0.0
2280
- * @since 2025-09-30
2281
- * @link https://github.com/xeno-js/xeno-js
2282
- */
2283
- constructor(_cache, _cacheKeyBuilder) {
2284
- this._cache = _cache;
2285
- this._cacheKeyBuilder = _cacheKeyBuilder;
2286
- }
2287
- _cache;
2288
- _cacheKeyBuilder;
2289
- async acquireLock(requestId, ttlSeconds) {
2290
- const key = this._cacheKeyBuilder.buildContextualKey(`command:${requestId}`);
2291
- return await this._cache.setIfAbsent(
2292
- `${import_shared47.IDEMPOTENCY_CONSTANTS.LOCK_KEY_PREFIX}${key}`,
2293
- import_shared47.IDEMPOTENCY_CONSTANTS.LOCKED_VALUE,
2294
- ttlSeconds
2295
- );
2296
- }
2297
- async hasBeenProcessed(commandId) {
2298
- const key = this._cacheKeyBuilder.buildContextualKey(`command:${commandId}`);
2299
- return await this._cache.has(`${import_shared47.IDEMPOTENCY_CONSTANTS.PROCESSED_KEY_PREFIX}${key}`);
2300
- }
2301
- async markAsProcessed(commandId, payload, ttlSeconds) {
2302
- const key = this._cacheKeyBuilder.buildContextualKey(`command:${commandId}`);
2303
- await this._cache.set(
2304
- `${import_shared47.IDEMPOTENCY_CONSTANTS.PROCESSED_KEY_PREFIX}${key}`,
2305
- payload,
2306
- ttlSeconds
2307
- );
2308
- }
2309
- async getPayload(commandId) {
2310
- const key = this._cacheKeyBuilder.buildContextualKey(`command:${commandId}`);
2311
- const payload = await this._cache.get(`${import_shared47.IDEMPOTENCY_CONSTANTS.PROCESSED_KEY_PREFIX}${key}`);
2312
- return payload;
2313
- }
2314
- async releaseLock(commandId) {
2315
- const key = this._cacheKeyBuilder.buildContextualKey(`command:${commandId}`);
2316
- await this._cache.remove(`${import_shared47.IDEMPOTENCY_CONSTANTS.LOCK_KEY_PREFIX}${key}`);
2071
+ PLimitConcurrencyService = class {
2072
+ async executeInParallel(tasks, concurrencyLimit) {
2073
+ const { default: pLimit } = await import("p-limit");
2074
+ const limit = pLimit(concurrencyLimit);
2075
+ const promises = tasks.map((task) => limit(task));
2076
+ return Promise.all(promises);
2317
2077
  }
2318
2078
  };
2319
2079
  }
2320
2080
  });
2321
2081
 
2322
- // src/infrastructure/idempotency/index.ts
2323
- var idempotency_exports = {};
2324
- __export(idempotency_exports, {
2325
- IdempotencyStore: () => IdempotencyStore
2082
+ // src/infrastructure/services/concurrency/index.ts
2083
+ var concurrency_exports = {};
2084
+ __export(concurrency_exports, {
2085
+ PLimitConcurrencyService: () => PLimitConcurrencyService
2326
2086
  });
2327
- var init_idempotency = __esm({
2328
- "src/infrastructure/idempotency/index.ts"() {
2087
+ var init_concurrency = __esm({
2088
+ "src/infrastructure/services/concurrency/index.ts"() {
2329
2089
  "use strict";
2330
- init_idempotency_store();
2090
+ init_p_limit_service();
2331
2091
  }
2332
2092
  });
2333
2093
 
2334
- // src/infrastructure/modules/utils/pipeline.utils.ts
2335
- var pipeline_utils_exports = {};
2336
- __export(pipeline_utils_exports, {
2337
- PipelineUtils: () => PipelineUtils
2338
- });
2339
- var PipelineUtils;
2340
- var init_pipeline_utils = __esm({
2341
- "src/infrastructure/modules/utils/pipeline.utils.ts"() {
2094
+ // src/infrastructure/services/cookies/cookies.service.ts
2095
+ var import_shared47, CookieHandler;
2096
+ var init_cookies_service = __esm({
2097
+ "src/infrastructure/services/cookies/cookies.service.ts"() {
2342
2098
  "use strict";
2343
- PipelineUtils = Object.freeze({
2344
- /**
2345
- * @description Checks if the provided command configuration requires any command strategies.
2346
- * @param commandConfig The command configuration to check.
2347
- * @returns True if any command strategies are required, false otherwise.
2348
- *
2349
- * @author Xeno
2350
- * @version 1.0.0
2351
- * @since 2025-09-30
2352
- * @link https://github.com/xeno-js/xeno-js
2353
- */
2354
- async addCommand(container, opts) {
2355
- const { Guards: Guards51, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
2356
- const pipelines = [];
2357
- if (Guards51.isDefined(opts.idempotency)) {
2358
- const { IdempotencyStore: IdempotencyStore2 } = await Promise.resolve().then(() => (init_idempotency(), idempotency_exports));
2359
- const imdStore = new IdempotencyStore2(
2360
- container.resolve(TOKENS5.CACHE),
2361
- container.resolve(TOKENS5.CACHE_KEY_BUILDER)
2362
- );
2363
- const { IdempotencyPipeline: IdempotencyPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2364
- const requestContext = container.resolve(TOKENS5.NETWORK_CONTEXT_ACCESSOR);
2365
- const config = opts.idempotency;
2366
- pipelines.push(
2367
- new IdempotencyPipeline2(
2368
- requestContext,
2369
- imdStore,
2370
- config?.lockTtlSeconds,
2371
- config?.processedTtlSeconds
2372
- )
2373
- );
2374
- }
2375
- if (Guards51.isDefined(opts.concurrency)) {
2376
- const { ConcurrencyRetryPipeline: ConcurrencyRetryPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2377
- const config = opts.concurrency;
2378
- pipelines.push(new ConcurrencyRetryPipeline2(config?.maxRetries, config?.delayConfig));
2099
+ import_shared47 = require("@xeno-js/shared");
2100
+ CookieHandler = class {
2101
+ constructor(contextAccessor, _config, _cookieOpts) {
2102
+ this.contextAccessor = contextAccessor;
2103
+ this._config = _config;
2104
+ this._cookieOpts = _cookieOpts;
2105
+ }
2106
+ contextAccessor;
2107
+ _config;
2108
+ _cookieOpts;
2109
+ getAll() {
2110
+ const network = this.contextAccessor.getNetworkContext();
2111
+ const req = network?.transport?.req;
2112
+ if (!import_shared47.Guards.isDefined(req) || import_shared47.Guards.isNullOrEmpty(req.headers.get("cookie"))) return [];
2113
+ return req.headers.get("cookie")?.split(";").map((cookie) => {
2114
+ const [name, ...rest] = cookie.split("=");
2115
+ return { name: name.trim(), value: rest.join("=") };
2116
+ }) ?? [];
2117
+ }
2118
+ setAll(cookies) {
2119
+ const network = this.contextAccessor.getNetworkContext();
2120
+ const res = network?.transport?.res;
2121
+ if (!import_shared47.Guards.isDefined(res)) return;
2122
+ const serializedCookies = cookies.map((c) => this.serialize(c));
2123
+ const existingSetCookie = res.headers.getSetCookie();
2124
+ res.headers.delete("Set-Cookie");
2125
+ for (const cookie of [...existingSetCookie, ...serializedCookies]) {
2126
+ res.headers.append("Set-Cookie", cookie);
2379
2127
  }
2380
- return pipelines;
2381
- },
2382
- /**
2383
- * @description Checks if the provided query configuration requires any query strategies.
2384
- * @param queryConfig The query configuration to check.
2385
- * @returns True if any query strategies are required, false otherwise.
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
- async addQuery(container) {
2393
- const { TOKENS: TOKENS5 } = await import("@xeno-js/shared");
2394
- const { QueryCachingPipeline: QueryCachingPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2395
- return new QueryCachingPipeline2(
2396
- container.resolve(TOKENS5.CACHE),
2397
- container.resolve(TOKENS5.CACHE_KEY_BUILDER),
2398
- container.resolve(TOKENS5.LOGGER)
2399
- );
2400
2128
  }
2401
- });
2129
+ serialize(cookie) {
2130
+ const safeName = encodeURIComponent(cookie.name);
2131
+ const safeValue = encodeURIComponent(cookie.value);
2132
+ let str = `${safeName}=${safeValue}`;
2133
+ const isProd = this._config.get("NODE_ENV") === "production";
2134
+ const defaultOptions = {
2135
+ path: this._cookieOpts.path,
2136
+ httpOnly: this._cookieOpts.httpOnly,
2137
+ secure: this._cookieOpts.secure ?? isProd,
2138
+ sameSite: this._cookieOpts.sameSite ?? "Lax"
2139
+ };
2140
+ const opts = { ...defaultOptions, ...cookie.options ?? {} };
2141
+ str += `; Path=${opts.path}`;
2142
+ if (import_shared47.Guards.isDefined(opts.maxAge)) str += `; Max-Age=${opts.maxAge}`;
2143
+ if (import_shared47.Guards.isDefined(opts.domain)) str += `; Domain=${opts.domain}`;
2144
+ if (import_shared47.Guards.isDefined(opts.sameSite)) str += `; SameSite=${opts.sameSite}`;
2145
+ if (opts.secure) str += `; Secure`;
2146
+ if (opts.httpOnly) str += `; HttpOnly`;
2147
+ return str;
2148
+ }
2149
+ };
2402
2150
  }
2403
2151
  });
2404
2152
 
2405
- // src/infrastructure/modules/cqrs.module.ts
2406
- var cqrs_module_exports = {};
2407
- __export(cqrs_module_exports, {
2408
- CqrsModule: () => CqrsModule
2153
+ // src/infrastructure/services/cookies/index.ts
2154
+ var init_cookies = __esm({
2155
+ "src/infrastructure/services/cookies/index.ts"() {
2156
+ "use strict";
2157
+ init_cookies_service();
2158
+ }
2409
2159
  });
2410
- var CqrsModule;
2411
- var init_cqrs_module = __esm({
2412
- "src/infrastructure/modules/cqrs.module.ts"() {
2160
+
2161
+ // src/infrastructure/services/crypto/crypto.service.ts
2162
+ var EdgeCryptoService;
2163
+ var init_crypto_service = __esm({
2164
+ "src/infrastructure/services/crypto/crypto.service.ts"() {
2413
2165
  "use strict";
2414
- CqrsModule = class {
2415
- async configure(container, opts) {
2416
- const { Guards: Guards51, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
2417
- const logger = container.resolve(TOKENS5.LOGGER);
2418
- const { Mediator: Mediator2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2419
- container.addSingleton(TOKENS5.MEDIATOR, (c) => {
2420
- const serviceScopeAccessor = c.resolve(TOKENS5.SERVICE_SCOPE_ACCESSOR);
2421
- return new Mediator2(serviceScopeAccessor);
2422
- });
2423
- const { ExceptionPipeline: ExceptionPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2424
- const { LoggingPipeline: LoggingPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2425
- const { PerformancePipeline: PerformancePipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2426
- const thresholdMs = opts.performance?.thresholdMs;
2427
- const pipelines = [
2428
- new ExceptionPipeline2(),
2429
- new LoggingPipeline2(logger),
2430
- new PerformancePipeline2(logger, opts.performance.intentThresholdMs, thresholdMs)
2431
- ];
2432
- if (Guards51.isDefined(opts.authorization.policies) || Guards51.isDefined(opts.authorization.customAuthorizationStrategy)) {
2433
- const { AuthUtils: AuthUtils2 } = await Promise.resolve().then(() => (init_auth_utils(), auth_utils_exports));
2434
- const authPipelines = await AuthUtils2.addAuthZ(container, opts.authorization);
2435
- pipelines.push(authPipelines);
2436
- }
2437
- if (Guards51.isDefined(opts.validation.zod) || Guards51.isDefined(opts.validation.customValidationStrategy)) {
2438
- const { ValidationUtils: ValidationUtils2 } = await Promise.resolve().then(() => (init_validation_utils(), validation_utils_exports));
2439
- const validationPipelines = await ValidationUtils2.addValidation(
2440
- container,
2441
- opts.validation,
2442
- logger
2443
- );
2444
- if (Guards51.isDefined(validationPipelines)) pipelines.push(validationPipelines);
2445
- }
2446
- const commandPipelines = [...pipelines];
2447
- const queryPipelines = [...pipelines];
2448
- if (Guards51.isDefined(opts.commandBus.idempotency) || Guards51.isDefined(opts.commandBus.concurrency)) {
2449
- const { PipelineUtils: PipelineUtils2 } = await Promise.resolve().then(() => (init_pipeline_utils(), pipeline_utils_exports));
2450
- const newCommandPipelines = await PipelineUtils2.addCommand(container, opts.commandBus);
2451
- commandPipelines.push(...newCommandPipelines);
2166
+ EdgeCryptoService = class {
2167
+ randomBytes(size) {
2168
+ const buffer = new Uint8Array(size);
2169
+ crypto.getRandomValues(buffer);
2170
+ return buffer;
2171
+ }
2172
+ async hmacSha256(secret, data) {
2173
+ const encoder = new TextEncoder();
2174
+ const keyData = encoder.encode(secret);
2175
+ const messageData = encoder.encode(data);
2176
+ const cryptoKey = await crypto.subtle.importKey(
2177
+ "raw",
2178
+ keyData,
2179
+ { name: "HMAC", hash: "SHA-256" },
2180
+ false,
2181
+ ["sign"]
2182
+ );
2183
+ const signature = await crypto.subtle.sign("HMAC", cryptoKey, messageData);
2184
+ return btoa(String.fromCharCode(...new Uint8Array(signature))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
2185
+ }
2186
+ timingSafeEqual(a, b) {
2187
+ if (a.length !== b.length) {
2188
+ return false;
2452
2189
  }
2453
- if (opts.queryBus.isEnabled) {
2454
- const { PipelineUtils: PipelineUtils2 } = await Promise.resolve().then(() => (init_pipeline_utils(), pipeline_utils_exports));
2455
- const newQueryPipelines = await PipelineUtils2.addQuery(container);
2456
- queryPipelines.push(newQueryPipelines);
2190
+ let mismatch = 0;
2191
+ for (let i = 0; i < a.length; i++) {
2192
+ mismatch |= a[i] ^ b[i];
2457
2193
  }
2458
- const { CompositePipeline: CompositePipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2459
- container.addSingleton(TOKENS5.COMMAND_PIPELINES_BEHAVIOR, () => {
2460
- return new CompositePipeline2(commandPipelines);
2461
- });
2462
- container.addSingleton(TOKENS5.QUERY_PIPELINES_BEHAVIOR, () => {
2463
- return new CompositePipeline2(queryPipelines);
2464
- });
2194
+ return mismatch === 0;
2465
2195
  }
2466
2196
  };
2467
2197
  }
2468
2198
  });
2469
2199
 
2470
- // src/infrastructure/factories/sql-light-db-client.factory.ts
2471
- var sql_light_db_client_factory_exports = {};
2472
- __export(sql_light_db_client_factory_exports, {
2473
- DbSqlLiteClientFactory: () => DbSqlLiteClientFactory
2474
- });
2475
- var import_client, import_libsql, DbSqlLiteClientFactory;
2476
- var init_sql_light_db_client_factory = __esm({
2477
- "src/infrastructure/factories/sql-light-db-client.factory.ts"() {
2200
+ // src/infrastructure/services/crypto/index.ts
2201
+ var init_crypto = __esm({
2202
+ "src/infrastructure/services/crypto/index.ts"() {
2478
2203
  "use strict";
2479
- import_client = require("@libsql/client");
2480
- import_libsql = require("drizzle-orm/libsql");
2481
- DbSqlLiteClientFactory = class {
2482
- create(opts) {
2483
- const client = (0, import_client.createClient)({ url: opts.connectionString });
2484
- return (0, import_libsql.drizzle)({ client });
2485
- }
2486
- };
2204
+ init_crypto_service();
2487
2205
  }
2488
2206
  });
2489
2207
 
2490
- // src/infrastructure/factories/db-client.factory.ts
2491
- var db_client_factory_exports = {};
2492
- __export(db_client_factory_exports, {
2493
- DbClientFactory: () => DbClientFactory
2494
- });
2495
- var import_node_postgres, import_pg, DbClientFactory;
2496
- var init_db_client_factory = __esm({
2497
- "src/infrastructure/factories/db-client.factory.ts"() {
2208
+ // src/infrastructure/services/csrf/csrf-token.service.ts
2209
+ var import_shared48, CsrfTokenService;
2210
+ var init_csrf_token_service = __esm({
2211
+ "src/infrastructure/services/csrf/csrf-token.service.ts"() {
2498
2212
  "use strict";
2499
- import_node_postgres = require("drizzle-orm/node-postgres");
2500
- import_pg = require("pg");
2501
- DbClientFactory = class {
2502
- create(opts) {
2503
- const pool = new import_pg.Pool({
2504
- connectionString: opts.connectionString
2505
- });
2506
- return (0, import_node_postgres.drizzle)({ client: pool });
2213
+ import_shared48 = require("@xeno-js/shared");
2214
+ CsrfTokenService = class {
2215
+ constructor(_secret, _cryptoService) {
2216
+ this._secret = _secret;
2217
+ this._cryptoService = _cryptoService;
2218
+ }
2219
+ _secret;
2220
+ _cryptoService;
2221
+ async generate(subject) {
2222
+ const randomBuffer = this._cryptoService.randomBytes(32);
2223
+ const nonce = btoa(String.fromCharCode(...randomBuffer)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
2224
+ const signature = await this._cryptoService.hmacSha256(this._secret, `${subject}.${nonce}`);
2225
+ return `${nonce}.${signature}`;
2226
+ }
2227
+ async validate(token, subject) {
2228
+ const separatorIndex = token.indexOf(".");
2229
+ if (separatorIndex <= 0) return false;
2230
+ const nonce = token.slice(0, separatorIndex);
2231
+ const signature = token.slice(separatorIndex + 1);
2232
+ if (import_shared48.Guards.isNullOrEmpty(nonce) || import_shared48.Guards.isNullOrEmpty(signature)) return false;
2233
+ const expected = await this._cryptoService.hmacSha256(this._secret, `${subject}.${nonce}`);
2234
+ const encoder = new TextEncoder();
2235
+ const actualBuffer = encoder.encode(signature);
2236
+ const expectedBuffer = encoder.encode(expected);
2237
+ if (actualBuffer.length !== expectedBuffer.length) return false;
2238
+ return this._cryptoService.timingSafeEqual(actualBuffer, expectedBuffer);
2507
2239
  }
2508
2240
  };
2509
2241
  }
2510
2242
  });
2511
2243
 
2512
- // src/infrastructure/modules/utils/db.utils.ts
2513
- var db_utils_exports = {};
2514
- __export(db_utils_exports, {
2515
- DbUtils: () => DbUtils
2516
- });
2517
- var DbUtils;
2518
- var init_db_utils = __esm({
2519
- "src/infrastructure/modules/utils/db.utils.ts"() {
2244
+ // src/infrastructure/services/csrf/index.ts
2245
+ var init_csrf = __esm({
2246
+ "src/infrastructure/services/csrf/index.ts"() {
2520
2247
  "use strict";
2521
- DbUtils = Object.freeze({
2522
- /**
2523
- * @description Creates a new instance of a database client configured for SQLite using the provided database configuration options. This utility function encapsulates the logic for initializing a SQLite database client, allowing for easy integration with the application's dependency injection system. It ensures that the necessary connection string and other configuration parameters are correctly applied to create a functional database client instance.
2524
- *
2525
- * @param opts - The database configuration options, including the connection string and any other relevant settings required for establishing a connection to the SQLite database.
2526
- * @returns A new instance of a database client configured for SQLite, ready for use in the application.
2527
- *
2528
- * @author Xeno
2529
- * @version 1.0.0
2530
- * @since 2025-09-30
2531
- * @link https://github.com/xeno-js/xeno-js
2532
- */
2533
- async addSqlLite(opts) {
2534
- const { DbSqlLiteClientFactory: DbSqlLiteClientFactory2 } = await Promise.resolve().then(() => (init_sql_light_db_client_factory(), sql_light_db_client_factory_exports));
2535
- return new DbSqlLiteClientFactory2().create(opts);
2536
- },
2537
- /**
2538
- * @description Creates a new instance of a database client based on the provided database configuration options. This utility function encapsulates the logic for initializing a database client, allowing for easy integration with the application's dependency injection system. It ensures that the necessary connection string and other configuration parameters are correctly applied to create a functional database client instance.
2539
- * @param opts - The database configuration options, including the connection string and any other relevant settings required for establishing a connection to the database.
2540
- * @returns A new instance of a database client, ready for use in the application.
2541
- * @author Xeno
2542
- * @version 1.0.0
2543
- * @since 2025-09-30
2544
- * @link https://github.com/xeno-js/xeno-js
2545
- */
2546
- async addDbClient(opts) {
2547
- const { DbClientFactory: DbClientFactory2 } = await Promise.resolve().then(() => (init_db_client_factory(), db_client_factory_exports));
2548
- return new DbClientFactory2().create(opts);
2549
- }
2550
- });
2248
+ init_csrf_token_service();
2551
2249
  }
2552
2250
  });
2553
2251
 
2554
- // src/infrastructure/transaction/transaction-state.ts
2555
- var transaction_state_exports = {};
2556
- __export(transaction_state_exports, {
2557
- TransactionState: () => TransactionState
2558
- });
2559
- var TransactionState;
2560
- var init_transaction_state = __esm({
2561
- "src/infrastructure/transaction/transaction-state.ts"() {
2252
+ // src/infrastructure/services/extractors/extract-bearer.extractor.ts
2253
+ var import_shared49, BearerTokenExtractor;
2254
+ var init_extract_bearer_extractor = __esm({
2255
+ "src/infrastructure/services/extractors/extract-bearer.extractor.ts"() {
2562
2256
  "use strict";
2563
- TransactionState = class {
2564
- /**
2565
- * The current state of the transaction, which can be either a specific transaction type or null.
2566
- * @author Xeno
2567
- * @version 1.0.0
2568
- * @since 2025-09-30
2569
- * @link https://github.com/xeno-js/xeno-js
2570
- */
2571
- _state = null;
2572
- /**
2573
- * Creates an instance of TransactionState.
2574
- * @param initialState - The initial state of the transaction, which can be either a specific transaction type or null.
2575
- * @author Xeno
2576
- * @version 1.0.0
2577
- * @since 2025-09-30
2578
- * @link https://github.com/xeno-js/xeno-js
2579
- */
2580
- constructor(initialState = null) {
2581
- this._state = initialState;
2257
+ import_shared49 = require("@xeno-js/shared");
2258
+ BearerTokenExtractor = class {
2259
+ constructor(_cookiePrefix) {
2260
+ this._cookiePrefix = _cookiePrefix;
2582
2261
  }
2583
- get state() {
2584
- return this._state;
2262
+ _cookiePrefix;
2263
+ extract(headers) {
2264
+ const authHeader = headers.get("Authorization");
2265
+ if (import_shared49.Guards.isDefined(authHeader) && authHeader.toLowerCase().startsWith("bearer ")) {
2266
+ return authHeader.substring(7);
2267
+ }
2268
+ const cookieHeader = headers.get("cookie");
2269
+ if (import_shared49.Guards.isDefined(cookieHeader)) {
2270
+ const regex = new RegExp(`${this._cookiePrefix}=([^;]+)`);
2271
+ const match = regex.exec(cookieHeader);
2272
+ if (!import_shared49.Guards.isNullOrEmpty(match) && import_shared49.Guards.isDefined(match[1])) {
2273
+ return match[1].trim();
2274
+ }
2275
+ }
2276
+ return void 0;
2585
2277
  }
2586
- set state(value) {
2587
- this._state = value;
2278
+ };
2279
+ }
2280
+ });
2281
+
2282
+ // src/infrastructure/services/extractors/extract-ssr-bearer.extractor.ts
2283
+ var import_shared50, SupabaseSsrTokenExtractor;
2284
+ var init_extract_ssr_bearer_extractor = __esm({
2285
+ "src/infrastructure/services/extractors/extract-ssr-bearer.extractor.ts"() {
2286
+ "use strict";
2287
+ import_shared50 = require("@xeno-js/shared");
2288
+ SupabaseSsrTokenExtractor = class {
2289
+ extract(headers) {
2290
+ const authHeader = headers.get("authorization");
2291
+ if (import_shared50.Guards.isDefined(authHeader) && authHeader.toLowerCase().startsWith("bearer ")) {
2292
+ return authHeader.substring(7);
2293
+ }
2294
+ const cookieHeader = headers.get("cookie");
2295
+ if (import_shared50.Guards.isNullOrEmpty(cookieHeader)) return void 0;
2296
+ const cookies = cookieHeader.split(";").map((c) => c.trim());
2297
+ const tokenChunks = {};
2298
+ let unchunkedToken;
2299
+ for (const cookie of cookies) {
2300
+ const [name, ...rest] = cookie.split("=");
2301
+ if (!import_shared50.Guards.isDefined(name) || import_shared50.Guards.isNullOrEmpty(rest)) continue;
2302
+ const value = decodeURIComponent(rest.join("="));
2303
+ if (import_shared50.Guards.isDefined(/^sb-[a-z0-9]+-auth-token$/.exec(name))) {
2304
+ unchunkedToken = value;
2305
+ } else {
2306
+ const match = /^sb-[a-z0-9]+-auth-token\.(\d+)$/.exec(name);
2307
+ if (import_shared50.Guards.isDefined(match)) tokenChunks[parseInt(match[1], 10)] = value;
2308
+ }
2309
+ }
2310
+ let fullTokenString = unchunkedToken;
2311
+ if (!import_shared50.Guards.isDefined(fullTokenString) && Object.keys(tokenChunks).length > 0) {
2312
+ const indices = Object.keys(tokenChunks).map(Number).sort((a, b) => a - b);
2313
+ fullTokenString = indices.map((i) => tokenChunks[i]).join("");
2314
+ }
2315
+ if (import_shared50.Guards.isNullOrEmpty(fullTokenString)) return void 0;
2316
+ try {
2317
+ const parsed = import_shared50.StringHelper.safeParse(fullTokenString);
2318
+ if (import_shared50.Guards.isDefined(parsed) && import_shared50.Guards.isObject(parsed) && "access_token" in parsed) {
2319
+ const accessToken = parsed["access_token"];
2320
+ if (import_shared50.Guards.isString(accessToken)) return accessToken;
2321
+ }
2322
+ } catch {
2323
+ return void 0;
2324
+ }
2325
+ }
2326
+ };
2327
+ }
2328
+ });
2329
+
2330
+ // src/infrastructure/services/extractors/http-cookie.extractor.ts
2331
+ var import_shared51, HttpCookieExtractor;
2332
+ var init_http_cookie_extractor = __esm({
2333
+ "src/infrastructure/services/extractors/http-cookie.extractor.ts"() {
2334
+ "use strict";
2335
+ import_shared51 = require("@xeno-js/shared");
2336
+ HttpCookieExtractor = class {
2337
+ extract(cookie) {
2338
+ if (!import_shared51.Guards.isDefined(cookie.header)) return void 0;
2339
+ for (const rawCookie of cookie.header.split(";")) {
2340
+ const separatorIndex = rawCookie.indexOf("=");
2341
+ if (separatorIndex <= 0) continue;
2342
+ const name = rawCookie.slice(0, separatorIndex).trim();
2343
+ if (name !== cookie.name) continue;
2344
+ const value = rawCookie.slice(separatorIndex + 1).trim();
2345
+ try {
2346
+ return decodeURIComponent(value);
2347
+ } catch {
2348
+ return void 0;
2349
+ }
2350
+ }
2351
+ return void 0;
2588
2352
  }
2589
2353
  };
2590
2354
  }
2591
2355
  });
2592
2356
 
2593
- // src/infrastructure/transaction/unit-of-work.ts
2594
- var unit_of_work_exports = {};
2595
- __export(unit_of_work_exports, {
2596
- UnitOfWork: () => UnitOfWork
2597
- });
2598
- var import_shared48, import_shared49, UnitOfWork;
2599
- var init_unit_of_work = __esm({
2600
- "src/infrastructure/transaction/unit-of-work.ts"() {
2357
+ // src/infrastructure/services/extractors/http-header.extractor.ts
2358
+ var import_shared52, HttpHeaderExtractor;
2359
+ var init_http_header_extractor = __esm({
2360
+ "src/infrastructure/services/extractors/http-header.extractor.ts"() {
2601
2361
  "use strict";
2602
- import_shared48 = require("@xeno-js/shared");
2603
- import_shared49 = require("@xeno-js/shared");
2604
- UnitOfWork = class {
2362
+ import_shared52 = require("@xeno-js/shared");
2363
+ HttpHeaderExtractor = class {
2605
2364
  /**
2606
- * Creates an instance of UnitOfWork.
2607
- * @param _dbContext - The database context used for managing transactions.
2608
- * @param _ttx - The transaction state, which can be either a specific transaction type or null.
2609
- *
2365
+ * @description Constructor for HttpHeaderExtractor. It takes an instance of IServiceExtractor for extracting Bearer tokens, allowing for separation of concerns and adherence to the Single Responsibility Principle (SRP). This design enables the HttpHeaderExtractor to focus on general header extraction while delegating the specific logic of Bearer token extraction to a dedicated extractor, promoting code reusability and maintainability.
2366
+
2367
+ *
2610
2368
  * @author Xeno
2611
2369
  * @version 1.0.0
2612
2370
  * @since 2025-09-30
2613
- * @link https://github.com/xeno-js/xeno-js
2371
+ * @link https://github.com/xeno-js/xeno-js
2614
2372
  */
2615
- constructor(_dbContext, _ttx) {
2616
- this._dbContext = _dbContext;
2617
- this._ttx = _ttx;
2373
+ constructor(_bearerExtractor, _cookieExtractor, _trustedIp, _cookieName) {
2374
+ this._bearerExtractor = _bearerExtractor;
2375
+ this._cookieExtractor = _cookieExtractor;
2376
+ this._trustedIp = _trustedIp;
2377
+ this._cookieName = _cookieName;
2618
2378
  }
2619
- _dbContext;
2620
- _ttx;
2621
- async runInTransaction(callback, signal) {
2622
- import_shared48.AppError.throwIfAborted(signal, "UnitOfWork.runInTransaction");
2623
- return this._dbContext.transaction(async (tx) => {
2624
- this._ttx.state = tx;
2625
- try {
2626
- const result = await callback();
2627
- return result;
2628
- } finally {
2629
- this._ttx.state = null;
2630
- }
2379
+ _bearerExtractor;
2380
+ _cookieExtractor;
2381
+ _trustedIp;
2382
+ _cookieName;
2383
+ extract(headers) {
2384
+ const correlationId = import_shared52.GuidHelper.parse(headers.get("x-correlation-id") ?? void 0);
2385
+ const requestId = import_shared52.GuidHelper.parse(headers.get("x-request-id") ?? void 0);
2386
+ const token = this._bearerExtractor.extract(headers);
2387
+ const clientIp = headers.get(this._trustedIp?.toLowerCase() ?? "x-forwarded-for") ?? headers.get("x-real-ip") ?? void 0;
2388
+ const spanId = import_shared52.GuidHelper.parse(headers.get("x-span-id") ?? void 0);
2389
+ const parentSpanId = headers.get("x-parent-span-id") ?? void 0;
2390
+ const acceptHeader = headers.get("accept");
2391
+ const contentTypeHeader = headers.get("content-type");
2392
+ const userAgent = headers.get("user-agent") ?? void 0;
2393
+ const returnAddress = headers.get("x-return-address") ?? void 0;
2394
+ const sequenceId = headers.get("x-sequence-id") ?? void 0;
2395
+ const position = headers.get("x-sequence-position");
2396
+ const size = headers.get("x-sequence-size");
2397
+ const expiration = headers.get("x-expiration");
2398
+ const csrf = headers.get("x-csrf-token") ?? void 0;
2399
+ const cookieHeader = headers.get("cookie") ?? void 0;
2400
+ const csrfCookie = this._cookieExtractor.extract({
2401
+ header: cookieHeader,
2402
+ name: this._cookieName
2631
2403
  });
2632
- }
2633
- async dispose() {
2634
- if (import_shared49.Guards.isDefined(this._ttx.state)) {
2635
- try {
2636
- if (import_shared49.Guards.hasMethod(this._ttx.state, "rollback")) {
2637
- await this._ttx.state.rollback();
2638
- }
2639
- } finally {
2640
- this._ttx.state = null;
2641
- }
2642
- }
2404
+ const origin = headers.get("origin") ?? void 0;
2405
+ const cleanOrigin = import_shared52.HttpHelper.sanitizeOriginUrl(origin);
2406
+ const referer = headers.get("referer") ?? void 0;
2407
+ const cleanReferer = import_shared52.HttpHelper.sanitizeOriginUrl(referer);
2408
+ const accept = acceptHeader === "*/*" ? void 0 : acceptHeader;
2409
+ const formatIndicator = accept ?? contentTypeHeader ?? "application/json";
2410
+ const metadata = {
2411
+ correlationId,
2412
+ requestId,
2413
+ token,
2414
+ clientIp,
2415
+ spanId,
2416
+ parentSpanId,
2417
+ formatIndicator,
2418
+ userAgent,
2419
+ returnAddress,
2420
+ csrf,
2421
+ csrfCookie,
2422
+ origin: cleanOrigin,
2423
+ referer: cleanReferer,
2424
+ sequence: {
2425
+ sequenceId,
2426
+ position: import_shared52.Guards.isDefined(position) ? import_shared52.MathHelper.toNumber(position) : void 0,
2427
+ size: import_shared52.Guards.isDefined(size) ? import_shared52.MathHelper.toNumber(size) : void 0
2428
+ },
2429
+ expiration: import_shared52.Guards.isDefined(expiration) ? import_shared52.MathHelper.toNumber(expiration) : void 0
2430
+ };
2431
+ return metadata;
2643
2432
  }
2644
2433
  };
2645
2434
  }
2646
2435
  });
2647
2436
 
2648
- // src/infrastructure/modules/db.module.ts
2649
- var db_module_exports = {};
2650
- __export(db_module_exports, {
2651
- DbModule: () => DbModule
2437
+ // src/infrastructure/services/extractors/index.ts
2438
+ var init_extractors = __esm({
2439
+ "src/infrastructure/services/extractors/index.ts"() {
2440
+ "use strict";
2441
+ init_extract_bearer_extractor();
2442
+ init_extract_ssr_bearer_extractor();
2443
+ init_http_cookie_extractor();
2444
+ init_http_header_extractor();
2445
+ }
2652
2446
  });
2653
- var DbModule;
2654
- var init_db_module = __esm({
2655
- "src/infrastructure/modules/db.module.ts"() {
2447
+
2448
+ // src/infrastructure/services/resiliences/resilience.service.ts
2449
+ var import_shared53, ServiceResilience;
2450
+ var init_resilience_service = __esm({
2451
+ "src/infrastructure/services/resiliences/resilience.service.ts"() {
2656
2452
  "use strict";
2657
- DbModule = class {
2658
- async configure(container, opts) {
2659
- const { Guards: Guards51, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
2660
- const { DbUtils: DbUtils2 } = await Promise.resolve().then(() => (init_db_utils(), db_utils_exports));
2661
- const db = opts.enableSqlLite ? await DbUtils2.addSqlLite(opts) : await DbUtils2.addDbClient(opts);
2662
- const { TransactionState: TransactionState2 } = await Promise.resolve().then(() => (init_transaction_state(), transaction_state_exports));
2663
- container.addScoped("TRANSACTION_STATE", () => {
2664
- return new TransactionState2();
2665
- });
2666
- const { UnitOfWork: UnitOfWork2 } = await Promise.resolve().then(() => (init_unit_of_work(), unit_of_work_exports));
2667
- container.addScoped(TOKENS5.UNIT_OF_WORK, (c) => {
2668
- const ttx = c.resolve("TRANSACTION_STATE");
2669
- return new UnitOfWork2(db, ttx);
2670
- });
2671
- container.addScoped(TOKENS5.DB_CONTEXT, (c) => {
2672
- const ttx = c.resolve("TRANSACTION_STATE");
2673
- return new Proxy(db, {
2674
- get(_target, prop, receiver) {
2675
- const activeState = ttx.state;
2676
- if (Guards51.isDefined(activeState)) {
2677
- if (prop === "transaction") {
2678
- return activeState.transaction.bind(activeState);
2679
- }
2680
- return Reflect.get(activeState, prop, receiver);
2681
- }
2682
- return Reflect.get(db, prop, receiver);
2683
- }
2684
- });
2685
- });
2453
+ import_shared53 = require("@xeno-js/shared");
2454
+ ServiceResilience = class {
2455
+ constructor(policy) {
2456
+ this.policy = policy;
2457
+ }
2458
+ policy;
2459
+ async execute(operation, signal) {
2460
+ import_shared53.AppError.throwIfAborted(signal, "ServiceResilience.execute");
2461
+ return this.policy.execute(() => operation(), signal);
2686
2462
  }
2687
2463
  };
2688
2464
  }
2689
2465
  });
2690
2466
 
2691
- // src/infrastructure/http/base.http-adapter.ts
2692
- var import_shared50, BaseHttpAdapter;
2693
- var init_base_http_adapter = __esm({
2694
- "src/infrastructure/http/base.http-adapter.ts"() {
2467
+ // src/infrastructure/services/resiliences/index.ts
2468
+ var init_resiliences = __esm({
2469
+ "src/infrastructure/services/resiliences/index.ts"() {
2695
2470
  "use strict";
2696
- import_shared50 = require("@xeno-js/shared");
2697
- BaseHttpAdapter = class {
2698
- /**
2699
- * @description Parse the URL from the request.
2700
- * @param rawUrl The raw URL.
2701
- * @param headers The headers.
2702
- * @param queryParams The query parameters.
2703
- * @returns The parsed URL.
2704
- */
2705
- parseUrl(rawUrl = "/", headers, queryParams) {
2706
- const protocol = import_shared50.StringHelper.getSingleValue(headers["x-forwarded-proto"]) ?? "https";
2707
- const host = import_shared50.StringHelper.safeStringify(headers["host"]) ?? "localhost";
2708
- const cleanHost = host.replace(/['"]/g, "");
2709
- const url = new URL(rawUrl, `${protocol}://${cleanHost}`);
2710
- if (!import_shared50.Guards.isNullOrEmpty(queryParams)) {
2711
- for (const [key, value] of Object.entries(queryParams)) {
2712
- if (import_shared50.Guards.isArray(value)) {
2713
- value.forEach((v) => url.searchParams.append(key, String(v)));
2714
- } else if (import_shared50.Guards.isDefined(value)) {
2715
- url.searchParams.set(key, String(value));
2716
- }
2717
- }
2718
- }
2719
- return url;
2720
- }
2721
- /**
2722
- * @description Parses the headers.
2723
- * @param rawHeaders The raw headers.
2724
- * @returns The parsed headers.
2725
- */
2726
- parseHeaders(rawHeaders) {
2727
- const headers = new Headers();
2728
- for (const [key, value] of Object.entries(rawHeaders)) {
2729
- if (import_shared50.Guards.isDefined(value)) {
2730
- if (import_shared50.Guards.isArray(value)) {
2731
- value.forEach((v) => headers.append(key, String(v)));
2732
- } else {
2733
- headers.set(key, String(value));
2734
- }
2735
- }
2736
- }
2737
- return headers;
2738
- }
2739
- /**
2740
- * @description Parses the body.
2741
- * @param method The method.
2742
- * @param rawBody The raw body.
2743
- * @returns The parsed body.
2744
- */
2745
- parseBody(method, rawBody) {
2746
- if (!import_shared50.Guards.isDefined(method) || !["POST", "PUT", "PATCH", "DELETE"].includes(method.toUpperCase()) || !import_shared50.Guards.isDefined(rawBody))
2747
- return void 0;
2748
- if (import_shared50.Guards.isObject(rawBody)) return JSON.stringify(rawBody);
2749
- if (import_shared50.Guards.isString(rawBody) || rawBody instanceof Blob || rawBody instanceof ArrayBuffer || ArrayBuffer.isView(rawBody) || rawBody instanceof URLSearchParams || rawBody instanceof FormData)
2750
- return rawBody;
2751
- return String(rawBody);
2752
- }
2471
+ init_resilience_service();
2472
+ }
2473
+ });
2474
+
2475
+ // src/infrastructure/services/resolver/utils/socket.utils.ts
2476
+ var import_shared54, SocketIpExtractor;
2477
+ var init_socket_utils = __esm({
2478
+ "src/infrastructure/services/resolver/utils/socket.utils.ts"() {
2479
+ "use strict";
2480
+ import_shared54 = require("@xeno-js/shared");
2481
+ SocketIpExtractor = Object.freeze({
2753
2482
  /**
2754
- * @description Creates the XenoWebTransport.
2755
- * @param url The url.
2756
- * @param method The method.
2757
- * @param headers The headers.
2758
- * @param body The body.
2759
- * @returns The XenoWebTransport.
2483
+ * @description Extracts the IP address of the remote socket from an incoming request.
2484
+ * @param req The incoming request object.
2485
+ * @returns The IP address of the remote socket, or undefined if not available.
2760
2486
  */
2761
- createXenoWebTransport(url, method = "GET", headers, body = void 0, res = void 0) {
2762
- const init2 = {
2763
- method: method.toUpperCase(),
2764
- headers
2765
- };
2766
- const parsedBody = this.parseBody(method, body);
2767
- if (import_shared50.Guards.isDefined(parsedBody)) {
2768
- init2.body = parsedBody;
2769
- init2.duplex = "half";
2770
- }
2771
- const extendedRequest = new Request(url, init2);
2772
- extendedRequest.path = url.pathname;
2773
- const webResponse = new Response();
2774
- if (import_shared50.Guards.isDefined(res)) {
2775
- const originalAppend = webResponse.headers.append.bind(webResponse.headers);
2776
- const originalSet = webResponse.headers.set.bind(webResponse.headers);
2777
- const originalDelete = webResponse.headers.delete.bind(webResponse.headers);
2778
- webResponse.headers.append = (name, value) => {
2779
- originalAppend(name, value);
2780
- this.handleHeaderChange(res, name, value, "append");
2781
- };
2782
- webResponse.headers.set = (name, value) => {
2783
- originalSet(name, value);
2784
- this.handleHeaderChange(res, name, value, "set");
2785
- };
2786
- webResponse.headers.delete = (name) => {
2787
- originalDelete(name);
2788
- this.handleHeaderChange(res, name, "", "delete");
2789
- };
2487
+ extract(req) {
2488
+ if (import_shared54.Guards.isDefined(req) && import_shared54.Guards.isObject(req)) {
2489
+ const candidate = req;
2490
+ return candidate.socket?.remoteAddress ?? candidate.connection?.remoteAddress;
2790
2491
  }
2791
- return {
2792
- request: extendedRequest,
2793
- response: webResponse
2794
- };
2492
+ return void 0;
2795
2493
  }
2796
- };
2494
+ });
2495
+ }
2496
+ });
2497
+
2498
+ // src/infrastructure/services/resolver/utils/index.ts
2499
+ var init_utils = __esm({
2500
+ "src/infrastructure/services/resolver/utils/index.ts"() {
2501
+ "use strict";
2502
+ init_socket_utils();
2797
2503
  }
2798
2504
  });
2799
2505
 
2800
- // src/infrastructure/http/vercel.http-adapter.ts
2801
- var vercel_http_adapter_exports = {};
2802
- __export(vercel_http_adapter_exports, {
2803
- VercelHttpAdapter: () => VercelHttpAdapter
2804
- });
2805
- var import_shared51, VercelHttpAdapter;
2806
- var init_vercel_http_adapter = __esm({
2807
- "src/infrastructure/http/vercel.http-adapter.ts"() {
2506
+ // src/infrastructure/services/resolver/client-ip.resolver.ts
2507
+ var import_shared55, ClientIpResolver;
2508
+ var init_client_ip_resolver = __esm({
2509
+ "src/infrastructure/services/resolver/client-ip.resolver.ts"() {
2808
2510
  "use strict";
2809
- import_shared51 = require("@xeno-js/shared");
2810
- init_base_http_adapter();
2811
- VercelHttpAdapter = class extends BaseHttpAdapter {
2812
- adapt(req, res) {
2813
- const headers = this.parseHeaders(req.headers);
2814
- const url = this.parseUrl(req.url, req.headers, req.query);
2815
- return this.createXenoWebTransport(url, req.method, headers, req.body, res);
2511
+ import_shared55 = require("@xeno-js/shared");
2512
+ init_utils();
2513
+ ClientIpResolver = class {
2514
+ constructor(_trustedProxies = []) {
2515
+ this._trustedProxies = _trustedProxies;
2816
2516
  }
2817
- handleHeaderChange(res, name, value, action) {
2818
- if (action === "delete") {
2819
- res.removeHeader(name);
2820
- return;
2821
- }
2822
- if (name.toLowerCase() === "set-cookie") {
2823
- const existing = res.getHeader("Set-Cookie");
2824
- let cookies = [];
2825
- if (import_shared51.Guards.isArray(existing)) {
2826
- cookies = existing;
2827
- } else if (import_shared51.Guards.isString(existing)) {
2828
- cookies = [existing];
2829
- }
2830
- if (action === "append") {
2831
- cookies.push(value);
2832
- } else {
2833
- cookies = [value];
2834
- }
2835
- res.setHeader("Set-Cookie", cookies);
2836
- } else {
2837
- res.setHeader(name, value);
2838
- }
2517
+ _trustedProxies;
2518
+ resolve(req, clientIp) {
2519
+ const socketIp = SocketIpExtractor.extract(req);
2520
+ if (!import_shared55.Guards.isDefined(socketIp))
2521
+ return !import_shared55.Guards.isNullOrEmpty(clientIp) ? clientIp.split(",")[0].trim() : void 0;
2522
+ const isTrustedProxy = this._trustedProxies.includes(socketIp);
2523
+ if (!isTrustedProxy) return socketIp;
2524
+ if (import_shared55.Guards.isDefined(clientIp)) return clientIp.split(",")[0].trim();
2525
+ return socketIp;
2839
2526
  }
2840
2527
  };
2841
2528
  }
2842
2529
  });
2843
2530
 
2844
- // src/infrastructure/http/fastify.http-adapter.ts
2845
- var fastify_http_adapter_exports = {};
2846
- __export(fastify_http_adapter_exports, {
2847
- FastifyHttpAdapter: () => FastifyHttpAdapter
2531
+ // src/infrastructure/services/resolver/index.ts
2532
+ var init_resolver = __esm({
2533
+ "src/infrastructure/services/resolver/index.ts"() {
2534
+ "use strict";
2535
+ init_client_ip_resolver();
2536
+ }
2848
2537
  });
2849
- var import_shared52, FastifyHttpAdapter;
2850
- var init_fastify_http_adapter = __esm({
2851
- "src/infrastructure/http/fastify.http-adapter.ts"() {
2538
+
2539
+ // src/infrastructure/services/index.ts
2540
+ var services_exports = {};
2541
+ __export(services_exports, {
2542
+ AllowMethodRegistry: () => AllowMethodRegistry,
2543
+ AllowOrigin: () => AllowOrigin,
2544
+ BearerTokenExtractor: () => BearerTokenExtractor,
2545
+ ClientIpResolver: () => ClientIpResolver,
2546
+ CookieHandler: () => CookieHandler,
2547
+ CsrfTokenService: () => CsrfTokenService,
2548
+ EdgeCryptoService: () => EdgeCryptoService,
2549
+ HttpCookieExtractor: () => HttpCookieExtractor,
2550
+ HttpHeaderExtractor: () => HttpHeaderExtractor,
2551
+ PLimitConcurrencyService: () => PLimitConcurrencyService,
2552
+ ServiceResilience: () => ServiceResilience,
2553
+ SupabaseSsrTokenExtractor: () => SupabaseSsrTokenExtractor
2554
+ });
2555
+ var init_services = __esm({
2556
+ "src/infrastructure/services/index.ts"() {
2852
2557
  "use strict";
2853
- import_shared52 = require("@xeno-js/shared");
2854
- init_base_http_adapter();
2855
- FastifyHttpAdapter = class extends BaseHttpAdapter {
2856
- adapt(req, res) {
2857
- const headers = this.parseHeaders(req.headers);
2858
- const url = this.parseUrl(req.url, req.headers, req.query);
2859
- const body = req.body;
2860
- return this.createXenoWebTransport(url, req.method, headers, body, res);
2861
- }
2862
- handleHeaderChange(res, name, value, action) {
2863
- if (action === "delete") {
2864
- res.removeHeader(name);
2865
- return;
2866
- }
2867
- if (name.toLowerCase() === "set-cookie") {
2868
- const existing = res.getHeader("set-cookie");
2869
- let cookies = [];
2870
- if (import_shared52.Guards.isArray(existing)) {
2871
- cookies = existing;
2872
- } else if (import_shared52.Guards.isString(existing)) {
2873
- cookies = [existing];
2874
- }
2875
- if (action === "append") {
2876
- cookies.push(value);
2877
- } else {
2878
- cookies = [value];
2879
- }
2880
- res.header("set-cookie", cookies);
2881
- } else {
2882
- res.header(name, value);
2883
- }
2884
- }
2885
- };
2558
+ init_allow_methods();
2559
+ init_allow_origins();
2560
+ init_concurrency();
2561
+ init_cookies();
2562
+ init_crypto();
2563
+ init_csrf();
2564
+ init_extractors();
2565
+ init_resiliences();
2566
+ init_resolver();
2886
2567
  }
2887
2568
  });
2888
2569
 
2889
- // src/infrastructure/http/native.http-adapter.ts
2890
- var native_http_adapter_exports = {};
2891
- __export(native_http_adapter_exports, {
2892
- NativeHttpAdapter: () => NativeHttpAdapter
2570
+ // src/infrastructure/factories/supabase.factory.ts
2571
+ var supabase_factory_exports = {};
2572
+ __export(supabase_factory_exports, {
2573
+ SupabaseServerAuthFactory: () => SupabaseServerAuthFactory
2893
2574
  });
2894
- var NativeHttpAdapter;
2895
- var init_native_http_adapter = __esm({
2896
- "src/infrastructure/http/native.http-adapter.ts"() {
2575
+ var import_ssr, import_shared56, import_supabase, SupabaseServerAuthFactory;
2576
+ var init_supabase_factory = __esm({
2577
+ "src/infrastructure/factories/supabase.factory.ts"() {
2897
2578
  "use strict";
2898
- init_base_http_adapter();
2899
- NativeHttpAdapter = class extends BaseHttpAdapter {
2900
- adapt(req, res) {
2901
- const extendedRequest = req;
2902
- extendedRequest.path = new URL(req.url).pathname;
2903
- return {
2904
- request: extendedRequest,
2905
- response: res
2906
- };
2579
+ import_ssr = require("@supabase/ssr");
2580
+ import_shared56 = require("@xeno-js/shared");
2581
+ import_supabase = require("@xeno-js/shared/supabase");
2582
+ init_services();
2583
+ SupabaseServerAuthFactory = class {
2584
+ create({
2585
+ config,
2586
+ container
2587
+ }) {
2588
+ const cookieService = this._getCookieSsr(config.ssrOpts, container, config.cookieOpts);
2589
+ const client = (0, import_ssr.createServerClient)(config.url, config.key, {
2590
+ ...config.opts,
2591
+ cookies: {
2592
+ getAll() {
2593
+ return cookieService.getAll();
2594
+ },
2595
+ setAll(cookiesToSet) {
2596
+ cookieService.setAll(cookiesToSet);
2597
+ }
2598
+ }
2599
+ });
2600
+ const mapper = new import_supabase.SupabaseClaimsMapper();
2601
+ const sessionMapper = new import_supabase.SupabaseSessionMapper(mapper);
2602
+ return new import_supabase.SupabaseAuthService(client, mapper, sessionMapper, config);
2907
2603
  }
2908
- handleHeaderChange(_res, _name, _value, _action) {
2909
- return;
2604
+ _getCookieSsr(ssrOpts, container, config) {
2605
+ if (import_shared56.Guards.isDefined(ssrOpts)) {
2606
+ return ssrOpts(container);
2607
+ } else {
2608
+ return new CookieHandler(
2609
+ container.resolve(import_shared56.TOKENS.NETWORK_CONTEXT_ACCESSOR),
2610
+ container.resolve(import_shared56.TOKENS.CONFIGURATION_SERVICE),
2611
+ config
2612
+ );
2613
+ }
2910
2614
  }
2911
2615
  };
2912
2616
  }
2913
2617
  });
2914
2618
 
2915
- // src/infrastructure/modules/http-adapter.module.ts
2916
- var import_shared53, HttpAdapterModule;
2917
- var init_http_adapter_module = __esm({
2918
- "src/infrastructure/modules/http-adapter.module.ts"() {
2619
+ // src/infrastructure/modules/utils/auth.utils.ts
2620
+ var auth_utils_exports = {};
2621
+ __export(auth_utils_exports, {
2622
+ AuthUtils: () => AuthUtils
2623
+ });
2624
+ var AuthUtils;
2625
+ var init_auth_utils = __esm({
2626
+ "src/infrastructure/modules/utils/auth.utils.ts"() {
2919
2627
  "use strict";
2920
- import_shared53 = require("@xeno-js/shared");
2921
- HttpAdapterModule = class {
2922
- async configure(container, opts) {
2923
- const adapter = await this._getAdapter(opts);
2924
- container.addSingleton("HTTP_ADAPTER", () => adapter);
2925
- }
2926
- async _getAdapter(opts) {
2927
- if (opts.vercel) {
2928
- const { VercelHttpAdapter: VercelHttpAdapter2 } = await Promise.resolve().then(() => (init_vercel_http_adapter(), vercel_http_adapter_exports));
2929
- return new VercelHttpAdapter2();
2930
- } else if (opts.fastify) {
2931
- const { FastifyHttpAdapter: FastifyHttpAdapter2 } = await Promise.resolve().then(() => (init_fastify_http_adapter(), fastify_http_adapter_exports));
2932
- return new FastifyHttpAdapter2();
2933
- } else if (import_shared53.Guards.isDefined(opts.custom)) {
2934
- return opts.custom();
2628
+ AuthUtils = Object.freeze({
2629
+ /**
2630
+ * @description Checks if the provided authorization configuration requires any authorization strategies.
2631
+ * @param authorizationConfig The authorization configuration to check.
2632
+ * @returns True if any authorization strategies are required, false otherwise.
2633
+
2634
+ *
2635
+ * @author Xeno
2636
+ * @version 1.0.0
2637
+ * @since 2025-09-30
2638
+ * @link https://github.com/xeno-js/xeno-js
2639
+ */
2640
+ async addAuthZ(container, opts) {
2641
+ const { TOKENS: TOKENS5 } = await import("@xeno-js/shared");
2642
+ const strategies = [];
2643
+ const { Guards: Guards51 } = await import("@xeno-js/shared");
2644
+ if (Guards51.isDefined(opts.policies)) {
2645
+ const { PolicyRegistry: PolicyRegistry2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2646
+ const policyRegistry = opts.policies;
2647
+ const registryInstance = new PolicyRegistry2();
2648
+ const ctxAccessor = container.resolve(TOKENS5.CONTEXT_ACCESSOR);
2649
+ const Policies = /* @__PURE__ */ new Set();
2650
+ for (const [intent, policy] of Object.entries(policyRegistry)) {
2651
+ const intentLower = intent.toLowerCase();
2652
+ registryInstance.addPolicy(intentLower, policy);
2653
+ if (!Guards51.isNullOrEmpty(policy.roles)) {
2654
+ Policies.add("roles");
2655
+ }
2656
+ if (!Guards51.isNullOrEmpty(policy.permissions)) {
2657
+ Policies.add("permissions");
2658
+ }
2659
+ if (!Guards51.isNullOrEmpty(policy.userId)) {
2660
+ Policies.add("userId");
2661
+ }
2662
+ if (!Guards51.isNullOrEmpty(policy.tenantId)) {
2663
+ Policies.add("tenantId");
2664
+ }
2665
+ }
2666
+ if (Policies.has("roles")) {
2667
+ const { RoleAuthorizationStrategy: RoleAuthorizationStrategy2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2668
+ strategies.push(new RoleAuthorizationStrategy2(registryInstance, ctxAccessor));
2669
+ }
2670
+ if (Policies.has("permissions")) {
2671
+ const { PermissionAuthorizationStrategy: PermissionAuthorizationStrategy2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2672
+ strategies.push(new PermissionAuthorizationStrategy2(registryInstance, ctxAccessor));
2673
+ }
2674
+ if (Policies.has("userId")) {
2675
+ const { UserAuthorizationStrategy: UserAuthorizationStrategy2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2676
+ strategies.push(new UserAuthorizationStrategy2(registryInstance, ctxAccessor));
2677
+ }
2678
+ if (Policies.has("tenantId")) {
2679
+ const { TenantAuthorizationStrategy: TenantAuthorizationStrategy2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2680
+ strategies.push(new TenantAuthorizationStrategy2(registryInstance, ctxAccessor));
2681
+ }
2682
+ }
2683
+ if (!Guards51.isNullOrEmpty(opts.customAuthorizationStrategy)) {
2684
+ const customStrategies = opts.customAuthorizationStrategy;
2685
+ customStrategies.forEach((strategyToken) => {
2686
+ if (Guards51.isDefined(strategyToken)) {
2687
+ strategies.push(strategyToken(container));
2688
+ }
2689
+ });
2690
+ }
2691
+ const { AuthorizationPipeline: AuthorizationPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2692
+ return new AuthorizationPipeline2(strategies);
2693
+ },
2694
+ /**
2695
+ * @description Configures the authentication service and gatekeeper in the service container.
2696
+ * @param container The service container to configure.
2697
+ * @param opts The authentication configuration options.
2698
+
2699
+ *
2700
+ * @author Xeno
2701
+ * @version 1.0.0
2702
+ * @since 2025-09-30
2703
+ * @link https://github.com/xeno-js/xeno-js
2704
+ */
2705
+ async addAuthN(container, opts) {
2706
+ const { Guards: Guards51, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
2707
+ if (Guards51.isDefined(opts.customAuth)) {
2708
+ const authService = opts.customAuth.authExtendedService();
2709
+ container.addScoped(TOKENS5.AUTH_SERVICE, () => {
2710
+ return authService;
2711
+ });
2712
+ container.addSingleton(TOKENS5.BASE_AUTH_SERVICE, () => {
2713
+ return authService;
2714
+ });
2935
2715
  } else {
2936
- const { NativeHttpAdapter: NativeHttpAdapter2 } = await Promise.resolve().then(() => (init_native_http_adapter(), native_http_adapter_exports));
2937
- return new NativeHttpAdapter2();
2716
+ const { SupabaseServerAuthFactory: SupabaseServerAuthFactory2 } = await Promise.resolve().then(() => (init_supabase_factory(), supabase_factory_exports));
2717
+ const factory = new SupabaseServerAuthFactory2();
2718
+ const supabase = factory.create({ config: opts, container });
2719
+ container.addScoped(TOKENS5.AUTH_SERVICE, () => {
2720
+ return supabase;
2721
+ });
2722
+ container.addSingleton(TOKENS5.BASE_AUTH_SERVICE, () => {
2723
+ return supabase;
2724
+ });
2938
2725
  }
2939
2726
  }
2940
- };
2727
+ });
2941
2728
  }
2942
2729
  });
2943
2730
 
@@ -2990,11 +2777,11 @@ var cockatiel_resilience_factory_exports = {};
2990
2777
  __export(cockatiel_resilience_factory_exports, {
2991
2778
  CockatielResilienceFactory: () => CockatielResilienceFactory
2992
2779
  });
2993
- var import_shared54, import_cockatiel, CockatielResilienceFactory;
2780
+ var import_shared57, import_cockatiel, CockatielResilienceFactory;
2994
2781
  var init_cockatiel_resilience_factory = __esm({
2995
2782
  "src/infrastructure/factories/cockatiel-resilience.factory.ts"() {
2996
2783
  "use strict";
2997
- import_shared54 = require("@xeno-js/shared");
2784
+ import_shared57 = require("@xeno-js/shared");
2998
2785
  import_cockatiel = require("cockatiel");
2999
2786
  init_resilience_service();
3000
2787
  CockatielResilienceFactory = class {
@@ -3004,36 +2791,36 @@ var init_cockatiel_resilience_factory = __esm({
3004
2791
  retry: {
3005
2792
  attempts: this.checkConfigValue(
3006
2793
  config.retry.attempts,
3007
- import_shared54.RESILIENCE_DEFAULTS.RETRY.ATTEMPTS,
2794
+ import_shared57.RESILIENCE_DEFAULTS.RETRY.ATTEMPTS,
3008
2795
  message
3009
2796
  ),
3010
2797
  baseDelayMs: this.checkConfigValue(
3011
2798
  config.retry.baseDelayMs,
3012
- import_shared54.RESILIENCE_DEFAULTS.RETRY.BASE_DELAY_MS,
2799
+ import_shared57.RESILIENCE_DEFAULTS.RETRY.BASE_DELAY_MS,
3013
2800
  message
3014
2801
  ),
3015
2802
  maxDelayMs: this.checkConfigValue(
3016
2803
  config.retry.maxDelayMs,
3017
- import_shared54.RESILIENCE_DEFAULTS.RETRY.MAX_DELAY_MS,
2804
+ import_shared57.RESILIENCE_DEFAULTS.RETRY.MAX_DELAY_MS,
3018
2805
  message
3019
2806
  )
3020
2807
  },
3021
2808
  circuitBreaker: {
3022
2809
  consecutiveFailures: this.checkConfigValue(
3023
2810
  config.circuitBreaker.consecutiveFailures,
3024
- import_shared54.RESILIENCE_DEFAULTS.CIRCUIT_BREAKER.CONSECUTIVE_FAILURES,
2811
+ import_shared57.RESILIENCE_DEFAULTS.CIRCUIT_BREAKER.CONSECUTIVE_FAILURES,
3025
2812
  message
3026
2813
  ),
3027
2814
  halfOpenTimeoutMs: this.checkConfigValue(
3028
2815
  config.circuitBreaker.halfOpenTimeoutMs,
3029
- import_shared54.RESILIENCE_DEFAULTS.CIRCUIT_BREAKER.HALF_OPEN_TIMEOUT_MS,
2816
+ import_shared57.RESILIENCE_DEFAULTS.CIRCUIT_BREAKER.HALF_OPEN_TIMEOUT_MS,
3030
2817
  message
3031
2818
  )
3032
2819
  },
3033
2820
  bulkhead: {
3034
2821
  maxConcurrent: this.checkConfigValue(
3035
2822
  config.bulkhead.maxConcurrent,
3036
- import_shared54.RESILIENCE_DEFAULTS.BULKHEAD.MAX_CONCURRENT,
2823
+ import_shared57.RESILIENCE_DEFAULTS.BULKHEAD.MAX_CONCURRENT,
3037
2824
  message
3038
2825
  )
3039
2826
  }
@@ -3059,13 +2846,13 @@ var init_cockatiel_resilience_factory = __esm({
3059
2846
  return new ServiceResilience((0, import_cockatiel.wrap)(bulkheadPolicy, circuitBreakerPolicy, retryPolicy));
3060
2847
  }
3061
2848
  isTransientError(error) {
3062
- if (!import_shared54.Guards.isDefined(error) || !import_shared54.Guards.isObject(error)) return false;
2849
+ if (!import_shared57.Guards.isDefined(error) || !import_shared57.Guards.isObject(error)) return false;
3063
2850
  let status;
3064
2851
  let isNetworkError = false;
3065
- if (error instanceof import_shared54.AppError) {
2852
+ if (error instanceof import_shared57.AppError) {
3066
2853
  status = error.status;
3067
2854
  const cause = error.cause;
3068
- if (import_shared54.Guards.isDefined(cause) && import_shared54.Guards.isString(cause.code)) {
2855
+ if (import_shared57.Guards.isDefined(cause) && import_shared57.Guards.isString(cause.code)) {
3069
2856
  isNetworkError = [
3070
2857
  "ECONNABORTED",
3071
2858
  "ECONNRESET",
@@ -3077,7 +2864,7 @@ var init_cockatiel_resilience_factory = __esm({
3077
2864
  } else {
3078
2865
  const err = error;
3079
2866
  status = err.status;
3080
- if (import_shared54.Guards.isString(err.code)) {
2867
+ if (import_shared57.Guards.isString(err.code)) {
3081
2868
  isNetworkError = [
3082
2869
  "ECONNABORTED",
3083
2870
  "ECONNRESET",
@@ -3088,30 +2875,30 @@ var init_cockatiel_resilience_factory = __esm({
3088
2875
  }
3089
2876
  }
3090
2877
  if (isNetworkError) return true;
3091
- if (import_shared54.Guards.isDefined(status)) return status === 408 || status >= 500 && status < 600;
2878
+ if (import_shared57.Guards.isDefined(status)) return status === 408 || status >= 500 && status < 600;
3092
2879
  return false;
3093
2880
  }
3094
2881
  isTransientAndIdempotent(error) {
3095
2882
  if (!this.isTransientError(error)) return false;
3096
2883
  let method;
3097
- if (error instanceof import_shared54.AppError) {
2884
+ if (error instanceof import_shared57.AppError) {
3098
2885
  const cause = error.cause;
3099
- if (import_shared54.Guards.isDefined(cause) && import_shared54.Guards.isDefined(cause.config) && import_shared54.Guards.isString(cause.config.method)) {
2886
+ if (import_shared57.Guards.isDefined(cause) && import_shared57.Guards.isDefined(cause.config) && import_shared57.Guards.isString(cause.config.method)) {
3100
2887
  method = cause.config.method.toUpperCase();
3101
2888
  }
3102
2889
  } else {
3103
2890
  const err = error;
3104
- if (import_shared54.Guards.isDefined(err.config) && import_shared54.Guards.isString(err.config.method)) {
2891
+ if (import_shared57.Guards.isDefined(err.config) && import_shared57.Guards.isString(err.config.method)) {
3105
2892
  method = err.config.method.toUpperCase();
3106
2893
  }
3107
2894
  }
3108
- if (import_shared54.Guards.isNullOrEmpty(method)) return false;
2895
+ if (import_shared57.Guards.isNullOrEmpty(method)) return false;
3109
2896
  const idempotentMethods = ["GET", "PUT", "DELETE", "HEAD", "OPTIONS"];
3110
2897
  return idempotentMethods.includes(method);
3111
2898
  }
3112
2899
  checkConfigValue(value, defaultValue, message) {
3113
- if (import_shared54.Guards.isDefined(value)) {
3114
- import_shared54.Guards.throwIfNegative(value, message);
2900
+ if (import_shared57.Guards.isDefined(value)) {
2901
+ import_shared57.Guards.throwIfNegative(value, message);
3115
2902
  return value;
3116
2903
  }
3117
2904
  return defaultValue;
@@ -3120,90 +2907,363 @@ var init_cockatiel_resilience_factory = __esm({
3120
2907
  }
3121
2908
  });
3122
2909
 
3123
- // src/infrastructure/modules/utils/http.utils.ts
3124
- var http_utils_exports = {};
3125
- __export(http_utils_exports, {
3126
- HttpUtils: () => HttpUtils
2910
+ // src/infrastructure/modules/utils/http.utils.ts
2911
+ var http_utils_exports = {};
2912
+ __export(http_utils_exports, {
2913
+ HttpUtils: () => HttpUtils
2914
+ });
2915
+ var HttpUtils;
2916
+ var init_http_utils = __esm({
2917
+ "src/infrastructure/modules/utils/http.utils.ts"() {
2918
+ "use strict";
2919
+ HttpUtils = Object.freeze({
2920
+ /**
2921
+ * @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.
2922
+ * @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.
2923
+ * @returns A string representing the encoded query string that can be appended to a URL for making HTTP requests.
2924
+ *
2925
+ * @author Xeno
2926
+ * @version 1.0.0
2927
+ * @since 2025-09-30
2928
+ * @link https://github.com/xeno-js/xeno-js
2929
+ */
2930
+ async addAxios(container, opts) {
2931
+ const { NodeAxiosFactory: NodeAxiosFactory2 } = await Promise.resolve().then(() => (init_axios_factory(), axios_factory_exports));
2932
+ const { Guards: Guards51 } = await import("@xeno-js/shared");
2933
+ if (!Guards51.isDefined(opts.token)) {
2934
+ throw new Error("HttpConfig.token is required and must be defined.");
2935
+ }
2936
+ container.addSingleton(opts.token, () => {
2937
+ const factory = new NodeAxiosFactory2();
2938
+ const instance = factory.create(opts.client);
2939
+ if (!Guards51.hasMethod(instance, "get") || !Guards51.hasMethod(instance, "post") || !Guards51.hasMethod(instance, "put") || !Guards51.hasMethod(instance, "patch") || !Guards51.hasMethod(instance, "delete")) {
2940
+ throw new Error(
2941
+ "The created HTTP client instance does not implement the required methods of IHttpClient."
2942
+ );
2943
+ }
2944
+ return instance;
2945
+ });
2946
+ },
2947
+ /**
2948
+ * @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.
2949
+ * @param container - The service container to register the resilience client with.
2950
+ * @param opts - The ResilienceConfig options that determine whether resilience features are enabled and provide the necessary settings for implementing resilience strategies.
2951
+ *
2952
+ * @author Xeno
2953
+ * @version 1.0.0
2954
+ * @since 2025-09-30
2955
+ * @link https://github.com/xeno-js/xeno-js
2956
+ */
2957
+ async addResilience(container, opts) {
2958
+ const { TOKENS: TOKENS5 } = await import("@xeno-js/shared");
2959
+ const { CockatielResilienceFactory: CockatielResilienceFactory2 } = await Promise.resolve().then(() => (init_cockatiel_resilience_factory(), cockatiel_resilience_factory_exports));
2960
+ container.addSingleton(TOKENS5.RESILIENCE_CLIENT, () => {
2961
+ const factory = new CockatielResilienceFactory2();
2962
+ return factory.create(opts);
2963
+ });
2964
+ }
2965
+ });
2966
+ }
2967
+ });
2968
+
2969
+ // src/infrastructure/modules/http-core.module.ts
2970
+ var http_core_module_exports = {};
2971
+ __export(http_core_module_exports, {
2972
+ HttpCoreModule: () => HttpCoreModule
2973
+ });
2974
+ var HttpCoreModule;
2975
+ var init_http_core_module = __esm({
2976
+ "src/infrastructure/modules/http-core.module.ts"() {
2977
+ "use strict";
2978
+ HttpCoreModule = class {
2979
+ async configure(container, opts) {
2980
+ const { HttpUtils: HttpUtils2 } = await Promise.resolve().then(() => (init_http_utils(), http_utils_exports));
2981
+ await HttpUtils2.addAxios(container, opts.http);
2982
+ await HttpUtils2.addResilience(container, opts.resilience);
2983
+ }
2984
+ };
2985
+ }
2986
+ });
2987
+
2988
+ // src/infrastructure/factories/zod-validator.factory.ts
2989
+ var zod_validator_factory_exports = {};
2990
+ __export(zod_validator_factory_exports, {
2991
+ ZodValidatorFactory: () => ZodValidatorFactory
2992
+ });
2993
+ var import_zod, ZodValidatorFactory;
2994
+ var init_zod_validator_factory = __esm({
2995
+ "src/infrastructure/factories/zod-validator.factory.ts"() {
2996
+ "use strict";
2997
+ import_zod = require("@xeno-js/shared/zod");
2998
+ ZodValidatorFactory = class {
2999
+ create(opts) {
3000
+ const validatorService = new import_zod.ZodValidatorService(/* @__PURE__ */ new Map(), opts.logger);
3001
+ for (const [intentKey, schema] of Object.entries(opts.schemas)) {
3002
+ validatorService.addSchema(intentKey, schema);
3003
+ }
3004
+ return validatorService;
3005
+ }
3006
+ };
3007
+ }
3008
+ });
3009
+
3010
+ // src/infrastructure/modules/utils/validation.utils.ts
3011
+ var validation_utils_exports = {};
3012
+ __export(validation_utils_exports, {
3013
+ ValidationUtils: () => ValidationUtils
3014
+ });
3015
+ var ValidationUtils;
3016
+ var init_validation_utils = __esm({
3017
+ "src/infrastructure/modules/utils/validation.utils.ts"() {
3018
+ "use strict";
3019
+ ValidationUtils = Object.freeze({
3020
+ /**
3021
+ * @description Checks if the provided validation configuration requires any validation strategies.
3022
+ * @param validationConfig The validation configuration to check.
3023
+ * @returns True if any validation strategies are required, false otherwise.
3024
+ *
3025
+ * @author Xeno
3026
+ * @version 1.0.0
3027
+ * @since 2025-09-30
3028
+ * @link https://github.com/xeno-js/xeno-js
3029
+ */
3030
+ async addValidation(container, opts, logger) {
3031
+ const { Guards: Guards51, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
3032
+ if (!Guards51.isDefined(opts.zod) && Guards51.isNullOrEmpty(opts.customValidationStrategy)) {
3033
+ return;
3034
+ }
3035
+ const validationStrategies = [];
3036
+ if (Guards51.isDefined(opts.zod)) {
3037
+ const config = opts.zod;
3038
+ const { ZodValidatorFactory: ZodValidatorFactory2 } = await Promise.resolve().then(() => (init_zod_validator_factory(), zod_validator_factory_exports));
3039
+ const { SchemaValidationStrategy: SchemaValidationStrategy2 } = await Promise.resolve().then(() => (init_application(), application_exports));
3040
+ const validatorService = new ZodValidatorFactory2().create({ ...config, logger });
3041
+ container.addSingleton(TOKENS5.VALIDATOR_SERVICE, () => validatorService);
3042
+ validationStrategies.push(new SchemaValidationStrategy2(validatorService));
3043
+ }
3044
+ if (!Guards51.isNullOrEmpty(opts.customValidationStrategy)) {
3045
+ for (const strategyToken of opts.customValidationStrategy) {
3046
+ if (Guards51.isDefined(strategyToken)) validationStrategies.push(strategyToken(container));
3047
+ }
3048
+ }
3049
+ const { ValidationPipeline: ValidationPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
3050
+ return new ValidationPipeline2(validationStrategies);
3051
+ }
3052
+ });
3053
+ }
3054
+ });
3055
+
3056
+ // src/infrastructure/idempotency/idempotency-store.ts
3057
+ var import_shared58, IdempotencyStore;
3058
+ var init_idempotency_store = __esm({
3059
+ "src/infrastructure/idempotency/idempotency-store.ts"() {
3060
+ "use strict";
3061
+ import_shared58 = require("@xeno-js/shared");
3062
+ IdempotencyStore = class {
3063
+ /**
3064
+ * @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.
3065
+ * @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.
3066
+ * @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.
3067
+
3068
+ *
3069
+ * @author Xeno
3070
+ * @version 1.0.0
3071
+ * @since 2025-09-30
3072
+ * @link https://github.com/xeno-js/xeno-js
3073
+ */
3074
+ constructor(_cache, _cacheKeyBuilder) {
3075
+ this._cache = _cache;
3076
+ this._cacheKeyBuilder = _cacheKeyBuilder;
3077
+ }
3078
+ _cache;
3079
+ _cacheKeyBuilder;
3080
+ async acquireLock(requestId, ttlSeconds) {
3081
+ const key = this._cacheKeyBuilder.buildContextualKey(`command:${requestId}`);
3082
+ return await this._cache.setIfAbsent(
3083
+ `${import_shared58.IDEMPOTENCY_CONSTANTS.LOCK_KEY_PREFIX}${key}`,
3084
+ import_shared58.IDEMPOTENCY_CONSTANTS.LOCKED_VALUE,
3085
+ ttlSeconds
3086
+ );
3087
+ }
3088
+ async hasBeenProcessed(commandId) {
3089
+ const key = this._cacheKeyBuilder.buildContextualKey(`command:${commandId}`);
3090
+ return await this._cache.has(`${import_shared58.IDEMPOTENCY_CONSTANTS.PROCESSED_KEY_PREFIX}${key}`);
3091
+ }
3092
+ async markAsProcessed(commandId, payload, ttlSeconds) {
3093
+ const key = this._cacheKeyBuilder.buildContextualKey(`command:${commandId}`);
3094
+ await this._cache.set(
3095
+ `${import_shared58.IDEMPOTENCY_CONSTANTS.PROCESSED_KEY_PREFIX}${key}`,
3096
+ payload,
3097
+ ttlSeconds
3098
+ );
3099
+ }
3100
+ async getPayload(commandId) {
3101
+ const key = this._cacheKeyBuilder.buildContextualKey(`command:${commandId}`);
3102
+ const payload = await this._cache.get(`${import_shared58.IDEMPOTENCY_CONSTANTS.PROCESSED_KEY_PREFIX}${key}`);
3103
+ return payload;
3104
+ }
3105
+ async releaseLock(commandId) {
3106
+ const key = this._cacheKeyBuilder.buildContextualKey(`command:${commandId}`);
3107
+ await this._cache.remove(`${import_shared58.IDEMPOTENCY_CONSTANTS.LOCK_KEY_PREFIX}${key}`);
3108
+ }
3109
+ };
3110
+ }
3111
+ });
3112
+
3113
+ // src/infrastructure/idempotency/index.ts
3114
+ var idempotency_exports = {};
3115
+ __export(idempotency_exports, {
3116
+ IdempotencyStore: () => IdempotencyStore
3117
+ });
3118
+ var init_idempotency = __esm({
3119
+ "src/infrastructure/idempotency/index.ts"() {
3120
+ "use strict";
3121
+ init_idempotency_store();
3122
+ }
3123
+ });
3124
+
3125
+ // src/infrastructure/modules/utils/pipeline.utils.ts
3126
+ var pipeline_utils_exports = {};
3127
+ __export(pipeline_utils_exports, {
3128
+ PipelineUtils: () => PipelineUtils
3127
3129
  });
3128
- var HttpUtils;
3129
- var init_http_utils = __esm({
3130
- "src/infrastructure/modules/utils/http.utils.ts"() {
3130
+ var PipelineUtils;
3131
+ var init_pipeline_utils = __esm({
3132
+ "src/infrastructure/modules/utils/pipeline.utils.ts"() {
3131
3133
  "use strict";
3132
- HttpUtils = Object.freeze({
3134
+ PipelineUtils = Object.freeze({
3133
3135
  /**
3134
- * @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.
3135
- * @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.
3136
- * @returns A string representing the encoded query string that can be appended to a URL for making HTTP requests.
3136
+ * @description Checks if the provided command configuration requires any command strategies.
3137
+ * @param commandConfig The command configuration to check.
3138
+ * @returns True if any command strategies are required, false otherwise.
3137
3139
  *
3138
3140
  * @author Xeno
3139
3141
  * @version 1.0.0
3140
3142
  * @since 2025-09-30
3141
3143
  * @link https://github.com/xeno-js/xeno-js
3142
3144
  */
3143
- async addAxios(container, opts) {
3144
- const { NodeAxiosFactory: NodeAxiosFactory2 } = await Promise.resolve().then(() => (init_axios_factory(), axios_factory_exports));
3145
- const { Guards: Guards51 } = await import("@xeno-js/shared");
3146
- if (!Guards51.isDefined(opts.token)) {
3147
- throw new Error("HttpConfig.token is required and must be defined.");
3145
+ async addCommand(container, opts) {
3146
+ const { Guards: Guards51, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
3147
+ const pipelines = [];
3148
+ if (Guards51.isDefined(opts.idempotency)) {
3149
+ const { IdempotencyStore: IdempotencyStore2 } = await Promise.resolve().then(() => (init_idempotency(), idempotency_exports));
3150
+ const imdStore = new IdempotencyStore2(
3151
+ container.resolve(TOKENS5.CACHE),
3152
+ container.resolve(TOKENS5.CACHE_KEY_BUILDER)
3153
+ );
3154
+ const { IdempotencyPipeline: IdempotencyPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
3155
+ const requestContext = container.resolve(TOKENS5.NETWORK_CONTEXT_ACCESSOR);
3156
+ const config = opts.idempotency;
3157
+ pipelines.push(
3158
+ new IdempotencyPipeline2(
3159
+ requestContext,
3160
+ imdStore,
3161
+ config?.lockTtlSeconds,
3162
+ config?.processedTtlSeconds
3163
+ )
3164
+ );
3148
3165
  }
3149
- container.addSingleton(opts.token, () => {
3150
- const factory = new NodeAxiosFactory2();
3151
- const instance = factory.create(opts.client);
3152
- if (!Guards51.hasMethod(instance, "get") || !Guards51.hasMethod(instance, "post") || !Guards51.hasMethod(instance, "put") || !Guards51.hasMethod(instance, "patch") || !Guards51.hasMethod(instance, "delete")) {
3153
- throw new Error(
3154
- "The created HTTP client instance does not implement the required methods of IHttpClient."
3155
- );
3156
- }
3157
- return instance;
3158
- });
3166
+ if (Guards51.isDefined(opts.concurrency)) {
3167
+ const { ConcurrencyRetryPipeline: ConcurrencyRetryPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
3168
+ const config = opts.concurrency;
3169
+ pipelines.push(new ConcurrencyRetryPipeline2(config?.maxRetries, config?.delayConfig));
3170
+ }
3171
+ return pipelines;
3159
3172
  },
3160
3173
  /**
3161
- * @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.
3162
- * @param container - The service container to register the resilience client with.
3163
- * @param opts - The ResilienceConfig options that determine whether resilience features are enabled and provide the necessary settings for implementing resilience strategies.
3174
+ * @description Checks if the provided query configuration requires any query strategies.
3175
+ * @param queryConfig The query configuration to check.
3176
+ * @returns True if any query strategies are required, false otherwise.
3164
3177
  *
3165
3178
  * @author Xeno
3166
3179
  * @version 1.0.0
3167
3180
  * @since 2025-09-30
3168
3181
  * @link https://github.com/xeno-js/xeno-js
3169
3182
  */
3170
- async addResilience(container, opts) {
3183
+ async addQuery(container) {
3171
3184
  const { TOKENS: TOKENS5 } = await import("@xeno-js/shared");
3172
- const { CockatielResilienceFactory: CockatielResilienceFactory2 } = await Promise.resolve().then(() => (init_cockatiel_resilience_factory(), cockatiel_resilience_factory_exports));
3173
- container.addSingleton(TOKENS5.RESILIENCE_CLIENT, () => {
3174
- const factory = new CockatielResilienceFactory2();
3175
- return factory.create(opts);
3176
- });
3185
+ const { QueryCachingPipeline: QueryCachingPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
3186
+ return new QueryCachingPipeline2(
3187
+ container.resolve(TOKENS5.CACHE),
3188
+ container.resolve(TOKENS5.CACHE_KEY_BUILDER),
3189
+ container.resolve(TOKENS5.LOGGER)
3190
+ );
3177
3191
  }
3178
3192
  });
3179
3193
  }
3180
3194
  });
3181
3195
 
3182
- // src/infrastructure/modules/http-core.module.ts
3183
- var http_core_module_exports = {};
3184
- __export(http_core_module_exports, {
3185
- HttpCoreModule: () => HttpCoreModule
3196
+ // src/infrastructure/modules/cqrs.module.ts
3197
+ var cqrs_module_exports = {};
3198
+ __export(cqrs_module_exports, {
3199
+ CqrsModule: () => CqrsModule
3186
3200
  });
3187
- var HttpCoreModule;
3188
- var init_http_core_module = __esm({
3189
- "src/infrastructure/modules/http-core.module.ts"() {
3201
+ var CqrsModule;
3202
+ var init_cqrs_module = __esm({
3203
+ "src/infrastructure/modules/cqrs.module.ts"() {
3190
3204
  "use strict";
3191
- HttpCoreModule = class {
3205
+ CqrsModule = class {
3192
3206
  async configure(container, opts) {
3193
- const { HttpUtils: HttpUtils2 } = await Promise.resolve().then(() => (init_http_utils(), http_utils_exports));
3194
- await HttpUtils2.addAxios(container, opts.http);
3195
- await HttpUtils2.addResilience(container, opts.resilience);
3207
+ const { Guards: Guards51, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
3208
+ const logger = container.resolve(TOKENS5.LOGGER);
3209
+ const { Mediator: Mediator2 } = await Promise.resolve().then(() => (init_application(), application_exports));
3210
+ container.addSingleton(TOKENS5.MEDIATOR, (c) => {
3211
+ const serviceScopeAccessor = c.resolve(TOKENS5.SERVICE_SCOPE_ACCESSOR);
3212
+ return new Mediator2(serviceScopeAccessor);
3213
+ });
3214
+ const { ExceptionPipeline: ExceptionPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
3215
+ const { LoggingPipeline: LoggingPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
3216
+ const { PerformancePipeline: PerformancePipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
3217
+ const thresholdMs = opts.performance?.thresholdMs;
3218
+ const pipelines = [
3219
+ new ExceptionPipeline2(),
3220
+ new LoggingPipeline2(logger),
3221
+ new PerformancePipeline2(logger, opts.performance.intentThresholdMs, thresholdMs)
3222
+ ];
3223
+ if (Guards51.isDefined(opts.authorization.policies) || Guards51.isDefined(opts.authorization.customAuthorizationStrategy)) {
3224
+ const { AuthUtils: AuthUtils2 } = await Promise.resolve().then(() => (init_auth_utils(), auth_utils_exports));
3225
+ const authPipelines = await AuthUtils2.addAuthZ(container, opts.authorization);
3226
+ pipelines.push(authPipelines);
3227
+ }
3228
+ if (Guards51.isDefined(opts.validation.zod) || Guards51.isDefined(opts.validation.customValidationStrategy)) {
3229
+ const { ValidationUtils: ValidationUtils2 } = await Promise.resolve().then(() => (init_validation_utils(), validation_utils_exports));
3230
+ const validationPipelines = await ValidationUtils2.addValidation(
3231
+ container,
3232
+ opts.validation,
3233
+ logger
3234
+ );
3235
+ if (Guards51.isDefined(validationPipelines)) pipelines.push(validationPipelines);
3236
+ }
3237
+ const commandPipelines = [...pipelines];
3238
+ const queryPipelines = [...pipelines];
3239
+ if (Guards51.isDefined(opts.commandBus.idempotency) || Guards51.isDefined(opts.commandBus.concurrency)) {
3240
+ const { PipelineUtils: PipelineUtils2 } = await Promise.resolve().then(() => (init_pipeline_utils(), pipeline_utils_exports));
3241
+ const newCommandPipelines = await PipelineUtils2.addCommand(container, opts.commandBus);
3242
+ commandPipelines.push(...newCommandPipelines);
3243
+ }
3244
+ if (opts.queryBus.isEnabled) {
3245
+ const { PipelineUtils: PipelineUtils2 } = await Promise.resolve().then(() => (init_pipeline_utils(), pipeline_utils_exports));
3246
+ const newQueryPipelines = await PipelineUtils2.addQuery(container);
3247
+ queryPipelines.push(newQueryPipelines);
3248
+ }
3249
+ const { CompositePipeline: CompositePipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
3250
+ container.addSingleton(TOKENS5.COMMAND_PIPELINES_BEHAVIOR, () => {
3251
+ return new CompositePipeline2(commandPipelines);
3252
+ });
3253
+ container.addSingleton(TOKENS5.QUERY_PIPELINES_BEHAVIOR, () => {
3254
+ return new CompositePipeline2(queryPipelines);
3255
+ });
3196
3256
  }
3197
3257
  };
3198
3258
  }
3199
3259
  });
3200
3260
 
3201
3261
  // src/presentation/controllers/base.controller.ts
3202
- var import_shared55, BaseController;
3262
+ var import_shared59, BaseController;
3203
3263
  var init_base_controller = __esm({
3204
3264
  "src/presentation/controllers/base.controller.ts"() {
3205
3265
  "use strict";
3206
- import_shared55 = require("@xeno-js/shared");
3266
+ import_shared59 = require("@xeno-js/shared");
3207
3267
  BaseController = class {
3208
3268
  /**
3209
3269
  * Constructs a new instance of the BaseController class.
@@ -3235,7 +3295,7 @@ var init_base_controller = __esm({
3235
3295
  * @link https://github.com/xeno-js/xeno-js
3236
3296
  */
3237
3297
  ok(data, status = 200, meta = {}, headers = {}) {
3238
- return import_shared55.HttpHelper.success(data, status, meta, headers);
3298
+ return import_shared59.HttpHelper.success(data, status, meta, headers);
3239
3299
  }
3240
3300
  /**
3241
3301
  * Helper to automatically map a failed Result (from the CQRS pipeline)
@@ -3253,7 +3313,7 @@ var init_base_controller = __esm({
3253
3313
  fail(error, details = void 0, headers = {}) {
3254
3314
  const context = this._requestContext.getContext();
3255
3315
  const customHeaders = error["header"];
3256
- return import_shared55.HttpHelper.error(
3316
+ return import_shared59.HttpHelper.error(
3257
3317
  {
3258
3318
  success: false,
3259
3319
  error: {
@@ -3262,9 +3322,9 @@ var init_base_controller = __esm({
3262
3322
  path: context?.network.path,
3263
3323
  details: details ?? error.message
3264
3324
  },
3265
- correlationId: context?.tracing.correlationId ?? import_shared55.GuidHelper.generate(),
3266
- requestId: context?.network.requestId ?? import_shared55.GuidHelper.generate(),
3267
- spanId: context?.tracing.spanId ?? import_shared55.GuidHelper.generate(),
3325
+ correlationId: context?.tracing.correlationId ?? import_shared59.GuidHelper.generate(),
3326
+ requestId: context?.network.requestId ?? import_shared59.GuidHelper.generate(),
3327
+ spanId: context?.tracing.spanId ?? import_shared59.GuidHelper.generate(),
3268
3328
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
3269
3329
  },
3270
3330
  error.status,
@@ -3319,11 +3379,11 @@ var init_controllers = __esm({
3319
3379
  });
3320
3380
 
3321
3381
  // src/presentation/middlewares/allow-method.middleware.ts
3322
- var import_shared56, MethodCheckMiddleware;
3382
+ var import_shared60, MethodCheckMiddleware;
3323
3383
  var init_allow_method_middleware = __esm({
3324
3384
  "src/presentation/middlewares/allow-method.middleware.ts"() {
3325
3385
  "use strict";
3326
- import_shared56 = require("@xeno-js/shared");
3386
+ import_shared60 = require("@xeno-js/shared");
3327
3387
  MethodCheckMiddleware = class {
3328
3388
  constructor(_requestContext, _allowMethod) {
3329
3389
  this._requestContext = _requestContext;
@@ -3335,21 +3395,21 @@ var init_allow_method_middleware = __esm({
3335
3395
  const isAllowed = this._allowMethod.check(req.path, req.method);
3336
3396
  if (!isAllowed) {
3337
3397
  const { network, tracing } = this._requestContext.getContext() ?? {};
3338
- return import_shared56.HttpHelper.error(
3398
+ return import_shared60.HttpHelper.error(
3339
3399
  {
3340
3400
  success: false,
3341
3401
  error: {
3342
- code: import_shared56.ERROR_CODES.NOT_ALLOWED,
3343
- message: import_shared56.ERROR_CODE_MESSAGES[import_shared56.ERROR_CODES.NOT_ALLOWED],
3402
+ code: import_shared60.ERROR_CODES.NOT_ALLOWED,
3403
+ message: import_shared60.ERROR_CODE_MESSAGES[import_shared60.ERROR_CODES.NOT_ALLOWED],
3344
3404
  details: `Operation blocked by allow method middleware`,
3345
3405
  path: req.path
3346
3406
  },
3347
- correlationId: tracing?.correlationId ?? import_shared56.GuidHelper.generate(),
3348
- requestId: network?.requestId ?? import_shared56.GuidHelper.generate(),
3349
- spanId: tracing?.spanId ?? import_shared56.GuidHelper.generate(),
3407
+ correlationId: tracing?.correlationId ?? import_shared60.GuidHelper.generate(),
3408
+ requestId: network?.requestId ?? import_shared60.GuidHelper.generate(),
3409
+ spanId: tracing?.spanId ?? import_shared60.GuidHelper.generate(),
3350
3410
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
3351
3411
  },
3352
- import_shared56.STATUS_CODES.NOT_ALLOWED,
3412
+ import_shared60.STATUS_CODES.NOT_ALLOWED,
3353
3413
  {
3354
3414
  Allow: this._allowMethod.getMethods(req.path)
3355
3415
  }
@@ -3362,11 +3422,11 @@ var init_allow_method_middleware = __esm({
3362
3422
  });
3363
3423
 
3364
3424
  // src/presentation/middlewares/allow-origin.middleware.ts
3365
- var import_shared57, AllowOriginMiddleware;
3425
+ var import_shared61, AllowOriginMiddleware;
3366
3426
  var init_allow_origin_middleware = __esm({
3367
3427
  "src/presentation/middlewares/allow-origin.middleware.ts"() {
3368
3428
  "use strict";
3369
- import_shared57 = require("@xeno-js/shared");
3429
+ import_shared61 = require("@xeno-js/shared");
3370
3430
  AllowOriginMiddleware = class {
3371
3431
  constructor(_allowOrigin, _requestContext, _logger) {
3372
3432
  this._allowOrigin = _allowOrigin;
@@ -3381,21 +3441,21 @@ var init_allow_origin_middleware = __esm({
3381
3441
  const origin = network?.origin;
3382
3442
  if (!this._allowOrigin.isAllowed(origin)) {
3383
3443
  this._logger.warn(`Access denied by AllowOrigin policy for origin: ${origin ?? "unknown"}`);
3384
- return import_shared57.HttpHelper.error(
3444
+ return import_shared61.HttpHelper.error(
3385
3445
  {
3386
3446
  success: false,
3387
3447
  error: {
3388
- code: import_shared57.ERROR_CODES.FORBIDDEN,
3389
- message: import_shared57.ERROR_CODE_MESSAGES[import_shared57.ERROR_CODES.FORBIDDEN],
3448
+ code: import_shared61.ERROR_CODES.FORBIDDEN,
3449
+ message: import_shared61.ERROR_CODE_MESSAGES[import_shared61.ERROR_CODES.FORBIDDEN],
3390
3450
  details: `The origin '${origin ?? "unknown"}' is not allowed to access this resource.`,
3391
3451
  path: req.path
3392
3452
  },
3393
- correlationId: tracing?.correlationId ?? import_shared57.GuidHelper.generate(),
3394
- requestId: network?.requestId ?? import_shared57.GuidHelper.generate(),
3395
- spanId: tracing?.spanId ?? import_shared57.GuidHelper.generate(),
3453
+ correlationId: tracing?.correlationId ?? import_shared61.GuidHelper.generate(),
3454
+ requestId: network?.requestId ?? import_shared61.GuidHelper.generate(),
3455
+ spanId: tracing?.spanId ?? import_shared61.GuidHelper.generate(),
3396
3456
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
3397
3457
  },
3398
- import_shared57.STATUS_CODES.FORBIDDEN
3458
+ import_shared61.STATUS_CODES.FORBIDDEN
3399
3459
  );
3400
3460
  }
3401
3461
  return next();
@@ -3405,11 +3465,11 @@ var init_allow_origin_middleware = __esm({
3405
3465
  });
3406
3466
 
3407
3467
  // src/presentation/middlewares/auth.middleware.ts
3408
- var import_shared58, AuthenticationMiddleware;
3468
+ var import_shared62, AuthenticationMiddleware;
3409
3469
  var init_auth_middleware = __esm({
3410
3470
  "src/presentation/middlewares/auth.middleware.ts"() {
3411
3471
  "use strict";
3412
- import_shared58 = require("@xeno-js/shared");
3472
+ import_shared62 = require("@xeno-js/shared");
3413
3473
  AuthenticationMiddleware = class {
3414
3474
  constructor(_requestContext, _tokenExtractor, _gateKeeper, _logger) {
3415
3475
  this._requestContext = _requestContext;
@@ -3430,7 +3490,7 @@ var init_auth_middleware = __esm({
3430
3490
  `Authentication failed for request on path: ${req.path}. Code: ${error.code}. Error: ${error}`
3431
3491
  );
3432
3492
  const { network, tracing } = this._requestContext.getContext() ?? {};
3433
- return import_shared58.HttpHelper.error(
3493
+ return import_shared62.HttpHelper.error(
3434
3494
  {
3435
3495
  success: false,
3436
3496
  error: {
@@ -3439,12 +3499,12 @@ var init_auth_middleware = __esm({
3439
3499
  details: `[Authentication Error] Failed to authenticate request on path: ${req.path}`,
3440
3500
  path: req.path
3441
3501
  },
3442
- correlationId: tracing?.correlationId ?? import_shared58.GuidHelper.generate(),
3443
- requestId: network?.requestId ?? import_shared58.GuidHelper.generate(),
3444
- spanId: tracing?.spanId ?? import_shared58.GuidHelper.generate(),
3502
+ correlationId: tracing?.correlationId ?? import_shared62.GuidHelper.generate(),
3503
+ requestId: network?.requestId ?? import_shared62.GuidHelper.generate(),
3504
+ spanId: tracing?.spanId ?? import_shared62.GuidHelper.generate(),
3445
3505
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
3446
3506
  },
3447
- error.status ?? import_shared58.STATUS_CODES.UNAUTHORIZED,
3507
+ error.status ?? import_shared62.STATUS_CODES.UNAUTHORIZED,
3448
3508
  { "Content-Type": [network?.formatIndicator ?? "application/json"] }
3449
3509
  );
3450
3510
  }
@@ -3479,11 +3539,11 @@ var init_composite_middleware = __esm({
3479
3539
  });
3480
3540
 
3481
3541
  // src/presentation/middlewares/cors.middleware.ts
3482
- var import_shared59, CORSMiddleware;
3542
+ var import_shared63, CORSMiddleware;
3483
3543
  var init_cors_middleware = __esm({
3484
3544
  "src/presentation/middlewares/cors.middleware.ts"() {
3485
3545
  "use strict";
3486
- import_shared59 = require("@xeno-js/shared");
3546
+ import_shared63 = require("@xeno-js/shared");
3487
3547
  CORSMiddleware = class {
3488
3548
  constructor(_requestContext, _withCredentials = "false") {
3489
3549
  this._requestContext = _requestContext;
@@ -3495,7 +3555,7 @@ var init_cors_middleware = __esm({
3495
3555
  const { network } = this._requestContext.getContext() ?? {};
3496
3556
  const origin = network?.origin;
3497
3557
  const response = await next();
3498
- if (import_shared59.Guards.isDefined(origin))
3558
+ if (import_shared63.Guards.isDefined(origin))
3499
3559
  response.headers = {
3500
3560
  ...response.headers ?? {},
3501
3561
  "Access-Control-Allow-Origin": origin,
@@ -3509,11 +3569,11 @@ var init_cors_middleware = __esm({
3509
3569
  });
3510
3570
 
3511
3571
  // src/presentation/middlewares/csrf.middleware.ts
3512
- var import_shared60, CsrfMiddleware;
3572
+ var import_shared64, CsrfMiddleware;
3513
3573
  var init_csrf_middleware = __esm({
3514
3574
  "src/presentation/middlewares/csrf.middleware.ts"() {
3515
3575
  "use strict";
3516
- import_shared60 = require("@xeno-js/shared");
3576
+ import_shared64 = require("@xeno-js/shared");
3517
3577
  CsrfMiddleware = class {
3518
3578
  constructor(_requestContext, _csrfTokenService) {
3519
3579
  this._requestContext = _requestContext;
@@ -3528,64 +3588,64 @@ var init_csrf_middleware = __esm({
3528
3588
  const { network, tracing, identity } = this._requestContext.getContext() ?? {};
3529
3589
  const headerToken = network?.csrf;
3530
3590
  const cookieToken = network?.csrfCookie;
3531
- if (!import_shared60.Guards.isDefined(headerToken) || !import_shared60.Guards.isDefined(cookieToken)) {
3532
- return import_shared60.HttpHelper.error(
3591
+ if (!import_shared64.Guards.isDefined(headerToken) || !import_shared64.Guards.isDefined(cookieToken)) {
3592
+ return import_shared64.HttpHelper.error(
3533
3593
  {
3534
3594
  success: false,
3535
3595
  error: {
3536
- code: import_shared60.ERROR_CODES.FORBIDDEN,
3537
- message: import_shared60.ERROR_CODE_MESSAGES[import_shared60.ERROR_CODES.FORBIDDEN],
3596
+ code: import_shared64.ERROR_CODES.FORBIDDEN,
3597
+ message: import_shared64.ERROR_CODE_MESSAGES[import_shared64.ERROR_CODES.FORBIDDEN],
3538
3598
  details: "CSRF token missing",
3539
3599
  path: req.path
3540
3600
  },
3541
- correlationId: tracing?.correlationId ?? import_shared60.GuidHelper.generate(),
3542
- requestId: network?.requestId ?? import_shared60.GuidHelper.generate(),
3543
- spanId: tracing?.spanId ?? import_shared60.GuidHelper.generate(),
3601
+ correlationId: tracing?.correlationId ?? import_shared64.GuidHelper.generate(),
3602
+ requestId: network?.requestId ?? import_shared64.GuidHelper.generate(),
3603
+ spanId: tracing?.spanId ?? import_shared64.GuidHelper.generate(),
3544
3604
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
3545
3605
  },
3546
- import_shared60.STATUS_CODES.FORBIDDEN,
3606
+ import_shared64.STATUS_CODES.FORBIDDEN,
3547
3607
  {
3548
3608
  "Content-Type": [network?.formatIndicator ?? "application/json"]
3549
3609
  }
3550
3610
  );
3551
3611
  }
3552
3612
  if (headerToken !== cookieToken) {
3553
- return import_shared60.HttpHelper.error(
3613
+ return import_shared64.HttpHelper.error(
3554
3614
  {
3555
3615
  success: false,
3556
3616
  error: {
3557
- code: import_shared60.ERROR_CODES.FORBIDDEN,
3558
- message: import_shared60.ERROR_CODE_MESSAGES[import_shared60.ERROR_CODES.FORBIDDEN],
3617
+ code: import_shared64.ERROR_CODES.FORBIDDEN,
3618
+ message: import_shared64.ERROR_CODE_MESSAGES[import_shared64.ERROR_CODES.FORBIDDEN],
3559
3619
  details: "CSRF token mismatch",
3560
3620
  path: req.path
3561
3621
  },
3562
- correlationId: tracing?.correlationId ?? import_shared60.GuidHelper.generate(),
3563
- requestId: network?.requestId ?? import_shared60.GuidHelper.generate(),
3564
- spanId: tracing?.spanId ?? import_shared60.GuidHelper.generate(),
3622
+ correlationId: tracing?.correlationId ?? import_shared64.GuidHelper.generate(),
3623
+ requestId: network?.requestId ?? import_shared64.GuidHelper.generate(),
3624
+ spanId: tracing?.spanId ?? import_shared64.GuidHelper.generate(),
3565
3625
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
3566
3626
  },
3567
- import_shared60.STATUS_CODES.FORBIDDEN,
3627
+ import_shared64.STATUS_CODES.FORBIDDEN,
3568
3628
  {
3569
3629
  "Content-Type": [network?.formatIndicator ?? "application/json"]
3570
3630
  }
3571
3631
  );
3572
3632
  }
3573
- if (!import_shared60.Guards.isDefined(identity?.userId) || !await this._csrfTokenService.validate(headerToken, identity?.userId)) {
3574
- return import_shared60.HttpHelper.error(
3633
+ if (!import_shared64.Guards.isDefined(identity?.userId) || !await this._csrfTokenService.validate(headerToken, identity?.userId)) {
3634
+ return import_shared64.HttpHelper.error(
3575
3635
  {
3576
3636
  success: false,
3577
3637
  error: {
3578
- code: import_shared60.ERROR_CODES.FORBIDDEN,
3579
- message: import_shared60.ERROR_CODE_MESSAGES[import_shared60.ERROR_CODES.FORBIDDEN],
3638
+ code: import_shared64.ERROR_CODES.FORBIDDEN,
3639
+ message: import_shared64.ERROR_CODE_MESSAGES[import_shared64.ERROR_CODES.FORBIDDEN],
3580
3640
  details: "CSRF token invalid",
3581
3641
  path: req.path
3582
3642
  },
3583
- correlationId: tracing?.correlationId ?? import_shared60.GuidHelper.generate(),
3584
- requestId: network?.requestId ?? import_shared60.GuidHelper.generate(),
3585
- spanId: tracing?.spanId ?? import_shared60.GuidHelper.generate(),
3643
+ correlationId: tracing?.correlationId ?? import_shared64.GuidHelper.generate(),
3644
+ requestId: network?.requestId ?? import_shared64.GuidHelper.generate(),
3645
+ spanId: tracing?.spanId ?? import_shared64.GuidHelper.generate(),
3586
3646
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
3587
3647
  },
3588
- import_shared60.STATUS_CODES.FORBIDDEN,
3648
+ import_shared64.STATUS_CODES.FORBIDDEN,
3589
3649
  {
3590
3650
  "Content-Type": [network?.formatIndicator ?? "application/json"]
3591
3651
  }
@@ -3599,11 +3659,11 @@ var init_csrf_middleware = __esm({
3599
3659
  });
3600
3660
 
3601
3661
  // src/presentation/middlewares/csrf-cookie.middleware.ts
3602
- var import_shared61, CsrfCookieMiddleware;
3662
+ var import_shared65, CsrfCookieMiddleware;
3603
3663
  var init_csrf_cookie_middleware = __esm({
3604
3664
  "src/presentation/middlewares/csrf-cookie.middleware.ts"() {
3605
3665
  "use strict";
3606
- import_shared61 = require("@xeno-js/shared");
3666
+ import_shared65 = require("@xeno-js/shared");
3607
3667
  CsrfCookieMiddleware = class {
3608
3668
  constructor(_requestContext, _csrfTokenService, _csrf) {
3609
3669
  this._requestContext = _requestContext;
@@ -3618,8 +3678,8 @@ var init_csrf_cookie_middleware = __esm({
3618
3678
  const context = this._requestContext.getContext();
3619
3679
  const identity = context?.identity;
3620
3680
  const network = context?.network;
3621
- if (!import_shared61.Guards.isDefined(identity?.userId)) return response;
3622
- if (import_shared61.Guards.isDefined(network?.csrfCookie)) return response;
3681
+ if (!import_shared65.Guards.isDefined(identity?.userId)) return response;
3682
+ if (import_shared65.Guards.isDefined(network?.csrfCookie)) return response;
3623
3683
  const token = await this._csrfTokenService.generate(identity.userId);
3624
3684
  const cookieName = this._csrf.cookieName ?? "__Host-xeno-csrf";
3625
3685
  const maxAge = this._csrf.cookieMaxAgeSeconds ?? 3600;
@@ -3637,11 +3697,11 @@ var init_csrf_cookie_middleware = __esm({
3637
3697
  });
3638
3698
 
3639
3699
  // src/presentation/middlewares/options.middleware.ts
3640
- var import_shared62, OptionsMiddleware;
3700
+ var import_shared66, OptionsMiddleware;
3641
3701
  var init_options_middleware = __esm({
3642
3702
  "src/presentation/middlewares/options.middleware.ts"() {
3643
3703
  "use strict";
3644
- import_shared62 = require("@xeno-js/shared");
3704
+ import_shared66 = require("@xeno-js/shared");
3645
3705
  OptionsMiddleware = class {
3646
3706
  constructor(_requestContext, _alloewMethod, _allowHeaders = [], _withCredentials = "false") {
3647
3707
  this._requestContext = _requestContext;
@@ -3658,14 +3718,14 @@ var init_options_middleware = __esm({
3658
3718
  const network = this._requestContext.getNetworkContext();
3659
3719
  const origin = network?.origin;
3660
3720
  const headers = {};
3661
- if (import_shared62.Guards.isDefined(origin)) {
3721
+ if (import_shared66.Guards.isDefined(origin)) {
3662
3722
  headers["Access-Control-Allow-Origin"] = origin;
3663
3723
  headers["Access-Control-Allow-Credentials"] = this._withCredentials;
3664
3724
  headers["Vary"] = "Origin";
3665
3725
  }
3666
3726
  headers["Access-Control-Allow-Methods"] = this._alloewMethod.getMethods(req.path);
3667
3727
  headers["Access-Control-Allow-Headers"] = this._allowHeaders.join(", ");
3668
- return import_shared62.HttpHelper.success(null, import_shared62.STATUS_CODES.NO_CONTENT, {}, headers);
3728
+ return import_shared66.HttpHelper.success(null, import_shared66.STATUS_CODES.NO_CONTENT, {}, headers);
3669
3729
  }
3670
3730
  return await next();
3671
3731
  }
@@ -3674,11 +3734,11 @@ var init_options_middleware = __esm({
3674
3734
  });
3675
3735
 
3676
3736
  // src/presentation/middlewares/rate-limiter.middleware.ts
3677
- var import_shared63, RateLimitMiddleware;
3737
+ var import_shared67, RateLimitMiddleware;
3678
3738
  var init_rate_limiter_middleware = __esm({
3679
3739
  "src/presentation/middlewares/rate-limiter.middleware.ts"() {
3680
3740
  "use strict";
3681
- import_shared63 = require("@xeno-js/shared");
3741
+ import_shared67 = require("@xeno-js/shared");
3682
3742
  RateLimitMiddleware = class {
3683
3743
  constructor(_ctxAccessor, _cache, _keyBuilder, _logger, _opts) {
3684
3744
  this._ctxAccessor = _ctxAccessor;
@@ -3695,22 +3755,22 @@ var init_rate_limiter_middleware = __esm({
3695
3755
  async execute(req, _res, next) {
3696
3756
  const cacheKey = this._keyBuilder.buildRateLimitKey(req.path);
3697
3757
  const { network, tracing } = this._ctxAccessor.getContext() ?? {};
3698
- if (!import_shared63.Guards.isDefined(cacheKey))
3699
- return import_shared63.HttpHelper.error(
3758
+ if (!import_shared67.Guards.isDefined(cacheKey))
3759
+ return import_shared67.HttpHelper.error(
3700
3760
  {
3701
3761
  success: false,
3702
3762
  error: {
3703
- code: import_shared63.ERROR_CODES.SYSTEM_ERROR,
3704
- message: import_shared63.ERROR_CODE_MESSAGES[import_shared63.ERROR_CODES.SYSTEM_ERROR],
3763
+ code: import_shared67.ERROR_CODES.SYSTEM_ERROR,
3764
+ message: import_shared67.ERROR_CODE_MESSAGES[import_shared67.ERROR_CODES.SYSTEM_ERROR],
3705
3765
  details: `Bad Request: Unable to identify client context for rate limiting.`,
3706
3766
  path: req.path
3707
3767
  },
3708
- correlationId: tracing?.correlationId ?? import_shared63.GuidHelper.generate(),
3709
- requestId: network?.requestId ?? import_shared63.GuidHelper.generate(),
3710
- spanId: tracing?.spanId ?? import_shared63.GuidHelper.generate(),
3768
+ correlationId: tracing?.correlationId ?? import_shared67.GuidHelper.generate(),
3769
+ requestId: network?.requestId ?? import_shared67.GuidHelper.generate(),
3770
+ spanId: tracing?.spanId ?? import_shared67.GuidHelper.generate(),
3711
3771
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
3712
3772
  },
3713
- import_shared63.STATUS_CODES.SERVICE_UNAVAILABLE,
3773
+ import_shared67.STATUS_CODES.SERVICE_UNAVAILABLE,
3714
3774
  {
3715
3775
  "Content-Type": [network?.formatIndicator ?? "application/json"],
3716
3776
  "Retry-After": [String(this._opts.windowSeconds)]
@@ -3719,21 +3779,21 @@ var init_rate_limiter_middleware = __esm({
3719
3779
  const currentHits = await this._cache.increment(cacheKey, this._opts.windowSeconds);
3720
3780
  if (currentHits > this._opts.maxRequests) {
3721
3781
  this._logger.warn(`[RateLimit] key ${cacheKey} has been blocked on ${req.path}`);
3722
- return import_shared63.HttpHelper.error(
3782
+ return import_shared67.HttpHelper.error(
3723
3783
  {
3724
3784
  success: false,
3725
3785
  error: {
3726
- code: import_shared63.ERROR_CODES.TOO_MANY_REQUESTS,
3727
- message: import_shared63.ERROR_CODE_MESSAGES[import_shared63.ERROR_CODES.TOO_MANY_REQUESTS],
3786
+ code: import_shared67.ERROR_CODES.TOO_MANY_REQUESTS,
3787
+ message: import_shared67.ERROR_CODE_MESSAGES[import_shared67.ERROR_CODES.TOO_MANY_REQUESTS],
3728
3788
  details: `Rate limit exceeded.`,
3729
3789
  path: req.path
3730
3790
  },
3731
- correlationId: tracing?.correlationId ?? import_shared63.GuidHelper.generate(),
3732
- requestId: network?.requestId ?? import_shared63.GuidHelper.generate(),
3733
- spanId: tracing?.spanId ?? import_shared63.GuidHelper.generate(),
3791
+ correlationId: tracing?.correlationId ?? import_shared67.GuidHelper.generate(),
3792
+ requestId: network?.requestId ?? import_shared67.GuidHelper.generate(),
3793
+ spanId: tracing?.spanId ?? import_shared67.GuidHelper.generate(),
3734
3794
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
3735
3795
  },
3736
- import_shared63.STATUS_CODES.TOO_MANY_REQUESTS,
3796
+ import_shared67.STATUS_CODES.TOO_MANY_REQUESTS,
3737
3797
  {
3738
3798
  "Content-Type": [network?.formatIndicator ?? "application/json"],
3739
3799
  "Retry-After": [String(this._opts.windowSeconds)]
@@ -3748,8 +3808,8 @@ var init_rate_limiter_middleware = __esm({
3748
3808
 
3749
3809
  // src/presentation/mappers/context.mapper.ts
3750
3810
  function _buildMessagingContext(meta) {
3751
- const hasSequenceData = import_shared64.Guards.isDefined(meta.sequence?.sequenceId) || import_shared64.Guards.isDefined(meta.sequence?.position) || import_shared64.Guards.isDefined(meta.sequence?.size);
3752
- const hasMessagingData = hasSequenceData || import_shared64.Guards.isDefined(meta.expiration) || import_shared64.Guards.isDefined(meta.returnAddress);
3811
+ const hasSequenceData = import_shared68.Guards.isDefined(meta.sequence?.sequenceId) || import_shared68.Guards.isDefined(meta.sequence?.position) || import_shared68.Guards.isDefined(meta.sequence?.size);
3812
+ const hasMessagingData = hasSequenceData || import_shared68.Guards.isDefined(meta.expiration) || import_shared68.Guards.isDefined(meta.returnAddress);
3753
3813
  const messaging = hasMessagingData ? {
3754
3814
  returnAddress: meta.returnAddress,
3755
3815
  expiration: meta.expiration,
@@ -3757,11 +3817,11 @@ function _buildMessagingContext(meta) {
3757
3817
  } : void 0;
3758
3818
  return messaging;
3759
3819
  }
3760
- var import_shared64, ContextMapper;
3820
+ var import_shared68, ContextMapper;
3761
3821
  var init_context_mapper = __esm({
3762
3822
  "src/presentation/mappers/context.mapper.ts"() {
3763
3823
  "use strict";
3764
- import_shared64 = require("@xeno-js/shared");
3824
+ import_shared68 = require("@xeno-js/shared");
3765
3825
  ContextMapper = Object.freeze({
3766
3826
  /**
3767
3827
  * @description Maps to RequestContext. It extracts relevant information from the object, such as correlation ID, request ID, authentication token, client IP, user agent, format indicator, and messaging context (if available). The method constructs a RequestContext object that encapsulates all this information, providing a structured representation of the request context for further processing in the application.
@@ -3805,11 +3865,11 @@ var init_context_mapper = __esm({
3805
3865
  });
3806
3866
 
3807
3867
  // src/presentation/middlewares/request.middleware.ts
3808
- var import_shared65, RequestContextMiddleware;
3868
+ var import_shared69, RequestContextMiddleware;
3809
3869
  var init_request_middleware = __esm({
3810
3870
  "src/presentation/middlewares/request.middleware.ts"() {
3811
3871
  "use strict";
3812
- import_shared65 = require("@xeno-js/shared");
3872
+ import_shared69 = require("@xeno-js/shared");
3813
3873
  init_context_mapper();
3814
3874
  RequestContextMiddleware = class {
3815
3875
  /**
@@ -3834,8 +3894,8 @@ var init_request_middleware = __esm({
3834
3894
  _resolver;
3835
3895
  _logger;
3836
3896
  async execute(req, res, next) {
3837
- const correlationId = import_shared65.GuidHelper.generate();
3838
- const requestId = import_shared65.GuidHelper.generate();
3897
+ const correlationId = import_shared69.GuidHelper.generate();
3898
+ const requestId = import_shared69.GuidHelper.generate();
3839
3899
  const spanId = correlationId;
3840
3900
  const formatIndicator = "application/json";
3841
3901
  try {
@@ -3851,7 +3911,7 @@ var init_request_middleware = __esm({
3851
3911
  };
3852
3912
  const tmpContext = ContextMapper.map({
3853
3913
  metadata,
3854
- identity: import_shared65.GUEST,
3914
+ identity: import_shared69.GUEST,
3855
3915
  path: req.path,
3856
3916
  transport: { req, res }
3857
3917
  });
@@ -3863,12 +3923,12 @@ var init_request_middleware = __esm({
3863
3923
  return result;
3864
3924
  } catch (error) {
3865
3925
  this._logger.error("RequestContextMiddleware encountered an error", error);
3866
- return import_shared65.HttpHelper.error(
3926
+ return import_shared69.HttpHelper.error(
3867
3927
  {
3868
3928
  success: false,
3869
3929
  error: {
3870
- code: import_shared65.ERROR_CODES.SYSTEM_ERROR,
3871
- message: import_shared65.ERROR_CODE_MESSAGES[import_shared65.ERROR_CODES.SYSTEM_ERROR],
3930
+ code: import_shared69.ERROR_CODES.SYSTEM_ERROR,
3931
+ message: import_shared69.ERROR_CODE_MESSAGES[import_shared69.ERROR_CODES.SYSTEM_ERROR],
3872
3932
  details: `[Fatal System Error] Exception caught during request handling on path: ${req.path}`,
3873
3933
  path: req.path
3874
3934
  },
@@ -3877,7 +3937,7 @@ var init_request_middleware = __esm({
3877
3937
  spanId,
3878
3938
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
3879
3939
  },
3880
- import_shared65.STATUS_CODES.INTERNAL_SERVER_ERROR,
3940
+ import_shared69.STATUS_CODES.INTERNAL_SERVER_ERROR,
3881
3941
  { "Content-Type": [formatIndicator] }
3882
3942
  );
3883
3943
  }
@@ -3926,111 +3986,29 @@ var init_presentation = __esm({
3926
3986
  }
3927
3987
  });
3928
3988
 
3929
- // src/infrastructure/cache/inmemory.cache.ts
3930
- var inmemory_cache_exports = {};
3931
- __export(inmemory_cache_exports, {
3932
- InMemoryCacheExtended: () => InMemoryCacheExtended
3933
- });
3934
- var import_shared66, InMemoryCacheExtended;
3935
- var init_inmemory_cache = __esm({
3936
- "src/infrastructure/cache/inmemory.cache.ts"() {
3937
- "use strict";
3938
- import_shared66 = require("@xeno-js/shared");
3939
- InMemoryCacheExtended = class extends import_shared66.InMemoryCache {
3940
- async increment(key, ttlSeconds) {
3941
- const current = await this.get(key) ?? 0;
3942
- const next = Number(current) + 1;
3943
- const ttl = import_shared66.Guards.isDefined(ttlSeconds) ? Number(ttlSeconds) : 60;
3944
- await this.set(key, next, ttl);
3945
- return next;
3946
- }
3947
- };
3948
- }
3949
- });
3950
-
3951
3989
  // src/infrastructure/cache/rate-limit-key-builder.cache.ts
3952
- var import_shared67, RateLimitKeyBuilder;
3990
+ var import_shared70, RateLimitKeyBuilder;
3953
3991
  var init_rate_limit_key_builder_cache = __esm({
3954
3992
  "src/infrastructure/cache/rate-limit-key-builder.cache.ts"() {
3955
3993
  "use strict";
3956
- import_shared67 = require("@xeno-js/shared");
3994
+ import_shared70 = require("@xeno-js/shared");
3957
3995
  RateLimitKeyBuilder = class {
3958
3996
  constructor(_contextAccessor) {
3959
3997
  this._contextAccessor = _contextAccessor;
3960
3998
  }
3961
- _contextAccessor;
3962
- buildRateLimitKey(resource) {
3963
- const ctx = this._contextAccessor.getContext();
3964
- const tenantId = ctx?.identity?.tenantId;
3965
- const userId = ctx?.identity?.userId;
3966
- const clientIp = ctx?.network?.clientIp;
3967
- if (!import_shared67.Guards.isNullOrEmpty(tenantId) && !import_shared67.Guards.isNullOrEmpty(userId))
3968
- return `ratelimit:tenant:${tenantId}:user:${userId}:${resource}`;
3969
- if (!import_shared67.Guards.isNullOrEmpty(tenantId) && !import_shared67.Guards.isNullOrEmpty(clientIp))
3970
- return `ratelimit:tenant:${tenantId}:ip:${clientIp}:${resource}`;
3971
- if (!import_shared67.Guards.isNullOrEmpty(userId)) return `ratelimit:user:${userId}:${resource}`;
3972
- if (!import_shared67.Guards.isNullOrEmpty(clientIp)) return `ratelimit:ip:${clientIp}:${resource}`;
3973
- return void 0;
3974
- }
3975
- };
3976
- }
3977
- });
3978
-
3979
- // src/infrastructure/cache/redis.cache.ts
3980
- var import_shared68, RedisCache;
3981
- var init_redis_cache = __esm({
3982
- "src/infrastructure/cache/redis.cache.ts"() {
3983
- "use strict";
3984
- import_shared68 = require("@xeno-js/shared");
3985
- RedisCache = class {
3986
- /**
3987
- * @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.
3988
- * @param _redisClient An instance of the Redis client from the ioredis library, used to perform caching operations in the Redis database.
3989
-
3990
- *
3991
- * @author Xeno
3992
- * @version 1.0.0
3993
- * @since 2025-09-30
3994
- * @link https://github.com/xeno-js/xeno-js
3995
- */
3996
- constructor(_redisClient) {
3997
- this._redisClient = _redisClient;
3998
- }
3999
- _redisClient;
4000
- async increment(key, ttlSeconds) {
4001
- const multi = this._redisClient.multi();
4002
- multi.incr(key);
4003
- multi.expire(key, ttlSeconds ?? 60);
4004
- const results = await multi.exec();
4005
- return results?.[0]?.[1] ?? 1;
4006
- }
4007
- async get(key) {
4008
- const value = await this._redisClient.get(key);
4009
- if (!import_shared68.Guards.isDefined(value)) {
4010
- return void 0;
4011
- }
4012
- return JSON.parse(value);
4013
- }
4014
- async set(key, value, ttl) {
4015
- const stringValue = import_shared68.StringHelper.safeStringify(value);
4016
- const ttlOption = import_shared68.Guards.isDefined(ttl) ? ttl : 86400;
4017
- await this._redisClient.set(key, stringValue, "EX", ttlOption);
4018
- }
4019
- async setIfAbsent(key, value, ttl) {
4020
- const stringValue = import_shared68.StringHelper.safeStringify(value);
4021
- const ttlOption = import_shared68.Guards.isDefined(ttl) ? ttl : 300;
4022
- const result = await this._redisClient.set(key, stringValue, "EX", ttlOption, "NX");
4023
- return result === "OK";
4024
- }
4025
- async remove(key) {
4026
- await this._redisClient.del(key);
4027
- }
4028
- async has(key) {
4029
- const exists = await this._redisClient.exists(key);
4030
- return exists === 1;
4031
- }
4032
- async clear() {
4033
- await this._redisClient.flushdb();
3999
+ _contextAccessor;
4000
+ buildRateLimitKey(resource) {
4001
+ const ctx = this._contextAccessor.getContext();
4002
+ const tenantId = ctx?.identity?.tenantId;
4003
+ const userId = ctx?.identity?.userId;
4004
+ const clientIp = ctx?.network?.clientIp;
4005
+ if (!import_shared70.Guards.isNullOrEmpty(tenantId) && !import_shared70.Guards.isNullOrEmpty(userId))
4006
+ return `ratelimit:tenant:${tenantId}:user:${userId}:${resource}`;
4007
+ if (!import_shared70.Guards.isNullOrEmpty(tenantId) && !import_shared70.Guards.isNullOrEmpty(clientIp))
4008
+ return `ratelimit:tenant:${tenantId}:ip:${clientIp}:${resource}`;
4009
+ if (!import_shared70.Guards.isNullOrEmpty(userId)) return `ratelimit:user:${userId}:${resource}`;
4010
+ if (!import_shared70.Guards.isNullOrEmpty(clientIp)) return `ratelimit:ip:${clientIp}:${resource}`;
4011
+ return void 0;
4034
4012
  }
4035
4013
  };
4036
4014
  }
@@ -4231,423 +4209,278 @@ var init_middleware_module = __esm({
4231
4209
  }
4232
4210
  });
4233
4211
 
4234
- // src/infrastructure/factories/redis-cache.factory.ts
4235
- var redis_cache_factory_exports = {};
4236
- __export(redis_cache_factory_exports, {
4237
- RedisCacheFactory: () => RedisCacheFactory
4212
+ // src/infrastructure/factories/service-scope.factory.ts
4213
+ var service_scope_factory_exports = {};
4214
+ __export(service_scope_factory_exports, {
4215
+ ServiceScopeFactory: () => ServiceScopeFactory
4238
4216
  });
4239
- var import_shared69, import_ioredis, RedisCacheFactory;
4240
- var init_redis_cache_factory = __esm({
4241
- "src/infrastructure/factories/redis-cache.factory.ts"() {
4217
+ var ServiceScopeFactory;
4218
+ var init_service_scope_factory = __esm({
4219
+ "src/infrastructure/factories/service-scope.factory.ts"() {
4242
4220
  "use strict";
4243
- import_shared69 = require("@xeno-js/shared");
4244
- import_ioredis = require("ioredis");
4245
- init_redis_cache();
4246
- RedisCacheFactory = class {
4247
- create(config) {
4248
- const host = config?.host ?? "localhost";
4249
- const port = config?.port ?? 6379;
4250
- const password = config?.password;
4251
- const username = config?.username;
4252
- const useTls = config?.tls ?? false;
4253
- const maxRetries = config?.maxRetriesPerRequest ?? 3;
4254
- const redisOptions = {
4255
- host,
4256
- port,
4257
- maxRetriesPerRequest: maxRetries,
4258
- // Strategia di riconnessione esponenziale per garantire resilienza
4259
- retryStrategy(times) {
4260
- const delay = Math.min(times * 50, 2e3);
4261
- return delay;
4262
- }
4263
- };
4264
- if (import_shared69.Guards.isDefined(password)) {
4265
- redisOptions.password = password;
4266
- }
4267
- if (import_shared69.Guards.isDefined(username)) {
4268
- redisOptions.username = username;
4269
- }
4270
- if (useTls) {
4271
- redisOptions.tls = {};
4272
- }
4273
- const nativeRedisInstance = new import_ioredis.Redis(redisOptions);
4274
- nativeRedisInstance.on("error", (err) => {
4275
- console.error("\u274C [Redis Error]:", err.message);
4276
- });
4277
- return new RedisCache(nativeRedisInstance);
4221
+ ServiceScopeFactory = class {
4222
+ constructor(_container) {
4223
+ this._container = _container;
4224
+ }
4225
+ _container;
4226
+ create() {
4227
+ return this._container.createScope();
4278
4228
  }
4279
4229
  };
4280
4230
  }
4281
4231
  });
4282
4232
 
4283
- // src/infrastructure/modules/utils/cache.utils.ts
4284
- var cache_utils_exports = {};
4285
- __export(cache_utils_exports, {
4286
- CacheUtils: () => CacheUtils
4287
- });
4288
- var CacheUtils;
4289
- var init_cache_utils = __esm({
4290
- "src/infrastructure/modules/utils/cache.utils.ts"() {
4233
+ // src/infrastructure/context/request-context.ts
4234
+ var import_shared71, NodeRequestContext;
4235
+ var init_request_context = __esm({
4236
+ "src/infrastructure/context/request-context.ts"() {
4291
4237
  "use strict";
4292
- CacheUtils = Object.freeze({
4238
+ import_shared71 = require("@xeno-js/shared");
4239
+ NodeRequestContext = class {
4293
4240
  /**
4294
- * @description Checks if the provided cache configuration requires any cache strategies.
4295
- * @param container The service container to which the cache strategies will be added.
4296
- * @param opts The cache configuration options.
4297
- * @returns True if any cache strategies are required, false otherwise.
4241
+ * @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.
4242
+ * @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.
4243
+ * @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.
4298
4244
  *
4299
4245
  * @author Xeno
4300
4246
  * @version 1.0.0
4301
4247
  * @since 2025-09-30
4302
4248
  * @link https://github.com/xeno-js/xeno-js
4303
4249
  */
4304
- async addCache(container, opts) {
4305
- const { Guards: Guards51, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
4306
- if (!opts.inMemory && !Guards51.isDefined(opts.redis)) {
4307
- throw new Error(
4308
- "No cache strategies are configured. Please provide at least one cache strategy."
4309
- );
4310
- }
4311
- const { CacheKeyBuilder } = await import("@xeno-js/shared");
4312
- container.addSingleton(
4313
- TOKENS5.CACHE_KEY_BUILDER,
4314
- (c) => new CacheKeyBuilder(c.resolve(TOKENS5.IDENTITY_ACCESSOR))
4315
- );
4316
- if (opts.inMemory || !Guards51.isDefined(opts.redis)) {
4317
- const { InMemoryCacheExtended: InMemoryCacheExtended2 } = await Promise.resolve().then(() => (init_inmemory_cache(), inmemory_cache_exports));
4318
- container.addSingleton(TOKENS5.CACHE, () => new InMemoryCacheExtended2());
4319
- return;
4250
+ constructor(_storage, _factoryScope) {
4251
+ this._storage = _storage;
4252
+ this._factoryScope = _factoryScope;
4253
+ }
4254
+ _storage;
4255
+ _factoryScope;
4256
+ async runAsync(context, fn) {
4257
+ const scope = this._factoryScope.create();
4258
+ try {
4259
+ return await this._storage.run({ context, scope }, fn);
4260
+ } finally {
4261
+ await scope.dispose();
4320
4262
  }
4321
- if (Guards51.isDefined(opts.redis)) {
4322
- const { RedisCacheFactory: RedisCacheFactory2 } = await Promise.resolve().then(() => (init_redis_cache_factory(), redis_cache_factory_exports));
4323
- container.addSingleton(TOKENS5.CACHE, () => {
4324
- const config = opts.redis;
4325
- return new RedisCacheFactory2().create(config);
4263
+ }
4264
+ updateIdentity(identity) {
4265
+ const store = this._storage.getStore();
4266
+ if (import_shared71.Guards.isDefined(store) && import_shared71.Guards.isDefined(store.context)) {
4267
+ store.context = Object.freeze({
4268
+ ...store.context,
4269
+ identity: Object.freeze(identity)
4326
4270
  });
4327
4271
  }
4328
4272
  }
4329
- });
4330
- }
4331
- });
4332
-
4333
- // src/infrastructure/loggers/console.logger.ts
4334
- var console_logger_exports = {};
4335
- __export(console_logger_exports, {
4336
- ConsoleLogger: () => ConsoleLogger
4337
- });
4338
- var import_shared70, ConsoleLogger;
4339
- var init_console_logger = __esm({
4340
- "src/infrastructure/loggers/console.logger.ts"() {
4341
- "use strict";
4342
- import_shared70 = require("@xeno-js/shared");
4343
- ConsoleLogger = class {
4344
- /**
4345
- * 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.
4346
- * @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.
4347
-
4348
- *
4349
- * @author Xeno
4350
- * @version 1.0.0
4351
- * @since 2025-09-30
4352
- * @link https://github.com/xeno-js/xeno-js
4353
- */
4354
- constructor(_minLevel = import_shared70.LOG_LEVEL.DEBUG) {
4355
- this._minLevel = _minLevel;
4273
+ getContext() {
4274
+ const store = this._storage.getStore();
4275
+ if (!import_shared71.Guards.isDefined(store)) return void 0;
4276
+ const context = store.context;
4277
+ return Object.freeze(context);
4356
4278
  }
4357
- _minLevel;
4358
- track(level, message, context, error = void 0) {
4359
- if (level < this._minLevel) return;
4360
- const logMessage = `[${level}] ${message}`;
4361
- const payload = import_shared70.Guards.isDefined(error) ? { ...context, error } : context;
4362
- switch (level) {
4363
- case import_shared70.LOG_LEVEL.ERROR:
4364
- console.error(logMessage, payload ?? {});
4365
- break;
4366
- case import_shared70.LOG_LEVEL.WARN:
4367
- console.warn(logMessage, payload ?? {});
4368
- break;
4369
- case import_shared70.LOG_LEVEL.DEBUG:
4370
- console.debug(logMessage, payload ?? {});
4371
- break;
4372
- default:
4373
- console.info(logMessage, payload ?? {});
4374
- break;
4375
- }
4279
+ getIdentity() {
4280
+ const store = this._storage.getStore();
4281
+ if (!import_shared71.Guards.isDefined(store)) return void 0;
4282
+ return Object.freeze(store.context?.identity);
4376
4283
  }
4377
- };
4378
- }
4379
- });
4380
-
4381
- // src/infrastructure/loggers/sentry.logger.ts
4382
- var import_shared71, SentryLogger;
4383
- var init_sentry_logger = __esm({
4384
- "src/infrastructure/loggers/sentry.logger.ts"() {
4385
- "use strict";
4386
- import_shared71 = require("@xeno-js/shared");
4387
- SentryLogger = class {
4388
- constructor(_client, _minLevel) {
4389
- this._client = _client;
4390
- this._minLevel = _minLevel;
4284
+ getScope() {
4285
+ const store = this._storage.getStore();
4286
+ if (!import_shared71.Guards.isDefined(store)) return void 0;
4287
+ return store.scope;
4391
4288
  }
4392
- _client;
4393
- _minLevel;
4394
- track(level, message, context = void 0, error = void 0) {
4395
- if (level < this._minLevel) return;
4396
- if (level === import_shared71.LOG_LEVEL.ERROR || level === import_shared71.LOG_LEVEL.WARN) {
4397
- this._client.withScope((scope) => {
4398
- if (import_shared71.Guards.isDefined(context)) scope.setExtras(context);
4399
- if (import_shared71.Guards.isDefined(error)) {
4400
- this._client.captureException(error);
4401
- } else {
4402
- this._client.captureMessage(message, "warning");
4403
- }
4404
- });
4405
- }
4289
+ getNetworkContext() {
4290
+ const store = this._storage.getStore();
4291
+ if (!import_shared71.Guards.isDefined(store)) return void 0;
4292
+ return Object.freeze(store.context?.network);
4406
4293
  }
4407
4294
  };
4408
4295
  }
4409
4296
  });
4410
4297
 
4411
- // src/infrastructure/factories/sentry-logger.factory.ts
4412
- var sentry_logger_factory_exports = {};
4413
- __export(sentry_logger_factory_exports, {
4414
- SentryLoggerFactory: () => SentryLoggerFactory
4298
+ // src/infrastructure/factories/request-context.factory.ts
4299
+ var request_context_factory_exports = {};
4300
+ __export(request_context_factory_exports, {
4301
+ NodeRequestContextFactory: () => NodeRequestContextFactory
4415
4302
  });
4416
- var Sentry, import_shared72, SentryLoggerFactory;
4417
- var init_sentry_logger_factory = __esm({
4418
- "src/infrastructure/factories/sentry-logger.factory.ts"() {
4303
+ var import_node_async_hooks2, NodeRequestContextFactory;
4304
+ var init_request_context_factory = __esm({
4305
+ "src/infrastructure/factories/request-context.factory.ts"() {
4419
4306
  "use strict";
4420
- Sentry = __toESM(require("@sentry/node"), 1);
4421
- import_shared72 = require("@xeno-js/shared");
4422
- init_sentry_logger();
4423
- SentryLoggerFactory = class {
4424
- create(config) {
4425
- const level = config.level ?? import_shared72.LOG_LEVEL.WARN;
4426
- const sentryConfig = config.sentry?.config;
4427
- const env = sentryConfig?.environment ?? process.env.NODE_ENV ?? "development";
4428
- if (!import_shared72.Guards.isDefined(sentryConfig))
4429
- throw new Error("Sentry configuration is required when Sentry logging is enabled.");
4430
- if (!import_shared72.Guards.isDefined(sentryConfig.dsn))
4431
- throw new Error("Sentry DSN is required when Sentry logging is enabled.");
4432
- Sentry.init({
4433
- dsn: sentryConfig.dsn,
4434
- environment: env,
4435
- tracesSampleRate: env === "production" ? 0.1 : 1,
4436
- integrations: [Sentry.httpIntegration()],
4437
- beforeSend(event, hint) {
4438
- const error = hint.originalException;
4439
- if (error instanceof Error && error.name === "ZodError") {
4440
- return null;
4441
- }
4442
- return event;
4443
- }
4444
- });
4445
- return new SentryLogger(Sentry, level);
4307
+ import_node_async_hooks2 = require("async_hooks");
4308
+ init_request_context();
4309
+ NodeRequestContextFactory = class {
4310
+ constructor(_factoryScope) {
4311
+ this._factoryScope = _factoryScope;
4312
+ }
4313
+ _factoryScope;
4314
+ _store = new import_node_async_hooks2.AsyncLocalStorage();
4315
+ create() {
4316
+ return new NodeRequestContext(this._store, this._factoryScope);
4446
4317
  }
4447
4318
  };
4448
4319
  }
4449
4320
  });
4450
4321
 
4451
- // src/infrastructure/loggers/pino.logger.ts
4452
- var import_shared73, PinoLogger;
4453
- var init_pino_logger = __esm({
4454
- "src/infrastructure/loggers/pino.logger.ts"() {
4322
+ // src/infrastructure/factories/user-context.factory.ts
4323
+ var user_context_factory_exports = {};
4324
+ __export(user_context_factory_exports, {
4325
+ UserContextFactory: () => UserContextFactory
4326
+ });
4327
+ var import_shared72, UserContextFactory;
4328
+ var init_user_context_factory = __esm({
4329
+ "src/infrastructure/factories/user-context.factory.ts"() {
4455
4330
  "use strict";
4456
- import_shared73 = require("@xeno-js/shared");
4457
- PinoLogger = class {
4331
+ import_shared72 = require("@xeno-js/shared");
4332
+ UserContextFactory = class {
4458
4333
  /**
4459
- * 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.
4460
- * @param _logger The Pino logger instance used for logging messages.
4461
- * @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.
4462
-
4463
- *
4334
+ * @description Constructs an instance of UserContextFactory.
4335
+ * @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.
4336
+ *
4464
4337
  * @author Xeno
4465
4338
  * @version 1.0.0
4466
4339
  * @since 2025-09-30
4467
- * @link https://github.com/xeno-js/xeno-js
4340
+ * @link https://github.com/xeno-js/xeno-js
4468
4341
  */
4469
- constructor(_logger, _minLevel = import_shared73.LOG_LEVEL.DEBUG) {
4470
- this._logger = _logger;
4471
- this._minLevel = _minLevel;
4342
+ constructor(_identityFactory) {
4343
+ this._identityFactory = _identityFactory;
4472
4344
  }
4473
- _logger;
4474
- _minLevel;
4475
- track(level, message, context, error = void 0) {
4476
- if (level < this._minLevel) return;
4477
- const payload = import_shared73.Guards.isDefined(error) ? { ...context, error } : context;
4478
- switch (level) {
4479
- case import_shared73.LOG_LEVEL.ERROR:
4480
- this._logger.error(payload ?? {}, message);
4481
- break;
4482
- case import_shared73.LOG_LEVEL.WARN:
4483
- this._logger.warn(payload ?? {}, message);
4484
- break;
4485
- case import_shared73.LOG_LEVEL.DEBUG:
4486
- this._logger.debug(payload ?? {}, message);
4487
- break;
4488
- default:
4489
- this._logger.info(payload ?? {}, message);
4490
- break;
4345
+ _identityFactory;
4346
+ create() {
4347
+ const output = {
4348
+ userId: void 0,
4349
+ tenantId: void 0
4350
+ };
4351
+ const identity = this._identityFactory.getIdentity();
4352
+ if (import_shared72.Guards.isDefined(identity)) {
4353
+ output.userId = identity.userId;
4354
+ output.tenantId = identity.tenantId;
4491
4355
  }
4356
+ return output;
4492
4357
  }
4493
4358
  };
4494
4359
  }
4495
4360
  });
4496
4361
 
4497
- // src/infrastructure/factories/pino-logger.factory.ts
4498
- var pino_logger_factory_exports = {};
4499
- __export(pino_logger_factory_exports, {
4500
- PinoLoggerFactory: () => PinoLoggerFactory
4362
+ // src/infrastructure/modules/context.module.ts
4363
+ var context_module_exports = {};
4364
+ __export(context_module_exports, {
4365
+ ContextModule: () => ContextModule
4501
4366
  });
4502
- var import_shared74, import_pino, PinoLoggerFactory;
4503
- var init_pino_logger_factory = __esm({
4504
- "src/infrastructure/factories/pino-logger.factory.ts"() {
4367
+ var ContextModule;
4368
+ var init_context_module = __esm({
4369
+ "src/infrastructure/modules/context.module.ts"() {
4505
4370
  "use strict";
4506
- import_shared74 = require("@xeno-js/shared");
4507
- import_pino = __toESM(require("pino"), 1);
4508
- init_pino_logger();
4509
- PinoLoggerFactory = class {
4510
- create(config) {
4511
- const level = config.level ?? import_shared74.LOG_LEVEL.DEBUG;
4512
- const env = config.pino.config?.env ?? process.env.NODE_ENV ?? "development";
4513
- const destinationType = config.pino.config?.destination ?? "stdout";
4514
- const filePath = config.pino.config?.filePath ?? "logs/app.log";
4515
- const prettyPrint = config.pino.config?.prettyPrint ?? env === "development";
4516
- const options = {
4517
- level: "trace",
4518
- serializers: {
4519
- err: import_pino.default.stdSerializers.err
4520
- },
4521
- timestamp: import_pino.default.stdTimeFunctions.isoTime,
4522
- redact: {
4523
- paths: ["password", "token", "secret", "authorization", "headers.authorization"],
4524
- censor: "***"
4525
- }
4526
- };
4527
- if (prettyPrint) {
4528
- return new PinoLogger(
4529
- (0, import_pino.default)({
4530
- ...options,
4531
- transport: {
4532
- target: "pino-pretty",
4533
- options: {
4534
- colorize: true,
4535
- ignore: "pid,hostname",
4536
- translateTime: "SYS:standard"
4537
- }
4538
- }
4539
- }),
4540
- level
4541
- );
4542
- }
4543
- if (destinationType === "file") {
4544
- const destination = import_pino.default.destination({ dest: filePath, sync: false });
4545
- return new PinoLogger((0, import_pino.default)(options, destination), level);
4546
- } else {
4547
- const stream = import_pino.default.destination({ dest: 1, sync: false });
4548
- return new PinoLogger((0, import_pino.default)(options, stream), level);
4549
- }
4371
+ ContextModule = class {
4372
+ async configure(container) {
4373
+ const { TOKENS: TOKENS5 } = await import("@xeno-js/shared");
4374
+ const { ServiceScopeFactory: ServiceScopeFactory2 } = await Promise.resolve().then(() => (init_service_scope_factory(), service_scope_factory_exports));
4375
+ const { NodeRequestContextFactory: NodeRequestContextFactory2 } = await Promise.resolve().then(() => (init_request_context_factory(), request_context_factory_exports));
4376
+ const requestContext = new NodeRequestContextFactory2(
4377
+ new ServiceScopeFactory2(container)
4378
+ ).create();
4379
+ container.addSingleton(TOKENS5.REQUEST_CONTEXT, () => requestContext);
4380
+ container.addSingleton(TOKENS5.CONTEXT_ACCESSOR, () => requestContext);
4381
+ container.addSingleton(TOKENS5.IDENTITY_ACCESSOR, () => requestContext);
4382
+ container.addSingleton(TOKENS5.SERVICE_SCOPE_ACCESSOR, () => requestContext);
4383
+ container.addSingleton(TOKENS5.NETWORK_CONTEXT_ACCESSOR, () => requestContext);
4384
+ const { UserContextFactory: UserContextFactory2 } = await Promise.resolve().then(() => (init_user_context_factory(), user_context_factory_exports));
4385
+ container.addSingleton("USER_CONTEXT_FACTORY", () => {
4386
+ return new UserContextFactory2(requestContext);
4387
+ });
4550
4388
  }
4551
4389
  };
4552
4390
  }
4553
4391
  });
4554
4392
 
4555
- // src/infrastructure/modules/utils/logger.utils.ts
4556
- var logger_utils_exports = {};
4557
- __export(logger_utils_exports, {
4558
- LoggerUtils: () => LoggerUtils
4393
+ // src/infrastructure/transaction/transaction-state.ts
4394
+ var transaction_state_exports = {};
4395
+ __export(transaction_state_exports, {
4396
+ TransactionState: () => TransactionState
4559
4397
  });
4560
- var LoggerUtils;
4561
- var init_logger_utils = __esm({
4562
- "src/infrastructure/modules/utils/logger.utils.ts"() {
4398
+ var TransactionState;
4399
+ var init_transaction_state = __esm({
4400
+ "src/infrastructure/transaction/transaction-state.ts"() {
4563
4401
  "use strict";
4564
- LoggerUtils = Object.freeze({
4402
+ TransactionState = class {
4565
4403
  /**
4566
- * @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.
4567
- *
4568
- * @param container - The service container to register logging services with.
4569
- * @param opts - The LoggerConfig options to determine which loggers to enable and their configurations.
4570
-
4571
- *
4404
+ * The current state of the transaction, which can be either a specific transaction type or null.
4572
4405
  * @author Xeno
4573
4406
  * @version 1.0.0
4574
4407
  * @since 2025-09-30
4575
- * @link https://github.com/xeno-js/xeno-js
4408
+ * @link https://github.com/xeno-js/xeno-js
4576
4409
  */
4577
- async addLogger(container, opts) {
4578
- const loggerDependencies = [];
4579
- const { Guards: Guards51, LOG_LEVEL: LOG_LEVEL7, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
4580
- if (!Guards51.isDefined(opts) || opts.console) {
4581
- const { ConsoleLogger: ConsoleLogger2 } = await Promise.resolve().then(() => (init_console_logger(), console_logger_exports));
4582
- loggerDependencies.push(new ConsoleLogger2(opts?.level));
4583
- }
4584
- if (Guards51.isDefined(opts)) {
4585
- if (Guards51.isDefined(opts.sentry.config)) {
4586
- const { SentryLoggerFactory: SentryLoggerFactory2 } = await Promise.resolve().then(() => (init_sentry_logger_factory(), sentry_logger_factory_exports));
4587
- loggerDependencies.push(new SentryLoggerFactory2().create(opts));
4588
- }
4589
- if (Guards51.isDefined(opts.pino.config)) {
4590
- const { PinoLoggerFactory: PinoLoggerFactory2 } = await Promise.resolve().then(() => (init_pino_logger_factory(), pino_logger_factory_exports));
4591
- loggerDependencies.push(new PinoLoggerFactory2().create(opts));
4592
- }
4593
- if (!Guards51.isNullOrEmpty(opts.customLoggers)) {
4594
- const customLoggers = opts.customLoggers;
4595
- customLoggers.forEach((fn) => {
4596
- if (Guards51.isDefined(fn)) loggerDependencies.push(fn(container));
4597
- });
4598
- }
4599
- }
4600
- const { BaseLogger } = await import("@xeno-js/shared");
4601
- container.addSingleton(TOKENS5.LOGGER, (c) => {
4602
- const context = c.resolve(TOKENS5.CONTEXT_ACCESSOR);
4603
- return new BaseLogger(context, opts?.level ?? LOG_LEVEL7.DEBUG, loggerDependencies);
4604
- });
4410
+ _state = null;
4411
+ /**
4412
+ * Creates an instance of TransactionState.
4413
+ * @param initialState - The initial state of the transaction, which can be either a specific transaction type or null.
4414
+ * @author Xeno
4415
+ * @version 1.0.0
4416
+ * @since 2025-09-30
4417
+ * @link https://github.com/xeno-js/xeno-js
4418
+ */
4419
+ constructor(initialState = null) {
4420
+ this._state = initialState;
4605
4421
  }
4606
- });
4607
- }
4608
- });
4609
-
4610
- // src/infrastructure/modules/utils/index.ts
4611
- var init_utils2 = __esm({
4612
- "src/infrastructure/modules/utils/index.ts"() {
4613
- "use strict";
4614
- init_auth_utils();
4615
- init_cache_utils();
4616
- init_db_utils();
4617
- init_http_utils();
4618
- init_logger_utils();
4619
- init_pipeline_utils();
4620
- init_validation_utils();
4422
+ get state() {
4423
+ return this._state;
4424
+ }
4425
+ set state(value) {
4426
+ this._state = value;
4427
+ }
4428
+ };
4621
4429
  }
4622
4430
  });
4623
4431
 
4624
- // src/infrastructure/modules/index.ts
4625
- var modules_exports = {};
4626
- __export(modules_exports, {
4627
- AuthUtils: () => AuthUtils,
4628
- CacheUtils: () => CacheUtils,
4629
- ContextModule: () => ContextModule,
4630
- CqrsModule: () => CqrsModule,
4631
- DbModule: () => DbModule,
4632
- DbUtils: () => DbUtils,
4633
- HttpAdapterModule: () => HttpAdapterModule,
4634
- HttpCoreModule: () => HttpCoreModule,
4635
- HttpUtils: () => HttpUtils,
4636
- LoggerUtils: () => LoggerUtils,
4637
- MiddlewareModule: () => MiddlewareModule,
4638
- PipelineUtils: () => PipelineUtils,
4639
- ValidationUtils: () => ValidationUtils
4432
+ // src/infrastructure/transaction/unit-of-work.ts
4433
+ var unit_of_work_exports = {};
4434
+ __export(unit_of_work_exports, {
4435
+ UnitOfWork: () => UnitOfWork
4640
4436
  });
4641
- var init_modules = __esm({
4642
- "src/infrastructure/modules/index.ts"() {
4437
+ var import_shared74, import_shared75, UnitOfWork;
4438
+ var init_unit_of_work = __esm({
4439
+ "src/infrastructure/transaction/unit-of-work.ts"() {
4643
4440
  "use strict";
4644
- init_context_module();
4645
- init_cqrs_module();
4646
- init_db_module();
4647
- init_http_adapter_module();
4648
- init_http_core_module();
4649
- init_middleware_module();
4650
- init_utils2();
4441
+ import_shared74 = require("@xeno-js/shared");
4442
+ import_shared75 = require("@xeno-js/shared");
4443
+ UnitOfWork = class {
4444
+ /**
4445
+ * Creates an instance of UnitOfWork.
4446
+ * @param _dbContext - The database context used for managing transactions.
4447
+ * @param _ttx - The transaction state, which can be either a specific transaction type or null.
4448
+ *
4449
+ * @author Xeno
4450
+ * @version 1.0.0
4451
+ * @since 2025-09-30
4452
+ * @link https://github.com/xeno-js/xeno-js
4453
+ */
4454
+ constructor(_dbContext, _ttx) {
4455
+ this._dbContext = _dbContext;
4456
+ this._ttx = _ttx;
4457
+ }
4458
+ _dbContext;
4459
+ _ttx;
4460
+ async runInTransaction(callback, signal) {
4461
+ import_shared74.AppError.throwIfAborted(signal, "UnitOfWork.runInTransaction");
4462
+ return this._dbContext.transaction(async (tx) => {
4463
+ this._ttx.state = tx;
4464
+ try {
4465
+ const result = await callback();
4466
+ return result;
4467
+ } finally {
4468
+ this._ttx.state = null;
4469
+ }
4470
+ });
4471
+ }
4472
+ async dispose() {
4473
+ if (import_shared75.Guards.isDefined(this._ttx.state)) {
4474
+ try {
4475
+ if (import_shared75.Guards.hasMethod(this._ttx.state, "rollback")) {
4476
+ await this._ttx.state.rollback();
4477
+ }
4478
+ } finally {
4479
+ this._ttx.state = null;
4480
+ }
4481
+ }
4482
+ }
4483
+ };
4651
4484
  }
4652
4485
  });
4653
4486
 
@@ -4659,6 +4492,7 @@ __export(index_exports, {
4659
4492
  BaseController: () => BaseController,
4660
4493
  BaseHttpAdapter: () => BaseHttpAdapter,
4661
4494
  ContainerUtils: () => ContainerUtils,
4495
+ DbModule: () => DbModule,
4662
4496
  Query: () => import_shared80.Query,
4663
4497
  ReadDao: () => ReadDao,
4664
4498
  Repository: () => Repository,
@@ -4668,7 +4502,7 @@ module.exports = __toCommonJS(index_exports);
4668
4502
  init_application();
4669
4503
 
4670
4504
  // src/infrastructure/builder/app.builder.ts
4671
- var import_shared75 = require("@xeno-js/shared");
4505
+ var import_shared73 = require("@xeno-js/shared");
4672
4506
 
4673
4507
  // src/infrastructure/configuration/configuration.ts
4674
4508
  var import_shared31 = require("@xeno-js/shared");
@@ -4947,7 +4781,7 @@ var AppBuilder = class {
4947
4781
  constructor(container, configurationService) {
4948
4782
  this._container = container ?? new ServiceContainer();
4949
4783
  this._configuration = configurationService ?? new EnvironmentConfigurationService();
4950
- this._container.addSingleton(import_shared75.TOKENS.CONFIGURATION_SERVICE, () => this._configuration);
4784
+ this._container.addSingleton(import_shared73.TOKENS.CONFIGURATION_SERVICE, () => this._configuration);
4951
4785
  this.addContext();
4952
4786
  }
4953
4787
  // --- Module Configurations ---
@@ -5027,7 +4861,7 @@ var AppBuilder = class {
5027
4861
  resilience: { retry: {}, circuitBreaker: {}, bulkhead: {} }
5028
4862
  };
5029
4863
  _loggerConfig = {
5030
- level: import_shared75.LOG_LEVEL.DEBUG,
4864
+ level: import_shared73.LOG_LEVEL.DEBUG,
5031
4865
  console: true,
5032
4866
  sentry: { config: void 0 },
5033
4867
  pino: { config: void 0 },
@@ -5054,7 +4888,7 @@ var AppBuilder = class {
5054
4888
  priority: 50,
5055
4889
  name: "AdapterModule",
5056
4890
  action: async () => {
5057
- const { HttpAdapterModule: HttpAdapterModule2 } = await Promise.resolve().then(() => (init_modules(), modules_exports));
4891
+ const { HttpAdapterModule: HttpAdapterModule2 } = await Promise.resolve().then(() => (init_http_adapter_module(), http_adapter_module_exports));
5058
4892
  await new HttpAdapterModule2().configure(this._container, this._adapterConfig);
5059
4893
  }
5060
4894
  });
@@ -5100,7 +4934,7 @@ var AppBuilder = class {
5100
4934
  * @link https://github.com/xeno-js/xeno-js
5101
4935
  */
5102
4936
  addLogger(setupAction) {
5103
- if (import_shared75.Guards.isDefined(setupAction)) setupAction(this._loggerConfig, this._configuration);
4937
+ if (import_shared73.Guards.isDefined(setupAction)) setupAction(this._loggerConfig, this._configuration);
5104
4938
  if (this._isLoggerModuleQueued) return this;
5105
4939
  this._isLoggerModuleQueued = true;
5106
4940
  this._modules.push({
@@ -5125,7 +4959,7 @@ var AppBuilder = class {
5125
4959
  * @link https://github.com/xeno-js/xeno-js
5126
4960
  */
5127
4961
  addCache(setupAction) {
5128
- if (import_shared75.Guards.isDefined(setupAction)) setupAction(this._config, this._configuration);
4962
+ if (import_shared73.Guards.isDefined(setupAction)) setupAction(this._config, this._configuration);
5129
4963
  if (this._isCacheModuleQueued) return this;
5130
4964
  this._isCacheModuleQueued = true;
5131
4965
  this._modules.push({
@@ -5174,21 +5008,11 @@ var AppBuilder = class {
5174
5008
  * @since 2025-09-30
5175
5009
  * @link https://github.com/xeno-js/xeno-js
5176
5010
  */
5177
- addDb(setupAction) {
5011
+ addDb(plugin) {
5178
5012
  if (this._isDbContextModuleQueued) return this;
5013
+ const result = plugin(this, this._configuration);
5179
5014
  this._isDbContextModuleQueued = true;
5180
- const config = { connectionString: "", enableSqlLite: false };
5181
- setupAction(config, this._configuration);
5182
- this._modules.push({
5183
- priority: 4,
5184
- name: "DbModule",
5185
- action: async () => {
5186
- const { DbModule: DbModule2 } = await Promise.resolve().then(() => (init_db_module(), db_module_exports));
5187
- const dbModule = new DbModule2();
5188
- await dbModule.configure(this._container, config);
5189
- }
5190
- });
5191
- return this;
5015
+ return result;
5192
5016
  }
5193
5017
  /**
5194
5018
  * @description Enables the use of the service for concurrency control in the application. This method allows you to limit the number of concurrent asynchronous tasks being executed, which is useful for managing system resources and preventing event loop blocking during massive batch operations.
@@ -5228,7 +5052,7 @@ var AppBuilder = class {
5228
5052
  * @link https://github.com/xeno-js/xeno-js
5229
5053
  */
5230
5054
  addPipeline(setupAction) {
5231
- if (import_shared75.Guards.isDefined(setupAction)) {
5055
+ if (import_shared73.Guards.isDefined(setupAction)) {
5232
5056
  setupAction(this._pipelineConfig, this._configuration);
5233
5057
  }
5234
5058
  this._queuePipelineModule();
@@ -5347,7 +5171,7 @@ var AppBuilder = class {
5347
5171
  console.error(`\u{1F449} Module: **${queued.name}**`);
5348
5172
  console.error(`\u{1F4DD} Reason: ${errorMessage}
5349
5173
  `);
5350
- if (error instanceof Error && import_shared75.Guards.isDefined(error.stack)) {
5174
+ if (error instanceof Error && import_shared73.Guards.isDefined(error.stack)) {
5351
5175
  console.error(error.stack);
5352
5176
  }
5353
5177
  throw new Error(`Bootstrap failed at [${queued.name}]: ${errorMessage}`, { cause: error });
@@ -5439,6 +5263,39 @@ var AppBuilder = class {
5439
5263
  // src/infrastructure/http/index.ts
5440
5264
  init_base_http_adapter();
5441
5265
 
5266
+ // src/infrastructure/modules/db.module.ts
5267
+ var DbModule = class {
5268
+ async configure(container, opts) {
5269
+ const { Guards: Guards51, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
5270
+ const db = opts.client;
5271
+ const { TransactionState: TransactionState2 } = await Promise.resolve().then(() => (init_transaction_state(), transaction_state_exports));
5272
+ container.addScoped("TRANSACTION_STATE", () => {
5273
+ return new TransactionState2();
5274
+ });
5275
+ const { UnitOfWork: UnitOfWork2 } = await Promise.resolve().then(() => (init_unit_of_work(), unit_of_work_exports));
5276
+ container.addScoped(TOKENS5.UNIT_OF_WORK, (c) => {
5277
+ const ttx = c.resolve("TRANSACTION_STATE");
5278
+ return new UnitOfWork2(db, ttx);
5279
+ });
5280
+ container.addScoped(TOKENS5.DB_CONTEXT, (c) => {
5281
+ const ttx = c.resolve("TRANSACTION_STATE");
5282
+ return new Proxy(db, {
5283
+ get(_target, prop, receiver) {
5284
+ const activeState = ttx.state;
5285
+ if (Guards51.isDefined(activeState)) {
5286
+ const value = Reflect.get(activeState, prop, receiver);
5287
+ if (Guards51.isFunction(value)) {
5288
+ return value.bind(activeState);
5289
+ }
5290
+ return value;
5291
+ }
5292
+ return Reflect.get(db, prop, receiver);
5293
+ }
5294
+ });
5295
+ });
5296
+ }
5297
+ };
5298
+
5442
5299
  // src/infrastructure/repositories/read-dao.ts
5443
5300
  var import_shared76 = require("@xeno-js/shared");
5444
5301
  var import_shared77 = require("@xeno-js/shared");
@@ -5540,6 +5397,7 @@ var import_shared80 = require("@xeno-js/shared");
5540
5397
  BaseController,
5541
5398
  BaseHttpAdapter,
5542
5399
  ContainerUtils,
5400
+ DbModule,
5543
5401
  Query,
5544
5402
  ReadDao,
5545
5403
  Repository,