@xeno-js/core 0.1.7 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/application/containers/container.utils.ts","../src/application/containers/index.ts","../src/application/cqrs/base-handler.ts","../src/application/cqrs/mediator.ts","../src/application/cqrs/pipelines/authorization.pipeline.ts","../src/application/cqrs/pipelines/composite.pipeline.ts","../src/application/cqrs/pipelines/concurrency-retry.pipeline.ts","../src/application/cqrs/pipelines/exception.pipeline.ts","../src/application/cqrs/pipelines/idempotency.pipeline.ts","../src/application/cqrs/pipelines/logging.pipeline.ts","../src/application/cqrs/pipelines/performance.pipeline.ts","../src/application/cqrs/pipelines/pipeline_strategies/auth/base-authorization.strategy.ts","../src/application/cqrs/pipelines/pipeline_strategies/auth/permission-authorization.strategy.ts","../src/application/cqrs/pipelines/pipeline_strategies/auth/role-authorization.strategy.ts","../src/application/cqrs/pipelines/pipeline_strategies/auth/tenant-authorization.strategy.ts","../src/application/cqrs/pipelines/pipeline_strategies/auth/user-authorization.strategy.ts","../src/application/cqrs/pipelines/pipeline_strategies/auth/index.ts","../src/application/cqrs/pipelines/pipeline_strategies/validation/schema-validation.strategy.ts","../src/application/cqrs/pipelines/pipeline_strategies/validation/index.ts","../src/application/cqrs/pipelines/pipeline_strategies/index.ts","../src/application/cqrs/pipelines/query-caching.pipeline.ts","../src/application/cqrs/pipelines/validation.pipeline.ts","../src/application/cqrs/pipelines/index.ts","../src/application/cqrs/index.ts","../src/application/gate_keepers/gate-keeper.ts","../src/application/gate_keepers/noauth.gate-keeper.ts","../src/application/gate_keepers/index.ts","../src/application/mappers/claims-identity.mapper.ts","../src/application/mappers/index.ts","../src/application/policies/policy-registry.ts","../src/application/policies/index.ts","../src/application/specifications/specification.ts","../src/application/specifications/index.ts","../src/application/index.ts","../src/infrastructure/loggers/console.logger.ts","../src/infrastructure/loggers/sentry.logger.ts","../src/infrastructure/factories/sentry-logger.factory.ts","../src/infrastructure/loggers/pino.logger.ts","../src/infrastructure/factories/pino-logger.factory.ts","../src/infrastructure/modules/utils/logger.utils.ts","../src/infrastructure/cache/inmemory.cache.ts","../src/infrastructure/cache/redis.cache.ts","../src/infrastructure/factories/redis-cache.factory.ts","../src/infrastructure/modules/utils/cache.utils.ts","../src/infrastructure/services/allow_methods/allow-method.service.ts","../src/infrastructure/services/allow_methods/index.ts","../src/infrastructure/services/allow_origins/allow-origin.http.ts","../src/infrastructure/services/allow_origins/index.ts","../src/infrastructure/services/concurrency/p-limit.service.ts","../src/infrastructure/services/concurrency/index.ts","../src/infrastructure/services/crypto/crypto.service.ts","../src/infrastructure/services/crypto/index.ts","../src/infrastructure/services/csrf/csrf-token.service.ts","../src/infrastructure/services/csrf/index.ts","../src/infrastructure/services/extractors/extract-bearer.extractor.ts","../src/infrastructure/services/extractors/extract-ssr-bearer.extractor.ts","../src/infrastructure/services/extractors/http-cookie.extractor.ts","../src/infrastructure/services/extractors/http-header.extractor.ts","../src/infrastructure/services/extractors/index.ts","../src/infrastructure/services/resiliences/resilience.service.ts","../src/infrastructure/services/resiliences/index.ts","../src/infrastructure/services/resolver/utils/socket.utils.ts","../src/infrastructure/services/resolver/utils/index.ts","../src/infrastructure/services/resolver/client-ip.resolver.ts","../src/infrastructure/services/resolver/index.ts","../src/infrastructure/services/index.ts","../src/infrastructure/factories/allow-method.factory.ts","../src/infrastructure/factories/axios.factory.ts","../src/infrastructure/factories/cockatiel-resilience.factory.ts","../src/infrastructure/factories/db-client.factory.ts","../src/infrastructure/context/request-context.ts","../src/infrastructure/factories/request-context.factory.ts","../src/infrastructure/factories/service-scope.factory.ts","../src/infrastructure/factories/sql-light-db-client.factory.ts","../src/infrastructure/factories/supabase.factory.ts","../src/infrastructure/factories/user-context.factory.ts","../src/infrastructure/factories/zod-validator.factory.ts","../src/infrastructure/factories/index.ts","../src/infrastructure/modules/utils/auth.utils.ts","../src/infrastructure/modules/utils/db.utils.ts","../src/infrastructure/transaction/transaction-state.ts","../src/infrastructure/transaction/unit-of-work.ts","../src/infrastructure/modules/db.module.ts","../src/infrastructure/modules/utils/http.utils.ts","../src/infrastructure/modules/http-core.module.ts","../src/infrastructure/modules/utils/validation.utils.ts","../src/infrastructure/idempotency/idempotency-store.ts","../src/infrastructure/modules/utils/pipeline.utils.ts","../src/infrastructure/modules/cqrs.module.ts","../src/presentation/controllers/base.controller.ts","../src/presentation/controllers/index.ts","../src/presentation/middlewares/allow-method.middleware.ts","../src/presentation/middlewares/allow-origin.middleware.ts","../src/presentation/middlewares/auth.middleware.ts","../src/presentation/middlewares/composite.middleware.ts","../src/presentation/middlewares/cors.middleware.ts","../src/presentation/middlewares/csrf.middleware.ts","../src/presentation/middlewares/csrf-cookie.middleware.ts","../src/presentation/middlewares/options.middleware.ts","../src/presentation/middlewares/rate-limiter.middleware.ts","../src/presentation/mappers/context.mapper.ts","../src/presentation/middlewares/request.middleware.ts","../src/presentation/middlewares/index.ts","../src/presentation/index.ts","../src/infrastructure/cache/rate-limit-key-builder.cache.ts","../src/infrastructure/cache/index.ts","../src/infrastructure/modules/middleware.module.ts","../src/infrastructure/modules/context.module.ts","../src/index.ts","../src/infrastructure/builder/app.builder.ts","../src/infrastructure/configuration/configuration.ts","../src/infrastructure/container/service-container.ts","../src/infrastructure/index.ts","../src/infrastructure/context/index.ts","../src/infrastructure/datasources/remote.datasource.ts","../src/infrastructure/idempotency/index.ts","../src/infrastructure/loggers/index.ts","../src/infrastructure/modules/index.ts","../src/infrastructure/modules/utils/index.ts","../src/infrastructure/repositories/read-dao.ts","../src/infrastructure/repositories/repository.ts","../src/infrastructure/transaction/index.ts","../src/infrastructure/db/drizzle.types.ts"],"sourcesContent":["import {\r\n Guards,\r\n type HttpHeaders,\r\n type HttpMethod,\r\n type Optional,\r\n type ResponseDto,\r\n TOKENS,\r\n} from '@xeno-js/shared'\r\n\r\nimport type { ApplicationRegistry, IServiceContainer, IServiceScope } from '@/domain'\r\n\r\n/**\r\n * Utils that provide utility functions for interacting with the service container and managing scoped service resolution.\r\n */\r\nexport const ContainerUtils = Object.freeze({\r\n /**\r\n * Resolves a scoped service from the container using the provided token.\r\n * @param token * The token to resolve from the registry.\r\n * @param container * The container to resolve the service from.\r\n *\r\n * @returns The resolved service instance.\r\n * @throws Error if the active service scope is not available.\r\n */\r\n resolveServiceScoped<K extends keyof T, T extends ApplicationRegistry>(\r\n token: K,\r\n container: IServiceContainer<T>,\r\n ) {\r\n const scope = container.resolve(TOKENS.SERVICE_SCOPE_ACCESSOR).getScope()\r\n if (!Guards.isDefined(scope)) {\r\n throw new Error('Active service scope is required to execute Scoped service.')\r\n }\r\n\r\n const service = (scope as IServiceScope<T>).resolve(token)\r\n return service\r\n },\r\n\r\n /**\r\n * Executes a service action within the context of a scoped service.\r\n * @param endpoint * The endpoint to execute the action on.\r\n * @param method * The HTTP method to use for the action.\r\n * @param headers * The headers to include in the request.\r\n * @param transport * The transport object containing the request and response objects.\r\n * @param container * The container to resolve the service from.\r\n * @param action * The action to execute within the scoped service.\r\n *\r\n * @returns Promise<ResponseDto<TResponse>> A promise that resolves to the response DTO of the executed action.\r\n * @throws Error If the active service scope is not available.\r\n * @throws Error If the service is not found in the container.\r\n * @throws Error If the service is not a scoped service.\r\n */\r\n async runExecute<TResponse, T extends ApplicationRegistry, TRes, TReq>(\r\n endpoint: string,\r\n method: Optional<string>,\r\n headers: HttpHeaders,\r\n transport: { res: TRes; req: TReq },\r\n container: IServiceContainer<T>,\r\n action: () => Promise<ResponseDto<TResponse>>,\r\n ): Promise<ResponseDto<TResponse>> {\r\n const middleware = container.resolve(TOKENS.MIDDLEWARE)\r\n\r\n return await middleware.execute(\r\n { path: endpoint, method: (method as HttpMethod) ?? 'GET', transport },\r\n { ...headers },\r\n async () => {\r\n return await action()\r\n },\r\n )\r\n },\r\n})\r\n","export * from './container.utils'\r\n","import {\r\n AppError,\r\n type IFactory,\r\n type IHandler,\r\n type IRequest,\r\n type Optional,\r\n type ResultType,\r\n type UserContext,\r\n} from '@xeno-js/shared'\r\n\r\n/**\r\n * BaseHandler is an abstract class that implements the IHandler interface.\r\n * It provides a base implementation for handling requests and executing strategies.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport abstract class BaseHandler<\r\n TRequest extends IRequest<TResponse>,\r\n TResponse,\r\n> implements IHandler<TRequest, TResponse> {\r\n constructor(private readonly _identityFactory: IFactory<void, UserContext>) {}\r\n\r\n public async handle(request: TRequest, signal: AbortSignal): Promise<ResultType<TResponse>> {\r\n AppError.throwIfAborted(signal, this.constructor.name)\r\n\r\n return await this.executeAsync(request)\r\n }\r\n\r\n /**\r\n * Executes the strategy for the given request.\r\n * @param request - The request to be handled.\r\n * @param signal - (Optional) The abort signal for the request.\r\n * @throws {AppError} If the strategy execution fails.\r\n * @protected - This method should be overridden by subclasses.\r\n * @abstract - This method must be implemented by subclasses.\r\n * @async - This method is asynchronous.\r\n * @template TRequest - The type of the request.\r\n * @template TResponse - The type of the response.\r\n * @returns {Promise<ResultType<TResponse>>} A promise that resolves to the result of the strategy execution.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n protected abstract executeAsync(\r\n request: TRequest,\r\n signal?: Optional<AbortSignal>,\r\n ): Promise<ResultType<TResponse>>\r\n\r\n /**\r\n * Gets the current context.\r\n * @returns {UserContext} The current context.\r\n * {@link UserContext}\r\n */\r\n protected _getCurrentContext(): UserContext {\r\n return this._identityFactory.create()\r\n }\r\n}\r\n","import type {\r\n Delegate,\r\n ICommand,\r\n IHandler,\r\n IMediator,\r\n IPipelineBehavior,\r\n IQuery,\r\n IRequest,\r\n ResultType,\r\n} from '@xeno-js/shared'\r\nimport { AppError, Result } from '@xeno-js/shared'\r\nimport { ERROR_CODE_MESSAGES, ERROR_CODES, Guards, STATUS_CODES, TOKENS } from '@xeno-js/shared'\r\n\r\nimport type { ApplicationRegistry, IServiceScopeAccessor } from '@/domain'\r\n\r\n/**\r\n * @description Mediator implementation for CQRS pattern. It is responsible for sending commands and executing queries by delegating them to the appropriate handlers, while also applying any registered pipeline behaviors (middlewares).\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class Mediator<\r\n TRegistry extends ApplicationRegistry<unknown> = ApplicationRegistry<unknown>,\r\n> implements IMediator {\r\n /**\r\n * @param _factoryScope - An instance of IServiceScopeAccessor used to access the current service scope, which is necessary for resolving handlers and pipeline behaviors for processing requests.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n constructor(private readonly _factoryScope: IServiceScopeAccessor<TRegistry>) {}\r\n\r\n /**\r\n * @inheritdoc\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n async send<TResponse>(\r\n request: ICommand<TResponse>,\r\n signal: AbortSignal,\r\n ): Promise<ResultType<TResponse>> {\r\n return this.process<TResponse>(request, TOKENS.COMMAND_PIPELINES_BEHAVIOR, signal)\r\n }\r\n\r\n /**\r\n * @inheritdoc\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n async query<TResponse>(\r\n request: IQuery<TResponse>,\r\n signal: AbortSignal,\r\n ): Promise<ResultType<TResponse>> {\r\n return this.process<TResponse>(request, TOKENS.QUERY_PIPELINES_BEHAVIOR, signal)\r\n }\r\n\r\n /**\r\n * @description Internal method to process both commands and queries. It resolves the appropriate handler for the request and applies the registered pipeline behaviors in the correct order.\r\n * @param request The command or query to be processed.\r\n * @param pipelineToken The token used to resolve the pipeline behaviors for the request.\r\n * @param signal An optional AbortSignal to allow cancellation of the request.\r\n * @returns A promise that resolves to the result of processing the request.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n private async process<TResponse>(\r\n request: IRequest<TResponse>,\r\n pipelineToken: keyof ApplicationRegistry<unknown>,\r\n signal: AbortSignal,\r\n ): Promise<ResultType<TResponse>> {\r\n if (Guards.isDefined(signal) && signal.aborted)\r\n return Result.fail(AppError.aborted(request.intent))\r\n\r\n const scope = this._factoryScope.getScope()\r\n\r\n if (!Guards.isDefined(scope))\r\n return Result.fail(\r\n AppError.create({\r\n code: ERROR_CODES.SCOPE_NOT_AVAILABLE,\r\n status: STATUS_CODES.INTERNAL_SERVER_ERROR,\r\n name: request.intent,\r\n message: ERROR_CODE_MESSAGES[ERROR_CODES.SCOPE_NOT_AVAILABLE],\r\n cause: new Error('Service scope is required to process the request.'),\r\n }),\r\n )\r\n\r\n const pipelines = scope.resolve(pipelineToken) as unknown as IPipelineBehavior<\r\n IRequest<TResponse>,\r\n TResponse\r\n >\r\n\r\n if (!Guards.isDefined(pipelines) || !Guards.hasMethod(pipelines, 'handle')) {\r\n return Result.fail(\r\n AppError.create({\r\n code: ERROR_CODES.PIPELINE_NOT_AVAILABLE,\r\n status: STATUS_CODES.INTERNAL_SERVER_ERROR,\r\n name: request.intent,\r\n message: ERROR_CODE_MESSAGES[ERROR_CODES.PIPELINE_NOT_AVAILABLE],\r\n cause: new Error('Pipeline behavior is required to process the request.'),\r\n }),\r\n )\r\n }\r\n\r\n const next: Delegate<TResponse> = () => {\r\n const handler = scope.resolve(request.intent as keyof TRegistry) as IHandler<\r\n IRequest<TResponse>,\r\n TResponse\r\n >\r\n\r\n if (!Guards.isDefined(handler) || !Guards.hasMethod(handler, 'handle')) {\r\n AppError.throw({\r\n code: ERROR_CODES.HANDLER_NOT_FOUND,\r\n status: STATUS_CODES.INTERNAL_SERVER_ERROR,\r\n name: request.intent,\r\n message: ERROR_CODE_MESSAGES[ERROR_CODES.HANDLER_NOT_FOUND],\r\n cause: new Error('Handler is required to process the request.'),\r\n })\r\n }\r\n return handler.handle(request, signal)\r\n }\r\n\r\n return pipelines.handle(request, next)\r\n }\r\n}\r\n","import type { Delegate, IPipelineBehavior, IRequest, IStrategy, ResultType } from '@xeno-js/shared'\r\nimport { Result } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description Middleware che gestisce l'autenticazione e l'autorizzazione dei comandi.\r\n * Intercetta i comandi che implementano ISecureCommand e verifica se l'utente è autenticato e ha i ruoli necessari.\r\n * Se il comando non richiede autorizzazione, delega semplicemente al prossimo middleware.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class AuthorizationPipeline<\r\n TInput extends IRequest<TResult>,\r\n TResult,\r\n> implements IPipelineBehavior<TInput, TResult> {\r\n /**\r\n * @description Costruisce una nuova istanza di AuthorizationPipeline, accettando un array di strategie di autorizzazione. Ogni strategia rappresenta una regola o un criterio specifico per determinare se un comando è autorizzato o meno. Durante l'esecuzione del pipeline, ogni strategia viene valutata in ordine, e se una qualsiasi strategia determina che il comando non è autorizzato, il pipeline restituisce un risultato di fallimento con l'errore corrispondente. Se tutte le strategie passano, il pipeline delega al prossimo comportamento nella catena.\r\n * @param _strategies Un array di oggetti che implementano l'interfaccia IStrategy, utilizzati per valutare l'autorizzazione dei comandi.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n constructor(private readonly _strategies: IStrategy<TInput>[]) {}\r\n\r\n public async handle(request: TInput, next: Delegate<TResult>): Promise<ResultType<TResult>> {\r\n for (const strategy of this._strategies) {\r\n const result = await strategy.execute(request)\r\n if (!result.isOk()) {\r\n return Result.fail(result.getErrorOrThrow())\r\n }\r\n }\r\n\r\n return next()\r\n }\r\n}\r\n","import type { Delegate, IPipelineBehavior, IRequest, ResultType } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description A composite pipeline behavior that allows for the combination of multiple pipeline behaviors into a single pipeline. This class takes an array of IPipelineBehavior instances and executes them in the order they were provided, allowing for a structured and modular approach to handling requests in a CQRS architecture. Each behavior can perform specific actions before and after invoking the next behavior in the pipeline, enabling cross-cutting concerns to be applied consistently across all requests.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class CompositePipeline<\r\n TInput extends IRequest<TResult>,\r\n TResult,\r\n> implements IPipelineBehavior<TInput, TResult> {\r\n /**\r\n * @description Constructs a new instance of the CompositePipeline class, which takes an optional array of IPipelineBehavior instances. If no behaviors are provided, it initializes with an empty array. The composite pipeline will execute each behavior in the order they were provided, allowing for a flexible and modular approach to handling requests in a CQRS architecture.\r\n * @param _pipelines An optional array of IPipelineBehavior instances that represent the individual behaviors to be combined into the composite pipeline.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n constructor(private readonly _pipelines: readonly IPipelineBehavior<TInput, TResult>[] = []) {}\r\n\r\n async handle(request: TInput, next: Delegate<TResult>): Promise<ResultType<TResult>> {\r\n let currentNext = next\r\n\r\n for (let i = this._pipelines.length - 1; i >= 0; i--) {\r\n const currentBehavior = this._pipelines[i]\r\n const previousNext = currentNext\r\n\r\n currentNext = () => currentBehavior.handle(request, previousNext)\r\n }\r\n\r\n return currentNext()\r\n }\r\n}\r\n","import type { Delegate, ICommand, IPipelineBehavior, ResultType } from '@xeno-js/shared'\r\nimport type { Optional } from '@xeno-js/shared'\r\nimport { AppError, Result } from '@xeno-js/shared'\r\nimport {\r\n DEFAULT_CONCURRENCY,\r\n ERROR_CODES,\r\n Guards,\r\n PromiseHelper,\r\n STATUS_CODES,\r\n} from '@xeno-js/shared'\r\n\r\n/**\r\n * @description A pipeline behavior that implements a retry mechanism for handling concurrency conflicts in the CQRS pipelines. When a request results in a concurrency conflict error, this behavior will automatically retry the request up to a specified maximum number of attempts, with an exponential backoff strategy and added jitter to prevent thundering herd problems. If the maximum number of retry attempts is exceeded, it returns a failed Result with an AppError indicating the concurrency conflict.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class ConcurrencyRetryPipeline<\r\n TInput extends ICommand<TResult>,\r\n TResult,\r\n> implements IPipelineBehavior<TInput, TResult> {\r\n /**\r\n * @description Configuration for the retry mechanism, including the base delay and maximum jitter for calculating the delay between retry attempts, as well as the maximum number of retry attempts allowed before giving up and returning a failed Result with an AppError indicating the concurrency conflict.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n private readonly _delayConfig: { baseDelayMs: number; maxJitterMs: number }\r\n /**\r\n * @description Maximum number of retry attempts for handling concurrency conflicts. If the number of attempts exceeds this value, the pipeline will return a failed Result with an AppError indicating that the maximum retry attempts have been exceeded due to concurrency conflicts.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n private readonly _maxRetries: number\r\n\r\n /**\r\n * @description Constructs a new instance of the ConcurrencyRetryBehavior class, which takes an optional maximum number of retry attempts and an optional delay configuration for the exponential backoff strategy. The delay configuration includes a base delay in milliseconds and a maximum jitter in milliseconds to be added to the base delay for each retry attempt. The constructor validates the input parameters to ensure that they are positive integers and throws an error if they are not.\r\n * @param maxRetries An optional parameter that specifies the maximum number of retry attempts for handling concurrency conflicts. The default value is DEFAULT_CONCURRENCY.MAX_RETRIES. It must be a positive integer.\r\n * @param delayConfig An optional parameter that specifies the delay configuration for the exponential backoff strategy, including a base delay in milliseconds and a maximum jitter in milliseconds. The default values are DEFAULT_CONCURRENCY.BASE_DELAY for the base delay and DEFAULT_CONCURRENCY.MAX_JITTER for the maximum jitter. Both values must be non-negative integers.\r\n * @throws Will throw an error if the provided maxRetries value is not a positive integer or if the provided delayConfig values are not valid non-negative integers.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n constructor(\r\n maxRetries: number = DEFAULT_CONCURRENCY.MAX_RETRIES,\r\n delayConfig: Optional<{ baseDelayMs: number; maxJitterMs: number }> = {\r\n baseDelayMs: DEFAULT_CONCURRENCY.BASE_DELAY,\r\n maxJitterMs: DEFAULT_CONCURRENCY.MAX_JITTER,\r\n },\r\n ) {\r\n const values = [maxRetries, delayConfig?.baseDelayMs, delayConfig?.maxJitterMs]\r\n const errorMessages = [\r\n `Invalid maxRetries value: ${maxRetries}. It must be a positive integer.`,\r\n `Invalid baseDelayMs value: ${delayConfig.baseDelayMs}. It must be a non-negative integer.`,\r\n `Invalid maxJitterMs value: ${delayConfig.maxJitterMs}. It must be a non-negative integer.`,\r\n ]\r\n\r\n values.forEach((value, index) => {\r\n Guards.throwIfNotInteger(value, errorMessages[index])\r\n Guards.throwIfNegative(value, errorMessages[index])\r\n if (index === 0 && value === 0) {\r\n throw new Error(errorMessages[index])\r\n }\r\n })\r\n\r\n this._maxRetries = maxRetries\r\n this._delayConfig = delayConfig\r\n }\r\n\r\n /**\r\n * @description Handles the request by implementing a retry mechanism for concurrency conflicts. It retries the request up to the maximum number of attempts with an exponential backoff strategy and added jitter. If the request succeeds or fails with an error that is not a concurrency conflict, it returns the result immediately. If the maximum number of retry attempts is exceeded due to concurrency conflicts, it returns a failed Result with an AppError indicating the concurrency conflict.\r\n * @param request The input request to be handled, which must extend ICommand.\r\n * @param next The delegate function that represents the next behavior or handler in the pipeline.\r\n * @returns A Promise that resolves to a ResultType containing either the successful result or a failed AppError if the maximum retry attempts are exceeded due to concurrency conflicts.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n public async handle(request: TInput, next: Delegate<TResult>): Promise<ResultType<TResult>> {\r\n let attempts = 0\r\n\r\n while (true) {\r\n attempts++\r\n\r\n const result = await next()\r\n\r\n if (result.isOk() || !this.isConcurrencyError(result.getErrorOrThrow())) return result\r\n\r\n if (attempts >= this._maxRetries)\r\n return Result.fail(\r\n AppError.conflict(\r\n request.intent,\r\n `Maximum retry attempts (${this._maxRetries}) exceeded due to concurrency conflicts.`,\r\n ),\r\n )\r\n\r\n const { baseDelayMs, maxJitterMs } = this._delayConfig\r\n\r\n await PromiseHelper.delayWithJitter(baseDelayMs, maxJitterMs)\r\n }\r\n }\r\n\r\n /**\r\n * @description Checks if the given error is a concurrency conflict error.\r\n * @param error The error to be checked.\r\n * @returns A boolean indicating whether the error is a concurrency conflict error.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n private isConcurrencyError(error: AppError): boolean {\r\n return error.code === ERROR_CODES.CONFLICT && error.status === STATUS_CODES.CONFLICT\r\n }\r\n}\r\n","import type { Delegate, IPipelineBehavior, IRequest, ResultType } from '@xeno-js/shared'\r\nimport { AppError, Result } from '@xeno-js/shared'\r\nimport { ERROR_CODE_MESSAGES, ERROR_CODES, STATUS_CODES } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description A pipeline behavior that handles exceptions thrown during the execution of a request in the CQRS pattern. It catches any unhandled exceptions, wraps them in an AppError with a standardized error code and message, and returns a failed Result containing the AppError. This ensures that exceptions are consistently handled and logged across the application, providing a clear mechanism for error reporting and debugging in the context of CQRS pipelines.\r\n * @template TInput - The type of the input request, which must extend IRequest.\r\n * @template TResult - The type of the result returned by the pipeline, which can be any type.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class ExceptionPipeline<\r\n TInput extends IRequest<TResult>,\r\n TResult,\r\n> implements IPipelineBehavior<TInput, TResult> {\r\n public async handle(request: TInput, next: Delegate<TResult>): Promise<ResultType<TResult>> {\r\n try {\r\n return await next()\r\n } catch (error: unknown) {\r\n if (error instanceof AppError) return Result.fail(error)\r\n\r\n const appError = AppError.create({\r\n code: ERROR_CODES.SYSTEM_ERROR,\r\n message: ERROR_CODE_MESSAGES[ERROR_CODES.SYSTEM_ERROR],\r\n status: STATUS_CODES.INTERNAL_SERVER_ERROR,\r\n name: request.intent,\r\n cause: error,\r\n })\r\n return Result.fail(appError)\r\n }\r\n }\r\n}\r\n","import type {\r\n Delegate,\r\n ICommand,\r\n IIdempotencyStore,\r\n INetworkContextAccessor,\r\n IPipelineBehavior,\r\n ResultType,\r\n} from '@xeno-js/shared'\r\nimport { AppError, Result } from '@xeno-js/shared'\r\nimport { Guards, IDEMPOTENCY_CONSTANTS } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description A pipeline behavior that implements idempotency for command requests in the CQRS architecture. This behavior ensures that if multiple requests with the same command ID are received, only one of them will be processed, and the others will receive the same result without reprocessing the command. The pipeline uses an IIdempotencyStore to manage locks and store results for processed commands, allowing it to handle concurrent requests safely and efficiently while preventing duplicate processing of commands. The behavior checks if the incoming request is a command and if it has a valid ID. If the command has already been processed, it retrieves the stored result and returns it. If the command is currently being processed by another request, it returns an error indicating that the command is locked. If the command has not been processed and is not locked, it acquires a lock, processes the command, stores the result, and releases the lock accordingly. The pipeline also includes error handling to ensure that locks are released in case of exceptions during command processing.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class IdempotencyPipeline<\r\n TInput extends ICommand<TResult>,\r\n TResult,\r\n> implements IPipelineBehavior<TInput, TResult> {\r\n /** @description TTL (time-to-live) in seconds for locks acquired in the idempotency mechanism. This value determines how long a lock will be held for a given command ID when it is being processed. If a lock is not released within this time frame, it will automatically expire, allowing other instances of the command to be processed. The default value is set to 300 seconds (5 minutes), which provides a reasonable balance between allowing sufficient time for command processing and preventing long-term locks that could lead to delays in processing subsequent commands with the same ID. This value can be overridden by providing a different lockTtlSeconds value when constructing the IdempotencyPipeline instance.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n private readonly _lockTtlSeconds: number\r\n /** @description TTL (time-to-live) in seconds for processed command results stored in the idempotency mechanism. This value determines how long the result of a processed command will be stored and available for retrieval when subsequent requests with the same command ID are received. If a result is not retrieved within this time frame, it will automatically expire and be removed from the store, meaning that subsequent requests with the same command ID will not be able to retrieve the previous result and may need to reprocess the command. The default value is set to 86400 seconds (24 hours), which allows for a reasonable window of time for clients to retrieve results of processed commands while also ensuring that stale results do not persist indefinitely in the store. This value can be overridden by providing a different processedTtlSeconds value when constructing the IdempotencyPipeline instance.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n private readonly _processedTtlSeconds: number\r\n\r\n /**\r\n * @description Constructs a new instance of the IdempotencyPipeline class, which requires an IIdempotencyStore for managing locks and storing results of processed commands. The constructor also accepts optional parameters for configuring the TTL (time-to-live) values for locks and processed results, allowing for customization of the idempotency behavior based on the specific needs of the application. The constructor validates the input parameters to ensure that they are positive integers and throws an error if they are not, ensuring that the pipeline is configured with valid TTL values for proper functioning of the idempotency mechanism.\r\n * @param idempotencyStore An instance of IIdempotencyStore used for managing locks and storing results of processed commands in the idempotency mechanism. This store is essential for ensuring that commands with the same ID are processed in an idempotent manner, allowing the pipeline to handle concurrent requests safely and efficiently while preventing duplicate processing of commands.\r\n * @param lockTtlSeconds TTL (time-to-live) in seconds for locks acquired in the idempotency mechanism. This value determines how long a lock will be held for a given command ID when it is being processed. If a lock is not released within this time frame, it will automatically expire, allowing other instances of the command to be processed. The default value is set to 300 seconds (5 minutes), which provides a reasonable balance between allowing sufficient time for command processing and preventing long-term locks that could lead to delays in processing subsequent commands with the same ID. This value can be overridden by providing a different lockTtlSeconds value when constructing the IdempotencyPipeline instance.\r\n * @param processedTtlSeconds TTL (time-to-live) in seconds for processed command results stored in the idempotency mechanism. This value determines how long the result of a processed command will be stored and available for retrieval when subsequent requests with the same command ID are received. If a result is not retrieved within this time frame, it will automatically expire and be removed from the store, meaning that subsequent requests with the same command ID will not be able to retrieve the previous result and may need to reprocess the command. The default value is set to 86400 seconds (24 hours), which allows for a reasonable window of time for clients to retrieve results of processed commands while also ensuring that stale results do not persist indefinitely in the store. This value can be overridden by providing a different processedTtlSeconds value when constructing the IdempotencyPipeline instance.\r\n * @throws Will throw an error if the provided lockTtlSeconds or processedTtlSeconds values are not positive integers, ensuring that the pipeline is configured with valid TTL values for proper functioning of the idempotency mechanism.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n constructor(\r\n private readonly _requestContextFactory: INetworkContextAccessor,\r\n private readonly _idempotencyStore: IIdempotencyStore,\r\n lockTtlSeconds: number = IDEMPOTENCY_CONSTANTS.DEFAULT_IDEMPOTENCY_LOCK_TTL_SECONDS,\r\n processedTtlSeconds: number = IDEMPOTENCY_CONSTANTS.DEFAULT_TTL_SECONDS,\r\n ) {\r\n const values: number[] = [lockTtlSeconds, processedTtlSeconds]\r\n const errorMessages = [\r\n `Invalid lockTtlSeconds value: ${lockTtlSeconds}. It must be a positive integer.`,\r\n `Invalid processedTtlSeconds value: ${processedTtlSeconds}. It must be a positive integer.`,\r\n ]\r\n values.forEach((value, index) => {\r\n Guards.throwIfNotInteger(value, errorMessages[index])\r\n Guards.throwIfNegative(value, errorMessages[index])\r\n if (value === 0) {\r\n throw new Error(errorMessages[index])\r\n }\r\n })\r\n\r\n this._lockTtlSeconds = lockTtlSeconds\r\n this._processedTtlSeconds = processedTtlSeconds\r\n }\r\n\r\n public async handle(request: TInput, next: Delegate<TResult>): Promise<ResultType<TResult>> {\r\n const network = this._requestContextFactory.getNetworkContext()\r\n if (!Guards.isDefined(network))\r\n return Result.fail(\r\n AppError.conflict(\r\n request.intent,\r\n `Network context is not defined for request ${request.intent}`,\r\n ),\r\n )\r\n\r\n try {\r\n const alreadyProcessed = await this._idempotencyStore.hasBeenProcessed(network.requestId)\r\n if (alreadyProcessed) {\r\n const payload = await this._idempotencyStore.getPayload<TResult>(network.requestId)\r\n if (Guards.isDefined(payload)) {\r\n return Result.ok(payload)\r\n } else {\r\n return Result.fail(\r\n AppError.conflict(\r\n request.intent,\r\n `Idempotency store indicates request has been processed but no payload found for request ID ${network.requestId}`,\r\n ),\r\n )\r\n }\r\n }\r\n\r\n const lockAcquired = await this._idempotencyStore.acquireLock(\r\n network.requestId,\r\n this._lockTtlSeconds,\r\n )\r\n\r\n if (!lockAcquired) {\r\n return Result.fail(\r\n AppError.conflict(\r\n request.intent,\r\n `Failed to acquire lock for request ID ${network.requestId}`,\r\n ),\r\n )\r\n }\r\n\r\n const result = await next()\r\n\r\n if (result.isOk()) {\r\n await this._idempotencyStore.markAsProcessed(\r\n network.requestId,\r\n result.getValueOrThrow(),\r\n this._processedTtlSeconds,\r\n )\r\n } else {\r\n await this._idempotencyStore.releaseLock(network.requestId)\r\n }\r\n\r\n return result\r\n } catch (error: unknown) {\r\n await this._idempotencyStore.releaseLock(network.requestId)\r\n\r\n throw error\r\n }\r\n }\r\n}\r\n","import type { Delegate, ILogger, IPipelineBehavior, IRequest, ResultType } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description A pipeline behavior that logs the handling of commands and queries, including their success or failure, along with contextual information such as request ID, correlation ID, and user ID.\r\n * This pipeline can be used to enhance observability and debugging capabilities in the application by providing detailed logs for each request processed through the CQRS pipeline.\r\n *\r\n * @template TInput - The type of the input request, which must extend the IRequest interface.\r\n * @template TResult - The type of the result returned by the request handler.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class LoggingPipeline<\r\n TInput extends IRequest<TResult>,\r\n TResult,\r\n> implements IPipelineBehavior<TInput, TResult> {\r\n /**\r\n * @description Constructs a new instance of the LoggingPipeline class, which requires an ILogger for logging. The pipeline will use this dependency to log relevant information about each request being handled, including any errors that occur during processing.\r\n * @param _logger An instance of ILogger used for logging informational messages and errors related to the handling of requests.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n constructor(private readonly _logger: ILogger) {}\r\n\r\n public async handle(request: TInput, next: Delegate<TResult>): Promise<ResultType<TResult>> {\r\n this._logger.info(`Handling ${request.type} ${request.intent}`)\r\n\r\n try {\r\n const result = await next()\r\n\r\n if (!result.isOk()) {\r\n const error = result.getErrorOrThrow()\r\n this._logger.error(\r\n `Failed to handle ${request.type} ${request.intent}: ${error.message}`,\r\n error,\r\n )\r\n } else {\r\n this._logger.info(`Successfully handled ${request.type} ${request.intent}`)\r\n }\r\n\r\n return result\r\n } catch (error: unknown) {\r\n this._logger.error(`Exception while handling ${request.type} ${request.intent}`, error)\r\n throw error\r\n }\r\n }\r\n}\r\n","import type { Delegate, ILogger, IPipelineBehavior, IRequest, ResultType } from '@xeno-js/shared'\r\nimport { Guards } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description Default threshold in milliseconds for logging performance warnings. If a request takes longer than this threshold to execute, a warning will be logged. This value can be overridden by providing a different thresholdMs value when constructing the PerformancePipeline instance.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nconst defaultThresholdMs = 500\r\n\r\n/**\r\n * @description A pipeline behavior that measures the execution time of commands and queries, logging a warning if the execution time exceeds a specified threshold. This pipeline can be used to identify performance bottlenecks in the application and ensure that requests are processed within acceptable time limits.\r\n *\r\n * @template TInput - The type of the input request, which must extend the IRequest interface.\r\n * @template TResult - The type of the result returned by the request handler.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class PerformancePipeline<\r\n TInput extends IRequest<TResult>,\r\n TResult,\r\n> implements IPipelineBehavior<TInput, TResult> {\r\n /**\r\n * @description Threshold in milliseconds for logging performance warnings. If a request takes longer than this threshold to execute, a warning will be logged. This value is set through the constructor and must be a positive integer.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n private readonly _thresholdMs: number\r\n\r\n /**\r\n * @description Constructs a new instance of the PerformancePipeline class, which requires an ILogger for logging. The pipeline will use this dependency to log performance-related information about each request being handled, including any warnings when execution times exceed the specified threshold.\r\n * @param _logger An instance of ILogger used for logging performance warnings related to the handling of requests.\r\n * @param thresholdMs An optional parameter that specifies the execution time threshold in milliseconds. If a request takes longer than this threshold to execute, a warning will be logged. The default value is 500ms.\r\n * @throws Will throw an error if the provided thresholdMs value is not a positive integer.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n constructor(\r\n private readonly _logger: ILogger,\r\n thresholdMs: number = defaultThresholdMs,\r\n ) {\r\n const message = `Invalid thresholdMs value: ${thresholdMs}. It must be a positive integer.`\r\n Guards.throwIfNegative(thresholdMs, message)\r\n if (thresholdMs === 0) {\r\n throw new Error(message)\r\n }\r\n this._thresholdMs = thresholdMs\r\n }\r\n\r\n public async handle(request: TInput, next: Delegate<TResult>): Promise<ResultType<TResult>> {\r\n const startTime = performance.now()\r\n try {\r\n return await next()\r\n } finally {\r\n const endTime = performance.now()\r\n const duration = endTime - startTime\r\n\r\n if (duration > this._thresholdMs) {\r\n this._logger.warn(`Performance warning: ${request.intent} took ${duration.toFixed(2)}ms`)\r\n }\r\n }\r\n }\r\n}\r\n","import type {\r\n IContextAccessor,\r\n Identity,\r\n IRequest,\r\n IStrategy,\r\n RequestContext,\r\n ResultType,\r\n} from '@xeno-js/shared'\r\nimport { AppError, Result } from '@xeno-js/shared'\r\nimport { Guards } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description Abstract base class for authorization strategies in the CQRS pipeline. This class implements the IStrategy interface and provides a common structure for performing authorization checks based on the identity of the authenticated user. It defines an abstract method performAuthorizationCheck that must be implemented by concrete authorization strategies to specify the logic for checking if the user has the necessary permissions to execute a given request. The execute method retrieves the user's identity from the request context and ensures that the user is authenticated before delegating to the performAuthorizationCheck method for further authorization validation. If the user is not authenticated, it returns a failed Result with an appropriate AppError indicating that authentication is required.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport abstract class BaseAuthorizationStrategy<\r\n TInput extends IRequest,\r\n> implements IStrategy<TInput> {\r\n /**\r\n * @description Constructs a new instance of the BaseAuthorizationStrategy class, which serves as an abstract base for specific authorization strategies in the CQRS pipeline. It takes an IRequestContext as a parameter, which is used to retrieve the identity of the currently authenticated user during the authorization process. This context is essential for performing the authorization checks based on the user's identity when executing requests that require specific permissions.\r\n * @param requestContext An instance of IRequestContext used to access the identity of the currently authenticated user. This context is essential for performing the authorization checks based on the user's identity when executing requests that require specific permissions.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n constructor(private readonly _requestContext: IContextAccessor<RequestContext>) {}\r\n\r\n public async execute(request: IRequest): Promise<ResultType<void>> {\r\n const context = this._requestContext.getContext()\r\n\r\n if (!Guards.isDefined(context)) {\r\n return Result.fail(AppError.unauthorized(request.intent, 'User is not authenticated.'))\r\n }\r\n\r\n return await this.performAuthorizationCheck(request, context.identity)\r\n }\r\n\r\n /**\r\n * @description Abstract method that must be implemented by concrete authorization strategies to perform the actual authorization check. This method is called after the user's identity has been retrieved and verified. It receives the request and the user's identity as parameters and should return a Result indicating whether the authorization check passed or failed.\r\n * @param request The incoming request for which the authorization check is being performed. This request contains information about the action being attempted and any relevant data needed for the authorization logic.\r\n * @param auth The identity of the currently authenticated user, which includes information such as the user's ID, tenant ID, and roles. This context is used to determine if the user has the necessary permissions to execute the request.\r\n * @returns A Result indicating the outcome of the authorization check. If the check passes, it should return a successful Result with a void value. If the check fails, it should return a failed Result with an appropriate AppError describing the reason for the failure.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n protected abstract performAuthorizationCheck(\r\n request: IRequest,\r\n auth: Identity,\r\n ): Promise<ResultType<void>>\r\n}\r\n","import type {\r\n IContextAccessor,\r\n Identity,\r\n IPolicyRegistry,\r\n IRequest,\r\n RequestContext,\r\n} from '@xeno-js/shared'\r\nimport { AppError, Result } from '@xeno-js/shared'\r\nimport { Guards } from '@xeno-js/shared'\r\n\r\nimport { BaseAuthorizationStrategy } from './base-authorization.strategy'\r\n\r\n/**\r\n * @description Authorization strategy that checks if the authenticated user has at least one of the required permissions specified in the command. It extends the BaseAuthorizationStrategy and implements the performAuthorizationCheck method to verify if the user's permissions match any of the required permissions for the command. If the user is not authenticated or does not have the necessary permissions, it returns a failed Result with an appropriate AppError.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class PermissionAuthorizationStrategy extends BaseAuthorizationStrategy<IRequest> {\r\n /** @description Constructs a new instance of the PermissionAuthorizationStrategy class, which is responsible for checking if the authenticated user has the required permissions specified in the command. It takes an IRequestContext as a parameter, which is used to retrieve the identity of the currently authenticated user during the authorization process.\r\n * @param _policy An instance of IPolicyRegistry used to retrieve the authorization policy associated with the command's intent. This policy contains the required permissions that the user must have to execute the command.\r\n * @param requestContext An instance of IRequestContext used to access the identity of the currently authenticated user. This context is essential for performing the authorization checks based on the user's permissions when executing commands that require specific permission-based access.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n constructor(\r\n private readonly _policy: IPolicyRegistry,\r\n requestContext: IContextAccessor<RequestContext>,\r\n ) {\r\n super(requestContext)\r\n }\r\n\r\n protected async performAuthorizationCheck(\r\n command: IRequest,\r\n auth: Identity,\r\n ): Promise<Result<void, AppError>> {\r\n const policy = this._policy.getPolicy(command.intent)\r\n\r\n if (!Guards.isNullOrEmpty(policy?.permissions)) {\r\n const permissions = auth.permissions ?? []\r\n const hasRequiredPermission = policy.permissions?.some((permission) =>\r\n permissions.includes(permission),\r\n )\r\n if (!hasRequiredPermission)\r\n return Result.fail(\r\n AppError.forbidden(command.intent, 'User does not have the required permissions.'),\r\n )\r\n }\r\n\r\n return Result.ok()\r\n }\r\n}\r\n","import type {\r\n IContextAccessor,\r\n Identity,\r\n IPolicyRegistry,\r\n IRequest,\r\n RequestContext,\r\n} from '@xeno-js/shared'\r\nimport { AppError, Result } from '@xeno-js/shared'\r\nimport { Guards } from '@xeno-js/shared'\r\n\r\nimport { BaseAuthorizationStrategy } from './base-authorization.strategy'\r\n\r\n/**\r\n * @description Authorization strategy that checks if the authenticated user has at least one of the required roles specified in the command. It extends the BaseAuthorizationStrategy and implements the performAuthorizationCheck method to verify if the user's roles match any of the required roles for the command. If the user is not authenticated or does not have the necessary roles, it returns a failed Result with an appropriate AppError.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class RoleAuthorizationStrategy extends BaseAuthorizationStrategy<IRequest> {\r\n /** @description Constructs a new instance of the RoleAuthorizationStrategy class, which is responsible for checking if the authenticated user has the required roles specified in the command. It takes an IRequestContext as a parameter, which is used to retrieve the identity of the currently authenticated user during the authorization process.\r\n * @param requestContext An instance of IRequestContext used to access the identity of the currently authenticated user. This context is essential for performing the authorization checks based on the user's roles when executing commands that require specific role-based permissions.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n constructor(\r\n private readonly _policy: IPolicyRegistry,\r\n requestContext: IContextAccessor<RequestContext>,\r\n ) {\r\n super(requestContext)\r\n }\r\n\r\n protected async performAuthorizationCheck(\r\n command: IRequest,\r\n auth: Identity,\r\n ): Promise<Result<void, AppError>> {\r\n const policy = this._policy.getPolicy(command.intent)\r\n\r\n if (!Guards.isNullOrEmpty(policy?.roles)) {\r\n const roles = auth.roles ?? []\r\n const hasRequiredRole = policy.roles?.some((role) => roles.includes(role))\r\n if (!hasRequiredRole)\r\n return Result.fail(\r\n AppError.forbidden(command.intent, 'User does not have the required roles.'),\r\n )\r\n }\r\n\r\n return Result.ok()\r\n }\r\n}\r\n","import type {\r\n IContextAccessor,\r\n Identity,\r\n IPolicyRegistry,\r\n IRequest,\r\n RequestContext,\r\n} from '@xeno-js/shared'\r\nimport { AppError, Result } from '@xeno-js/shared'\r\nimport { Guards, GuidHelper } from '@xeno-js/shared'\r\n\r\nimport { BaseAuthorizationStrategy } from './base-authorization.strategy'\r\n\r\n/**\r\n * @description Authorization strategy that checks if the authenticated tenant has the required tenant ID specified in the command. It extends the BaseAuthorizationStrategy and implements the performAuthorizationCheck method to verify if the tenant's ID matches the required tenant ID for the command. If the tenant is not authenticated or does not have the necessary tenant ID, it returns a failed Result with an appropriate AppError.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class TenantAuthorizationStrategy extends BaseAuthorizationStrategy<IRequest> {\r\n /** @description Constructs a new instance of the TenantAuthorizationStrategy class, which is responsible for checking if the authenticated tenant has the required tenant ID specified in the command. It takes an IContextAccessor as a parameter, which is used to retrieve the identity of the currently authenticated tenant during the authorization process.\r\n * @param requestContext An instance of IContextAccessor used to access the identity of the currently authenticated tenant. This context is essential for performing the authorization checks based on the tenant's ID when executing commands that require specific tenant-based permissions.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n constructor(\r\n private readonly _policy: IPolicyRegistry,\r\n requestContext: IContextAccessor<RequestContext>,\r\n ) {\r\n super(requestContext)\r\n }\r\n\r\n protected async performAuthorizationCheck(\r\n command: IRequest,\r\n auth: Identity,\r\n ): Promise<Result<void, AppError>> {\r\n const policy = this._policy.getPolicy(command.intent)\r\n\r\n if (Guards.isDefined(policy?.tenantId)) {\r\n if (Guards.isNullOrEmpty(auth.tenantId) || !GuidHelper.isValidGuid(auth.tenantId))\r\n return Result.fail(AppError.unauthorized(command.intent, 'Tenant is not authenticated.'))\r\n }\r\n\r\n return Result.ok()\r\n }\r\n}\r\n","import type {\r\n IContextAccessor,\r\n Identity,\r\n IPolicyRegistry,\r\n IRequest,\r\n RequestContext,\r\n} from '@xeno-js/shared'\r\nimport { AppError, Result } from '@xeno-js/shared'\r\nimport { Guards, GuidHelper } from '@xeno-js/shared'\r\n\r\nimport { BaseAuthorizationStrategy } from './base-authorization.strategy'\r\n\r\n/**\r\n * @description Authorization strategy that checks if the authenticated user has the required user ID specified in the command. It extends the BaseAuthorizationStrategy and implements the performAuthorizationCheck method to verify if the user's ID matches the required user ID for the command. If the user is not authenticated or does not have the necessary user ID, it returns a failed Result with an appropriate AppError.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class UserAuthorizationStrategy extends BaseAuthorizationStrategy<IRequest> {\r\n /** @description Constructs a new instance of the UserAuthorizationStrategy class, which is responsible for checking if the authenticated user has the required user ID specified in the command. It takes an IContextAccessor as a parameter, which is used to retrieve the identity of the currently authenticated user during the authorization process.\r\n * @param requestContext An instance of IContextAccessor used to access the identity of the currently authenticated user. This context is essential for performing the authorization checks based on the user's ID when executing commands that require specific user-based permissions.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n constructor(\r\n private readonly _policy: IPolicyRegistry,\r\n requestContext: IContextAccessor<RequestContext>,\r\n ) {\r\n super(requestContext)\r\n }\r\n\r\n protected async performAuthorizationCheck(\r\n command: IRequest,\r\n auth: Identity,\r\n ): Promise<Result<void, AppError>> {\r\n const policy = this._policy.getPolicy(command.intent)\r\n\r\n if (Guards.isDefined(policy?.userId)) {\r\n if (Guards.isNullOrEmpty(auth.userId) || !GuidHelper.isValidGuid(auth.userId))\r\n return Result.fail(AppError.unauthorized(command.intent, 'User is not authenticated.'))\r\n }\r\n\r\n return Result.ok()\r\n }\r\n}\r\n","export * from './base-authorization.strategy'\r\nexport * from './permission-authorization.strategy'\r\nexport * from './role-authorization.strategy'\r\nexport * from './tenant-authorization.strategy'\r\nexport * from './user-authorization.strategy'\r\n","import type { IRequest, IStrategy, IValidatorService, ResultType } from '@xeno-js/shared'\r\nimport { AppError, Result } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description Strategy that validates incoming requests against predefined schemas. It implements the IStrategy interface and uses a schema registry to determine if a schema exists for the given request type. If a schema is found, it validates the request against the schema using a safe parsing method. If the validation fails, it returns a failed Result with an appropriate AppError indicating a validation error. If the validation succeeds, it returns a successful Result with a boolean value of true.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class SchemaValidationStrategy implements IStrategy<IRequest, boolean> {\r\n /**\r\n * @description Constructs a new instance of the SchemaValidationStrategy class, which takes an IValidatorService as a parameter. This service is used to check for the existence of validation schemas and to perform the actual validation of requests against those schemas. The constructor initializes the strategy with the provided validator service, allowing it to execute the validation logic when handling requests in the CQRS pipeline.\r\n * @param _validator An instance of IValidatorService that provides methods to check for the existence of validation schemas and to validate data against those schemas. This service is essential for performing the schema validation logic in this strategy.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n constructor(private readonly _validator: IValidatorService) {}\r\n\r\n public async execute(request: IRequest): Promise<ResultType<boolean>> {\r\n const key = request.intent\r\n const parseResult = await this._validator.validate(key, request)\r\n\r\n if (!parseResult.isOk())\r\n return Result.fail(\r\n AppError.validationError(\r\n request.intent,\r\n `Validation failed: ${parseResult.getErrorOrThrow().message}`,\r\n ),\r\n )\r\n\r\n return Result.ok(true)\r\n }\r\n}\r\n","export * from './schema-validation.strategy'\r\n","export * from './auth/index'\r\nexport * from './validation/index'\r\n","import type {\r\n Delegate,\r\n ICache,\r\n ICacheKeyBuilder,\r\n ILogger,\r\n IPipelineBehavior,\r\n IQuery,\r\n ResultType,\r\n} from '@xeno-js/shared'\r\nimport { Result } from '@xeno-js/shared'\r\nimport { Guards } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description A pipeline behavior that implements caching for query requests in the CQRS architecture. This behavior checks if the incoming request is a query and if it implements the IQuery interface. If so, it attempts to retrieve the response from the cache using the provided cache key. If a cached response is found, it returns it immediately. If not, it delegates control to the next handler in the pipeline to execute the query and retrieve the data from the database. After successfully retrieving the data, it stores the result in the cache with the specified TTL (time-to-live) for future requests. This behavior also includes error handling for cache read/write operations, ensuring that any cache-related errors do not disrupt the normal flow of query execution and that appropriate warnings are logged.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class QueryCachingPipeline<\r\n TInput extends IQuery<TResult>,\r\n TResult,\r\n> implements IPipelineBehavior<TInput, TResult> {\r\n /**\r\n * @description Constructs a new instance of the QueryCachingPipeline class, which requires an ICache implementation for interacting with the cache and an ILogger for logging cache-related operations and errors. The constructor initializes the dependencies needed for the caching behavior to function properly within the CQRS pipeline.\r\n * @param _cacheService An instance of ICache used for interacting with the cache, including retrieving and storing cached responses based on cache keys.\r\n * @param _logger An instance of ILogger used for logging cache-related operations, such as cache hits, cache misses, and any errors that occur during cache read/write operations.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n constructor(\r\n private readonly _cacheService: ICache,\r\n private readonly _cacheKeyBuilder: ICacheKeyBuilder,\r\n private readonly _logger: ILogger,\r\n ) {}\r\n\r\n public async handle(request: TInput, next: Delegate<TResult>): Promise<ResultType<TResult>> {\r\n if (\r\n Guards.isNullOrEmpty(request.cacheOptions) ||\r\n Guards.isNullOrEmpty(request.cacheOptions.cacheKey)\r\n )\r\n return next()\r\n\r\n const bypass =\r\n request.cacheOptions.bypassCache === true || request.cacheOptions.consistentRead === true\r\n\r\n const key = request.cacheOptions.isUserScoped\r\n ? this._cacheKeyBuilder.buildUserScopedKey(request.cacheOptions.cacheKey)\r\n : this._cacheKeyBuilder.buildContextualKey(request.cacheOptions.cacheKey)\r\n // 1. Read (Cache Hit)\r\n if (!bypass) {\r\n try {\r\n const cachedResponse = await this._cacheService.get<TResult>(key)\r\n if (Guards.isDefined(cachedResponse)) {\r\n this._logger.debug(\r\n `[Cache HIT] Returning data from cache for: ${request.cacheOptions.cacheKey}`,\r\n )\r\n return Result.ok(cachedResponse)\r\n }\r\n } catch (error) {\r\n // If Redis fails, we don't crash the app. Log and proceed to the DB.\r\n this._logger.warn(\r\n `[Cache ERROR] Unable to read cache for: ${request.cacheOptions.cacheKey}. Proceeding to DB. Error: ${error instanceof Error ? error.message : String(error)}`,\r\n )\r\n }\r\n }\r\n\r\n // 2. Cache Miss: Delegate control to the Handler that queries the DB\r\n const result = await next()\r\n\r\n // 3. Write: If the Handler succeeded, save the result in cache\r\n if (result.isOk()) {\r\n try {\r\n await this._cacheService.set(key, result.getValueOrThrow(), request.cacheOptions.ttl)\r\n this._logger.debug(`[Cache SET] Data saved in cache for: ${key}`)\r\n } catch (error) {\r\n this._logger.warn(\r\n `[Cache ERROR] Unable to save cache for: ${key}. Error: ${error instanceof Error ? error.message : String(error)}`,\r\n )\r\n }\r\n }\r\n\r\n return result\r\n }\r\n}\r\n","import type { Delegate, IPipelineBehavior, IRequest, IStrategy, ResultType } from '@xeno-js/shared'\r\nimport { Result } from '@xeno-js/shared'\r\n/**\r\n * @description A pipeline behavior that performs validation on the incoming request in a CQRS architecture. It checks if the request has a validate method and, if so, invokes it to perform validation. If the validation fails, it returns a failed Result containing the validation error. If the validation succeeds or if there is no validate method, it proceeds to the next behavior in the pipeline. This allows for a structured approach to ensuring that requests meet certain criteria before being processed further in the CQRS pipeline.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class ValidationPipeline<\r\n TInput extends IRequest<TResult>,\r\n TResult,\r\n> implements IPipelineBehavior<TInput, TResult> {\r\n /** @description Constructs a new instance of the ValidationPipeline class, which takes an array of IStrategy instances as validators. These validators are used to perform validation checks on the incoming requests. The constructor initializes the pipeline with the provided validators, allowing it to execute the validation logic when handling requests in the CQRS pipeline.\r\n * @param _validators An array of IStrategy instances that represent the validation strategies to be applied to incoming requests. Each strategy should implement the isApplicable method to determine if it should be applied to a given request and the execute method to perform the actual validation logic, returning a Result indicating the success or failure of the validation.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n constructor(private readonly _validators: readonly IStrategy<TInput, boolean>[]) {}\r\n\r\n public async handle(request: TInput, next: Delegate<TResult>): Promise<ResultType<TResult>> {\r\n for (const validator of this._validators) {\r\n const validationResult = await validator.execute(request)\r\n if (!validationResult.isOk()) {\r\n return Result.fail(validationResult.getErrorOrThrow())\r\n }\r\n }\r\n return next()\r\n }\r\n}\r\n","export * from './authorization.pipeline'\r\nexport * from './composite.pipeline'\r\nexport * from './concurrency-retry.pipeline'\r\nexport * from './exception.pipeline'\r\nexport * from './idempotency.pipeline'\r\nexport * from './logging.pipeline'\r\nexport * from './performance.pipeline'\r\nexport * from './pipeline_strategies/index'\r\nexport * from './query-caching.pipeline'\r\nexport * from './validation.pipeline'\r\n","export * from './base-handler'\r\nexport * from './mediator'\r\nexport * from './pipelines/index'\r\n","import type {\r\n IBaseAuthService,\r\n IBaseMapper,\r\n Identity,\r\n IGateKeeper,\r\n ResultType,\r\n} from '@xeno-js/shared'\r\nimport type { AuthClaims, Optional } from '@xeno-js/shared'\r\nimport { Result } from '@xeno-js/shared'\r\nimport { Guards, GUEST } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description The GateKeeper class is responsible for authenticating users based on their identity and permissions. It provides a method to authenticate a user using a token and returns their identity. If the token is invalid or missing, it returns a guest identity.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class GateKeeper implements IGateKeeper {\r\n constructor(\r\n private readonly _authService: IBaseAuthService,\r\n private readonly _mapper: IBaseMapper<AuthClaims, Identity>,\r\n ) {}\r\n\r\n public async authenticate(token: Optional<string>): Promise<ResultType<Identity>> {\r\n const guest = GUEST as unknown as Identity\r\n\r\n if (!Guards.isNullOrEmpty(token)) {\r\n const authResult = await this._authService.authenticate(token)\r\n if (authResult.isOk()) {\r\n const claims = authResult.getValueOrThrow()\r\n if (Guards.isDefined(claims)) return Result.ok(this._mapper.map(claims))\r\n }\r\n }\r\n\r\n const userResult = await this._authService.getUser()\r\n\r\n if (userResult.isOk()) {\r\n const user = userResult.getValueOrThrow()\r\n if (Guards.isDefined(user)) {\r\n return Result.ok(this._mapper.map(user))\r\n }\r\n }\r\n\r\n return Result.ok(guest)\r\n\r\n return Result.ok(guest)\r\n }\r\n}\r\n","import type { Identity, IGateKeeper, ResultType } from '@xeno-js/shared'\r\nimport type { Optional } from '@xeno-js/shared'\r\nimport { Result } from '@xeno-js/shared'\r\nimport { GUEST } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description The NoAuthGateKeeper class is a specialized implementation of the IGateKeeper interface that bypasses authentication and authorization checks. It is designed for scenarios where authentication is not required, such as public endpoints or testing environments. The authenticate method returns a guest identity, effectively granting access without requiring a valid token.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class NoAuthGateKeeper implements IGateKeeper {\r\n public async authenticate(_token: Optional<string>): Promise<ResultType<Identity>> {\r\n const guest = GUEST as unknown as Identity\r\n\r\n return Result.ok(guest)\r\n }\r\n}\r\n","export * from './gate-keeper'\r\nexport * from './noauth.gate-keeper'\r\n","import type { IBaseMapper, Identity } from '@xeno-js/shared'\r\nimport type { AuthClaims } from '@xeno-js/shared'\r\nimport { GuidHelper } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description ClaimsIdentityMapper is responsible for mapping authentication claims (AuthClaims) to an Identity object. This mapper takes the claims extracted from a token (such as a JWT) and transforms them into a structured Identity that can be used throughout the application for authentication and authorization purposes. The mapping includes parsing the user ID and tenant ID from the claims, as well as extracting roles and permissions.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class ClaimsIdentityMapper implements IBaseMapper<AuthClaims, Identity> {\r\n public map(claims: AuthClaims): Identity {\r\n return {\r\n userId: GuidHelper.parse(claims.sub),\r\n email: claims.email,\r\n name: claims.name,\r\n tenantId: GuidHelper.parse(claims.tenantId),\r\n roles: claims.roles,\r\n permissions: claims.permissions,\r\n }\r\n }\r\n}\r\n","export * from './claims-identity.mapper'\r\n","import type { IPolicyRegistry } from '@xeno-js/shared'\r\nimport type { AuthPolicy, Optional } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description The PolicyRegistry class is an implementation of the IPolicyRegistry interface that manages role-based access control policies. It provides methods to add policies for certain intents and to retrieve the access control policy for a given intent. The policies are stored in a cache, allowing for efficient retrieval and management of access control policies across the application.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class PolicyRegistry implements IPolicyRegistry {\r\n /**\r\n * @description Constructs a new instance of the PolicyRegistry class, which is responsible for managing role-based access control policies. It takes an ICache instance as a parameter, which is used to store and retrieve policies for specific intents. The cache allows for efficient management of access control policies across the application.\r\n * @param _cache An instance of ICache used to store and retrieve policies for specific intents. This cache is essential for efficient management of access control policies across the application.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n constructor(private readonly _cache: Map<string, AuthPolicy> = new Map()) {}\r\n\r\n public addPolicy(intent: string, policy: AuthPolicy): this {\r\n const key = this.getKey(intent)\r\n this._cache.set(key, policy)\r\n return this\r\n }\r\n\r\n public getPolicy(intent: string): Optional<AuthPolicy> {\r\n const key = this.getKey(intent)\r\n return this._cache.get(key)\r\n }\r\n\r\n private getKey(intent: string): string {\r\n return `policy:${intent.toLowerCase()}`\r\n }\r\n}\r\n","export * from './policy-registry'\r\n","import type { ISpecification } from '@xeno-js/shared'\r\n\r\n/**\r\n * Base class for specifications, providing default implementations for logical operations (AND, OR, NOT).\r\n *\r\n * @template T - The type of the candidate object that the specification will evaluate.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport abstract class Specification<T> implements ISpecification<T> {\r\n /**\r\n * Determines if the candidate satisfies the specification criteria.\r\n *\r\n * @param candidate - The object to evaluate against the specification.\r\n * @returns A boolean indicating whether the candidate satisfies the specification.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n public abstract isSatisfiedBy(candidate: T): boolean\r\n\r\n /**\r\n * Combines this specification with another specification using a logical AND operation.\r\n *\r\n * @param other - Another specification to combine with this specification.\r\n * @returns A new specification that represents the logical AND of this and the other specification.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n public and(other: ISpecification<T>): ISpecification<T> {\r\n return new AndSpecification<T>(this, other)\r\n }\r\n\r\n /**\r\n * Combines this specification with another specification using a logical OR operation.\r\n *\r\n * @param other - Another specification to combine with this specification.\r\n * @returns A new specification that represents the logical OR of this and the other specification.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n public or(other: ISpecification<T>): ISpecification<T> {\r\n return new OrSpecification<T>(this, other)\r\n }\r\n\r\n /**\r\n * Inverts this specification using a logical NOT operation.\r\n *\r\n * @returns A new specification that represents the logical NOT of this specification.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n public not(): ISpecification<T> {\r\n return new NotSpecification<T>(this)\r\n }\r\n}\r\n\r\n/**\r\n * A specification that represents the logical AND of two specifications. It evaluates to true if both specifications are satisfied by the candidate.\r\n *\r\n * @template T - The type of the candidate object that the specification will evaluate.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nclass AndSpecification<T> extends Specification<T> {\r\n constructor(\r\n private _left: ISpecification<T>,\r\n private _right: ISpecification<T>,\r\n ) {\r\n super()\r\n }\r\n public isSatisfiedBy(candidate: T): boolean {\r\n return this._left.isSatisfiedBy(candidate) && this._right.isSatisfiedBy(candidate)\r\n }\r\n}\r\n\r\n/**\r\n * A specification that represents the logical OR of two specifications. It evaluates to true if at least one of the specifications is satisfied by the candidate.\r\n *\r\n * @template T - The type of the candidate object that the specification will evaluate.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nclass OrSpecification<T> extends Specification<T> {\r\n constructor(\r\n private _left: ISpecification<T>,\r\n private _right: ISpecification<T>,\r\n ) {\r\n super()\r\n }\r\n public isSatisfiedBy(candidate: T): boolean {\r\n return this._left.isSatisfiedBy(candidate) || this._right.isSatisfiedBy(candidate)\r\n }\r\n}\r\n\r\n/**\r\n * A specification that represents the logical NOT of another specification. It evaluates to true if the original specification is not satisfied by the candidate.\r\n *\r\n * @template T - The type of the candidate object that the specification will evaluate.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nclass NotSpecification<T> extends Specification<T> {\r\n constructor(private _spec: ISpecification<T>) {\r\n super()\r\n }\r\n public isSatisfiedBy(candidate: T): boolean {\r\n return !this._spec.isSatisfiedBy(candidate)\r\n }\r\n}\r\n","export * from './specification'\r\n","export * from './containers/index'\r\nexport * from './cqrs/index'\r\nexport * from './gate_keepers/index'\r\nexport * from './mappers/index'\r\nexport * from './policies/index'\r\nexport * from './specifications/index'\r\n","import type { ILoggerClient } from '@xeno-js/shared'\r\nimport type { LogLevel, Optional } from '@xeno-js/shared'\r\nimport { Guards, LOG_LEVEL } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description Concrete implementation of ILoggerClient that uses the built-in console for logging. This class serves as a simple logging provider that can be used for development and debugging purposes, allowing log messages to be output to the console with different log levels (e.g., error, warning, info, debug) and optional context and error information.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class ConsoleLogger implements ILoggerClient {\r\n /**\r\n * 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.\r\n * @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.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n constructor(private readonly _minLevel: LogLevel = LOG_LEVEL.DEBUG) {}\r\n\r\n public track<T>(\r\n level: LogLevel,\r\n message: string,\r\n context: T,\r\n error: Optional<unknown> = undefined,\r\n ): void {\r\n if (level < this._minLevel) return\r\n\r\n const logMessage = `[${level}] ${message}`\r\n const payload = Guards.isDefined(error) ? { ...context, error } : context\r\n switch (level) {\r\n case LOG_LEVEL.ERROR:\r\n console.error(logMessage, payload ?? {})\r\n break\r\n case LOG_LEVEL.WARN:\r\n console.warn(logMessage, payload ?? {})\r\n break\r\n case LOG_LEVEL.DEBUG:\r\n console.debug(logMessage, payload ?? {})\r\n break\r\n default:\r\n console.info(logMessage, payload ?? {})\r\n break\r\n }\r\n }\r\n}\r\n","import type * as Sentry from '@sentry/node'\r\nimport type { ILoggerClient } from '@xeno-js/shared'\r\nimport type { Dictionary, LogLevel, Optional } from '@xeno-js/shared'\r\nimport { Guards, LOG_LEVEL } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description Concrete implementation of ILoggerClient that uses Sentry as the error tracking system. This class acts as an adapter between the ILoggerClient interface and the Sentry library, allowing the use of Sentry as a logging provider within the application's architecture without directly coupling the code to the specific tracking framework.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class SentryLogger implements ILoggerClient {\r\n constructor(\r\n private readonly _client: typeof Sentry,\r\n public readonly _minLevel: LogLevel,\r\n ) {}\r\n\r\n public track<T>(\r\n level: LogLevel,\r\n message: string,\r\n context: Optional<T extends Dictionary<unknown> ? T : never> = undefined,\r\n error: Optional<unknown> = undefined,\r\n ): void {\r\n if (level < this._minLevel) return\r\n\r\n if (level === LOG_LEVEL.ERROR || level === LOG_LEVEL.WARN) {\r\n this._client.withScope((scope) => {\r\n if (Guards.isDefined(context)) scope.setExtras(context)\r\n\r\n if (Guards.isDefined(error)) {\r\n this._client.captureException(error)\r\n } else {\r\n this._client.captureMessage(message, 'warning')\r\n }\r\n })\r\n }\r\n }\r\n}\r\n","import * as Sentry from '@sentry/node'\r\nimport type { IFactory, ILoggerClient } from '@xeno-js/shared'\r\nimport { Guards, LOG_LEVEL } from '@xeno-js/shared'\r\n\r\nimport type { LoggerConfig } from '@/domain'\r\n\r\nimport { SentryLogger } from '../loggers/sentry.logger'\r\nimport type { XenoRegistry } from '../xeno-registry'\r\n\r\n/**\r\n * @description Factory class responsible for creating instances of SentryLogger based on the provided configuration. It implements the IFactory interface, allowing for easy integration with dependency injection systems. The factory encapsulates the creation logic for the SentryLogger, including the initialization of the underlying Sentry instance with the specified configuration options such as DSN and environment. This design promotes separation of concerns and allows for flexibility in managing SentryLogger instances across the application.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class SentryLoggerFactory<TRegistry extends XenoRegistry = XenoRegistry> implements IFactory<\r\n LoggerConfig<TRegistry>,\r\n ILoggerClient\r\n> {\r\n public create(config: LoggerConfig<TRegistry>): ILoggerClient {\r\n const level = config.level ?? LOG_LEVEL.WARN\r\n const sentryConfig = config.sentry?.config\r\n\r\n const env = sentryConfig?.environment ?? process.env.NODE_ENV ?? 'development'\r\n\r\n if (!Guards.isDefined(sentryConfig))\r\n throw new Error('Sentry configuration is required when Sentry logging is enabled.')\r\n\r\n if (!Guards.isDefined(sentryConfig.dsn))\r\n throw new Error('Sentry DSN is required when Sentry logging is enabled.')\r\n\r\n Sentry.init({\r\n dsn: sentryConfig.dsn,\r\n environment: env,\r\n tracesSampleRate: env === 'production' ? 0.1 : 1.0,\r\n integrations: [Sentry.httpIntegration()],\r\n beforeSend(event, hint) {\r\n const error = hint.originalException\r\n\r\n if (error instanceof Error && error.name === 'ZodError') {\r\n return null\r\n }\r\n\r\n return event\r\n },\r\n })\r\n\r\n return new SentryLogger(Sentry, level)\r\n }\r\n}\r\n","import type { ILoggerClient } from '@xeno-js/shared'\r\nimport type { LogLevel, Optional } from '@xeno-js/shared'\r\nimport { Guards, LOG_LEVEL } from '@xeno-js/shared'\r\nimport type { Logger } from 'pino'\r\n\r\n/**\r\n * @description Class that implements the ILoggerClient interface using the Pino logging library. This class serves as an adapter between the ILoggerClient interface and the Pino logging library, allowing the use of Pino as a logging provider within the application's architecture without directly coupling the code to the specific logging framework.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class PinoLogger implements ILoggerClient {\r\n /**\r\n * 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.\r\n * @param _logger The Pino logger instance used for logging messages.\r\n * @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.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n constructor(\r\n private readonly _logger: Logger,\r\n private readonly _minLevel: LogLevel = LOG_LEVEL.DEBUG,\r\n ) {}\r\n\r\n public track<T>(\r\n level: LogLevel,\r\n message: string,\r\n context: T,\r\n error: Optional<unknown> = undefined,\r\n ): void {\r\n if (level < this._minLevel) return\r\n\r\n const payload = Guards.isDefined(error) ? { ...context, error } : context\r\n\r\n switch (level) {\r\n case LOG_LEVEL.ERROR:\r\n this._logger.error(payload ?? {}, message)\r\n break\r\n case LOG_LEVEL.WARN:\r\n this._logger.warn(payload ?? {}, message)\r\n break\r\n case LOG_LEVEL.DEBUG:\r\n this._logger.debug(payload ?? {}, message)\r\n break\r\n default:\r\n this._logger.info(payload ?? {}, message)\r\n break\r\n }\r\n }\r\n}\r\n","import type { IFactory, ILoggerClient } from '@xeno-js/shared'\r\nimport { LOG_LEVEL } from '@xeno-js/shared'\r\nimport type { DestinationStream, LoggerOptions } from 'pino'\r\nimport pino from 'pino'\r\n\r\nimport type { LoggerConfig } from '@/domain'\r\n\r\nimport { PinoLogger } from '../loggers/pino.logger'\r\nimport type { XenoRegistry } from '../xeno-registry'\r\n\r\n/**\r\n * @description Factory class responsible for creating instances of PinoLogger based on the provided configuration. It implements the IFactory interface, allowing for easy integration with dependency injection systems. The factory encapsulates the creation logic for the PinoLogger, including the initialization of the underlying Pino instance with the specified configuration options such as log level. This design promotes separation of concerns and allows for flexibility in managing PinoLogger instances across the application.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class PinoLoggerFactory<TRegistry extends XenoRegistry = XenoRegistry> implements IFactory<\r\n LoggerConfig<TRegistry>,\r\n ILoggerClient\r\n> {\r\n public create(config: LoggerConfig<TRegistry>): ILoggerClient {\r\n const level = config.level ?? LOG_LEVEL.DEBUG\r\n\r\n const env = config.pino.config?.env ?? process.env.NODE_ENV ?? 'development'\r\n const destinationType = config.pino.config?.destination ?? 'stdout'\r\n const filePath = config.pino.config?.filePath ?? 'logs/app.log'\r\n const prettyPrint = config.pino.config?.prettyPrint ?? env === 'development'\r\n\r\n const options: LoggerOptions = {\r\n level: 'trace',\r\n\r\n serializers: {\r\n err: pino.stdSerializers.err,\r\n },\r\n\r\n timestamp: pino.stdTimeFunctions.isoTime,\r\n\r\n redact: {\r\n paths: ['password', 'token', 'secret', 'authorization', 'headers.authorization'],\r\n censor: '***',\r\n },\r\n }\r\n\r\n if (prettyPrint) {\r\n return new PinoLogger(\r\n pino({\r\n ...options,\r\n transport: {\r\n target: 'pino-pretty',\r\n options: {\r\n colorize: true,\r\n ignore: 'pid,hostname',\r\n translateTime: 'SYS:standard',\r\n },\r\n },\r\n }),\r\n level,\r\n )\r\n }\r\n\r\n if (destinationType === 'file') {\r\n const destination: DestinationStream = pino.destination({ dest: filePath, sync: false })\r\n return new PinoLogger(pino(options, destination), level)\r\n } else {\r\n const stream = pino.destination({ dest: 1, sync: false })\r\n return new PinoLogger(pino(options, stream), level)\r\n }\r\n }\r\n}\r\n","import type { ILoggerClient } from '@xeno-js/shared'\r\nimport type { KeysOfType, Optional } from '@xeno-js/shared'\r\n\r\nimport type { IServiceContainer, IServiceScope, LoggerConfig } from '@/domain'\r\n\r\nimport type { XenoRegistry } from '../../xeno-registry'\r\n/**\r\n * @description LoggerUtils is a utility object that provides helper functions for the CoreModule. It includes the addLogger function, which is responsible for configuring and registering the logging services in the dependency injection container based on the provided LoggerConfig options. This function 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.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport const LoggerUtils = Object.freeze({\r\n /**\r\n * @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.\r\n *\r\n * @param container - The service container to register logging services with.\r\n * @param opts - The LoggerConfig options to determine which loggers to enable and their configurations.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n async addLogger<TRegistry extends XenoRegistry = XenoRegistry>(\r\n container: IServiceContainer<TRegistry>,\r\n opts: Optional<LoggerConfig<XenoRegistry>>,\r\n ): Promise<void> {\r\n const loggerDependencies: KeysOfType<XenoRegistry, ILoggerClient>[] = []\r\n\r\n const { Guards, LOG_LEVEL, TOKENS } = await import('@xeno-js/shared')\r\n\r\n if (!Guards.isDefined(opts) || opts.console) {\r\n const { ConsoleLogger } = await import('../../loggers/console.logger')\r\n container.addSingleton(TOKENS.CONSOLE_LOGGER, () => new ConsoleLogger(opts?.level))\r\n loggerDependencies.push(TOKENS.CONSOLE_LOGGER)\r\n }\r\n\r\n const customLoggerFactories: ((c: IServiceScope<TRegistry>) => ILoggerClient)[] = []\r\n\r\n if (Guards.isDefined(opts)) {\r\n if (Guards.isDefined(opts.sentry.config)) {\r\n const { SentryLoggerFactory } = await import('../../factories/sentry-logger.factory')\r\n container.addSingleton(TOKENS.SENTRY_LOGGER, () => {\r\n const factory = new SentryLoggerFactory()\r\n return factory.create(opts)\r\n })\r\n loggerDependencies.push(TOKENS.SENTRY_LOGGER)\r\n }\r\n\r\n if (Guards.isDefined(opts.pino.config)) {\r\n const { PinoLoggerFactory } = await import('../../factories/pino-logger.factory')\r\n container.addSingleton(TOKENS.PINO_LOGGER, () => {\r\n const factory = new PinoLoggerFactory()\r\n return factory.create(opts)\r\n })\r\n loggerDependencies.push(TOKENS.PINO_LOGGER)\r\n }\r\n\r\n if (!Guards.isNullOrEmpty(opts.customLoggers)) {\r\n const customLoggers = opts.customLoggers\r\n customLoggers.forEach((f) => {\r\n if (Guards.isDefined(f)) {\r\n customLoggerFactories.push(f)\r\n }\r\n })\r\n }\r\n }\r\n\r\n const { BaseLogger } = await import('@xeno-js/shared')\r\n container.addSingleton(TOKENS.LOGGER, (c) => {\r\n const context = c.resolve(TOKENS.CONTEXT_ACCESSOR)\r\n const resolvedDependencies = [\r\n ...loggerDependencies.map((token) => c.resolve(token)),\r\n ...customLoggerFactories.map((factory) => factory(c)),\r\n ]\r\n return new BaseLogger(context, opts?.level ?? LOG_LEVEL.DEBUG, resolvedDependencies)\r\n })\r\n },\r\n} as const)\r\n","import { Guards, InMemoryCache, type Optional } from '@xeno-js/shared'\r\n\r\nimport type { IAtomicCache } from '@/domain'\r\n\r\n/**\r\n * @description The InMemoryCacheExtended class extends the InMemoryCache class and implements the IAtomicCache interface. It provides an implementation of the increment method, which increments the value associated with the given key in the cache. If the key does not exist, it is created with an initial value of 1. The method returns a Promise that resolves to the incremented value.\r\n */\r\nexport class InMemoryCacheExtended extends InMemoryCache implements IAtomicCache {\r\n public async increment(key: string, ttlSeconds: Optional<string | number>): Promise<number> {\r\n const current = (await this.get<number>(key)) ?? 0\r\n const next = Number(current) + 1\r\n const ttl = Guards.isDefined(ttlSeconds) ? Number(ttlSeconds) : 60\r\n await this.set(key, next, ttl)\r\n return next\r\n }\r\n}\r\n","import type { Optional } from '@xeno-js/shared'\r\nimport { Guards, StringHelper } from '@xeno-js/shared'\r\nimport type { Redis } from 'ioredis'\r\n\r\nimport type { IAtomicCache } from '@/domain'\r\n\r\n/**\r\n * @description The RedisCache class provides an implementation of the ICache interface using Redis as the underlying caching mechanism. This class allows for storing, retrieving, and managing cached values in a Redis database, supporting features such as time-to-live (TTL) for cache entries and atomic operations for setting values only if they do not already exist. The RedisCache class abstracts away the details of interacting with Redis, providing a simple and consistent interface for caching operations within the application.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class RedisCache implements IAtomicCache {\r\n /**\r\n * @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.\r\n * @param _redisClient An instance of the Redis client from the ioredis library, used to perform caching operations in the Redis database.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n constructor(private readonly _redisClient: Redis) {}\r\n\r\n public async increment(key: string, ttlSeconds: Optional<number | string>): Promise<number> {\r\n const multi = this._redisClient.multi()\r\n multi.incr(key)\r\n multi.expire(key, ttlSeconds ?? 60)\r\n const results = await multi.exec()\r\n return (results?.[0]?.[1] as number) ?? 1\r\n }\r\n\r\n public async get<T>(key: string): Promise<Optional<T>> {\r\n const value: string | null = await this._redisClient.get(key)\r\n if (!Guards.isDefined(value)) {\r\n return undefined\r\n }\r\n return JSON.parse(value) as T\r\n }\r\n\r\n public async set<T>(key: string, value: T, ttl: Optional<number>): Promise<void> {\r\n const stringValue = StringHelper.safeStringify(value)\r\n const ttlOption = Guards.isDefined(ttl) ? ttl : 86400 // Default TTL of 1 day if not provided\r\n\r\n await this._redisClient.set(key, stringValue, 'EX', ttlOption)\r\n }\r\n\r\n public async setIfAbsent<T>(key: string, value: T, ttl: Optional<number>): Promise<boolean> {\r\n const stringValue = StringHelper.safeStringify(value)\r\n const ttlOption = Guards.isDefined(ttl) ? ttl : 300 // Default TTL of 5 minutes for locks if not provided\r\n const result = await this._redisClient.set(key, stringValue, 'EX', ttlOption, 'NX')\r\n return result === 'OK'\r\n }\r\n\r\n public async remove(key: string): Promise<void> {\r\n await this._redisClient.del(key)\r\n }\r\n\r\n public async has(key: string): Promise<boolean> {\r\n const exists = await this._redisClient.exists(key)\r\n return exists === 1\r\n }\r\n\r\n public async clear(): Promise<void> {\r\n await this._redisClient.flushdb()\r\n }\r\n}\r\n","import type { CacheClientConfig, IFactory } from '@xeno-js/shared'\r\nimport { Guards } from '@xeno-js/shared'\r\nimport type { RedisOptions } from 'ioredis'\r\nimport { Redis } from 'ioredis'\r\n\r\nimport type { IAtomicCache } from '@/domain'\r\n\r\nimport { RedisCache } from '../cache/redis.cache'\r\n\r\n/**\r\n * @description Factory class responsible for creating instances of RedisCache based on the provided configuration. It implements the IFactory interface, allowing for easy integration with dependency injection systems. The factory encapsulates the creation logic for the RedisCache, including the initialization of the underlying Redis instance with the specified configuration options such as host, port, and authentication settings. This design promotes separation of concerns and allows for flexibility in managing RedisCache instances across the application.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class RedisCacheFactory implements IFactory<CacheClientConfig, IAtomicCache> {\r\n public create(config: CacheClientConfig): IAtomicCache {\r\n const host = config?.host ?? 'localhost'\r\n const port = config?.port ?? 6379\r\n const password = config?.password\r\n const username = config?.username\r\n const useTls = config?.tls ?? false\r\n const maxRetries = config?.maxRetriesPerRequest ?? 3\r\n\r\n const redisOptions: RedisOptions = {\r\n host,\r\n port,\r\n maxRetriesPerRequest: maxRetries,\r\n\r\n // Strategia di riconnessione esponenziale per garantire resilienza\r\n retryStrategy(times) {\r\n const delay = Math.min(times * 50, 2000)\r\n return delay\r\n },\r\n }\r\n\r\n if (Guards.isDefined(password)) {\r\n redisOptions.password = password\r\n }\r\n\r\n if (Guards.isDefined(username)) {\r\n redisOptions.username = username\r\n }\r\n\r\n if (useTls) {\r\n redisOptions.tls = {}\r\n }\r\n\r\n const nativeRedisInstance = new Redis(redisOptions)\r\n\r\n nativeRedisInstance.on('error', (err) => {\r\n console.error('❌ [Redis Error]:', err.message)\r\n })\r\n\r\n return new RedisCache(nativeRedisInstance)\r\n }\r\n}\r\n","import type { CacheConfig } from '@xeno-js/shared'\r\n\r\nimport type { IServiceContainer } from '@/domain'\r\n\r\nimport type { XenoRegistry } from '../../xeno-registry'\r\n\r\n/**\r\n * @description Utility functions for configuring caching in the service container.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport const CacheUtils = Object.freeze({\r\n /**\r\n * @description Checks if the provided cache configuration requires any cache strategies.\r\n * @param container The service container to which the cache strategies will be added.\r\n * @param opts The cache configuration options.\r\n * @returns True if any cache strategies are required, false otherwise.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n async addCache<TRegistry extends XenoRegistry = XenoRegistry>(\r\n container: IServiceContainer<TRegistry>,\r\n opts: CacheConfig,\r\n ): Promise<void> {\r\n const { Guards, TOKENS } = await import('@xeno-js/shared')\r\n if (!opts.inMemory && !Guards.isDefined(opts.redis)) {\r\n throw new Error(\r\n 'No cache strategies are configured. Please provide at least one cache strategy.',\r\n )\r\n }\r\n\r\n const { CacheKeyBuilder } = await import('@xeno-js/shared')\r\n container.addSingleton(\r\n TOKENS.CACHE_KEY_BUILDER,\r\n (c) => new CacheKeyBuilder(c.resolve(TOKENS.IDENTITY_ACCESSOR)),\r\n )\r\n\r\n if (opts.inMemory || !Guards.isDefined(opts.redis)) {\r\n const { InMemoryCacheExtended } = await import('../../cache/inmemory.cache')\r\n container.addSingleton(TOKENS.CACHE, () => new InMemoryCacheExtended())\r\n return\r\n }\r\n\r\n if (Guards.isDefined(opts.redis)) {\r\n const { RedisCacheFactory } = await import('../../factories/redis-cache.factory')\r\n container.addSingleton(TOKENS.CACHE, () => {\r\n const config = opts.redis\r\n return new RedisCacheFactory().create(config!)\r\n })\r\n }\r\n },\r\n} as const)\r\n","import { Guards, type HttpMethod, type Optional } from '@xeno-js/shared'\r\n\r\nimport type { IAllowMethod } from '@/domain'\r\n\r\ninterface DynamicRoute {\r\n pattern: RegExp\r\n methods: HttpMethod[]\r\n}\r\n\r\nexport class AllowMethodRegistry implements IAllowMethod {\r\n private readonly _staticRoutes = new Map<string, HttpMethod[]>()\r\n private readonly _dynamicRoutes: DynamicRoute[] = []\r\n\r\n public add(path: string, methods: HttpMethod[]): void {\r\n const normalizedPath = this.normalizePath(path)\r\n\r\n if (this.isDynamicPath(normalizedPath)) {\r\n const pattern = this.createRoutePattern(normalizedPath)\r\n this._dynamicRoutes.push({ pattern, methods })\r\n } else {\r\n this._staticRoutes.set(normalizedPath, methods)\r\n }\r\n }\r\n\r\n public check(path: string, method: HttpMethod): boolean {\r\n const cleanPath = this.normalizePath(path.split('?')[0].split('#')[0])\r\n\r\n const staticMethods = this._staticRoutes.get(cleanPath)\r\n if (Guards.isDefined(staticMethods)) return staticMethods.includes(method)\r\n\r\n for (const route of this._dynamicRoutes) {\r\n if (route.pattern.test(cleanPath)) return route.methods.includes(method)\r\n }\r\n\r\n return false\r\n }\r\n\r\n public getMethods(path: string): string {\r\n const cleanPath = this.normalizePath(path.split('?')[0].split('#')[0])\r\n const methods = this.findMethods(cleanPath)\r\n\r\n return Guards.isDefined(methods) ? methods.join(', ').toUpperCase() : ''\r\n }\r\n\r\n private findMethods(cleanPath: string): Optional<HttpMethod[]> {\r\n const staticMethods = this._staticRoutes.get(cleanPath)\r\n if (Guards.isDefined(staticMethods)) return staticMethods\r\n\r\n for (const route of this._dynamicRoutes) if (route.pattern.test(cleanPath)) return route.methods\r\n\r\n return undefined\r\n }\r\n\r\n private isDynamicPath(path: string): boolean {\r\n return path.includes(':') || (path.includes('{') && path.includes('}'))\r\n }\r\n\r\n private normalizePath(path: string): string {\r\n const trimmed = path.trim()\r\n const withLeadingSlash = trimmed.startsWith('/') ? trimmed : `/${trimmed}`\r\n if (withLeadingSlash === '/') return '/'\r\n return withLeadingSlash.replace(/\\/+$/, '')\r\n }\r\n\r\n private createRoutePattern(path: string): RegExp {\r\n const segments = path.split('/').filter(Boolean)\r\n\r\n const regexSegments = segments.map((segment) => {\r\n if (segment.startsWith(':') || (segment.startsWith('{') && segment.endsWith('}')))\r\n return '([^/]+)'\r\n return segment.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\r\n })\r\n\r\n return new RegExp(`^\\\\/${regexSegments.join('\\\\/')}\\\\/?$`)\r\n }\r\n}\r\n","export * from './allow-method.service'\r\n","import type { Optional } from '@xeno-js/shared'\r\nimport { Guards } from '@xeno-js/shared'\r\n\r\nimport type { IAllowOrigin } from '@/domain'\r\n\r\n/**\r\n * @description A class that implements the IAllowOrigin interface.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class AllowOrigin implements IAllowOrigin {\r\n constructor(private readonly _list: string[]) {}\r\n\r\n public isAllowed(origin: Optional<string>): boolean {\r\n if (Guards.isNullOrEmpty(origin)) return true\r\n\r\n const cleanOrigin = origin.trim().toLowerCase()\r\n\r\n for (const pattern of this._list) {\r\n const cleanPattern = pattern.trim().toLowerCase()\r\n\r\n if (cleanPattern === '*') return true\r\n\r\n if (cleanPattern === cleanOrigin) return true\r\n\r\n if (cleanPattern.startsWith('*.')) {\r\n const domainSuffix = cleanPattern.substring(1)\r\n if (cleanOrigin.endsWith(domainSuffix)) {\r\n const prefix = cleanOrigin.slice(0, cleanOrigin.length - domainSuffix.length)\r\n if (!Guards.isNullOrEmpty(prefix) && !prefix.includes('.')) return true\r\n }\r\n }\r\n }\r\n\r\n return false\r\n }\r\n}\r\n","export * from './allow-origin.http'\r\n","import type { IConcurrencyService } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description Concrete implementation of IConcurrencyService utilizing the 'p-limit' library.\r\n * This service ensures that no matter how many tasks are submitted, only the specified 'concurrencyLimit' number of tasks will be in a pending state simultaneously.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class PLimitConcurrencyService implements IConcurrencyService {\r\n public async executeInParallel<T>(\r\n tasks: (() => Promise<T>)[],\r\n concurrencyLimit: number,\r\n ): Promise<T[]> {\r\n const { default: pLimit } = await import('p-limit')\r\n\r\n const limit = pLimit(concurrencyLimit)\r\n\r\n const promises = tasks.map((task) => limit(task))\r\n\r\n return Promise.all(promises)\r\n }\r\n}\r\n","export * from './p-limit.service'\r\n","import type { ICryptoService } from '@/domain'\r\n\r\n/**\r\n * @description The EdgeCryptoService class implements the ICryptoService interface, providing a concrete implementation for cryptographic operations using the Web Cryptography API.\r\n *\r\n */\r\nexport class EdgeCryptoService implements ICryptoService {\r\n public randomBytes(size: number): Uint8Array {\r\n const buffer = new Uint8Array(size)\r\n crypto.getRandomValues(buffer)\r\n return buffer\r\n }\r\n\r\n public async hmacSha256(secret: string, data: string): Promise<string> {\r\n const encoder = new TextEncoder()\r\n const keyData = encoder.encode(secret)\r\n const messageData = encoder.encode(data)\r\n\r\n const cryptoKey = await crypto.subtle.importKey(\r\n 'raw',\r\n keyData,\r\n { name: 'HMAC', hash: 'SHA-256' },\r\n false,\r\n ['sign'],\r\n )\r\n\r\n const signature = await crypto.subtle.sign('HMAC', cryptoKey, messageData)\r\n\r\n // Converte l'ArrayBuffer risultante in una stringa base64url compatibile\r\n return btoa(String.fromCharCode(...new Uint8Array(signature)))\r\n .replace(/\\+/g, '-')\r\n .replace(/\\//g, '_')\r\n .replace(/=/g, '')\r\n }\r\n\r\n public timingSafeEqual(a: Uint8Array, b: Uint8Array): boolean {\r\n if (a.length !== b.length) {\r\n return false\r\n }\r\n let mismatch = 0\r\n for (let i = 0; i < a.length; i++) {\r\n mismatch |= a[i] ^ b[i]\r\n }\r\n return mismatch === 0\r\n }\r\n}\r\n","export * from './crypto.service'\r\n","import { Guards } from '@xeno-js/shared'\r\n\r\nimport type { ICryptoService, ICsrfTokenService } from '@/domain'\r\n\r\n/**\r\n * @description Service for generating and validating CSRF tokens\r\n */\r\nexport class CsrfTokenService implements ICsrfTokenService {\r\n constructor(\r\n private readonly _secret: string,\r\n private readonly _cryptoService: ICryptoService,\r\n ) {}\r\n\r\n public async generate(subject: string): Promise<string> {\r\n const randomBuffer = this._cryptoService.randomBytes(32)\r\n const nonce = btoa(String.fromCharCode(...randomBuffer))\r\n .replace(/\\+/g, '-')\r\n .replace(/\\//g, '_')\r\n .replace(/=/g, '')\r\n\r\n const signature = await this._cryptoService.hmacSha256(this._secret, `${subject}.${nonce}`)\r\n\r\n return `${nonce}.${signature}`\r\n }\r\n\r\n public async validate(token: string, subject: string): Promise<boolean> {\r\n const separatorIndex = token.indexOf('.')\r\n\r\n if (separatorIndex <= 0) return false\r\n\r\n const nonce = token.slice(0, separatorIndex)\r\n const signature = token.slice(separatorIndex + 1)\r\n\r\n if (Guards.isNullOrEmpty(nonce) || Guards.isNullOrEmpty(signature)) return false\r\n\r\n const expected = await this._cryptoService.hmacSha256(this._secret, `${subject}.${nonce}`)\r\n\r\n const encoder = new TextEncoder()\r\n const actualBuffer = encoder.encode(signature)\r\n const expectedBuffer = encoder.encode(expected)\r\n\r\n if (actualBuffer.length !== expectedBuffer.length) return false\r\n\r\n return this._cryptoService.timingSafeEqual(actualBuffer, expectedBuffer)\r\n }\r\n}\r\n","export * from './csrf-token.service'\r\n","import type { HttpHeaders, IServiceExtractor, Optional } from '@xeno-js/shared'\r\nimport { Guards, StringHelper } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description The BearerTokenExtractor class implements the IExtractor interface, providing a concrete implementation for extracting Bearer tokens from the Authorization header of an incoming HTTP request. The extract method checks for the presence of the Authorization header, verifies that it starts with the \"Bearer \" prefix, and returns the token value if valid. If the header is missing or does not conform to the expected format, it returns undefined, allowing for consistent handling of authentication tokens in the application.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class BearerTokenExtractor implements IServiceExtractor<HttpHeaders, Optional<string>> {\r\n extract(headers: HttpHeaders): Optional<string> {\r\n const authHeader = StringHelper.getSingleValue(headers['authorization'])\r\n if (!Guards.isDefined(authHeader)) {\r\n return undefined\r\n }\r\n\r\n if (authHeader.toLowerCase().startsWith('bearer ')) {\r\n return authHeader.substring(7)\r\n }\r\n\r\n const cookieHeader = StringHelper.getSingleValue(headers['cookie'])\r\n if (Guards.isDefined(cookieHeader)) {\r\n const match = /sb-access-token=([^;]+)/.exec(cookieHeader)\r\n if (!Guards.isNullOrEmpty(match) && Guards.isDefined(match[1])) {\r\n return match[1].trim()\r\n }\r\n }\r\n\r\n return undefined\r\n }\r\n}\r\n","import {\r\n Guards,\r\n type HttpHeaders,\r\n type IServiceExtractor,\r\n type Optional,\r\n StringHelper,\r\n} from '@xeno-js/shared'\r\n\r\n/**\r\n * @description The SupabaseSsrTokenExtractor class is a specialized implementation of the IServiceExtractor interface that extracts the Supabase SSR token from the HTTP headers. It is designed to work with Supabase's server-side rendering (SSR) functionality, where the token is stored in the HTTP headers for server-side rendering purposes. The extract method retrieves the token from the headers and returns it as a string.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class SupabaseSsrTokenExtractor implements IServiceExtractor<HttpHeaders, Optional<string>> {\r\n extract(headers: HttpHeaders): Optional<string> {\r\n const authHeader = StringHelper.getSingleValue(headers['authorization'])\r\n if (Guards.isDefined(authHeader) && authHeader.toLowerCase().startsWith('bearer ')) {\r\n return authHeader.substring(7)\r\n }\r\n\r\n const cookieHeader = StringHelper.getSingleValue(headers['cookie'])\r\n if (Guards.isNullOrEmpty(cookieHeader)) return undefined\r\n\r\n const cookies = cookieHeader.split(';').map((c) => c.trim())\r\n const tokenChunks: Record<number, string> = {}\r\n let unchunkedToken: Optional<string>\r\n\r\n for (const cookie of cookies) {\r\n const [name, ...rest] = cookie.split('=')\r\n if (!Guards.isDefined(name) || Guards.isNullOrEmpty(rest)) continue\r\n const value = decodeURIComponent(rest.join('='))\r\n\r\n if (Guards.isDefined(/^sb-[a-z0-9]+-auth-token$/.exec(name))) {\r\n unchunkedToken = value\r\n } else {\r\n const match = /^sb-[a-z0-9]+-auth-token\\.(\\d+)$/.exec(name)\r\n if (Guards.isDefined(match)) tokenChunks[parseInt(match[1], 10)] = value\r\n }\r\n }\r\n\r\n let fullTokenString = unchunkedToken\r\n if (!Guards.isDefined(fullTokenString) && Object.keys(tokenChunks).length > 0) {\r\n const indices = Object.keys(tokenChunks)\r\n .map(Number)\r\n .sort((a, b) => a - b)\r\n fullTokenString = indices.map((i) => tokenChunks[i]).join('')\r\n }\r\n\r\n if (Guards.isNullOrEmpty(fullTokenString)) return undefined\r\n\r\n try {\r\n const parsed = StringHelper.safeParse(fullTokenString)\r\n if (Guards.isDefined(parsed) && Guards.isObject(parsed) && 'access_token' in parsed) {\r\n const accessToken = parsed['access_token']\r\n if (Guards.isString(accessToken)) return accessToken\r\n }\r\n } catch {\r\n return undefined\r\n }\r\n }\r\n}\r\n","import { Guards, type IServiceExtractor, type Optional } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description The HttpCookieExtractor class implements the IServiceExtractor interface, providing a concrete implementation for extracting HTTP cookie values from an incoming HttpRequest. The extract method retrieves the value of a specified cookie, handling both string and array formats for cookie values. If the cookie is not present or if the cookies object is null or empty, it returns undefined, allowing for consistent handling of missing cookies in the application.\r\n */\r\nexport class HttpCookieExtractor implements IServiceExtractor<\r\n {\r\n header: Optional<string>\r\n name: string\r\n },\r\n Optional<string>\r\n> {\r\n extract(cookie: { header: Optional<string>; name: string }): Optional<string> {\r\n if (!Guards.isDefined(cookie.header)) return undefined\r\n\r\n for (const rawCookie of cookie.header.split(';')) {\r\n const separatorIndex = rawCookie.indexOf('=')\r\n\r\n if (separatorIndex <= 0) continue\r\n\r\n const name = rawCookie.slice(0, separatorIndex).trim()\r\n\r\n if (name !== cookie.name) continue\r\n\r\n const value = rawCookie.slice(separatorIndex + 1).trim()\r\n\r\n try {\r\n return decodeURIComponent(value)\r\n } catch {\r\n return undefined\r\n }\r\n }\r\n\r\n return undefined\r\n }\r\n}\r\n","import type { IServiceExtractor } from '@xeno-js/shared'\r\nimport type { Metadata } from '@xeno-js/shared'\r\nimport {\r\n Guards,\r\n GuidHelper,\r\n type HttpHeaders,\r\n HttpHelper,\r\n MathHelper,\r\n type Optional,\r\n StringHelper,\r\n} from '@xeno-js/shared'\r\n\r\n/**\r\n * @description The HttpHeaderExtractor class implements the IServiceExtractor interface, providing a concrete implementation for extracting HTTP header values from an incoming HttpRequest. The extract method retrieves the value of a specified header, handling both string and array formats for header values. If the header is not present or if the headers object is null or empty, it returns undefined, allowing for consistent handling of missing headers in the application.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class HttpHeaderExtractor implements IServiceExtractor<HttpHeaders, Metadata> {\r\n /**\r\n * @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.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n constructor(\r\n private readonly _bearerExtractor: IServiceExtractor<HttpHeaders, Optional<string>>,\r\n private readonly _cookieExtractor: IServiceExtractor<\r\n {\r\n header: Optional<string>\r\n name: string\r\n },\r\n Optional<string>\r\n >,\r\n private readonly _trustedIp: Optional<string>,\r\n private readonly _cookieName: string,\r\n ) {}\r\n\r\n extract(headers: HttpHeaders): Metadata {\r\n const correlationId = GuidHelper.parse(StringHelper.getSingleValue(headers['x-correlation-id']))\r\n const requestId = GuidHelper.parse(StringHelper.getSingleValue(headers['x-request-id']))\r\n const token = this._bearerExtractor.extract(headers)\r\n const clientIp =\r\n StringHelper.getSingleValue(headers[this._trustedIp?.toLowerCase() ?? 'x-forwarded-for']) ??\r\n StringHelper.getSingleValue(headers['x-real-ip'])\r\n const spanId = GuidHelper.parse(StringHelper.getSingleValue(headers['x-span-id']))\r\n const parentSpanId = StringHelper.getSingleValue(headers['x-parent-span-id'])\r\n const acceptHeader = StringHelper.getSingleValue(headers['accept'])\r\n const contentTypeHeader = StringHelper.getSingleValue(headers['content-type'])\r\n const userAgent = StringHelper.getSingleValue(headers['user-agent'])\r\n const returnAddress = StringHelper.getSingleValue(headers['x-return-address'])\r\n const sequenceId = StringHelper.getSingleValue(headers['x-sequence-id'])\r\n const position = StringHelper.getSingleValue(headers['x-sequence-position'])\r\n const size = StringHelper.getSingleValue(headers['x-sequence-size'])\r\n const expiration = StringHelper.getSingleValue(headers['x-expiration'])\r\n\r\n const csrf = StringHelper.getSingleValue(headers['x-csrf-token'])\r\n const cookieHeader = StringHelper.getSingleValue(headers['cookie'])\r\n const csrfCookie = this._cookieExtractor.extract({\r\n header: cookieHeader,\r\n name: this._cookieName,\r\n })\r\n const origin = StringHelper.getSingleValue(headers['origin'])\r\n const cleanOrigin = HttpHelper.sanitizeOriginUrl(origin)\r\n const referer = StringHelper.getSingleValue(headers['referer'])\r\n const cleanReferer = HttpHelper.sanitizeOriginUrl(referer)\r\n\r\n const accept = acceptHeader === '*/*' ? undefined : acceptHeader\r\n const formatIndicator = accept ?? contentTypeHeader ?? 'application/json'\r\n\r\n const metadata: Metadata = {\r\n correlationId,\r\n requestId,\r\n token,\r\n clientIp,\r\n spanId,\r\n parentSpanId,\r\n formatIndicator,\r\n userAgent,\r\n returnAddress,\r\n csrf,\r\n csrfCookie,\r\n origin: cleanOrigin,\r\n referer: cleanReferer,\r\n sequence: {\r\n sequenceId,\r\n position: Guards.isDefined(position) ? MathHelper.toNumber(position) : undefined,\r\n size: Guards.isDefined(size) ? MathHelper.toNumber(size) : undefined,\r\n },\r\n expiration: Guards.isDefined(expiration) ? MathHelper.toNumber(expiration) : undefined,\r\n }\r\n\r\n return metadata\r\n }\r\n}\r\n","export * from './extract-bearer.extractor'\r\nexport * from './extract-ssr-bearer.extractor'\r\nexport * from './http-cookie.extractor'\r\nexport * from './http-header.extractor'\r\n","import type { IServiceResilience, Optional } from '@xeno-js/shared'\r\nimport { AppError } from '@xeno-js/shared'\r\nimport type { IPolicy } from 'cockatiel'\r\n\r\n/**\r\n * @description The ServiceResilience class implements the IServiceResilience interface, providing a concrete implementation of resilience features for service calls. This class is designed to enhance the reliability of service interactions by automatically handling transient faults and preventing cascading failures in distributed systems. The execute method allows for the execution of asynchronous operations with built-in support for retries, timeouts, and circuit breakers, ensuring that service calls are more resilient to failures and can recover gracefully from errors.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class ServiceResilience implements IServiceResilience {\r\n constructor(private readonly policy: IPolicy) {}\r\n\r\n public async execute<T>(operation: () => Promise<T>, signal: Optional<AbortSignal>): Promise<T> {\r\n AppError.throwIfAborted(signal, 'ServiceResilience.execute')\r\n\r\n return this.policy.execute(() => operation(), signal)\r\n }\r\n}\r\n","export * from './resilience.service'\r\n","import type { Optional } from '@xeno-js/shared'\r\nimport { Guards } from '@xeno-js/shared'\r\n\r\ninterface HasRemoteSocket {\r\n readonly socket?: {\r\n readonly remoteAddress?: string\r\n }\r\n readonly connection?: {\r\n readonly remoteAddress?: string\r\n }\r\n}\r\n\r\n/**\r\n * @description SocketIpExtractor extracts the IP address of the remote socket from an incoming request. It checks for the presence of a 'socket' or 'connection' property in the request object and returns the 'remoteAddress' value if available. If the request object is not defined or not an object, it returns undefined.\r\n */\r\nexport const SocketIpExtractor = Object.freeze({\r\n /**\r\n * @description Extracts the IP address of the remote socket from an incoming request.\r\n * @param req The incoming request object.\r\n * @returns The IP address of the remote socket, or undefined if not available.\r\n */\r\n extract<T>(req: T): Optional<string> {\r\n if (Guards.isDefined(req) && Guards.isObject(req)) {\r\n const candidate = req as HasRemoteSocket\r\n return candidate.socket?.remoteAddress ?? candidate.connection?.remoteAddress\r\n }\r\n return undefined\r\n },\r\n} as const)\r\n","export * from './socket.utils'\r\n","import type { Optional } from '@xeno-js/shared'\r\nimport { Guards } from '@xeno-js/shared'\r\n\r\nimport type { IIPResolver } from '@/domain'\r\n\r\nimport { SocketIpExtractor } from './utils'\r\n\r\n/**\r\n * @description ClientIpResolver is a resolver that extracts the client IP address from the network context or the socket IP address.\r\n */\r\nexport class ClientIpResolver implements IIPResolver {\r\n constructor(private readonly _trustedProxies: string[] = []) {}\r\n\r\n public resolve<T>(req: T, clientIp: Optional<string>): Optional<string> {\r\n const socketIp = SocketIpExtractor.extract(req)\r\n\r\n if (!Guards.isDefined(socketIp))\r\n return !Guards.isNullOrEmpty(clientIp) ? clientIp.split(',')[0].trim() : undefined\r\n\r\n const isTrustedProxy = this._trustedProxies.includes(socketIp)\r\n if (!isTrustedProxy) return socketIp\r\n\r\n if (Guards.isDefined(clientIp)) return clientIp.split(',')[0].trim()\r\n\r\n return socketIp\r\n }\r\n}\r\n","export * from './client-ip.resolver'\r\n","export * from './allow_methods/index'\r\nexport * from './allow_origins/index'\r\nexport * from './concurrency/index'\r\nexport * from './crypto/index'\r\nexport * from './csrf/index'\r\nexport * from './extractors/index'\r\nexport * from './resiliences/index'\r\nexport * from './resolver/index'\r\n","import type { Dictionary, HttpMethod, IFactory } from '@xeno-js/shared'\r\n\r\nimport type { IAllowMethod } from '@/domain'\r\n\r\nimport { AllowMethodRegistry } from '../services'\r\n\r\n/**\r\n * @description Factory class responsible for creating instances of ZodValidatorService based on the provided configuration. It implements the IFactory interface, allowing for easy integration with dependency injection systems. The factory encapsulates the creation logic for the ZodValidatorService, including the initialization of the underlying ZodValidatorService instance with the specified configuration options such as URL and API key. This design promotes separation of concerns and allows for flexibility in managing ZodValidatorService instances across the application.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class AllowMethodFactory implements IFactory<Dictionary<HttpMethod[]>, IAllowMethod> {\r\n public create(opts: Dictionary<HttpMethod[]>): IAllowMethod {\r\n const allowMethodService = new AllowMethodRegistry()\r\n\r\n // 2. Iteriamo sugli schemi passati nella configurazione e li registriamo (Ora in modo sincrono!)\r\n for (const [intentKey, schema] of Object.entries(opts)) {\r\n allowMethodService.add(intentKey, schema)\r\n }\r\n\r\n return allowMethodService\r\n }\r\n}\r\n","import http from 'node:http'\r\nimport https from 'node:https'\r\n\r\nimport type { HttpClientConfig, IHttpClient } from '@xeno-js/shared'\r\nimport { AxiosFactory, AxiosHttpClient } from '@xeno-js/shared'\r\nimport axios from 'axios'\r\n\r\nexport class NodeAxiosFactory extends AxiosFactory {\r\n public override create(config: HttpClientConfig): IHttpClient {\r\n const isKeepAlive = config.keepAlive ?? true\r\n const maxSockets = config.maxSockets ?? 100\r\n\r\n const httpAgent = new http.Agent({\r\n keepAlive: isKeepAlive,\r\n maxSockets,\r\n scheduling: 'lifo',\r\n })\r\n\r\n const httpsAgent = new https.Agent({\r\n keepAlive: isKeepAlive,\r\n maxSockets,\r\n scheduling: 'lifo',\r\n })\r\n\r\n const axiosInstance = axios.create({\r\n baseURL: config.baseURL,\r\n headers: config.defaultHeaders,\r\n timeout: config.timeoutMs,\r\n httpAgent,\r\n httpsAgent,\r\n maxRedirects: config.maxRedirects ?? 5,\r\n decompress: config.decompress ?? true,\r\n proxy: config.proxy,\r\n withCredentials: config.withCredentials,\r\n })\r\n\r\n return new AxiosHttpClient(axiosInstance)\r\n }\r\n}\r\n","import type { IFactory, IServiceResilience, Optional } from '@xeno-js/shared'\r\nimport { AppError, Guards, RESILIENCE_DEFAULTS } from '@xeno-js/shared'\r\nimport {\r\n bulkhead,\r\n circuitBreaker,\r\n ConsecutiveBreaker,\r\n ExponentialBackoff,\r\n handleWhen,\r\n retry,\r\n wrap,\r\n} from 'cockatiel'\r\n\r\nimport type { ResilienceConfig } from '@/domain'\r\n\r\nimport { ServiceResilience } from '../services/resiliences/resilience.service'\r\n\r\ninterface HttpErrorLike {\r\n code?: string\r\n status?: number\r\n config?: {\r\n method?: string\r\n }\r\n}\r\n\r\n/**\r\n * @description Factory class responsible for creating instances of ServiceResilience based on the provided configuration. It implements the IFactory interface, allowing for easy integration with dependency injection systems. The factory encapsulates the creation logic for the ServiceResilience, including the initialization of the underlying resilience policies with the specified configuration options such as retry, circuit breaker, and bulkhead. This design promotes separation of concerns and allows for flexibility in managing ServiceResilience instances across the application.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class CockatielResilienceFactory implements IFactory<ResilienceConfig, IServiceResilience> {\r\n public create(config: ResilienceConfig): IServiceResilience {\r\n const message =\r\n 'The resilience configuration provided is invalid. Please ensure that all values are non-negative numbers.'\r\n const normalizedConfig = {\r\n retry: {\r\n attempts: this.checkConfigValue(\r\n config.retry.attempts,\r\n RESILIENCE_DEFAULTS.RETRY.ATTEMPTS,\r\n message,\r\n ),\r\n baseDelayMs: this.checkConfigValue(\r\n config.retry.baseDelayMs,\r\n RESILIENCE_DEFAULTS.RETRY.BASE_DELAY_MS,\r\n message,\r\n ),\r\n maxDelayMs: this.checkConfigValue(\r\n config.retry.maxDelayMs,\r\n RESILIENCE_DEFAULTS.RETRY.MAX_DELAY_MS,\r\n message,\r\n ),\r\n },\r\n circuitBreaker: {\r\n consecutiveFailures: this.checkConfigValue(\r\n config.circuitBreaker.consecutiveFailures,\r\n RESILIENCE_DEFAULTS.CIRCUIT_BREAKER.CONSECUTIVE_FAILURES,\r\n message,\r\n ),\r\n halfOpenTimeoutMs: this.checkConfigValue(\r\n config.circuitBreaker.halfOpenTimeoutMs,\r\n RESILIENCE_DEFAULTS.CIRCUIT_BREAKER.HALF_OPEN_TIMEOUT_MS,\r\n message,\r\n ),\r\n },\r\n bulkhead: {\r\n maxConcurrent: this.checkConfigValue(\r\n config.bulkhead.maxConcurrent,\r\n RESILIENCE_DEFAULTS.BULKHEAD.MAX_CONCURRENT,\r\n message,\r\n ),\r\n },\r\n }\r\n\r\n const retryPolicy = retry(\r\n handleWhen((error: unknown) => this.isTransientAndIdempotent(error)),\r\n {\r\n maxAttempts: normalizedConfig.retry.attempts,\r\n backoff: new ExponentialBackoff({\r\n initialDelay: normalizedConfig.retry.baseDelayMs,\r\n maxDelay: normalizedConfig.retry.maxDelayMs,\r\n }),\r\n },\r\n )\r\n\r\n const circuitBreakerPolicy = circuitBreaker(\r\n handleWhen((error: unknown) => this.isTransientError(error)),\r\n {\r\n breaker: new ConsecutiveBreaker(normalizedConfig.circuitBreaker.consecutiveFailures),\r\n halfOpenAfter: normalizedConfig.circuitBreaker.halfOpenTimeoutMs,\r\n },\r\n )\r\n\r\n const bulkheadPolicy = bulkhead(normalizedConfig.bulkhead.maxConcurrent)\r\n\r\n return new ServiceResilience(wrap(bulkheadPolicy, circuitBreakerPolicy, retryPolicy))\r\n }\r\n\r\n private isTransientError(error: unknown): boolean {\r\n if (!Guards.isDefined(error) || !Guards.isObject(error)) return false\r\n\r\n let status: number | undefined\r\n let isNetworkError = false\r\n\r\n if (error instanceof AppError) {\r\n status = error.status\r\n const cause = error.cause as HttpErrorLike\r\n if (Guards.isDefined(cause) && Guards.isString(cause.code)) {\r\n isNetworkError = [\r\n 'ECONNABORTED',\r\n 'ECONNRESET',\r\n 'ETIMEDOUT',\r\n 'ENOTFOUND',\r\n 'ECONNREFUSED',\r\n ].includes(cause.code.toUpperCase())\r\n }\r\n } else {\r\n const err = error as HttpErrorLike\r\n status = err.status\r\n if (Guards.isString(err.code)) {\r\n isNetworkError = [\r\n 'ECONNABORTED',\r\n 'ECONNRESET',\r\n 'ETIMEDOUT',\r\n 'ENOTFOUND',\r\n 'ECONNREFUSED',\r\n ].includes(err.code.toUpperCase())\r\n }\r\n }\r\n\r\n if (isNetworkError) return true\r\n\r\n if (Guards.isDefined(status)) {\r\n // 408 Request Timeout, 429 Too Many Requests, and Server Errors (5xx)\r\n return status === 408 || status === 429 || (status >= 500 && status < 600)\r\n }\r\n\r\n return false\r\n }\r\n\r\n private isTransientAndIdempotent(error: unknown): boolean {\r\n if (!this.isTransientError(error)) return false\r\n\r\n let method: string | undefined\r\n\r\n if (error instanceof AppError) {\r\n const cause = error.cause as HttpErrorLike\r\n if (\r\n Guards.isDefined(cause) &&\r\n Guards.isDefined(cause.config) &&\r\n Guards.isString(cause.config.method)\r\n ) {\r\n method = cause.config.method.toUpperCase()\r\n }\r\n } else {\r\n const err = error as HttpErrorLike\r\n if (Guards.isDefined(err.config) && Guards.isString(err.config.method)) {\r\n method = err.config.method.toUpperCase()\r\n }\r\n }\r\n\r\n if (Guards.isNullOrEmpty(method)) return false\r\n\r\n const idempotentMethods = ['GET', 'PUT', 'DELETE', 'HEAD', 'OPTIONS']\r\n return idempotentMethods.includes(method)\r\n }\r\n\r\n private checkConfigValue(value: Optional<number>, defaultValue: number, message: string): number {\r\n if (Guards.isDefined(value)) {\r\n Guards.throwIfNegative(value, message)\r\n return value\r\n }\r\n return defaultValue\r\n }\r\n}\r\n","import type { DbConfig, IFactory } from '@xeno-js/shared'\r\nimport type { Dictionary } from '@xeno-js/shared'\r\nimport { drizzle } from 'drizzle-orm/node-postgres'\r\nimport { Pool } from 'pg'\r\n\r\nimport type { DbContext } from '../db/db.types'\r\n\r\n/**\r\n * @description Factory class responsible for creating instances of IDbClient based on the provided configuration. It implements the IFactory interface, allowing for easy integration with dependency injection systems. The factory encapsulates the creation logic for the IDbClient, including the initialization of the underlying database client with the specified configuration options such as connection string and table mappings. This design promotes separation of concerns and allows for flexibility in managing IDbClient instances across the application.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class DbClientFactory implements IFactory<DbConfig, DbContext<Dictionary>> {\r\n public create(opts: DbConfig): DbContext<Dictionary> {\r\n const pool = new Pool({\r\n connectionString: opts.connectionString,\r\n })\r\n\r\n return drizzle({ client: pool })\r\n }\r\n}\r\n","import type { AsyncLocalStorage } from 'node:async_hooks'\r\n\r\nimport type { Identity, IFactory, NetworkContext, Optional, RequestContext } from '@xeno-js/shared'\r\nimport { Guards } from '@xeno-js/shared'\r\n\r\nimport type { ExecutionContext, IRequestContext, IServiceScope } from '@/domain'\r\n\r\nimport type { XenoRegistry } from '../xeno-registry'\r\n\r\n/**\r\n * @description The NodeRequestContext class is an implementation of the IRequestContext interface that utilizes Node.js's AsyncLocalStorage to manage and access request-specific context data, such as user identity information, across asynchronous operations. This class provides methods to run asynchronous functions within a specific context and to retrieve the current identity information from the context when needed. By leveraging AsyncLocalStorage, the NodeRequestContext ensures that the context data is properly propagated across asynchronous calls, allowing for seamless access to identity information throughout the execution flow of a request.\r\n * @template TCtx - The type of the context data that will be stored and accessed using this request context implementation. This typically includes user identity information, such as user ID, roles, and correlation ID, which can be used for authentication and authorization purposes within the application.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class NodeRequestContext<\r\n TRegistry extends XenoRegistry = XenoRegistry,\r\n> implements IRequestContext<RequestContext, TRegistry> {\r\n /**\r\n * @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.\r\n * @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.\r\n * @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.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n constructor(\r\n private readonly _storage: AsyncLocalStorage<ExecutionContext<TRegistry>>,\r\n private readonly _factoryScope: IFactory<void, IServiceScope<TRegistry>>,\r\n ) {}\r\n\r\n public async runAsync<T>(context: RequestContext, fn: () => Promise<T>): Promise<T> {\r\n const scope = this._factoryScope.create()\r\n try {\r\n return await this._storage.run({ context, scope }, fn)\r\n } finally {\r\n await scope.dispose()\r\n }\r\n }\r\n\r\n public updateIdentity(identity: Identity): void {\r\n const store = this._storage.getStore()\r\n if (Guards.isDefined(store) && Guards.isDefined(store.context)) {\r\n store.context = Object.freeze({\r\n ...store.context,\r\n identity: Object.freeze(identity),\r\n })\r\n }\r\n }\r\n\r\n public getContext(): Optional<RequestContext> {\r\n const store = this._storage.getStore()\r\n if (!Guards.isDefined(store)) return undefined\r\n const context = store.context\r\n return Object.freeze(context)\r\n }\r\n\r\n public getIdentity(): Optional<Identity> {\r\n const store = this._storage.getStore()\r\n if (!Guards.isDefined(store)) return undefined\r\n return Object.freeze(store.context?.identity)\r\n }\r\n\r\n public getScope(): Optional<IServiceScope<TRegistry>> {\r\n const store = this._storage.getStore()\r\n if (!Guards.isDefined(store)) return undefined\r\n return store.scope\r\n }\r\n\r\n public getNetworkContext(): Optional<NetworkContext> {\r\n const store = this._storage.getStore()\r\n if (!Guards.isDefined(store)) return undefined\r\n return Object.freeze(store.context?.network)\r\n }\r\n}\r\n","import { AsyncLocalStorage } from 'node:async_hooks'\r\n\r\nimport type { IFactory, RequestContext } from '@xeno-js/shared'\r\n\r\nimport type { ExecutionContext, IRequestContext, IServiceScope } from '@/domain'\r\n\r\nimport { NodeRequestContext } from '../context/request-context'\r\nimport type { XenoRegistry } from '../xeno-registry'\r\n\r\n/**\r\n * @description Factory class responsible for creating instances of NodeRequestContext. It implements the IFactory interface, allowing for easy integration with dependency injection systems. The factory encapsulates the creation logic for the NodeRequestContext, promoting separation of concerns and flexibility in managing request context instances across the application.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class NodeRequestContextFactory<TRegistry extends XenoRegistry> implements IFactory<\r\n void,\r\n IRequestContext<RequestContext, TRegistry>\r\n> {\r\n private _store: AsyncLocalStorage<ExecutionContext<TRegistry>> = new AsyncLocalStorage<\r\n ExecutionContext<TRegistry>\r\n >()\r\n\r\n constructor(private readonly _factoryScope: IFactory<void, IServiceScope<TRegistry>>) {}\r\n\r\n public create(): IRequestContext<RequestContext, TRegistry> {\r\n return new NodeRequestContext<TRegistry>(this._store, this._factoryScope)\r\n }\r\n}\r\n","import type { IFactory } from '@xeno-js/shared'\r\n\r\nimport type { IServiceContainer, IServiceScope } from '@/domain'\r\n\r\nimport type { XenoRegistry } from '../xeno-registry'\r\n\r\n/**\r\n * @description Factory class responsible for creating instances of IServiceScope. It implements the IFactory interface, allowing for easy integration with dependency injection systems. The factory encapsulates the creation logic for the IServiceScope, promoting separation of concerns and allowing for flexibility in managing IServiceScope instances across the application.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class ServiceScopeFactory<T extends XenoRegistry = XenoRegistry> implements IFactory<\r\n void,\r\n IServiceScope<T>\r\n> {\r\n constructor(private readonly _container: IServiceContainer<T>) {}\r\n\r\n public create(): IServiceScope<T> {\r\n return this._container.createScope()\r\n }\r\n}\r\n","import { createClient } from '@libsql/client'\r\nimport type { DbConfig, IFactory } from '@xeno-js/shared'\r\nimport type { Dictionary } from '@xeno-js/shared'\r\nimport { drizzle } from 'drizzle-orm/libsql'\r\n\r\nimport type { DbContext } from '../db/db.types'\r\n\r\n/**\r\n * @description Factory class responsible for creating instances of IDbClient based on the provided configuration. It implements the IFactory interface, allowing for easy integration with dependency injection systems. The factory encapsulates the creation logic for the IDbClient, including the initialization of the underlying database client with the specified configuration options such as connection string and table mappings. This design promotes separation of concerns and allows for flexibility in managing IDbClient instances across the application.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class DbSqlLiteClientFactory implements IFactory<DbConfig, DbContext<Dictionary>> {\r\n public create(opts: DbConfig): DbContext<Dictionary> {\r\n const client = createClient({ url: opts.connectionString })\r\n return drizzle({ client })\r\n }\r\n}\r\n","import { createServerClient } from '@supabase/ssr'\r\nimport type { SupabaseClientOptions } from '@supabase/supabase-js'\r\nimport type { IExtendendService, IFactory } from '@xeno-js/shared'\r\nimport {\r\n Guards,\r\n SupabaseAuthService,\r\n SupabaseClaimsMapper,\r\n SupabaseSessionMapper,\r\n} from '@xeno-js/shared'\r\n\r\nimport type { AuthSsrConfig, IServiceContainer } from '@/domain'\r\n\r\nimport type { XenoRegistry } from '../xeno-registry'\r\n\r\ninterface SupabaseServerAuthFactoryInput<TRegistry extends XenoRegistry> {\r\n config: AuthSsrConfig<SupabaseClientOptions<'public'>>\r\n container: IServiceContainer<TRegistry>\r\n}\r\n\r\nexport class SupabaseServerAuthFactory<\r\n TRegistry extends XenoRegistry = XenoRegistry,\r\n> implements IFactory<SupabaseServerAuthFactoryInput<TRegistry>, IExtendendService> {\r\n public create({\r\n config,\r\n container,\r\n }: SupabaseServerAuthFactoryInput<TRegistry>): IExtendendService {\r\n if (!Guards.isDefined(config.ssrOpts)) {\r\n throw new Error('ISsrCookieHandler is required for @supabase/ssr initialization.')\r\n }\r\n\r\n const cookieService = config.ssrOpts(container)\r\n const client = createServerClient(config.url, config.key, {\r\n ...config.opts,\r\n cookies: {\r\n getAll() {\r\n return cookieService.getAll()\r\n },\r\n setAll(cookiesToSet) {\r\n // Mappa array di cookie in entrata verso il gestore agnostico del backend\r\n cookieService.setAll(cookiesToSet)\r\n },\r\n },\r\n })\r\n\r\n const mapper = new SupabaseClaimsMapper()\r\n const sessionMapper = new SupabaseSessionMapper(mapper)\r\n\r\n return new SupabaseAuthService(client, mapper, sessionMapper, config)\r\n }\r\n}\r\n","import type { IFactory, IIdentityAccessor } from '@xeno-js/shared'\r\nimport type { Guid, Optional, UserContext } from '@xeno-js/shared'\r\nimport { Guards } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description Factory class responsible for creating instances of UserContext. It implements the IFactory interface, allowing for easy integration with dependency injection systems. The factory encapsulates the creation logic for the UserContext, promoting separation of concerns and flexibility in managing user context instances across the application.\r\n *\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class UserContextFactory implements IFactory<void, UserContext> {\r\n /**\r\n * @description Constructs an instance of UserContextFactory.\r\n * @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.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n constructor(private readonly _identityFactory: IIdentityAccessor) {}\r\n\r\n public create(): UserContext {\r\n const output: { userId: Optional<Guid>; tenantId: Optional<Guid> } = {\r\n userId: undefined,\r\n tenantId: undefined,\r\n }\r\n\r\n const identity = this._identityFactory.getIdentity()\r\n\r\n if (Guards.isDefined(identity)) {\r\n output.userId = identity.userId\r\n output.tenantId = identity.tenantId\r\n }\r\n\r\n return output\r\n }\r\n}\r\n","import type { IFactory, ILogger, IValidatorService } from '@xeno-js/shared'\r\nimport { ZodValidatorService } from '@xeno-js/shared'\r\nimport type { ZodType } from 'zod'\r\n\r\nimport type { SchemaConfig } from '@/domain'\r\n\r\n/**\r\n * @description Factory class responsible for creating instances of ZodValidatorService based on the provided configuration. It implements the IFactory interface, allowing for easy integration with dependency injection systems. The factory encapsulates the creation logic for the ZodValidatorService, including the initialization of the underlying ZodValidatorService instance with the specified configuration options such as URL and API key. This design promotes separation of concerns and allows for flexibility in managing ZodValidatorService instances across the application.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class ZodValidatorFactory implements IFactory<\r\n SchemaConfig<ZodType> & { logger: ILogger },\r\n IValidatorService\r\n> {\r\n public create(opts: SchemaConfig<ZodType> & { logger: ILogger }): IValidatorService {\r\n const validatorService = new ZodValidatorService(new Map(), opts.logger)\r\n\r\n // 2. Iteriamo sugli schemi passati nella configurazione e li registriamo (Ora in modo sincrono!)\r\n for (const [intentKey, schema] of Object.entries(opts.schemas)) {\r\n validatorService.addSchema(intentKey, schema)\r\n }\r\n\r\n return validatorService\r\n }\r\n}\r\n","export * from './allow-method.factory'\r\nexport * from './axios.factory'\r\nexport * from './cockatiel-resilience.factory'\r\nexport * from './db-client.factory'\r\nexport * from './pino-logger.factory'\r\nexport * from './redis-cache.factory'\r\nexport * from './request-context.factory'\r\nexport * from './sentry-logger.factory'\r\nexport * from './service-scope.factory'\r\nexport * from './sql-light-db-client.factory'\r\nexport * from './supabase.factory'\r\nexport * from './user-context.factory'\r\nexport * from './zod-validator.factory'\r\n","import type { SupabaseClientOptions } from '@supabase/supabase-js'\r\nimport type { IRequest, IStrategy } from '@xeno-js/shared'\r\nimport type { ZodType } from 'zod'\r\n\r\nimport type { AuthSsrConfig, IServiceContainer, PipelineConfig } from '@/domain'\r\nimport type { XenoRegistry } from '@/infrastructure'\r\n\r\n/**\r\n * @description Utility functions for configuring authentication and authorization in the service container.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport const AuthUtils = Object.freeze({\r\n /**\r\n * @description Checks if the provided authorization configuration requires any authorization strategies.\r\n * @param authorizationConfig The authorization configuration to check.\r\n * @returns True if any authorization strategies are required, false otherwise.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n\r\n async addAuthZ<TRegistry extends XenoRegistry = XenoRegistry>(\r\n container: IServiceContainer<TRegistry>,\r\n opts: PipelineConfig<TRegistry, ZodType>['authorization'],\r\n ): Promise<(keyof TRegistry)[]> {\r\n const { TOKENS } = await import('@xeno-js/shared')\r\n const pipelines: (keyof TRegistry)[] = []\r\n type StrategiesToken = keyof TRegistry\r\n const strategies: StrategiesToken[] = []\r\n\r\n const { Guards } = await import('@xeno-js/shared')\r\n if (Guards.isDefined(opts.policies)) {\r\n const { PolicyRegistry } = await import('@/application')\r\n container.addSingleton(TOKENS.POLICY_REGISTRY, () => new PolicyRegistry())\r\n\r\n const policyRegistry = opts.policies\r\n const registryInstance = container.resolve(TOKENS.POLICY_REGISTRY)\r\n const Policies = new Set<string>()\r\n for (const [intent, policy] of Object.entries(policyRegistry)) {\r\n const intentLower = intent.toLowerCase()\r\n registryInstance.addPolicy(intentLower, policy)\r\n\r\n if (!Guards.isNullOrEmpty(policy.roles)) {\r\n Policies.add('roles')\r\n }\r\n\r\n if (!Guards.isNullOrEmpty(policy.permissions)) {\r\n Policies.add('permissions')\r\n }\r\n\r\n if (!Guards.isNullOrEmpty(policy.userId)) {\r\n Policies.add('userId')\r\n }\r\n\r\n if (!Guards.isNullOrEmpty(policy.tenantId)) {\r\n Policies.add('tenantId')\r\n }\r\n }\r\n\r\n if (Policies.has('roles')) {\r\n const { RoleAuthorizationStrategy } = await import('@/application')\r\n container.addSingleton(\r\n TOKENS.ROLE_AUTHORIZATION_PIPELINE,\r\n (c) =>\r\n new RoleAuthorizationStrategy(\r\n c.resolve(TOKENS.POLICY_REGISTRY),\r\n c.resolve(TOKENS.CONTEXT_ACCESSOR),\r\n ),\r\n )\r\n strategies.push(TOKENS.ROLE_AUTHORIZATION_PIPELINE)\r\n }\r\n\r\n if (Policies.has('permissions')) {\r\n const { PermissionAuthorizationStrategy } = await import('@/application')\r\n container.addSingleton(\r\n TOKENS.PERMISSION_AUTHORIZATION_PIPELINE,\r\n (c) =>\r\n new PermissionAuthorizationStrategy(\r\n c.resolve(TOKENS.POLICY_REGISTRY),\r\n c.resolve(TOKENS.CONTEXT_ACCESSOR),\r\n ),\r\n )\r\n strategies.push(TOKENS.PERMISSION_AUTHORIZATION_PIPELINE)\r\n }\r\n\r\n if (Policies.has('userId')) {\r\n const { UserAuthorizationStrategy } = await import('@/application')\r\n container.addSingleton(\r\n TOKENS.USER_AUTHORIZATION_PIPELINE,\r\n (c) =>\r\n new UserAuthorizationStrategy(\r\n c.resolve(TOKENS.POLICY_REGISTRY),\r\n c.resolve(TOKENS.CONTEXT_ACCESSOR),\r\n ),\r\n )\r\n strategies.push(TOKENS.USER_AUTHORIZATION_PIPELINE)\r\n }\r\n\r\n if (Policies.has('tenantId')) {\r\n const { TenantAuthorizationStrategy } = await import('@/application')\r\n container.addSingleton(\r\n TOKENS.TENANT_AUTHORIZATION_PIPELINE,\r\n (c) =>\r\n new TenantAuthorizationStrategy(\r\n c.resolve(TOKENS.POLICY_REGISTRY),\r\n c.resolve(TOKENS.CONTEXT_ACCESSOR),\r\n ),\r\n )\r\n strategies.push(TOKENS.TENANT_AUTHORIZATION_PIPELINE)\r\n }\r\n }\r\n\r\n if (!Guards.isNullOrEmpty(opts.customAuthorizationStrategy)) {\r\n const customStrategies = opts.customAuthorizationStrategy\r\n customStrategies.forEach((strategyToken, index) => {\r\n if (Guards.isDefined(strategyToken)) {\r\n const token = `CUSTOM_AUTHORIZATION_STRATEGY_${index}` as keyof TRegistry\r\n\r\n container.addSingleton(token, (c) => {\r\n return strategyToken(c) as unknown as TRegistry[typeof token]\r\n })\r\n strategies.push(token)\r\n }\r\n })\r\n }\r\n\r\n const { AuthorizationPipeline } = await import('@/application')\r\n container.addSingleton(TOKENS.AUTHORIZATION_PIPELINE, (c) => {\r\n const resolvedStrategies = strategies.map(\r\n (strategy) => c.resolve(strategy) as unknown as IStrategy<IRequest, void>,\r\n )\r\n return new AuthorizationPipeline(resolvedStrategies)\r\n })\r\n pipelines.push(TOKENS.AUTHORIZATION_PIPELINE)\r\n return pipelines\r\n },\r\n\r\n /**\r\n * @description Configures the authentication service and gatekeeper in the service container.\r\n * @param container The service container to configure.\r\n * @param opts The authentication configuration options.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n async addAuthN<TRegistry extends XenoRegistry = XenoRegistry>(\r\n container: IServiceContainer<TRegistry>,\r\n opts: AuthSsrConfig<SupabaseClientOptions<'public'>>,\r\n ): Promise<void> {\r\n const { TOKENS } = await import('@xeno-js/shared')\r\n const _t = opts\r\n const { SupabaseServerAuthFactory } = await import('../../factories')\r\n container.addScoped(TOKENS.AUTH_SERVICE, () => {\r\n const factory = new SupabaseServerAuthFactory()\r\n return factory.create({ config: opts, container })\r\n })\r\n\r\n container.addSingleton(TOKENS.BASE_AUTH_SERVICE, () => {\r\n const factory = new SupabaseServerAuthFactory()\r\n return factory.create({ config: opts, container })\r\n })\r\n\r\n const { ClaimsIdentityMapper } = await import('@/application')\r\n container.addSingleton(TOKENS.CLAIMS_IDENTITY_MAPPER, () => new ClaimsIdentityMapper())\r\n\r\n const { GateKeeper } = await import('@/application')\r\n container.addSingleton(TOKENS.GATE_KEEPER, (c) => {\r\n return new GateKeeper(\r\n c.resolve(TOKENS.BASE_AUTH_SERVICE),\r\n c.resolve(TOKENS.CLAIMS_IDENTITY_MAPPER),\r\n )\r\n })\r\n },\r\n} as const)\r\n","import type { DbConfig } from '@xeno-js/shared'\r\nimport type { Dictionary } from '@xeno-js/shared'\r\n\r\nimport type { DbContext } from '../../db/db.types'\r\n\r\n/**\r\n * @description Utility functions for database operations, including the creation of database clients based on configuration options. These utilities provide a convenient way to initialize and manage database connections, supporting both SQLite and other database engines as specified in the configuration.\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport const DbUtils = Object.freeze({\r\n /**\r\n * @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.\r\n *\r\n * @param opts - The database configuration options, including the connection string and any other relevant settings required for establishing a connection to the SQLite database.\r\n * @returns A new instance of a database client configured for SQLite, ready for use in the application.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n async addSqlLite(opts: DbConfig): Promise<DbContext<Dictionary>> {\r\n const { DbSqlLiteClientFactory } = await import('../../factories/sql-light-db-client.factory')\r\n return new DbSqlLiteClientFactory().create(opts)\r\n },\r\n\r\n /**\r\n * @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.\r\n * @param opts - The database configuration options, including the connection string and any other relevant settings required for establishing a connection to the database.\r\n * @returns A new instance of a database client, ready for use in the application.\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n async addDbClient(opts: DbConfig): Promise<DbContext<Dictionary>> {\r\n const { DbClientFactory } = await import('../../factories/db-client.factory')\r\n return new DbClientFactory().create(opts)\r\n },\r\n})\r\n","import type { ITransactionState, Maybe } from '@xeno-js/shared'\r\n\r\n/**\r\n * @file transaction-state.ts\r\n * @description This file contains the definition of the TransactionState class.\r\n * @version 1.0.0\r\n * @author Xeno\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class TransactionState<T> implements ITransactionState<T> {\r\n /**\r\n * The current state of the transaction, which can be either a specific transaction type or null.\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n private _state: Maybe<T> = null\r\n\r\n /**\r\n * Creates an instance of TransactionState.\r\n * @param initialState - The initial state of the transaction, which can be either a specific transaction type or null.\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n constructor(initialState: Maybe<T> = null) {\r\n this._state = initialState\r\n }\r\n\r\n get state(): Maybe<T> {\r\n return this._state\r\n }\r\n\r\n set state(value: Maybe<T>) {\r\n this._state = value\r\n }\r\n}\r\n","import type { IDisposable, ITransactionState, IUnitOfWork } from '@xeno-js/shared'\r\nimport { AppError } from '@xeno-js/shared'\r\nimport { Guards, type Optional } from '@xeno-js/shared'\r\n\r\nimport type { DbContext, DbTransaction } from '../db/db.types'\r\n\r\n/**\r\n * @file unit-of-work.ts\r\n * @description This file contains the implementation of the Unit of Work pattern.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class UnitOfWork implements IUnitOfWork, IDisposable {\r\n /**\r\n * Creates an instance of UnitOfWork.\r\n * @param _dbContext - The database context used for managing transactions.\r\n * @param _ttx - The transaction state, which can be either a specific transaction type or null.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n constructor(\r\n private readonly _dbContext: DbContext,\r\n private readonly _ttx: ITransactionState<DbTransaction>,\r\n ) {}\r\n\r\n async runInTransaction<T>(callback: () => Promise<T>, signal: Optional<AbortSignal>): Promise<T> {\r\n AppError.throwIfAborted(signal, 'UnitOfWork.runInTransaction')\r\n\r\n return this._dbContext.transaction(async (tx) => {\r\n this._ttx.state = tx\r\n try {\r\n const result = await callback()\r\n return result\r\n } finally {\r\n this._ttx.state = null\r\n }\r\n })\r\n }\r\n\r\n async dispose(): Promise<void> {\r\n if (Guards.isDefined(this._ttx.state)) {\r\n try {\r\n if (Guards.hasMethod(this._ttx.state, 'rollback')) {\r\n await (this._ttx.state as DbContext & { rollback: () => Promise<void> }).rollback()\r\n }\r\n } finally {\r\n this._ttx.state = null\r\n }\r\n }\r\n }\r\n}\r\n","import type { DbConfig } from '@xeno-js/shared'\r\n\r\nimport type { IModule, IServiceContainer } from '@/domain'\r\n\r\nimport type { DbContext, DbTransaction } from '../db/db.types'\r\nimport type { XenoRegistry } from '../xeno-registry'\r\n\r\n/**\r\n * @description The DbModule class is responsible for configuring the database module within the application. It implements the IModule interface, allowing it to be integrated into the application's dependency injection system. The configure method registers a singleton factory for creating an IDbClient instance using the provided configuration options. This design promotes modularity and allows for easy management of database connections and operations throughout the application.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class DbModule<TRegistry extends XenoRegistry = XenoRegistry> implements IModule<\r\n TRegistry,\r\n DbConfig\r\n> {\r\n async configure(container: IServiceContainer<TRegistry>, opts: DbConfig): Promise<void> {\r\n const { Guards, TOKENS } = await import('@xeno-js/shared')\r\n\r\n const { DbUtils } = await import('./utils/db.utils')\r\n const db = opts.enableSqlLite ? await DbUtils.addSqlLite(opts) : await DbUtils.addDbClient(opts)\r\n\r\n const { TransactionState } = await import('../transaction/transaction-state')\r\n\r\n container.addScoped(TOKENS.TRANSACTION_STATE, () => {\r\n return new TransactionState<DbTransaction>()\r\n })\r\n\r\n const { UnitOfWork } = await import('../transaction/unit-of-work')\r\n container.addScoped(TOKENS.UNIT_OF_WORK, (c) => {\r\n const ttx = c.resolve(TOKENS.TRANSACTION_STATE)\r\n return new UnitOfWork(db, ttx)\r\n })\r\n\r\n container.addScoped(TOKENS.DB_CONTEXT, (c) => {\r\n const ttx = c.resolve(TOKENS.TRANSACTION_STATE)\r\n\r\n return new Proxy(db, {\r\n get(_target, prop, receiver) {\r\n const activeState = ttx.state\r\n if (Guards.isDefined(activeState)) {\r\n if (prop === 'transaction') {\r\n return activeState.transaction.bind(activeState)\r\n }\r\n return Reflect.get(activeState, prop, receiver) as DbContext\r\n }\r\n return Reflect.get(db, prop, receiver) as DbContext\r\n },\r\n })\r\n })\r\n }\r\n}\r\n","import type { HttpConfig, IServiceContainer, ResilienceConfig } from '@/domain'\r\n\r\nimport type { XenoRegistry } from '../../xeno-registry'\r\n\r\n/**\r\n * @description Utility functions for configuring HTTP clients and resilience features in the service container.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport const HttpUtils = Object.freeze({\r\n /**\r\n * @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.\r\n * @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.\r\n * @returns A string representing the encoded query string that can be appended to a URL for making HTTP requests.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n async addAxios<TRegistry extends XenoRegistry = XenoRegistry>(\r\n container: IServiceContainer<TRegistry>,\r\n opts: HttpConfig<TRegistry>,\r\n ): Promise<void> {\r\n const { NodeAxiosFactory } = await import('../../factories')\r\n const { Guards } = await import('@xeno-js/shared')\r\n if (!Guards.isDefined(opts.token)) {\r\n throw new Error('HttpConfig.token is required and must be defined.')\r\n }\r\n\r\n container.addSingleton(opts.token, () => {\r\n const factory = new NodeAxiosFactory()\r\n const instance = factory.create(opts.client)\r\n if (\r\n !Guards.hasMethod(instance, 'get') ||\r\n !Guards.hasMethod(instance, 'post') ||\r\n !Guards.hasMethod(instance, 'put') ||\r\n !Guards.hasMethod(instance, 'patch') ||\r\n !Guards.hasMethod(instance, 'delete')\r\n ) {\r\n throw new Error(\r\n 'The created HTTP client instance does not implement the required methods of IHttpClient.',\r\n )\r\n }\r\n return instance as unknown as TRegistry[typeof opts.token]\r\n })\r\n },\r\n /**\r\n * @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.\r\n * @param container - The service container to register the resilience client with.\r\n * @param opts - The ResilienceConfig options that determine whether resilience features are enabled and provide the necessary settings for implementing resilience strategies.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n async addResilience<TRegistry extends XenoRegistry = XenoRegistry>(\r\n container: IServiceContainer<TRegistry>,\r\n opts: ResilienceConfig,\r\n ): Promise<void> {\r\n const { TOKENS } = await import('@xeno-js/shared')\r\n const { CockatielResilienceFactory } = await import('../../factories')\r\n container.addSingleton(TOKENS.RESILIENCE_CLIENT, () => {\r\n const factory = new CockatielResilienceFactory()\r\n return factory.create(opts)\r\n })\r\n },\r\n\r\n async addAllowOrigin<TRegistry extends XenoRegistry = XenoRegistry>(\r\n container: IServiceContainer<TRegistry>,\r\n opts: string[],\r\n ): Promise<void> {\r\n const { Guards } = await import('@xeno-js/shared')\r\n if (Guards.isNullOrEmpty(opts)) throw new Error('At least an allow origin must be passed')\r\n\r\n const { TOKENS } = await import('@xeno-js/shared')\r\n const { AllowOrigin } = await import('../../services')\r\n const allowOrigin: string[] = []\r\n\r\n opts.forEach((x) => {\r\n allowOrigin.push(x.trim().toLowerCase())\r\n })\r\n\r\n container.addSingleton(TOKENS.ALLOW_ORIGIN, () => new AllowOrigin(allowOrigin))\r\n },\r\n} as const)\r\n","import type { HttpCoreConfig, IModule, IServiceContainer } from '@/domain'\r\n\r\nimport type { XenoRegistry } from '../xeno-registry'\r\n\r\n/**\r\n * @description HttpCoreModule is responsible for configuring the core HTTP functionalities of the application. It implements the IModule interface, allowing it to be integrated into the application's dependency injection system. The configure method registers essential services such as the HTTP client and resilience features based on the provided configuration options. This design promotes modularity and allows for easy management of HTTP-related operations throughout the application.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class HttpCoreModule<TRegistry extends XenoRegistry = XenoRegistry> implements IModule<\r\n TRegistry,\r\n HttpCoreConfig<TRegistry>\r\n> {\r\n async configure(\r\n container: IServiceContainer<TRegistry>,\r\n opts: HttpCoreConfig<TRegistry>,\r\n ): Promise<void> {\r\n const { HttpUtils } = await import('./utils/http.utils')\r\n await HttpUtils.addAxios(container, opts.http)\r\n await HttpUtils.addResilience(container, opts.resilience)\r\n }\r\n}\r\n\r\nexport class HttpOriginModule<TRegistry extends XenoRegistry = XenoRegistry> implements IModule<\r\n TRegistry,\r\n string[]\r\n> {\r\n async configure(container: IServiceContainer<TRegistry>, opts: string[]): Promise<void> {\r\n const { HttpUtils } = await import('./utils/http.utils')\r\n await HttpUtils.addAllowOrigin(container, opts)\r\n }\r\n}\r\n","import type { ILogger, IRequest, IStrategy } from '@xeno-js/shared'\r\nimport type { KeysOfType } from '@xeno-js/shared'\r\nimport type { ZodType } from 'zod'\r\n\r\nimport type {\r\n ApplicationRegistry,\r\n IServiceContainer,\r\n IServiceScope,\r\n PipelineConfig,\r\n} from '@/domain'\r\n\r\nimport type { XenoRegistry } from '../../xeno-registry'\r\n\r\n/**\r\n * @description ValidationUtils is a utility class that provides methods for adding validation strategies to the dependency injection container based on the provided configuration. It checks if the validation configuration is defined and, if so, it registers the appropriate validation strategies (such as Zod schema validation) in the container and adds them to the pipeline behaviors. This allows for flexible and configurable validation of requests in the application.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport const ValidationUtils = Object.freeze({\r\n /**\r\n * @description Checks if the provided validation configuration requires any validation strategies.\r\n * @param validationConfig The validation configuration to check.\r\n * @returns True if any validation strategies are required, false otherwise.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n\r\n async addValidation<TRegistry extends XenoRegistry = XenoRegistry>(\r\n container: IServiceContainer<TRegistry>,\r\n opts: PipelineConfig<TRegistry, ZodType>['validation'],\r\n logger: ILogger,\r\n ): Promise<(keyof TRegistry)[]> {\r\n const { Guards, TOKENS } = await import('@xeno-js/shared')\r\n\r\n if (!Guards.isDefined(opts.zod) && Guards.isNullOrEmpty(opts.customValidationStrategy)) {\r\n return []\r\n }\r\n\r\n const pipelines: (keyof TRegistry)[] = []\r\n const validationStrategies: KeysOfType<\r\n ApplicationRegistry<unknown>,\r\n IStrategy<IRequest, boolean>\r\n >[] = []\r\n\r\n if (Guards.isDefined(opts.zod)) {\r\n const config = opts.zod\r\n const { ZodValidatorFactory } = await import('../../factories/zod-validator.factory')\r\n container.addSingleton(TOKENS.ZOD_VALIDATOR, () => {\r\n return new ZodValidatorFactory().create({ ...config, logger })\r\n })\r\n\r\n const { SchemaValidationStrategy } = await import('@/application')\r\n container.addSingleton(\r\n TOKENS.SCHEMA_VALIDATION_STRATEGY,\r\n (c) => new SchemaValidationStrategy(c.resolve(TOKENS.ZOD_VALIDATOR)),\r\n )\r\n validationStrategies.push(TOKENS.SCHEMA_VALIDATION_STRATEGY)\r\n }\r\n const customValidationFactory: ((\r\n c: IServiceScope<TRegistry>,\r\n ) => IStrategy<IRequest, boolean>)[] = []\r\n\r\n if (!Guards.isNullOrEmpty(opts.customValidationStrategy)) {\r\n for (const strategyToken of opts.customValidationStrategy) {\r\n if (Guards.isDefined(strategyToken)) {\r\n customValidationFactory.push(strategyToken)\r\n }\r\n }\r\n }\r\n\r\n const { ValidationPipeline } = await import('@/application')\r\n container.addSingleton(TOKENS.VALIDATION_PIPELINE, (c) => {\r\n const resolvedStrategies = [\r\n ...validationStrategies.map((token) => c.resolve(token)),\r\n ...customValidationFactory.map((factory) => factory(c)),\r\n ]\r\n return new ValidationPipeline(resolvedStrategies)\r\n })\r\n\r\n pipelines.push(TOKENS.VALIDATION_PIPELINE)\r\n return pipelines\r\n },\r\n} as const)\r\n","import type { ICache, ICacheKeyBuilder, IIdempotencyStore } from '@xeno-js/shared'\r\nimport type { Optional } from '@xeno-js/shared'\r\nimport { IDEMPOTENCY_CONSTANTS } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description The IdempotencyStore class provides an implementation of the IIdempotencyStore interface, utilizing a caching mechanism to manage locks and processed command results for idempotent operations. This class is designed to ensure that commands with the same ID are processed only once, preventing duplicate processing and allowing for retrieval of results from previously processed commands. The IdempotencyStore uses the IRequestContext to build contextual keys for storing locks and results in a multi-tenant environment, following the AWS SaaS Factory Pattern for logical partitioning. By leveraging the ICache interface, the IdempotencyStore can efficiently manage locks and stored results with configurable time-to-live (TTL) values, ensuring that stale data is automatically cleaned up over time.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class IdempotencyStore implements IIdempotencyStore {\r\n /**\r\n * @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.\r\n * @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.\r\n * @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.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n constructor(\r\n private readonly _cache: ICache,\r\n private readonly _cacheKeyBuilder: ICacheKeyBuilder,\r\n ) {}\r\n\r\n public async acquireLock(requestId: string, ttlSeconds: number): Promise<boolean> {\r\n const key = this._cacheKeyBuilder.buildContextualKey(`command:${requestId}`)\r\n return await this._cache.setIfAbsent(\r\n `${IDEMPOTENCY_CONSTANTS.LOCK_KEY_PREFIX}${key}`,\r\n IDEMPOTENCY_CONSTANTS.LOCKED_VALUE,\r\n ttlSeconds,\r\n )\r\n }\r\n\r\n public async hasBeenProcessed(commandId: string): Promise<boolean> {\r\n const key = this._cacheKeyBuilder.buildContextualKey(`command:${commandId}`)\r\n return await this._cache.has(`${IDEMPOTENCY_CONSTANTS.PROCESSED_KEY_PREFIX}${key}`)\r\n }\r\n\r\n public async markAsProcessed<T>(\r\n commandId: string,\r\n payload: T,\r\n ttlSeconds: number,\r\n ): Promise<void> {\r\n const key = this._cacheKeyBuilder.buildContextualKey(`command:${commandId}`)\r\n await this._cache.set(\r\n `${IDEMPOTENCY_CONSTANTS.PROCESSED_KEY_PREFIX}${key}`,\r\n payload,\r\n ttlSeconds,\r\n )\r\n }\r\n\r\n public async getPayload<T>(commandId: string): Promise<Optional<T>> {\r\n const key = this._cacheKeyBuilder.buildContextualKey(`command:${commandId}`)\r\n const payload = await this._cache.get<T>(`${IDEMPOTENCY_CONSTANTS.PROCESSED_KEY_PREFIX}${key}`)\r\n\r\n return payload\r\n }\r\n\r\n public async releaseLock(commandId: string): Promise<void> {\r\n const key = this._cacheKeyBuilder.buildContextualKey(`command:${commandId}`)\r\n await this._cache.remove(`${IDEMPOTENCY_CONSTANTS.LOCK_KEY_PREFIX}${key}`)\r\n }\r\n}\r\n","import type { IServiceContainer, PipelineConfig } from '@/domain'\r\n\r\nimport type { XenoRegistry } from '../../xeno-registry'\r\n\r\n/**\r\n * @description Utility functions for configuring command and query pipelines in the service container.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport const PipelineUtils = Object.freeze({\r\n /**\r\n * @description Checks if the provided command configuration requires any command strategies.\r\n * @param commandConfig The command configuration to check.\r\n * @returns True if any command strategies are required, false otherwise.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n async addCommand<TRegistry extends XenoRegistry = XenoRegistry>(\r\n container: IServiceContainer<TRegistry>,\r\n opts: PipelineConfig<TRegistry>['commandBus'] & { isCache: boolean },\r\n ): Promise<(keyof TRegistry)[]> {\r\n const pipelines: (keyof TRegistry)[] = []\r\n const { Guards, TOKENS } = await import('@xeno-js/shared')\r\n if (Guards.isDefined(opts.idempotency)) {\r\n const { IdempotencyStore } = await import('../../idempotency/idempotency-store')\r\n container.addSingleton(\r\n TOKENS.IDEMPOTENCY_STORE,\r\n (c) => new IdempotencyStore(c.resolve(TOKENS.CACHE), c.resolve(TOKENS.CACHE_KEY_BUILDER)),\r\n )\r\n\r\n const { IdempotencyPipeline } = await import('@/application')\r\n container.addSingleton(TOKENS.IDEMPOTENCY_PIPELINE, (c) => {\r\n const requestContext = c.resolve(TOKENS.NETWORK_CONTEXT_ACCESSOR)\r\n const idempotencyStore = c.resolve(TOKENS.IDEMPOTENCY_STORE)\r\n const config = opts.idempotency\r\n return new IdempotencyPipeline(\r\n requestContext,\r\n idempotencyStore,\r\n config?.lockTtlSeconds,\r\n config?.processedTtlSeconds,\r\n )\r\n })\r\n pipelines.push(TOKENS.IDEMPOTENCY_PIPELINE)\r\n }\r\n\r\n if (Guards.isDefined(opts.concurrency)) {\r\n const { ConcurrencyRetryPipeline } = await import('@/application')\r\n container.addSingleton(TOKENS.CONCURRENCY_RETRY_PIPELINE, () => {\r\n const config = opts.concurrency\r\n return new ConcurrencyRetryPipeline(config?.maxRetries, config?.delayConfig)\r\n })\r\n pipelines.push(TOKENS.CONCURRENCY_RETRY_PIPELINE)\r\n }\r\n return pipelines\r\n },\r\n /**\r\n * @description Checks if the provided query configuration requires any query strategies.\r\n * @param queryConfig The query configuration to check.\r\n * @returns True if any query strategies are required, false otherwise.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n async addQuery<TRegistry extends XenoRegistry = XenoRegistry>(\r\n container: IServiceContainer<TRegistry>,\r\n opts: { isCache: boolean },\r\n ): Promise<(keyof TRegistry)[]> {\r\n const { TOKENS } = await import('@xeno-js/shared')\r\n const pipelines: (keyof TRegistry)[] = []\r\n\r\n if (!opts.isCache) {\r\n const { CacheUtils } = await import('./cache.utils')\r\n await CacheUtils.addCache(container, { inMemory: true, redis: undefined })\r\n }\r\n\r\n const { QueryCachingPipeline } = await import('@/application')\r\n container.addSingleton(\r\n TOKENS.QUERY_CACHING_PIPELINE,\r\n (c) =>\r\n new QueryCachingPipeline(\r\n c.resolve(TOKENS.CACHE),\r\n c.resolve(TOKENS.CACHE_KEY_BUILDER),\r\n c.resolve(TOKENS.LOGGER),\r\n ),\r\n )\r\n pipelines.push(TOKENS.QUERY_CACHING_PIPELINE)\r\n return pipelines\r\n },\r\n} as const)\r\n","import type { ICommand, IPipelineBehavior, IQuery } from '@xeno-js/shared'\r\nimport type { ZodType } from 'zod'\r\n\r\nimport type { IModule, IServiceContainer, IServiceScopeAccessor, PipelineConfig } from '@/domain'\r\n\r\nimport type { XenoRegistry } from '../xeno-registry'\r\n\r\n/**\r\n * @description CqrsModule is responsible for configuring and registering the necessary services and dependencies related to the Command Query Responsibility Segregation (CQRS) pattern in the application. It sets up the Mediator service, which acts as a central hub for handling commands and queries, allowing for a clean separation of concerns between the command and query sides of the application. By registering the Mediator in the dependency injection container, it enables other parts of the application to easily resolve and utilize its functionality for processing commands and queries.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class CqrsModule<TRegistry extends XenoRegistry = XenoRegistry> implements IModule<\r\n TRegistry,\r\n PipelineConfig<TRegistry, ZodType>\r\n> {\r\n async configure(\r\n container: IServiceContainer<TRegistry>,\r\n opts: PipelineConfig<TRegistry, ZodType> & { isLogger: boolean; isCache: boolean },\r\n ): Promise<void> {\r\n const { TOKENS } = await import('@xeno-js/shared')\r\n let isCache = opts.isCache\r\n\r\n const { Mediator } = await import('@/application')\r\n container.addSingleton(TOKENS.MEDIATOR, (c) => {\r\n const serviceScopeAccessor = c.resolve(TOKENS.SERVICE_SCOPE_ACCESSOR)\r\n return new Mediator<TRegistry>(serviceScopeAccessor as IServiceScopeAccessor<TRegistry>)\r\n })\r\n\r\n const { ExceptionPipeline } = await import('@/application')\r\n container.addSingleton(TOKENS.EXCEPTION_PIPELINE, () => new ExceptionPipeline())\r\n if (!opts.isLogger) {\r\n const { LoggerUtils } = await import('./utils/logger.utils')\r\n await LoggerUtils.addLogger(container, undefined)\r\n }\r\n\r\n const { LoggingPipeline } = await import('@/application')\r\n container.addSingleton(\r\n TOKENS.LOGGING_PIPELINE,\r\n (c) => new LoggingPipeline(c.resolve(TOKENS.LOGGER)),\r\n )\r\n const pipelines: (keyof TRegistry)[] = [TOKENS.EXCEPTION_PIPELINE, TOKENS.LOGGING_PIPELINE]\r\n\r\n const { PerformancePipeline } = await import('@/application')\r\n container.addSingleton(TOKENS.PERFORMANCE_PIPELINE, (c) => {\r\n const logger = c.resolve(TOKENS.LOGGER)\r\n const thresholdMs = opts.performance?.thresholdMs\r\n return new PerformancePipeline(logger, thresholdMs)\r\n })\r\n pipelines.push(TOKENS.PERFORMANCE_PIPELINE)\r\n\r\n const { Guards } = await import('@xeno-js/shared')\r\n if (\r\n Guards.isDefined(opts.authorization.policies) ||\r\n Guards.isDefined(opts.authorization.customAuthorizationStrategy)\r\n ) {\r\n const { AuthUtils } = await import('./utils/auth.utils')\r\n const authPipelines = await AuthUtils.addAuthZ(container, opts.authorization)\r\n pipelines.push(...authPipelines)\r\n }\r\n\r\n if (\r\n Guards.isDefined(opts.validation.zod) ||\r\n Guards.isDefined(opts.validation.customValidationStrategy)\r\n ) {\r\n const { ValidationUtils } = await import('./utils/validation.utils')\r\n const logger = container.resolve(TOKENS.LOGGER)\r\n const validationPipelines = await ValidationUtils.addValidation(\r\n container,\r\n opts.validation,\r\n logger,\r\n )\r\n pipelines.push(...validationPipelines)\r\n }\r\n\r\n const commandPipelines = pipelines\r\n const queryPipelines = pipelines\r\n\r\n if (\r\n (Guards.isDefined(opts.commandBus.idempotency) || opts.queryBus.isEnabled) &&\r\n opts.isCache\r\n ) {\r\n const { CacheUtils } = await import('./utils/cache.utils')\r\n await CacheUtils.addCache(container, { inMemory: true, redis: undefined })\r\n }\r\n\r\n if (\r\n Guards.isDefined(opts.commandBus.idempotency) ||\r\n Guards.isDefined(opts.commandBus.concurrency)\r\n ) {\r\n const { PipelineUtils } = await import('./utils/pipeline.utils')\r\n const newCommandPipelines = await PipelineUtils.addCommand(container, {\r\n ...opts.commandBus,\r\n isCache,\r\n })\r\n isCache = true\r\n commandPipelines.push(...newCommandPipelines)\r\n }\r\n\r\n if (opts.queryBus.isEnabled) {\r\n const { PipelineUtils } = await import('./utils/pipeline.utils')\r\n const newQueryPipelines = await PipelineUtils.addQuery(container, { isCache })\r\n queryPipelines.push(...newQueryPipelines)\r\n }\r\n\r\n const { CompositePipeline } = await import('@/application')\r\n container.addSingleton(TOKENS.COMMAND_PIPELINES_BEHAVIOR, (c) => {\r\n const resolvedCommandPipelines = commandPipelines.map((token) => {\r\n return c.resolve(token) as IPipelineBehavior<ICommand<unknown>, unknown>\r\n })\r\n return new CompositePipeline<ICommand<unknown>, unknown>(resolvedCommandPipelines)\r\n })\r\n\r\n container.addSingleton(TOKENS.QUERY_PIPELINES_BEHAVIOR, (c) => {\r\n const resolvedQueryPipelines = queryPipelines.map(\r\n (token) => c.resolve(token) as IPipelineBehavior<IQuery<unknown>, unknown>,\r\n )\r\n return new CompositePipeline<IQuery<unknown>, unknown>(resolvedQueryPipelines)\r\n })\r\n }\r\n}\r\n","import type {\r\n AppError,\r\n ICommand,\r\n IContextAccessor,\r\n IController,\r\n IMediator,\r\n IQuery,\r\n RequestContext,\r\n ResultType,\r\n} from '@xeno-js/shared'\r\nimport type { Dictionary, Optional, ResponseDto } from '@xeno-js/shared'\r\nimport { GuidHelper, HttpHelper } from '@xeno-js/shared'\r\n\r\n/**\r\n * BaseController is an abstract class that implements the IController interface. It provides a foundation for creating specific controllers that handle incoming requests and return responses. The class requires a mediator to facilitate communication between different parts of the application.\r\n * @template TRequest - The type of the request object that the controller will handle.\r\n * @template TResponse - The type of the response object that the controller will return.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport abstract class BaseController<TRequest, TResponse> implements IController<\r\n TRequest,\r\n TResponse\r\n> {\r\n /**\r\n * Constructs a new instance of the BaseController class.\r\n * @param _requestContext - An instance of IContextAccessor used to manage the execution context for requests.\r\n * @param _mediator - An instance of IMediator used to facilitate communication between different parts of the application.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n constructor(\r\n private readonly _requestContext: IContextAccessor<RequestContext>,\r\n private readonly _mediator: IMediator,\r\n ) {}\r\n\r\n abstract handle(request: TRequest): Promise<ResponseDto<TResponse>>\r\n\r\n /**\r\n * Helper to return a successful 200/201 response.\r\n * @param data - The data to include in the response.\r\n * @param status - The HTTP status code (default is 200).\r\n * @param meta - Optional metadata to include in the response.\r\n * @param headers - Optional headers to include in the response.\r\n * @returns A ResponseDto containing the data and status.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n protected ok<T>(\r\n data: T,\r\n status = 200,\r\n meta: Optional<Dictionary> = {},\r\n headers: Optional<Dictionary<string[]>> = {},\r\n ): ResponseDto<T> {\r\n return HttpHelper.success(data, status, meta, headers)\r\n }\r\n\r\n /**\r\n * Helper to automatically map a failed Result (from the CQRS pipeline)\r\n * into a standardized ErrorResponseDto.\r\n * @param error - The AppError instance representing the error.\r\n * @param details - Optional additional details about the error.\r\n * @param headers - Optional headers to include in the error response.\r\n * @returns A ResponseDto representing the error response.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n protected fail(\r\n error: AppError,\r\n details: Optional<string> = undefined,\r\n headers: Optional<Dictionary<string[]>> = {},\r\n ): ResponseDto<TResponse> {\r\n const context = this._requestContext.getContext()\r\n\r\n const customHeaders = error['header'] as Optional<Dictionary<string[]>>\r\n\r\n return HttpHelper.error<TResponse>(\r\n {\r\n success: false,\r\n error: {\r\n code: error.code,\r\n message: error.message,\r\n path: context?.network.path,\r\n details: details ?? error.message,\r\n },\r\n correlationId: context?.tracing.correlationId ?? GuidHelper.generate(),\r\n requestId: context?.network.requestId ?? GuidHelper.generate(),\r\n spanId: context?.tracing.spanId ?? GuidHelper.generate(),\r\n timestamp: new Date().toISOString(),\r\n },\r\n error.status,\r\n {\r\n 'Content-Type': [context?.network.formatIndicator ?? 'application/json'],\r\n ...customHeaders,\r\n ...headers,\r\n },\r\n )\r\n }\r\n\r\n /**\r\n * Helper to send a query through the mediator and return the result.\r\n * @param request - The IQuery instance to be sent.\r\n * @returns A promise resolving to the result of the query.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n protected _query(request: IQuery<TResponse>): Promise<ResultType<TResponse>> {\r\n const signal = new AbortController().signal\r\n return this._mediator.query(request, signal)\r\n }\r\n\r\n /**\r\n * Helper to send a command through the mediator and return the result.\r\n * @param request - The ICommand instance to be sent.\r\n * @returns A promise resolving to the result of the command.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n protected _send(request: ICommand<TResponse>): Promise<ResultType<TResponse>> {\r\n const signal = new AbortController().signal\r\n return this._mediator.send(request, signal)\r\n }\r\n\r\n protected getContext(): Optional<RequestContext> {\r\n return this._requestContext.getContext()\r\n }\r\n}\r\n","export * from './base.controller'\r\n","import type {\r\n HttpHeaders,\r\n HttpMethod,\r\n IMiddleware,\r\n RequestContext,\r\n ResponseDto,\r\n} from '@xeno-js/shared'\r\nimport {\r\n ERROR_CODE_MESSAGES,\r\n ERROR_CODES,\r\n GuidHelper,\r\n HttpHelper,\r\n STATUS_CODES,\r\n} from '@xeno-js/shared'\r\n\r\nimport type { ApplicationRegistry, IAllowMethod, IRequestContext } from '@/domain'\r\n\r\n/**\r\n * @description Middleware that checks if the requested method is allowed for the given path. If the method is not allowed, it returns a 405\r\n * status code with an error message.\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n * @param {IAllowMethod} _allowMethod - The allow method service to check if the method is allowed.\r\n * @param {IRequestContext<RequestContext, ApplicationRegistry<unknown>>} _requestContext - The request context to get the request context.\r\n * @returns {IMiddleware<HttpHeaders>} - The middleware function that checks if the method is allowed.\r\n * @throws {Error} - If the method is not allowed, it throws an error with a 405 status code and an error message.\r\n * @see {@link IAllowMethod} - The allow method service.\r\n * @see {@link IRequestContext} - The request context.\r\n * @see {@link IMiddleware} - The middleware interface.\r\n * @see {@link IResponseDto} - The response DTO.\r\n */\r\nexport class MethodCheckMiddleware implements IMiddleware<HttpHeaders> {\r\n constructor(\r\n private readonly _requestContext: IRequestContext<RequestContext, ApplicationRegistry<unknown>>,\r\n private readonly _allowMethod: IAllowMethod,\r\n ) {}\r\n\r\n public async execute<T, TRes, TReq>(\r\n req: { method: HttpMethod; path: string; transport: { req: TRes; res: TReq } },\r\n _headers: HttpHeaders,\r\n next: () => Promise<ResponseDto<T>>,\r\n ): Promise<ResponseDto<T>> {\r\n const isAllowed = this._allowMethod.check(req.path, req.method)\r\n\r\n if (!isAllowed) {\r\n const { network, tracing } = this._requestContext.getContext() ?? {}\r\n\r\n return HttpHelper.error(\r\n {\r\n success: false,\r\n error: {\r\n code: ERROR_CODES.NOT_ALLOWED,\r\n message: ERROR_CODE_MESSAGES[ERROR_CODES.NOT_ALLOWED],\r\n details: `Operation blocked by allow method middleware`,\r\n path: req.path,\r\n },\r\n correlationId: tracing?.correlationId ?? GuidHelper.generate(),\r\n requestId: network?.requestId ?? GuidHelper.generate(),\r\n spanId: tracing?.spanId ?? GuidHelper.generate(),\r\n timestamp: new Date().toISOString(),\r\n },\r\n STATUS_CODES.NOT_ALLOWED,\r\n {\r\n Allow: this._allowMethod.getMethods(req.path),\r\n },\r\n )\r\n }\r\n\r\n return await next()\r\n }\r\n}\r\n","import type {\r\n HttpHeaders,\r\n HttpMethod,\r\n IContextAccessor,\r\n ILogger,\r\n IMiddleware,\r\n RequestContext,\r\n ResponseDto,\r\n} from '@xeno-js/shared'\r\nimport {\r\n ERROR_CODE_MESSAGES,\r\n ERROR_CODES,\r\n GuidHelper,\r\n HttpHelper,\r\n STATUS_CODES,\r\n} from '@xeno-js/shared'\r\n\r\nimport type { IAllowOrigin } from '@/domain'\r\n\r\n/**\r\n * @description A middleware that checks if the origin of the request is allowed.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class AllowOriginMiddleware implements IMiddleware<HttpHeaders> {\r\n constructor(\r\n private readonly _allowOrigin: IAllowOrigin,\r\n private readonly _requestContext: IContextAccessor<RequestContext>,\r\n private readonly _logger: ILogger,\r\n ) {}\r\n\r\n public async execute<T, TRes, TReq>(\r\n req: { method: HttpMethod; path: string; transport: { req: TRes; res: TReq } },\r\n _headers: HttpHeaders,\r\n next: () => Promise<ResponseDto<T>>,\r\n ): Promise<ResponseDto<T>> {\r\n const { network, tracing } = this._requestContext.getContext() ?? {}\r\n const origin = network?.origin\r\n\r\n if (!this._allowOrigin.isAllowed(origin)) {\r\n this._logger.warn(`Access denied by AllowOrigin policy for origin: ${origin ?? 'unknown'}`)\r\n\r\n return HttpHelper.error(\r\n {\r\n success: false,\r\n error: {\r\n code: ERROR_CODES.FORBIDDEN,\r\n message: ERROR_CODE_MESSAGES[ERROR_CODES.FORBIDDEN],\r\n details: `The origin '${origin ?? 'unknown'}' is not allowed to access this resource.`,\r\n path: req.path,\r\n },\r\n correlationId: tracing?.correlationId ?? GuidHelper.generate(),\r\n requestId: network?.requestId ?? GuidHelper.generate(),\r\n spanId: tracing?.spanId ?? GuidHelper.generate(),\r\n timestamp: new Date().toISOString(),\r\n },\r\n STATUS_CODES.FORBIDDEN,\r\n )\r\n }\r\n\r\n return next()\r\n }\r\n}\r\n","import type {\r\n HttpHeaders,\r\n HttpMethod,\r\n IGateKeeper,\r\n ILogger,\r\n IMiddleware,\r\n IServiceExtractor,\r\n Optional,\r\n RequestContext,\r\n ResponseDto,\r\n} from '@xeno-js/shared'\r\nimport { GuidHelper, HttpHelper, STATUS_CODES } from '@xeno-js/shared'\r\n\r\nimport type { ApplicationRegistry, IRequestContext } from '@/domain'\r\n\r\n/**\r\n * @description Middleware that checks if the request is authenticated. If the request is not authenticated, it returns a 401\r\n * status code with an error message.\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @param {IRequestContext<RequestContext, ApplicationRegistry<unknown>>} _requestContext - The request context to use for resolving services.\r\n * @param {IGateKeeper} _gateKeeper - The gate keeper to use for authentication.\r\n * @param {ILogger} _logger - The logger to use for logging.\r\n * @param {IServiceExtractor<HttpHeaders, Optional<string>>} _tokenExtractor - The token extractor to use for extracting the token from the request.\r\n * @returns {IMiddleware<HttpHeaders>} - The middleware function.\r\n * @link https://github.com/xeno-js/xeno-js\r\n *\r\n * @see {@link IRequestContext} - The request context interface.\r\n * @see {@link IGateKeeper} - The gate keeper interface.\r\n * @see {@link ILogger} - The logger interface.\r\n * @see {@link IServiceExtractor} - The service extractor interface.\r\n */\r\nexport class AuthenticationMiddleware implements IMiddleware<HttpHeaders> {\r\n constructor(\r\n private readonly _requestContext: IRequestContext<RequestContext, ApplicationRegistry<unknown>>,\r\n private readonly _tokenExtractor: IServiceExtractor<HttpHeaders, Optional<string>>,\r\n private readonly _gateKeeper: IGateKeeper,\r\n private readonly _logger: ILogger,\r\n ) {}\r\n\r\n public async execute<T, TRes, TReq>(\r\n req: { method: HttpMethod; path: string; transport: { req: TRes; res: TReq } },\r\n headers: HttpHeaders,\r\n next: () => Promise<ResponseDto<T>>,\r\n ): Promise<ResponseDto<T>> {\r\n const token = this._tokenExtractor.extract(headers)\r\n const authResult = await this._gateKeeper.authenticate(token)\r\n\r\n if (!authResult.isOk()) {\r\n const error = authResult.getErrorOrThrow()\r\n this._logger.warn(\r\n `Authentication failed for request on path: ${req.path}. Code: ${error.code}. Error: ${error}`,\r\n )\r\n\r\n const { network, tracing } = this._requestContext.getContext() ?? {}\r\n\r\n return HttpHelper.error(\r\n {\r\n success: false,\r\n error: {\r\n code: error.code,\r\n message: error.message,\r\n details: `[Authentication Error] Failed to authenticate request on path: ${req.path}`,\r\n path: req.path,\r\n },\r\n correlationId: tracing?.correlationId ?? GuidHelper.generate(),\r\n requestId: network?.requestId ?? GuidHelper.generate(),\r\n spanId: tracing?.spanId ?? GuidHelper.generate(),\r\n timestamp: new Date().toISOString(),\r\n },\r\n error.status ?? STATUS_CODES.UNAUTHORIZED,\r\n { 'Content-Type': [network?.formatIndicator ?? 'application/json'] },\r\n )\r\n }\r\n\r\n this._requestContext.updateIdentity(authResult.getValueOrThrow()!)\r\n\r\n return next()\r\n }\r\n}\r\n","import type { HttpHeaders, HttpMethod, IMiddleware, ResponseDto } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description A middleware that executes a list of middlewares in a chain.\r\n *\r\n * @author Xeno\r\n * @version 1.0.1\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class CompositeMiddleware implements IMiddleware<HttpHeaders> {\r\n constructor(private readonly _middlewares: IMiddleware<HttpHeaders>[]) {}\r\n\r\n public async execute<T, TRes, TReq>(\r\n req: { method: HttpMethod; path: string; transport: { req: TRes; res: TReq } },\r\n headers: HttpHeaders,\r\n next: () => Promise<ResponseDto<T>>,\r\n ): Promise<ResponseDto<T>> {\r\n let currentNext = next\r\n\r\n for (let i = this._middlewares.length - 1; i >= 0; i--) {\r\n const currentBehavior = this._middlewares[i]\r\n const previousNext = currentNext\r\n currentNext = () => currentBehavior.execute(req, headers, previousNext)\r\n }\r\n\r\n return currentNext()\r\n }\r\n}\r\n","import type {\r\n HttpHeaders,\r\n HttpMethod,\r\n IContextAccessor,\r\n IMiddleware,\r\n RequestContext,\r\n ResponseDto,\r\n} from '@xeno-js/shared'\r\nimport { Guards } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description A cors middleware that checks if the origin of the request is allowed.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class CORSMiddleware implements IMiddleware<HttpHeaders> {\r\n constructor(\r\n private readonly _requestContext: IContextAccessor<RequestContext>,\r\n private readonly _withCredentials: 'true' | 'false' = 'false',\r\n ) {}\r\n\r\n public async execute<T, TRes, TReq>(\r\n _req: { method: HttpMethod; path: string; transport: { req: TRes; res: TReq } },\r\n _headers: HttpHeaders,\r\n next: () => Promise<ResponseDto<T>>,\r\n ): Promise<ResponseDto<T>> {\r\n const { network } = this._requestContext.getContext() ?? {}\r\n const origin = network?.origin\r\n\r\n const response = await next()\r\n if (Guards.isDefined(origin))\r\n response.headers = {\r\n ...(response.headers ?? {}),\r\n 'Access-Control-Allow-Origin': origin,\r\n 'Access-Control-Allow-Credentials': this._withCredentials,\r\n 'Vary': 'Origin',\r\n }\r\n return response\r\n }\r\n}\r\n","import type { HttpHeaders, HttpMethod, RequestContext, ResponseDto } from '@xeno-js/shared'\r\nimport {\r\n ERROR_CODE_MESSAGES,\r\n ERROR_CODES,\r\n Guards,\r\n GuidHelper,\r\n HttpHelper,\r\n STATUS_CODES,\r\n} from '@xeno-js/shared'\r\n\r\nimport type { ApplicationRegistry, ICsrfTokenService, IRequestContext } from '@/domain'\r\n\r\n/**\r\n * @description The CsrfMiddleware class implements the IMiddleware interface, providing a concrete implementation for handling CSRF token validation. It checks the incoming request for a valid CSRF token and returns an error response if the token is missing or invalid.\r\n */\r\nexport class CsrfMiddleware {\r\n constructor(\r\n private readonly _requestContext: IRequestContext<RequestContext, ApplicationRegistry<unknown>>,\r\n private readonly _csrfTokenService: ICsrfTokenService,\r\n ) {}\r\n\r\n public async execute<T, TRes, TReq>(\r\n req: { method: HttpMethod; path: string; transport: { req: TRes; res: TReq } },\r\n _headers: HttpHeaders,\r\n next: () => Promise<ResponseDto<T>>,\r\n ): Promise<ResponseDto<T>> {\r\n const method = req.method.toUpperCase()\r\n const isStateChanging = ['POST', 'PUT', 'DELETE', 'PATCH'].includes(method)\r\n\r\n if (isStateChanging) {\r\n const { network, tracing, identity } = this._requestContext.getContext() ?? {}\r\n const headerToken = network?.csrf\r\n const cookieToken = network?.csrfCookie\r\n\r\n if (!Guards.isDefined(headerToken) || !Guards.isDefined(cookieToken)) {\r\n return HttpHelper.error(\r\n {\r\n success: false,\r\n error: {\r\n code: ERROR_CODES.FORBIDDEN,\r\n message: ERROR_CODE_MESSAGES[ERROR_CODES.FORBIDDEN],\r\n details: 'CSRF token missing',\r\n path: req.path,\r\n },\r\n correlationId: tracing?.correlationId ?? GuidHelper.generate(),\r\n requestId: network?.requestId ?? GuidHelper.generate(),\r\n spanId: tracing?.spanId ?? GuidHelper.generate(),\r\n timestamp: new Date().toISOString(),\r\n },\r\n STATUS_CODES.FORBIDDEN,\r\n {\r\n 'Content-Type': [network?.formatIndicator ?? 'application/json'],\r\n },\r\n )\r\n }\r\n\r\n if (headerToken !== cookieToken) {\r\n return HttpHelper.error(\r\n {\r\n success: false,\r\n error: {\r\n code: ERROR_CODES.FORBIDDEN,\r\n message: ERROR_CODE_MESSAGES[ERROR_CODES.FORBIDDEN],\r\n details: 'CSRF token mismatch',\r\n path: req.path,\r\n },\r\n correlationId: tracing?.correlationId ?? GuidHelper.generate(),\r\n requestId: network?.requestId ?? GuidHelper.generate(),\r\n spanId: tracing?.spanId ?? GuidHelper.generate(),\r\n timestamp: new Date().toISOString(),\r\n },\r\n STATUS_CODES.FORBIDDEN,\r\n {\r\n 'Content-Type': [network?.formatIndicator ?? 'application/json'],\r\n },\r\n )\r\n }\r\n\r\n if (\r\n !Guards.isDefined(identity?.userId) ||\r\n !(await this._csrfTokenService.validate(headerToken, identity?.userId))\r\n ) {\r\n return HttpHelper.error(\r\n {\r\n success: false,\r\n error: {\r\n code: ERROR_CODES.FORBIDDEN,\r\n message: ERROR_CODE_MESSAGES[ERROR_CODES.FORBIDDEN],\r\n details: 'CSRF token invalid',\r\n path: req.path,\r\n },\r\n correlationId: tracing?.correlationId ?? GuidHelper.generate(),\r\n requestId: network?.requestId ?? GuidHelper.generate(),\r\n spanId: tracing?.spanId ?? GuidHelper.generate(),\r\n timestamp: new Date().toISOString(),\r\n },\r\n STATUS_CODES.FORBIDDEN,\r\n {\r\n 'Content-Type': [network?.formatIndicator ?? 'application/json'],\r\n },\r\n )\r\n }\r\n }\r\n\r\n return await next()\r\n }\r\n}\r\n","import type {\r\n HttpHeaders,\r\n HttpMethod,\r\n IContextAccessor,\r\n IMiddleware,\r\n RequestContext,\r\n ResponseDto,\r\n} from '@xeno-js/shared'\r\nimport { Guards } from '@xeno-js/shared'\r\n\r\nimport type { ICsrfTokenService, MiddlewareConfig } from '@/domain'\r\n\r\n/**\r\n * @description The CsrfCookieMiddleware class implements the IMiddleware interface, providing a concrete implementation for handling CSRF token validation and cookie management. It checks the incoming request for a valid CSRF token and sets a CSRF cookie if necessary.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n * @license MIT\r\n */\r\nexport class CsrfCookieMiddleware implements IMiddleware<HttpHeaders> {\r\n constructor(\r\n private readonly _requestContext: IContextAccessor<RequestContext>,\r\n private readonly _csrfTokenService: ICsrfTokenService,\r\n private readonly _csrf: NonNullable<MiddlewareConfig['csrf']>,\r\n ) {}\r\n\r\n public async execute<T, TRes, TReq>(\r\n _req: {\r\n method: HttpMethod\r\n path: string\r\n transport: {\r\n req: TRes\r\n res: TReq\r\n }\r\n },\r\n _headers: HttpHeaders,\r\n next: () => Promise<ResponseDto<T>>,\r\n ): Promise<ResponseDto<T>> {\r\n const response = await next()\r\n\r\n const context = this._requestContext.getContext()\r\n const identity = context?.identity\r\n const network = context?.network\r\n\r\n if (!Guards.isDefined(identity?.userId)) return response\r\n\r\n if (Guards.isDefined(network?.csrfCookie)) return response\r\n\r\n const token = await this._csrfTokenService.generate(identity.userId)\r\n\r\n const cookieName = this._csrf.cookieName ?? '__Host-xeno-csrf'\r\n const maxAge = this._csrf.cookieMaxAgeSeconds ?? 3600\r\n const sameSite = this._csrf.sameSite ?? 'lax'\r\n\r\n const cookie =\r\n `${cookieName}=${encodeURIComponent(token)}; ` +\r\n `Path=/; ` +\r\n `Secure; ` +\r\n `SameSite=${sameSite}; ` +\r\n `Max-Age=${maxAge}`\r\n\r\n const existingCookies = response.headers['Set-Cookie']\r\n\r\n response.headers = {\r\n ...(response.headers ?? {}),\r\n 'Set-Cookie': [...(existingCookies ?? []), cookie],\r\n }\r\n\r\n return response\r\n }\r\n}\r\n","import type { HttpHeaders, HttpMethod, INetworkContextAccessor, ResponseDto } from '@xeno-js/shared'\r\nimport { Guards, HttpHelper, STATUS_CODES } from '@xeno-js/shared'\r\n\r\nimport type { IAllowMethod } from '@/domain'\r\n\r\n/**\r\n * @description A middleware that handles OPTIONS requests.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class OptionsMiddleware {\r\n constructor(\r\n private readonly _requestContext: INetworkContextAccessor,\r\n private readonly _alloewMethod: IAllowMethod,\r\n private readonly _allowHeaders: string[] = [],\r\n private readonly _withCredentials: 'true' | 'false' = 'false',\r\n ) {}\r\n\r\n public async execute<T, TRes, TReq>(\r\n req: { method: HttpMethod; path: string; transport: { req: TRes; res: TReq } },\r\n _headers: HttpHeaders,\r\n next: () => Promise<ResponseDto<T>>,\r\n ): Promise<ResponseDto<T>> {\r\n if (req.method.toUpperCase() === 'OPTIONS') {\r\n const network = this._requestContext.getNetworkContext()\r\n const origin = network?.origin\r\n\r\n const headers: HttpHeaders = {}\r\n if (Guards.isDefined(origin)) {\r\n headers['Access-Control-Allow-Origin'] = origin\r\n headers['Access-Control-Allow-Credentials'] = this._withCredentials\r\n headers['Vary'] = 'Origin'\r\n }\r\n headers['Access-Control-Allow-Methods'] = this._alloewMethod.getMethods(req.path)\r\n headers['Access-Control-Allow-Headers'] = this._allowHeaders.join(', ')\r\n\r\n return HttpHelper.success(null as T, STATUS_CODES.NO_CONTENT, {}, headers)\r\n }\r\n\r\n return await next()\r\n }\r\n}\r\n","import type {\r\n HttpHeaders,\r\n HttpMethod,\r\n IContextAccessor,\r\n ILogger,\r\n IMiddleware,\r\n RequestContext,\r\n ResponseDto,\r\n} from '@xeno-js/shared'\r\nimport {\r\n ERROR_CODE_MESSAGES,\r\n ERROR_CODES,\r\n Guards,\r\n GuidHelper,\r\n HttpHelper,\r\n STATUS_CODES,\r\n} from '@xeno-js/shared'\r\n\r\nimport type { IAtomicCache, IRateLimitKeyBuilder } from '@/domain'\r\n\r\n/**\r\n * @description The RateLimitMiddleware class implements the IMiddleware interface and provides rate limiting functionality for incoming requests. It uses an IAtomicCache instance to track the number of requests made by each client within a specified time window. If the number of requests exceeds the maximum allowed, the middleware returns a 429 Too Many Requests response. Otherwise it calls the next middleware in the chain.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 1.0.0\r\n * @param {IContextAccessor<RequestContext>} _ctxAccessor - The context accessor for the request.\r\n * @param {IAtomicCache} _cache - The cache used to store the request counts.\r\n * @param {ILogger} _logger - The logger used to log messages.\r\n * @param {number} _opts.maxRequests - The maximum number of requests allowed within the time window.\r\n * @param {number} _opts.windowSeconds - The time window in seconds within which the maximum number of requests is allowed.\r\n * @link https://github.com/xenowits/xeno-js\r\n */\r\nexport class RateLimitMiddleware implements IMiddleware<HttpHeaders> {\r\n constructor(\r\n private readonly _ctxAccessor: IContextAccessor<RequestContext>,\r\n private readonly _cache: IAtomicCache,\r\n private readonly _keyBuilder: IRateLimitKeyBuilder,\r\n private readonly _logger: ILogger,\r\n private readonly _opts: {\r\n maxRequests: number\r\n windowSeconds: number\r\n },\r\n ) {}\r\n\r\n public async execute<T, TRes, TReq>(\r\n req: { method: HttpMethod; path: string; transport: { req: TRes; res: TReq } },\r\n _headers: HttpHeaders,\r\n next: () => Promise<ResponseDto<T>>,\r\n ): Promise<ResponseDto<T>> {\r\n const cacheKey = this._keyBuilder.buildRateLimitKey(req.path)\r\n const { network, tracing } = this._ctxAccessor.getContext() ?? {}\r\n\r\n if (!Guards.isDefined(cacheKey))\r\n return HttpHelper.error(\r\n {\r\n success: false,\r\n error: {\r\n code: ERROR_CODES.SYSTEM_ERROR,\r\n message: ERROR_CODE_MESSAGES[ERROR_CODES.SYSTEM_ERROR],\r\n details: `Bad Request: Unable to identify client context for rate limiting.`,\r\n path: req.path,\r\n },\r\n correlationId: tracing?.correlationId ?? GuidHelper.generate(),\r\n requestId: network?.requestId ?? GuidHelper.generate(),\r\n spanId: tracing?.spanId ?? GuidHelper.generate(),\r\n timestamp: new Date().toISOString(),\r\n },\r\n STATUS_CODES.SERVICE_UNAVAILABLE,\r\n {\r\n 'Content-Type': [network?.formatIndicator ?? 'application/json'],\r\n 'Retry-After': [String(this._opts.windowSeconds)],\r\n },\r\n )\r\n\r\n const currentHits = await this._cache.increment(cacheKey, this._opts.windowSeconds)\r\n\r\n if (currentHits > this._opts.maxRequests) {\r\n this._logger.warn(`[RateLimit] key ${cacheKey} has been blocked on ${req.path}`)\r\n\r\n return HttpHelper.error(\r\n {\r\n success: false,\r\n error: {\r\n code: ERROR_CODES.TOO_MANY_REQUESTS,\r\n message: ERROR_CODE_MESSAGES[ERROR_CODES.TOO_MANY_REQUESTS],\r\n details: `Rate limit exceeded. Key ${cacheKey} throttled.`,\r\n path: req.path,\r\n },\r\n correlationId: tracing?.correlationId ?? GuidHelper.generate(),\r\n requestId: network?.requestId ?? GuidHelper.generate(),\r\n spanId: tracing?.spanId ?? GuidHelper.generate(),\r\n timestamp: new Date().toISOString(),\r\n },\r\n STATUS_CODES.TOO_MANY_REQUESTS,\r\n {\r\n 'Content-Type': [network?.formatIndicator ?? 'application/json'],\r\n 'Retry-After': [String(this._opts.windowSeconds)],\r\n },\r\n )\r\n }\r\n\r\n return next()\r\n }\r\n}\r\n","import type {\r\n IBaseMapper,\r\n Identity,\r\n MessagingContext,\r\n NetworkContext,\r\n RequestContext,\r\n TracingContext,\r\n} from '@xeno-js/shared'\r\nimport { Guards, type Metadata, type Optional } from '@xeno-js/shared'\r\n\r\ninterface ContextMapperSource {\r\n readonly metadata: Metadata\r\n readonly identity: Identity\r\n readonly path: string\r\n readonly transport: { req: unknown; res: unknown }\r\n}\r\n\r\nexport const ContextMapper: IBaseMapper<ContextMapperSource, RequestContext> = Object.freeze({\r\n /**\r\n * @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.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n map: (source: ContextMapperSource): RequestContext => {\r\n const { metadata, identity, path, transport } = source\r\n\r\n const network: NetworkContext = {\r\n requestId: metadata.requestId!,\r\n clientIp: metadata.clientIp,\r\n userAgent: metadata.userAgent,\r\n formatIndicator: metadata.formatIndicator,\r\n path,\r\n transport,\r\n csrf: metadata.csrf,\r\n csrfCookie: metadata.csrfCookie,\r\n origin: metadata.origin,\r\n }\r\n const tracing: TracingContext = {\r\n correlationId: metadata.correlationId!,\r\n startTime: Date.now(),\r\n spanId: metadata.spanId,\r\n parentSpanId: metadata.parentSpanId,\r\n referer: metadata.referer,\r\n }\r\n const messaging = _buildMessagingContext(metadata)\r\n\r\n const requestContext: RequestContext = {\r\n identity,\r\n network,\r\n tracing,\r\n messaging,\r\n }\r\n\r\n return requestContext\r\n },\r\n} as const)\r\n\r\n/**\r\n * @description Builds the MessagingContext based on the provided Metadata. It checks for the presence of sequence data, expiration, and return address in the metadata to determine if a MessagingContext should be created. If any of these properties are defined, it constructs a MessagingContext object with the relevant information; otherwise, it returns undefined. This method encapsulates the logic for determining whether messaging-related context is available and ensures that the resulting MessagingContext is properly structured.\r\n * @param meta The Metadata object extracted from the HTTP request headers, containing information such as correlation ID, request ID, authentication token, client IP, user agent, format indicator, return address, expiration, and sequence data. This metadata is used to determine whether a MessagingContext should be created and what properties it should contain.\r\n * @returns An Optional<MessagingContext> object that contains messaging-related context information if available; otherwise, it returns undefined. The MessagingContext includes properties such as return address, expiration time, and sequence information (sequence ID, position, and size) if they are present in the metadata.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nfunction _buildMessagingContext(meta: Metadata): Optional<MessagingContext> {\r\n const hasSequenceData =\r\n Guards.isDefined(meta.sequence?.sequenceId) ||\r\n Guards.isDefined(meta.sequence?.position) ||\r\n Guards.isDefined(meta.sequence?.size)\r\n\r\n const hasMessagingData =\r\n hasSequenceData || Guards.isDefined(meta.expiration) || Guards.isDefined(meta.returnAddress)\r\n\r\n const messaging: Optional<MessagingContext> = hasMessagingData\r\n ? {\r\n returnAddress: meta.returnAddress,\r\n expiration: meta.expiration,\r\n sequence: hasSequenceData ? meta.sequence : undefined,\r\n }\r\n : undefined\r\n return messaging\r\n}\r\n","import type {\r\n Identity,\r\n ILogger,\r\n IMiddleware,\r\n IServiceExtractor,\r\n RequestContext,\r\n} from '@xeno-js/shared'\r\nimport type { Guid, HttpHeaders, HttpMethod, Metadata, ResponseDto } from '@xeno-js/shared'\r\nimport {\r\n ERROR_CODE_MESSAGES,\r\n ERROR_CODES,\r\n GUEST,\r\n GuidHelper,\r\n HttpHelper,\r\n STATUS_CODES,\r\n} from '@xeno-js/shared'\r\n\r\nimport type { ApplicationRegistry, IIPResolver, IRequestContext } from '@/domain'\r\n\r\nimport { ContextMapper } from '../mappers/context.mapper'\r\n\r\n/**\r\n * @description The RequestContextMiddleware class is responsible for extracting metadata from incoming HTTP requests, performing authentication using the provided authentication middleware, and composing an ExecutionContext that includes identity, network, and tracing information. It implements the IMiddleware interface, allowing it to be used as part of a middleware chain in the request processing pipeline. The middleware ensures that the ExecutionContext is properly set up for downstream handlers, controllers, or use cases to access necessary contextual information for processing the request.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class RequestContextMiddleware implements IMiddleware<HttpHeaders> {\r\n /**\r\n * @description Constructs a new instance of the RequestContextMiddleware class, which is responsible for handling the request context in the middleware chain. It takes several dependencies as parameters, including an IRequestContext for managing the execution context, an IServiceExtractor for extracting metadata from HTTP headers, an IGateKeeper for performing authentication, and an IServiceContainer for managing service scopes and dependencies. These dependencies are essential for the middleware to function correctly, allowing it to extract necessary information from incoming requests, authenticate users, and set up the execution context for downstream processing.\r\n * @param _requestContext An instance of IRequestContext used to manage the execution context for the request. This context allows the middleware to set and retrieve contextual information that can be accessed by downstream handlers, controllers, or use cases during the processing of the request.\r\n * @param _extractor An instance of IServiceExtractor used to extract metadata from the incoming HTTP request headers. This extractor is responsible for parsing the headers and retrieving relevant information such as correlation IDs, request IDs, authentication tokens, client IP addresses, and tracing span IDs, which are essential for building the ExecutionContext.\r\n * @param _logger\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n constructor(\r\n private readonly _requestContext: IRequestContext<RequestContext, ApplicationRegistry<unknown>>,\r\n private readonly _extractor: IServiceExtractor<HttpHeaders, Metadata>,\r\n private readonly _resolver: IIPResolver,\r\n private readonly _logger: ILogger,\r\n ) {}\r\n\r\n public async execute<T, TRes, TReq>(\r\n req: { method: HttpMethod; path: string; transport: { req: TRes; res: TReq } },\r\n headers: HttpHeaders,\r\n next: () => Promise<ResponseDto<T>>,\r\n ): Promise<ResponseDto<T>> {\r\n const correlationId = GuidHelper.generate()\r\n const requestId = GuidHelper.generate()\r\n const spanId: Guid = correlationId\r\n const formatIndicator = 'application/json'\r\n\r\n try {\r\n const meta = this._extractor.extract(headers)\r\n\r\n const clientIp = this._resolver.resolve(req.transport.req, meta.clientIp)\r\n\r\n const metadata: Metadata = {\r\n ...meta,\r\n clientIp,\r\n correlationId: meta.correlationId ?? correlationId,\r\n requestId: meta.requestId ?? requestId,\r\n spanId: meta.spanId ?? spanId,\r\n formatIndicator: meta.formatIndicator,\r\n }\r\n\r\n const tmpContext = ContextMapper.map({\r\n metadata,\r\n identity: GUEST as unknown as Identity,\r\n path: req.path,\r\n transport: req.transport,\r\n })\r\n\r\n const result = await this._requestContext.runAsync(tmpContext, async () => {\r\n return next()\r\n })\r\n if (!result.ok && !result.data.success)\r\n this._logger.error(result.data.error.message, result.data)\r\n\r\n return result\r\n } catch (error) {\r\n this._logger.error('RequestContextMiddleware encountered an error', error)\r\n return HttpHelper.error(\r\n {\r\n success: false,\r\n error: {\r\n code: ERROR_CODES.SYSTEM_ERROR,\r\n message: ERROR_CODE_MESSAGES[ERROR_CODES.SYSTEM_ERROR],\r\n details: `[Fatal System Error] Exception caught during request handling on path: ${req.path}`,\r\n path: req.path,\r\n },\r\n correlationId,\r\n requestId,\r\n spanId,\r\n timestamp: new Date().toISOString(),\r\n },\r\n STATUS_CODES.INTERNAL_SERVER_ERROR,\r\n { 'Content-Type': [formatIndicator] },\r\n )\r\n }\r\n }\r\n}\r\n","export * from './allow-method.middleware'\r\nexport * from './allow-origin.middleware'\r\nexport * from './auth.middleware'\r\nexport * from './composite.middleware'\r\nexport * from './cors.middleware'\r\nexport * from './csrf.middleware'\r\nexport * from './csrf-cookie.middleware'\r\nexport * from './options.middleware'\r\nexport * from './rate-limiter.middleware'\r\nexport * from './request.middleware'\r\n","export * from './controllers/index'\r\nexport * from './middlewares/index'\r\n","import type { Optional, RequestContext } from '@xeno-js/shared'\r\nimport { Guards } from '@xeno-js/shared'\r\n\r\nimport type { ApplicationRegistry, IRateLimitKeyBuilder, IRequestContext } from '@/domain'\r\n\r\n/**\r\n * @description The RateLimitKeyBuilder class implements the IRateLimitKeyBuilder interface, providing a method to build rate limit keys based on the user's identity. This class utilizes an instance of IIdentityAccessor to retrieve the current user's identity, allowing for the creation of tenant-specific rate limit keys in multi-tenant applications. If a tenant ID is present in the identity, the rate limit key is prefixed with the tenant ID; otherwise, it defaults to a public rate limit key. This approach ensures that rate limit data is appropriately scoped to the user's context, preventing data leakage between tenants.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-vue\r\n * @copyright Xeno\r\n * @license MIT\r\n */\r\nexport class RateLimitKeyBuilder implements IRateLimitKeyBuilder {\r\n constructor(\r\n private readonly _contextAccessor: IRequestContext<\r\n RequestContext,\r\n ApplicationRegistry<unknown>\r\n >,\r\n ) {}\r\n\r\n public buildRateLimitKey(resource: string): Optional<string> {\r\n const ctx = this._contextAccessor.getContext()\r\n\r\n const tenantId = ctx?.identity?.tenantId\r\n const userId = ctx?.identity?.userId\r\n const clientIp = ctx?.network?.clientIp\r\n\r\n if (!Guards.isNullOrEmpty(tenantId) && !Guards.isNullOrEmpty(userId))\r\n return `ratelimit:tenant:${tenantId}:user:${userId}:${resource}`\r\n\r\n if (!Guards.isNullOrEmpty(tenantId) && !Guards.isNullOrEmpty(clientIp))\r\n return `ratelimit:tenant:${tenantId}:ip:${clientIp}:${resource}`\r\n\r\n if (!Guards.isNullOrEmpty(userId)) return `ratelimit:user:${userId}:${resource}`\r\n\r\n if (!Guards.isNullOrEmpty(clientIp)) return `ratelimit:ip:${clientIp}:${resource}`\r\n\r\n return undefined\r\n }\r\n}\r\n","export * from './inmemory.cache'\r\nexport * from './rate-limit-key-builder.cache'\r\nexport * from './redis.cache'\r\n","import { Guards, type HttpHeaders, type IGateKeeper, type IMiddleware } from '@xeno-js/shared'\n\nimport type { IModule, IServiceContainer, MiddlewareConfig } from '@/domain'\n\nimport type { XenoRegistry } from '../xeno-registry'\n\n/**\n * @description MiddlewareModule is responsible for registering essential services and middlewares that are fundamental to the application's operation. This includes setting up the logging infrastructure and the request context middleware. By implementing the IModule interface, MiddlewareModule can be easily integrated into the application's dependency injection container, allowing it to configure necessary services and middlewares during the application startup phase.\n *\n * @author Xeno\n * @version 1.0.0\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-js\n */\nexport class MiddlewareModule<TRegistry extends XenoRegistry = XenoRegistry> implements IModule<\n TRegistry,\n MiddlewareConfig & {\n isAuth: boolean\n isLogger: boolean\n isCache: boolean\n }\n> {\n async configure(\n container: IServiceContainer<TRegistry>,\n opts: MiddlewareConfig & {\n isAuth: boolean\n isLogger: boolean\n isCache: boolean\n },\n ): Promise<void> {\n const { TOKENS } = await import('@xeno-js/shared')\n\n if (!opts.isAuth) {\n const { NoAuthGateKeeper } = await import('@/application')\n container.addSingleton(TOKENS.GATE_KEEPER, (): IGateKeeper => new NoAuthGateKeeper())\n }\n\n if (opts.isSSR) {\n const { SupabaseSsrTokenExtractor } = await import('../services')\n container.addSingleton(TOKENS.BEARER_TOKEN_EXTRACTOR, () => new SupabaseSsrTokenExtractor())\n } else {\n const { BearerTokenExtractor } = await import('../services')\n container.addSingleton(TOKENS.BEARER_TOKEN_EXTRACTOR, () => new BearerTokenExtractor())\n }\n\n const { HttpCookieExtractor } = await import('../services')\n container.addSingleton('COOKIE_EXTRACTOR', () => new HttpCookieExtractor())\n\n const { HttpHeaderExtractor } = await import('../services')\n container.addSingleton(\n TOKENS.SERVICE_EXTRACTOR,\n (c) =>\n new HttpHeaderExtractor(\n c.resolve(TOKENS.BEARER_TOKEN_EXTRACTOR),\n c.resolve('COOKIE_EXTRACTOR'),\n opts.trustedIpHeader,\n opts.csrf?.cookieName ?? '__Host-xeno-csrf',\n ),\n )\n\n if (!opts.isLogger) {\n const { LoggerUtils } = await import('./utils/logger.utils')\n await LoggerUtils.addLogger(container, undefined)\n }\n\n const { ClientIpResolver } = await import('../services')\n container.addSingleton('IP_RESOLVER', () => new ClientIpResolver(opts.trustedProxies))\n\n const middlewares: (keyof TRegistry)[] = [TOKENS.REQUEST_CONTEXT_MIDDLEWARE]\n\n const { RequestContextMiddleware } = await import('@/presentation')\n container.addSingleton(\n TOKENS.REQUEST_CONTEXT_MIDDLEWARE,\n (c) =>\n new RequestContextMiddleware(\n c.resolve(TOKENS.REQUEST_CONTEXT),\n c.resolve(TOKENS.SERVICE_EXTRACTOR),\n c.resolve('IP_RESOLVER'),\n c.resolve(TOKENS.LOGGER),\n ),\n )\n\n if (!Guards.isNullOrEmpty(opts.allowOrigins)) {\n if (opts.withCredentials && opts.allowOrigins.includes('*'))\n throw new Error(\n 'Wildcard CORS origin is not allowed when withCredentials is set to true in addHttpCore',\n )\n\n const { AllowOrigin } = await import('../services')\n container.addSingleton('ALLOW_ORIGIN', () => {\n return new AllowOrigin(opts.allowOrigins!)\n })\n\n const { AllowOriginMiddleware } = await import('@/presentation')\n container.addSingleton(TOKENS.ALLOW_ORIGIN_MIDDLEWARE, (c) => {\n return new AllowOriginMiddleware(\n c.resolve(TOKENS.ALLOW_ORIGIN),\n c.resolve(TOKENS.CONTEXT_ACCESSOR),\n c.resolve(TOKENS.LOGGER),\n )\n })\n middlewares.push(TOKENS.ALLOW_ORIGIN_MIDDLEWARE)\n }\n\n const withCredentials = opts.withCredentials ? 'true' : 'false'\n if (opts.optionsMiddleware) {\n const { OptionsMiddleware } = await import('@/presentation')\n container.addSingleton(\n TOKENS.OPTIONS_MIDDLEWARE,\n (c) =>\n new OptionsMiddleware(\n c.resolve(TOKENS.NETWORK_CONTEXT_ACCESSOR),\n c.resolve(TOKENS.ALLOW_METHOD),\n opts.allowHeaders,\n withCredentials,\n ),\n )\n middlewares.push(TOKENS.OPTIONS_MIDDLEWARE)\n }\n\n if (opts.cors) {\n const { CORSMiddleware } = await import('@/presentation')\n container.addSingleton(TOKENS.CORS_MIDDLEWARE, (c) => {\n return new CORSMiddleware(c.resolve(TOKENS.CONTEXT_ACCESSOR), withCredentials)\n })\n middlewares.push(TOKENS.CORS_MIDDLEWARE)\n }\n\n if (Guards.isDefined(opts.routeRegistry)) {\n const registry = opts.routeRegistry\n const { AllowMethodFactory } = await import('../factories')\n container.addSingleton(TOKENS.ALLOW_METHOD, () => new AllowMethodFactory().create(registry))\n\n const { MethodCheckMiddleware } = await import('@/presentation')\n container.addSingleton(\n TOKENS.METHOD_CHECK_MIDDLEWARE,\n (c) =>\n new MethodCheckMiddleware(\n c.resolve(TOKENS.REQUEST_CONTEXT),\n c.resolve(TOKENS.ALLOW_METHOD),\n ),\n )\n middlewares.push(TOKENS.METHOD_CHECK_MIDDLEWARE)\n }\n\n const { AuthenticationMiddleware } = await import('@/presentation')\n container.addSingleton(TOKENS.AUTH_MIDDLEWARE, (c) => {\n return new AuthenticationMiddleware(\n c.resolve(TOKENS.REQUEST_CONTEXT),\n c.resolve(TOKENS.BEARER_TOKEN_EXTRACTOR),\n c.resolve(TOKENS.GATE_KEEPER),\n c.resolve(TOKENS.LOGGER),\n )\n })\n middlewares.push(TOKENS.AUTH_MIDDLEWARE)\n\n if (\n Guards.isDefined(opts.rateLimite.maxRequests) ||\n Guards.isDefined(opts.rateLimite.windowSeconds)\n ) {\n const maxRequests = opts.rateLimite.maxRequests ?? 30\n Guards.throwIfNegative(maxRequests, 'MaxRequests must be positive')\n Guards.throwIfNotInteger(maxRequests, 'MaxRequests must be an integer')\n const windowSeconds = opts.rateLimite.windowSeconds ?? 30\n Guards.throwIfNegative(windowSeconds, 'WindowSeconds must be positive')\n Guards.throwIfNotInteger(windowSeconds, 'WindowSeconds must be an integer')\n\n if (!opts.isCache) {\n const { CacheUtils } = await import('./utils/cache.utils')\n await CacheUtils.addCache(container, { inMemory: true, redis: undefined })\n }\n\n const { RateLimitKeyBuilder } = await import('../cache')\n container.addSingleton(\n 'RATE_LIMIT_KEY_BUILDER',\n (c) => new RateLimitKeyBuilder(c.resolve(TOKENS.REQUEST_CONTEXT)),\n )\n\n const { RateLimitMiddleware } = await import('@/presentation')\n container.addSingleton(TOKENS.RATE_LIMITER_MIDDLEWARE, (c) => {\n return new RateLimitMiddleware(\n c.resolve(TOKENS.CONTEXT_ACCESSOR),\n c.resolve(TOKENS.CACHE),\n c.resolve('RATE_LIMIT_KEY_BUILDER'),\n c.resolve(TOKENS.LOGGER),\n {\n maxRequests,\n windowSeconds,\n },\n )\n })\n middlewares.push(TOKENS.RATE_LIMITER_MIDDLEWARE)\n }\n\n if (Guards.isDefined(opts.csrf)) {\n const csrf = opts.csrf\n const { CsrfTokenService } = await import('../services')\n container.addSingleton('CSRF_TOKEN_SERVICE', (c) => {\n return new CsrfTokenService(csrf.secret, c.resolve('CRYPTO_SERVICE'))\n })\n\n const { CsrfCookieMiddleware } = await import('@/presentation')\n container.addSingleton('CSRF_COOKIE_MIDDLEWARE', (c) => {\n return new CsrfCookieMiddleware(\n c.resolve(TOKENS.REQUEST_CONTEXT),\n c.resolve('CSRF_TOKEN_SERVICE'),\n csrf,\n )\n })\n middlewares.push('CSRF_COOKIE_MIDDLEWARE')\n\n const { CsrfMiddleware } = await import('@/presentation')\n container.addSingleton(TOKENS.CSRF_MIDDLEWARE, (c) => {\n return new CsrfMiddleware(\n c.resolve(TOKENS.REQUEST_CONTEXT),\n c.resolve('CSRF_TOKEN_SERVICE'),\n )\n })\n middlewares.push(TOKENS.CSRF_MIDDLEWARE)\n }\n\n const { CompositeMiddleware } = await import('@/presentation')\n container.addSingleton(TOKENS.MIDDLEWARE, (c) => {\n const resolvedMiddleware = middlewares.map(\n (token) => c.resolve(token) as IMiddleware<HttpHeaders>,\n )\n return new CompositeMiddleware(resolvedMiddleware)\n })\n }\n}\n","import type { IFactory } from '@xeno-js/shared'\r\n\r\nimport type { IModule, IServiceContainer, IServiceScope } from '@/domain'\r\n\r\nimport type { XenoRegistry } from '../xeno-registry'\r\n\r\n/**\r\n * @description ContextModule is responsible for configuring and registering the necessary services and dependencies related to the request context in the application. It sets up the RequestContext service, which provides a way to manage and access contextual information related to a specific request or operation. By registering the RequestContext in the dependency injection container, it enables other parts of the application to easily resolve and utilize its functionality for managing request-specific data and state.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class ContextModule<TRegistry extends XenoRegistry = XenoRegistry> implements IModule<\r\n TRegistry,\r\n void\r\n> {\r\n async configure(container: IServiceContainer<TRegistry>): Promise<void> {\r\n const { TOKENS } = await import('@xeno-js/shared')\r\n const { ServiceScopeFactory } = await import('../factories/service-scope.factory')\r\n container.addSingleton(TOKENS.SERVICE_SCOPE_FACTORY, () => {\r\n const factory = new ServiceScopeFactory<TRegistry>(container)\r\n return factory\r\n })\r\n\r\n const { NodeRequestContextFactory } = await import('../factories/request-context.factory')\r\n container.addSingleton(TOKENS.REQUEST_CONTEXT, (c) => {\r\n return new NodeRequestContextFactory<TRegistry>(\r\n c.resolve(TOKENS.SERVICE_SCOPE_FACTORY) as IFactory<void, IServiceScope<TRegistry>>,\r\n ).create()\r\n })\r\n\r\n container.addSingleton(TOKENS.CONTEXT_ACCESSOR, (c) => c.resolve(TOKENS.REQUEST_CONTEXT))\r\n container.addSingleton(TOKENS.IDENTITY_ACCESSOR, (c) => c.resolve(TOKENS.REQUEST_CONTEXT))\r\n container.addSingleton(TOKENS.SERVICE_SCOPE_ACCESSOR, (c) => c.resolve(TOKENS.REQUEST_CONTEXT))\r\n container.addSingleton(TOKENS.NETWORK_CONTEXT_ACCESSOR, (c) =>\r\n c.resolve(TOKENS.REQUEST_CONTEXT),\r\n )\r\n const { UserContextFactory } = await import('../factories/user-context.factory')\r\n container.addSingleton(TOKENS.USER_CONTEXT_FACTORY, (c) => {\r\n const requestContext = c.resolve(TOKENS.REQUEST_CONTEXT)\r\n return new UserContextFactory(requestContext)\r\n })\r\n }\r\n}\r\n","export {\r\n BaseAuthorizationStrategy,\r\n BaseHandler,\r\n ContainerUtils,\r\n Specification,\r\n} from './application'\r\nexport type * from './domain'\r\nexport type { XenoRegistry } from './infrastructure'\r\nexport { AppBuilder, ReadDao, Repository, SupabaseServerAuthFactory } from './infrastructure'\r\nexport type * from './infrastructure/db/db.types'\r\nexport type { Query } from './infrastructure/db/drizzle.types'\r\nexport * from './infrastructure/db/drizzle.types'\r\nexport { BaseController } from './presentation'\r\nexport * from '@xeno-js/shared'\r\nexport { Query as BaseQuery } from '@xeno-js/shared'\r\n","import type { SupabaseClientOptions } from '@supabase/supabase-js'\nimport type { CacheConfig, DbConfig, IConfigurationService } from '@xeno-js/shared'\nimport type { Optional, SetupAction } from '@xeno-js/shared'\nimport { Guards, LOG_LEVEL, TOKENS } from '@xeno-js/shared'\nimport type { ZodType } from 'zod'\n\nimport type {\n ApplicationRegistry,\n AuthSsrConfig,\n HttpCoreConfig,\n IModule,\n IServiceContainer,\n LoggerConfig,\n MiddlewareConfig,\n PipelineConfig,\n} from '@/domain'\n\nimport { EnvironmentConfigurationService } from '../configuration'\nimport { ServiceContainer } from '../container/service-container'\nimport type { XenoRegistry } from '../xeno-registry'\n\n/**\n * @description The AppBuilder class provides a fluent, .NET-style API for configuring and bootstrapping the application. It orchestrates the registration of various modules (CQRS, HTTP, Database, Logging, Auth) into the ServiceContainer.\n\n * \n * @author Xeno\n * @version 1.0.0\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-js \n */\ninterface QueuedModule {\n priority: number\n name: string\n action: () => Promise<void>\n}\n\n/**\n * @description The AppBuilder class provides a fluent, .NET-style API for configuring and bootstrapping the application.\n * It orchestrates the registration of various modules (CQRS, HTTP, Database, Logging, Auth) into the ServiceContainer.\n\n * \n * @author Xeno\n * @version 1.0.0\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-js \n */\nexport class AppBuilder<TRegistry extends XenoRegistry = XenoRegistry> {\n private readonly _container: IServiceContainer<TRegistry> = new ServiceContainer<TRegistry>()\n private readonly _configuration: IConfigurationService\n\n constructor(container?: IServiceContainer<TRegistry>) {\n this._container = container ?? new ServiceContainer<TRegistry>()\n\n this._container.addSingleton(\n TOKENS.CONFIGURATION_SERVICE,\n () => new EnvironmentConfigurationService(),\n )\n this._configuration = this._container.resolve(TOKENS.CONFIGURATION_SERVICE)\n this._middlewareConfig.allowOrigins?.push(\n this._configuration.get('APP_URL') ??\n `http://localhost:${this._configuration.getNumber('PORT', 3000)}`,\n )\n }\n\n // --- Module Configurations ---\n private readonly _modules: QueuedModule[] = []\n\n // --- Specific Configurations ---\n private _pipelineConfig: PipelineConfig<TRegistry, ZodType> = {\n performance: { thresholdMs: 500 },\n authorization: {\n policies: undefined,\n customAuthorizationStrategy: undefined,\n },\n validation: {\n zod: undefined,\n customValidationStrategy: undefined,\n },\n commandBus: {\n idempotency: undefined,\n concurrency: undefined,\n },\n queryBus: { isEnabled: false },\n }\n private _config: CacheConfig = { inMemory: true, redis: undefined }\n private _middlewareConfig: MiddlewareConfig = {\n isSSR: false,\n rateLimite: {\n maxRequests: 3,\n windowSeconds: 100,\n },\n csrf: undefined,\n optionsMiddleware: false,\n routeRegistry: undefined,\n trustedIpHeader: undefined,\n trustedProxies: [],\n allowOrigins: [],\n allowHeaders: [],\n cors: true,\n withCredentials: true,\n }\n private readonly _httpConfig: HttpCoreConfig<TRegistry> = {\n dataSourceToken: undefined,\n http: {\n token: undefined,\n client: {\n defaultHeaders: undefined,\n baseURL: undefined,\n timeoutMs: undefined,\n keepAlive: undefined,\n maxSockets: undefined,\n maxRedirects: undefined,\n decompress: undefined,\n withCredentials: undefined,\n proxy: false,\n },\n },\n resilience: { retry: {}, circuitBreaker: {}, bulkhead: {} },\n } as unknown as HttpCoreConfig<TRegistry>\n\n // --- Module Queuing Flags ---\n private _isContextModuleQueued = false\n private _isMiddlewareModuleQueued = false\n private _isPipelineModuleQueued = false\n private _isLoggerModuleQueued = false\n private _isAuthModuleQueued = false\n private _isDbContextModuleQueued = false\n private _isConcurrencyServiceQueued = false\n private _isCacheModuleQueued = false\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Application Modules Configuration\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * @description Enables the use of middlewares in the application. Middlewares can be used for cross-cutting concerns such as logging, authentication, and request/response manipulation.\n * @returns The current instance of AppBuilder for method chaining.\n \n * \n * @author Xeno\n * @version 1.0.0\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-js \n */\n public addMiddlewares(setupAction: SetupAction<MiddlewareConfig, IConfigurationService>): this {\n setupAction(this._middlewareConfig, this._configuration)\n this._queueMiddlewareModule()\n return this\n }\n\n /**\n * @description Enables the use of context in the application. Context can be used to store and manage request-specific data, such as user information, correlation IDs, and other metadata that needs to be accessible throughout the request lifecycle.\n * @returns The current instance of AppBuilder for method chaining.\n \n * \n * @author Xeno\n * @version 1.0.0\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-js \n */\n public addContext(): this {\n this._queueContextModule()\n return this\n }\n\n /**\n * @description Configures the logger for the application. This method allows you to set up logging options such as log level, console logging, and integration with external logging services like Sentry or Pino.\n * @param setupAction A callback function that receives a LoggerConfig object to configure the logger settings.\n * @returns The current instance of AppBuilder for method chaining.\n \n * \n * @author Xeno\n * @version 1.0.0\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-js \n */\n public addLogger(\n setupAction?: SetupAction<LoggerConfig<TRegistry>, IConfigurationService>,\n ): this {\n if (this._isLoggerModuleQueued) return this\n this._isLoggerModuleQueued = true\n const config = {\n level: LOG_LEVEL.DEBUG,\n console: true,\n sentry: { config: undefined },\n pino: { config: undefined },\n customLoggers: undefined,\n } as unknown as Optional<LoggerConfig<ApplicationRegistry<unknown>>>\n if (Guards.isDefined(setupAction) && Guards.isDefined(config))\n setupAction(config, this._configuration)\n\n this._modules.push({\n priority: 3,\n name: 'LoggerModule',\n action: async () => {\n const { LoggerUtils } = await import('../modules/utils/logger.utils')\n await LoggerUtils.addLogger(this._container, config)\n },\n })\n return this\n }\n\n /**\n * @description Configures the caching settings for the application. This method allows you to set up caching options such as Redis configuration or in-memory caching.\n * @param setupAction A callback function that receives a CacheConfig object to configure the caching settings.\n * @returns The current instance of AppBuilder for method chaining.\n \n * \n * @author Xeno\n * @version 1.0.0\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-js \n */\n public addCache(setupAction?: SetupAction<CacheConfig, IConfigurationService>): this {\n if (this._isCacheModuleQueued) return this\n this._isCacheModuleQueued = true\n if (Guards.isDefined(setupAction)) setupAction(this._config, this._configuration)\n\n this._modules.push({\n priority: 3,\n name: 'CacheModule',\n action: async () => {\n const { CacheUtils } = await import('../modules/utils/cache.utils')\n await CacheUtils.addCache(this._container, this._config)\n },\n })\n return this\n }\n\n /**\n * @description Configures the authentication client for the application. This method allows you to set up authentication options such as the authentication server URL, API key, and additional options.\n * @param setupAction A callback function that receives an AuthClientConfig object to configure the authentication client settings.\n * @returns The current instance of AppBuilder for method chaining.\n \n * \n * @author Xeno\n * @version 1.0.0\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-js \n */\n public addAuth(\n setupAction: SetupAction<AuthSsrConfig<SupabaseClientOptions<'public'>>, IConfigurationService>,\n ): this {\n if (this._isAuthModuleQueued) return this\n this._isAuthModuleQueued = true\n const config: AuthSsrConfig<SupabaseClientOptions<'public'>> = {\n url: '',\n key: '',\n opts: undefined,\n redirectTo: '',\n storageOpts: { type: 'memory', cookieOpts: undefined, storage: undefined },\n ssrOpts: undefined,\n }\n setupAction(config, this._configuration)\n this._modules.push({\n priority: 2,\n name: 'AuthModule',\n action: async () => {\n const { AuthUtils } = await import('../modules/utils/auth.utils')\n await AuthUtils.addAuthN(this._container, config)\n },\n })\n return this\n }\n\n /**\n * @description Configures the database settings for the application. This method allows you to set up database options such as enabling/disabling the database, connection string, and table definitions.\n * @param setupAction A callback function that receives a DbConfig object to configure the database settings.\n * @returns The current instance of AppBuilder for method chaining.\n \n * \n * @author Xeno\n * @version 1.0.0\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-js \n */\n public addDb(setupAction: SetupAction<DbConfig, IConfigurationService>): this {\n if (this._isDbContextModuleQueued) return this\n this._isDbContextModuleQueued = true\n const config = { connectionString: '', enableSqlLite: false }\n setupAction(config, this._configuration)\n this._modules.push({\n priority: 4,\n name: 'DbModule',\n action: async () => {\n const { DbModule } = await import('../modules/db.module')\n const dbModule = new DbModule()\n await dbModule.configure(this._container, config)\n },\n })\n return this\n }\n\n /**\n * @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.\n * @returns The current instance of AppBuilder for method chaining.\n \n * \n * @author Xeno\n * @version 1.0.0\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-js \n */\n public addConcurrencyService(): this {\n if (this._isConcurrencyServiceQueued) return this\n this._isConcurrencyServiceQueued = true\n this._modules.push({\n priority: 40,\n name: 'ConcurrencyServiceModule',\n action: async () => {\n const { PLimitConcurrencyService } = await import('../services/concurrency')\n this._container.addSingleton('CONCURRENCY_SERVICE', () => new PLimitConcurrencyService())\n },\n })\n return this\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // CQRS Pipeline Configuration\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * @description Configures the CQRS pipeline settings for the application. This method allows you to set up various aspects of the CQRS pipeline, including performance monitoring, authorization, validation, command bus settings, and query bus settings.\n * @param setupAction A callback function that receives a PipelineConfig object to configure the CQRS pipeline settings.\n * @returns The current instance of AppBuilder for method chaining.\n \n * \n * @author Xeno\n * @version 1.0.0\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-js \n */\n public addPipeline(\n setupAction?: SetupAction<PipelineConfig<TRegistry>, IConfigurationService>,\n ): this {\n if (Guards.isDefined(setupAction)) {\n setupAction(this._pipelineConfig, this._configuration)\n }\n this._queuePipelineModule()\n return this\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // HTTP & Resilience Configuration\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * @description Configures the HTTP core settings for the application. This method allows you to set up HTTP core options such as data source token, HTTP client configuration, and resilience settings.\n * @param setupAction A callback function that receives an HttpCoreConfig object to configure the HTTP core settings.\n * @returns The current instance of AppBuilder for method chaining.\n \n * \n * @author Xeno\n * @version 1.0.0\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-js \n */\n public addHttpCore(\n setupAction: SetupAction<HttpCoreConfig<TRegistry>, IConfigurationService>,\n ): this {\n setupAction(this._httpConfig, this._configuration)\n this._modules.push({\n priority: 30,\n name: 'HttpCoreModule',\n action: async () => {\n const { HttpCoreModule } = await import('../modules/http-core.module')\n const coreModule = new HttpCoreModule<TRegistry>()\n await coreModule.configure(this._container, this._httpConfig)\n },\n })\n return this\n }\n\n public addAllowOrigin(setupAction: SetupAction<string[], IConfigurationService>): this {\n const config: string[] = []\n setupAction(config, this._configuration)\n this._modules.push({\n priority: 30,\n name: 'HttpCoreModule',\n action: async () => {\n const { HttpOriginModule } = await import('../modules/http-core.module')\n const httpOriginModule = new HttpOriginModule()\n await httpOriginModule.configure(this._container, config)\n },\n })\n return this\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Dependency Injection Pass-through Methods\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * @description Registers services in the application. This method allows you to add custom services to the dependency injection container, enabling modular and organized configuration of services.\n * @param setupAction A callback function that receives the IServiceContainer to register services.\n * @returns The current instance of AppBuilder for method chaining.\n *\n * @author Xeno\n * @version 1.0.0\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-js\n */\n public addServices(\n setupAction: SetupAction<IServiceContainer<TRegistry>, IConfigurationService>,\n ): this {\n this._modules.push({\n priority: 99,\n name: 'ClientServicesModule',\n action: async () => {\n setupAction(this._container, this._configuration)\n },\n })\n return this\n }\n\n /**\n * @description Registers a module in the application. A module is a self-contained unit of functionality that can configure services and dependencies in the service container. This method allows you to add custom modules to the application, enabling modular and organized configuration of services.\n * @param factory A factory function that creates the module instance.\n * @param opts Optional configuration options for the module.\n * @returns The current instance of AppBuilder for method chaining.\n *\n *\n * @author Xeno\n * @version 1.0.0\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-js\n */\n public addModule<T>(name: string, factory: () => Promise<IModule<TRegistry, T>>, opts?: T): this {\n this._modules.push({\n priority: 50,\n name,\n action: async () => {\n const module = await factory()\n await module.configure(this._container, opts)\n },\n })\n return this\n }\n\n /**\n * @description Resolves a service from the dependency injection container.\n * @param token The injection token used to identify the service.\n * @returns The resolved service instance.\n \n * \n * @author Xeno\n * @version 1.0.0\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-js \n */\n public resolve<K extends keyof TRegistry>(token: K): TRegistry[K] {\n return this._container.resolve(token)\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Build\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * @description Finalizes the configuration and initializes all registered modules in the container.\n * @returns The fully configured ServiceContainer.\n \n * \n * @author Xeno\n * @version 1.0.0\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-js \n */\n public async build(): Promise<IServiceContainer<TRegistry>> {\n console.info('⚙️ Bootstrapping application modules...')\n const sortedModules = this._modules.sort((a, b) => a.priority - b.priority)\n for (const queued of sortedModules) {\n try {\n await queued.action()\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error)\n\n console.error(`\\n❌ [AppBuilder Fatal Error]`)\n console.error(`An error occurred while initializing the module:`)\n console.error(`👉 Module: **${queued.name}**`)\n console.error(`📝 Reason: ${errorMessage}\\n`)\n\n if (error instanceof Error && Guards.isDefined(error.stack)) {\n console.error(error.stack)\n }\n\n throw new Error(`Bootstrap failed at [${queued.name}]: ${errorMessage}`, { cause: error })\n }\n }\n console.info('✅ Application modules bootstrapped successfully.')\n return this._container\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Private Helper Methods\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * @description Queues the configuration of the CQRS pipeline module if it has not already been queued. This method ensures that the pipeline module is only added once, even if multiple pipeline-related configurations are made.\n \n * \n * @author Xeno\n * @version 1.0.0\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-js \n */\n private _queuePipelineModule(): void {\n if (this._isPipelineModuleQueued) return\n this._isPipelineModuleQueued = true\n\n this._queueContextModule()\n\n this._modules.push({\n priority: 5,\n name: 'CqrsModule',\n action: async () => {\n const { CqrsModule } = await import('../modules/cqrs.module')\n const pipelineModule = new CqrsModule<TRegistry>()\n await pipelineModule.configure(this._container, {\n ...this._pipelineConfig,\n isLogger: this._isLoggerModuleQueued || this._isMiddlewareModuleQueued,\n isCache: !this._isCacheModuleQueued,\n })\n },\n })\n }\n\n /**\n * @description Queues the configuration of the middleware module if it has not already been queued. This method ensures that the middleware module is only added once, even if multiple middleware-related configurations are made.\n \n * \n * @author Xeno\n * @version 1.0.0\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-js \n */\n private _queueMiddlewareModule(): void {\n if (this._isMiddlewareModuleQueued) return\n this._isMiddlewareModuleQueued = true\n\n this._queueContextModule()\n\n this._modules.push({\n priority: 3,\n name: 'MiddlewareModule',\n action: async () => {\n const { MiddlewareModule } = await import('../modules/middleware.module')\n const middlewareModule = new MiddlewareModule()\n await middlewareModule.configure(this._container, {\n ...this._middlewareConfig,\n isAuth: this._isAuthModuleQueued,\n isLogger: this._isLoggerModuleQueued,\n isCache: this._isCacheModuleQueued || this._isPipelineModuleQueued,\n })\n },\n })\n }\n\n /**\n * @description Queues the configuration of the context module if it has not already been queued. This method ensures that the context module is only added once, even if multiple context-related configurations are made.\n \n * \n * @author Xeno\n * @version 1.0.0\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-js \n */\n private _queueContextModule(): void {\n if (this._isContextModuleQueued) return\n this._isContextModuleQueued = true\n\n this._modules.push({\n priority: 0,\n name: 'ContextModule',\n action: async () => {\n const { ContextModule } = await import('../modules/context.module')\n const contextModule = new ContextModule<TRegistry>()\n await contextModule.configure(this._container)\n },\n })\n }\n}\n","import type { IConfigurationService } from '@xeno-js/shared'\r\nimport type { Dictionary, Optional } from '@xeno-js/shared'\r\nimport { Guards } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description\r\n * This class implements the IConfigurationService interface and provides methods to retrieve configuration values from environment variables.\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class EnvironmentConfigurationService implements IConfigurationService {\r\n /**\r\n * @description Internal dictionary to hold environment variables.\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n private readonly _env: Dictionary<Optional<string>>\r\n\r\n /**\r\n * @description Constructs an instance of EnvironmentConfigurationService and initializes the internal environment variable dictionary.\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n constructor() {\r\n this._env = process.env\r\n }\r\n\r\n public get(key: string, defaultValue?: string): Optional<string> {\r\n const value = this._env[key]\r\n if (Guards.isNullOrEmpty(value)) {\r\n return defaultValue\r\n }\r\n return value\r\n }\r\n\r\n public getNumber(key: string, defaultValue?: number): Optional<number> {\r\n const value = this.get(key)\r\n if (!Guards.isDefined(value)) {\r\n return defaultValue\r\n }\r\n const parsed = Number(value)\r\n if (isNaN(parsed)) {\r\n throw new Error(\r\n `[Configuration Error]: Key \"${key}\" with value \"${value}\" is not a valid number.`,\r\n )\r\n }\r\n return parsed\r\n }\r\n\r\n public getBoolean(key: string, defaultValue?: boolean): Optional<boolean> {\r\n const value = this.get(key)\r\n if (!Guards.isDefined(value)) {\r\n return defaultValue\r\n }\r\n const normalized = value.toLowerCase().trim()\r\n if (normalized === 'true' || normalized === '1') return true\r\n if (normalized === 'false' || normalized === '0') return false\r\n\r\n throw new Error(\r\n `[Configuration Error]: Key \"${key}\" with value \"${value}\" is not a valid boolean.`,\r\n )\r\n }\r\n\r\n public getOrThrow(key: string): string {\r\n const value = this.get(key)\r\n if (!Guards.isDefined(value)) {\r\n throw new Error(\r\n `[Configuration Error]: Required configuration key \"${key}\" is missing in the environment.`,\r\n )\r\n }\r\n return value\r\n }\r\n}\r\n","import { AsyncLocalStorage } from 'node:async_hooks'\r\n\r\nimport type { Factory, IDisposable } from '@xeno-js/shared'\r\nimport { Guards } from '@xeno-js/shared'\r\n\r\nimport type { ApplicationRegistry, IServiceContainer, IServiceScope, Lifetime } from '@/domain'\r\n\r\nimport type { DbContext } from '../db'\r\n\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n\r\n/**\r\n * @description Represents a registration entry in the service container, encapsulating the token, lifetime, and factory function for creating instances of the service.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\ninterface RegistrationEntry<\r\n T,\r\n Registry extends ApplicationRegistry<DbContext> = ApplicationRegistry<DbContext>,\r\n> {\r\n /**\r\n * The unique injection token that identifies the service registration.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n token: keyof Registry\r\n /**\r\n * The lifetime of the service registration, indicating how instances are managed and reused.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n lifetime: Lifetime\r\n /**\r\n * The factory function responsible for creating instances of the service.\r\n * It receives the current service scope as an argument, allowing for dependency resolution within that scope.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n factory: Factory<T, [IServiceScope<Registry>]>\r\n}\r\n\r\n/**\r\n * @description Represents the context of service resolution, including the stack of tokens being resolved and the active lifetime of the current resolution.\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\ninterface ResolutionContext<Registry> {\r\n /**\r\n * A set of tokens currently being resolved, used to detect circular dependencies.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n stack: Set<keyof Registry>\r\n /**\r\n * The active lifetime of the current resolution, indicating whether we are constructing a singleton, scoped, or transient service.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n activeLifetime?: Lifetime\r\n}\r\n\r\n/**\r\n * @description Concrete implementation of {@link IServiceScope}, representing a logical scope for resolving scoped services within the service container.\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nclass ContainerScope<\r\n Registry extends ApplicationRegistry<DbContext> = ApplicationRegistry<DbContext>,\r\n> implements IServiceScope<Registry> {\r\n private readonly scopedInstances = new Map<keyof Registry, unknown>()\r\n private readonly trackedDisposables: unknown[] = []\r\n private isDisposed = false\r\n\r\n constructor(\r\n private readonly container: ServiceContainer<Registry>,\r\n private readonly parentScope?: ContainerScope<Registry>,\r\n ) {}\r\n\r\n public resolve<K extends keyof Registry>(token: K): Registry[K] {\r\n if (this.isDisposed) {\r\n throw new Error(\r\n `[DI Container Error]: Unable to resolve '${token as string}'. The scope has been closed.`,\r\n )\r\n }\r\n return this.container.internalExecuteInContext(() =>\r\n this.container.internalResolveInternal(token, this),\r\n )\r\n }\r\n\r\n public getScopedInstance<K extends keyof Registry>(token: K): Registry[K] | undefined {\r\n return this.scopedInstances.get(token) as Registry[K] | undefined\r\n }\r\n\r\n public setScopedInstance<K extends keyof Registry>(token: K, instance: Registry[K]): void {\r\n this.scopedInstances.set(token, instance)\r\n if (isDisposable.check(instance)) {\r\n this.trackedDisposables.push(instance)\r\n }\r\n }\r\n\r\n public trackInstance(instance: unknown): void {\r\n if (isDisposable.check(instance) && !this.trackedDisposables.includes(instance)) {\r\n this.trackedDisposables.push(instance)\r\n }\r\n }\r\n\r\n public async dispose(): Promise<void> {\r\n if (this.isDisposed) return\r\n this.isDisposed = true\r\n\r\n for (let i = this.trackedDisposables.length - 1; i >= 0; i--) {\r\n const disposable = this.trackedDisposables[i]\r\n if (isDisposable.check(disposable)) {\r\n try {\r\n await disposable.dispose()\r\n } catch (err) {\r\n console.error(`[DI Container Dispose Error]: Failed to dispose resource`, err)\r\n }\r\n }\r\n }\r\n\r\n this.scopedInstances.clear()\r\n this.trackedDisposables.length = 0\r\n }\r\n}\r\n\r\n/**\r\n * @description Concrete implementation of {@link IServiceContainer}.\r\n *\r\n * Supports three registration lifetimes:\r\n * - **singleton** — one shared instance per container.\r\n * - **transient** — a new instance on every {@link resolve} call.\r\n * - **scoped** — one instance per {@link IServiceScope}; must be resolved\r\n * through a scope obtained via {@link createScope}.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class ServiceContainer<\r\n Registry extends ApplicationRegistry<DbContext> = ApplicationRegistry<DbContext>,\r\n> implements IServiceContainer<Registry> {\r\n private readonly registrations = new Map<keyof Registry, RegistrationEntry<unknown, Registry>>()\r\n private readonly singletonInstances = new Map<keyof Registry, unknown>()\r\n private readonly rootScope: ContainerScope<Registry>\r\n private readonly resolutionStack = new AsyncLocalStorage<ResolutionContext<Registry>>()\r\n\r\n constructor() {\r\n this.rootScope = new ContainerScope<Registry>(this)\r\n }\r\n\r\n public addSingleton<K extends keyof Registry>(\r\n token: K,\r\n factory: Factory<Registry[K], [IServiceScope<Registry>]>,\r\n ): this {\r\n this.register(token, 'singleton', factory)\r\n return this\r\n }\r\n\r\n public addScoped<K extends keyof Registry>(\r\n token: K,\r\n factory: Factory<Registry[K], [IServiceScope<Registry>]>,\r\n ): this {\r\n this.register(token, 'scoped', factory)\r\n return this\r\n }\r\n\r\n public addTransient<K extends keyof Registry>(\r\n token: K,\r\n factory: Factory<Registry[K], [IServiceScope<Registry>]>,\r\n ): this {\r\n this.register(token, 'transient', factory)\r\n return this\r\n }\r\n\r\n private register<K extends keyof Registry>(\r\n token: K,\r\n lifetime: Lifetime,\r\n factory: Factory<Registry[K], [IServiceScope<Registry>]>,\r\n ): void {\r\n if (this.registrations.has(token)) {\r\n const tokenName = token.toString()\r\n throw new Error(\r\n `[DI Container Error]: The token '${tokenName}' is already registered in the container.`,\r\n )\r\n }\r\n this.registrations.set(token, { token, lifetime, factory })\r\n }\r\n\r\n public resolve<K extends keyof Registry>(token: K): Registry[K] {\r\n return this.internalExecuteInContext(() => this.rootScope.resolve(token))\r\n }\r\n\r\n public createScope(): IServiceScope<Registry> {\r\n return new ContainerScope<Registry>(this, this.rootScope)\r\n }\r\n\r\n /**\r\n * Executes a callback function within the context of the service container's resolution stack.\r\n * This method ensures that the resolution stack is properly managed, allowing for circular dependency detection and lifetime tracking during service resolution.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n internalExecuteInContext<T>(callback: () => T): T {\r\n const currentStack = this.resolutionStack.getStore()\r\n if (!Guards.isDefined(currentStack)) {\r\n const initialContext: ResolutionContext<Registry> = {\r\n stack: new Set<keyof Registry>(),\r\n }\r\n return this.resolutionStack.run(initialContext, callback)\r\n }\r\n return callback()\r\n }\r\n\r\n /**\r\n * Resolve the service for the given token within the provided scope.\r\n * @param token The injection token to resolve.\r\n * @param currentScope The current service scope for resolving scoped services.\r\n * @returns The resolved service instance of type `T`.\r\n * @throws An error if no registration is found for the given token.\r\n * @throws An error if a circular dependency is detected.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n internalResolveInternal<K extends keyof Registry>(\r\n token: K,\r\n currentScope: ContainerScope<Registry>,\r\n ): Registry[K] {\r\n const registration = this.registrations.get(token)\r\n if (!Guards.isDefined(registration)) {\r\n const tokenName = token.toString()\r\n throw new Error(\r\n `[DI Container Error]: Registration not found for token '${tokenName}'. Ensure the service is registered before resolving.`,\r\n )\r\n }\r\n\r\n const currentStack = this.resolutionStack.getStore()\r\n if (!Guards.isDefined(currentStack)) {\r\n throw new Error(`[DI Container Error]: Execution outside the IoC container context.`)\r\n }\r\n\r\n if (currentStack.stack.has(token)) {\r\n const cyclePath = [...currentStack.stack, token].map((t) => t.toString()).join(' -> ')\r\n const tokenName = token.toString()\r\n throw new Error(\r\n `[DI Circular Dependency Error]: Detected circular dependency while resolving '${tokenName}'. Resolution path: ${cyclePath}`,\r\n )\r\n }\r\n\r\n if (currentStack.activeLifetime === 'singleton' && registration.lifetime === 'scoped') {\r\n const captivePath = [...currentStack.stack, token].map((t) => t.toString()).join(' -> ')\r\n throw new Error(\r\n `[DI Captive Dependency Error]: Attempted to resolve a scoped service '${token.toString()}' from a singleton context. This can lead to captive dependencies. Resolution path: ${captivePath}`,\r\n )\r\n }\r\n\r\n const executeWithStackIsolation = (\r\n targetLifetime: Lifetime,\r\n factoryFn: () => Registry[K],\r\n ): Registry[K] => {\r\n const previousLifetime = currentStack.activeLifetime\r\n currentStack.stack.add(token)\r\n\r\n currentStack.activeLifetime =\r\n registration.lifetime === 'singleton' ? 'singleton' : previousLifetime\r\n try {\r\n return factoryFn()\r\n } finally {\r\n currentStack.stack.delete(token)\r\n currentStack.activeLifetime = previousLifetime\r\n }\r\n }\r\n\r\n if (registration.lifetime === 'singleton') {\r\n if (this.singletonInstances.has(token)) {\r\n return this.singletonInstances.get(token) as Registry[K]\r\n }\r\n\r\n return executeWithStackIsolation('singleton', () => {\r\n const instance = registration.factory(currentScope) as Registry[K]\r\n this.singletonInstances.set(token, instance)\r\n this.rootScope.trackInstance(instance)\r\n return instance\r\n })\r\n }\r\n\r\n if (registration.lifetime === 'scoped') {\r\n const existingInstance = currentScope.getScopedInstance(token)\r\n if (Guards.isDefined(existingInstance)) {\r\n return existingInstance\r\n }\r\n\r\n return executeWithStackIsolation('scoped', () => {\r\n const instance = registration.factory(currentScope) as Registry[K]\r\n currentScope.setScopedInstance(token, instance)\r\n return instance\r\n })\r\n }\r\n\r\n return executeWithStackIsolation('transient', () => {\r\n const instance = registration.factory(currentScope) as Registry[K]\r\n if (isDisposable.check(instance)) {\r\n currentScope.trackInstance(instance)\r\n }\r\n return instance\r\n })\r\n }\r\n\r\n public async dispose(): Promise<void> {\r\n await this.rootScope.dispose()\r\n this.singletonInstances.clear()\r\n this.registrations.clear()\r\n }\r\n}\r\n\r\nconst isDisposable = Object.freeze({\r\n check: (obj: unknown): obj is IDisposable => {\r\n return (\r\n Guards.isDefined(obj) &&\r\n Guards.isObject(obj) &&\r\n 'dispose' in obj &&\r\n Guards.hasMethod(obj, 'dispose')\r\n )\r\n },\r\n} as const)\r\n","export * from './builder/index'\r\nexport * from './cache/index'\r\nexport * from './configuration/index'\r\nexport * from './container/index'\r\nexport * from './context/index'\r\nexport * from './datasources'\r\nexport type * from './db/index'\r\nexport * from './factories/index'\r\nexport * from './idempotency/index'\r\nexport * from './loggers/index'\r\nexport * from './modules/index'\r\nexport * from './repositories/index'\r\nexport * from './services/index'\r\nexport * from './transaction/index'\r\nexport type * from './xeno-registry/index'\r\n","export * from './request-context'\r\n","import type {\r\n HttpBaseRequest,\r\n HttpMethod,\r\n HttpRequest,\r\n IHttpClient,\r\n IRemoteDataSource,\r\n IServiceResilience,\r\n Optional,\r\n ResultType,\r\n} from '@xeno-js/shared'\r\nimport { AppError, Result } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description Concrete implementation of the IRemoteDataSource contract that utilizes an agnostic HTTP client and a resilience service to fetch data from remote endpoints. The RemoteDataSource class is responsible for sending HTTP requests based on the provided HttpClientRequest parameters, while leveraging the resilience features of the IServiceResilience to ensure reliable communication with external services. This implementation abstracts away the details of how HTTP requests are made and how resilience is handled, allowing for flexibility in choosing different HTTP clients and resilience strategies without affecting the consumers of the IRemoteDataSource interface.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport abstract class RemoteDataSource implements IRemoteDataSource {\r\n /** The constructor of the RemoteDataSource class takes two dependencies: an instance of an agnostic HTTP client that implements the IHttpClient interface, and an instance of a resilience service that implements the IServiceResilience interface.\r\n * These dependencies are injected into the class, allowing for greater flexibility and testability.\r\n * The HTTP client is used to send requests to remote endpoints, while the resilience service is used to execute these requests with built-in support for retries, timeouts, and circuit breakers, ensuring that the remote calls are more resilient to failures and can recover gracefully from errors.\r\n * @param _httpClient An instance of an agnostic HTTP client that implements the IHttpClient interface, used for sending HTTP requests to remote endpoints.\r\n * @param _resilienceService An instance of a resilience service that implements the IServiceResilience interface, used for executing HTTP requests with built-in support for retries, timeouts, and circuit breakers to enhance the reliability of remote calls.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n constructor(\r\n private readonly _httpClient: IHttpClient,\r\n private readonly _resilienceService: IServiceResilience,\r\n ) {}\r\n\r\n /** @description Private method that sends an HTTP request to a specified endpoint using the provided HttpRequest options. The method utilizes the resilience service to execute the request, ensuring that it is performed with built-in support for retries, timeouts, and circuit breakers. The response from the HTTP client is then wrapped in a ResultType, which encapsulates either the successful response data or an error, providing a consistent way to handle both success and failure cases.\r\n * @param endpoint The URL or endpoint to which the HTTP request is sent.\r\n * @param options The HttpRequest options that specify the HTTP method, headers, query parameters, body, and other request configurations.\r\n * @returns A Promise that resolves to a ResultType containing either the successful response data or an error if the request fails.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n private async send<TResponse, TBody = unknown>(\r\n endpoint: string,\r\n options: HttpRequest<TBody>,\r\n ): Promise<ResultType<TResponse>> {\r\n const response = await this._resilienceService.execute(async () => {\r\n switch (options.method) {\r\n case 'GET':\r\n return await this._httpClient.get<TResponse>(endpoint, options)\r\n case 'POST':\r\n return await this._httpClient.post<TResponse, TBody>(endpoint, options.body, options)\r\n case 'PUT':\r\n return await this._httpClient.put<TResponse, TBody>(endpoint, options.body, options)\r\n case 'PATCH':\r\n return await this._httpClient.patch<TResponse, TBody>(endpoint, options.body, options)\r\n case 'DELETE':\r\n return await this._httpClient.delete<TResponse>(endpoint, options)\r\n default:\r\n throw AppError.notSupported(\r\n this.constructor.name,\r\n `Unsupported HTTP method: ${options.method}`,\r\n )\r\n }\r\n }, options.signal)\r\n\r\n return Result.ok(response.data)\r\n }\r\n\r\n protected setOptions<T>(\r\n request: Optional<HttpBaseRequest>,\r\n method: HttpMethod,\r\n body: Optional<T> = undefined,\r\n ): HttpRequest<T> {\r\n return {\r\n query: request?.query,\r\n signal: request?.signal,\r\n timeoutMs: request?.timeoutMs,\r\n headers: request?.headers,\r\n responseType: request?.responseType,\r\n method,\r\n body,\r\n }\r\n }\r\n\r\n public async get<TResponse>(\r\n endpoint: string,\r\n request?: HttpBaseRequest,\r\n ): Promise<ResultType<TResponse>> {\r\n const options = this.setOptions(request, 'GET')\r\n\r\n return await this.send<TResponse>(endpoint, options)\r\n }\r\n\r\n public async post<TResponse, TBody = unknown>(\r\n endpoint: string,\r\n body: TBody,\r\n request?: HttpBaseRequest,\r\n ): Promise<ResultType<TResponse>> {\r\n const options = this.setOptions(request, 'POST', body)\r\n\r\n return await this.send<TResponse, TBody>(endpoint, options)\r\n }\r\n\r\n public async put<TResponse, TBody = unknown>(\r\n endpoint: string,\r\n body: TBody,\r\n request?: HttpBaseRequest,\r\n ): Promise<ResultType<TResponse>> {\r\n const options = this.setOptions(request, 'PUT', body)\r\n\r\n return await this.send<TResponse, TBody>(endpoint, options)\r\n }\r\n\r\n public async patch<TResponse, TBody = unknown>(\r\n endpoint: string,\r\n body: TBody,\r\n request?: HttpBaseRequest,\r\n ): Promise<ResultType<TResponse>> {\r\n const options = this.setOptions(request, 'PATCH', body)\r\n\r\n return await this.send<TResponse, TBody>(endpoint, options)\r\n }\r\n\r\n public async delete<TResponse>(\r\n endpoint: string,\r\n request?: HttpBaseRequest,\r\n ): Promise<ResultType<TResponse>> {\r\n const options = this.setOptions(request, 'DELETE')\r\n\r\n return await this.send<TResponse>(endpoint, options)\r\n }\r\n}\r\n","export * from './idempotency-store'\r\n","export * from './console.logger'\r\nexport * from './pino.logger'\r\nexport * from './sentry.logger'\r\n","export * from './context.module'\r\nexport * from './cqrs.module'\r\nexport * from './db.module'\r\nexport * from './http-core.module'\r\nexport * from './middleware.module'\r\nexport * from './utils/index'\r\n","export * from './auth.utils'\r\nexport * from './cache.utils'\r\nexport * from './db.utils'\r\nexport * from './http.utils'\r\nexport * from './logger.utils'\r\nexport * from './pipeline.utils'\r\nexport * from './validation.utils'\r\n","import type { IMapper, IReadDao, IReadDataSource, ResultType } from '@xeno-js/shared'\r\nimport type { Optional, UserContext } from '@xeno-js/shared'\r\nimport { AppError, Result } from '@xeno-js/shared'\r\nimport { Guards } from '@xeno-js/shared'\r\n\r\n/**\r\n * An abstract generic read-only DAO that provides basic read operations for entities of type T, using a Data Transfer Object (DTO) of type TDto for data access. This class relies on an IReadDataSource to perform database operations and an IMapper to convert between entities and DTOs.\r\n * @template T - The type of the entity that the DAO will manage.\r\n * @template TDto - The type of the Data Transfer Object (DTO) used for data access.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport abstract class ReadDao<T, TDto> implements IReadDao<T> {\r\n /**\r\n * Constructs a new ReadDao instance.\r\n * @param _dataSource An instance of IReadDataSource used to execute SQL queries and commands for data access.\r\n * @param _mapper An instance of IMapper used to convert between entities and DTOs.\r\n *\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n constructor(\r\n private readonly _dataSource: IReadDataSource<TDto>,\r\n private readonly _mapper: IMapper<T, TDto>,\r\n ) {}\r\n\r\n public async findById(\r\n id: string | number,\r\n ctx: UserContext,\r\n signal: Optional<AbortSignal>,\r\n ): Promise<ResultType<Optional<T>>> {\r\n AppError.throwIfAborted(signal, 'ReadDao.findById')\r\n const result = await this._dataSource.findById(id, ctx, signal)\r\n if (Guards.isNullOrEmpty(result)) return Result.ok()\r\n\r\n const entity = this._mapper.toEntity(result)\r\n return Result.ok(entity)\r\n }\r\n\r\n public async findAll(ctx: UserContext, signal: Optional<AbortSignal>): Promise<ResultType<T[]>> {\r\n AppError.throwIfAborted(signal, 'ReadDao.findAll')\r\n const results = await this._dataSource.findAll(ctx, signal)\r\n const entities = results.map((result) => this._mapper.toEntity(result))\r\n return Result.ok(entities)\r\n }\r\n}\r\n","import type { IMapper, IRepository, IWriteDataSource, ResultType } from '@xeno-js/shared'\r\nimport type { Optional, UserContext } from '@xeno-js/shared'\r\nimport { AppError, Result } from '@xeno-js/shared'\r\nimport { Guards } from '@xeno-js/shared'\r\n\r\n/**\r\n * An abstract generic repository that provides basic CRUD operations for entities of type T, using a Data Transfer Object (DTO) of type TDto for data access. This class relies on an IWriteDataSource to perform database operations and an IMapper to convert between entities and DTOs.\r\n * @template T - The type of the entity that the repository will manage.\r\n * @template TDto - The type of the Data Transfer Object (DTO) used for data access.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport abstract class Repository<T, TDto> implements IRepository<T> {\r\n /**\r\n * Constructs a new Repository instance.\r\n * @param _dataSource An instance of IWriteDataSource used to execute SQL queries and commands for data access.\r\n * @param _mapper An instance of IMapper used to convert between entities and DTOs.\r\n *\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n constructor(\r\n private readonly _dataSource: IWriteDataSource<TDto>,\r\n private readonly _mapper: IMapper<T, TDto>,\r\n ) {}\r\n\r\n public async findById(\r\n id: string | number,\r\n ctx: UserContext,\r\n signal: Optional<AbortSignal>,\r\n ): Promise<ResultType<Optional<T>>> {\r\n AppError.throwIfAborted(signal, 'Repository.findById')\r\n\r\n const result = await this._dataSource.findById(id, ctx, signal)\r\n if (Guards.isNullOrEmpty(result)) return Result.ok()\r\n\r\n const entity = this._mapper.toEntity(result)\r\n return Result.ok(entity)\r\n }\r\n\r\n public async findAll(ctx: UserContext, signal: Optional<AbortSignal>): Promise<ResultType<T[]>> {\r\n AppError.throwIfAborted(signal, 'Repository.findAll')\r\n\r\n const results = await this._dataSource.findAll(ctx, signal)\r\n const entities = results.map((result) => this._mapper.toEntity(result))\r\n return Result.ok(entities)\r\n }\r\n\r\n public async save(entity: T, signal: Optional<AbortSignal>): Promise<ResultType<void>> {\r\n const dto = this._mapper.toDto(entity)\r\n\r\n AppError.throwIfAborted(signal, 'Repository.save')\r\n\r\n await this._dataSource.insert(dto, signal)\r\n return Result.ok()\r\n }\r\n\r\n public async delete(\r\n entity: T,\r\n ctx: UserContext,\r\n signal: Optional<AbortSignal>,\r\n ): Promise<ResultType<void>> {\r\n const dto = this._mapper.toDto(entity)\r\n\r\n AppError.throwIfAborted(signal, 'Repository.delete')\r\n\r\n await this._dataSource.delete(dto, ctx, signal)\r\n return Result.ok()\r\n }\r\n\r\n public async update(\r\n id: string | number,\r\n entity: Partial<T>,\r\n ctx: UserContext,\r\n signal: Optional<AbortSignal>,\r\n ): Promise<ResultType<void>> {\r\n const dto = this._mapper.toPartialDto(entity)\r\n\r\n AppError.throwIfAborted(signal, 'Repository.update')\r\n\r\n await this._dataSource.update(id, dto, ctx, signal)\r\n return Result.ok()\r\n }\r\n}\r\n","export * from './unit-of-work'\r\n","export * from 'drizzle-orm'\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,EACE;AAAA,EAKA;AAAA,OACK;AAPP,IAca;AAdb;AAAA;AAAA;AAcO,IAAM,iBAAiB,OAAO,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAS1C,qBACE,OACA,WACA;AACA,cAAM,QAAQ,UAAU,QAAQ,OAAO,sBAAsB,EAAE,SAAS;AACxE,YAAI,CAAC,OAAO,UAAU,KAAK,GAAG;AAC5B,gBAAM,IAAI,MAAM,6DAA6D;AAAA,QAC/E;AAEA,cAAM,UAAW,MAA2B,QAAQ,KAAK;AACzD,eAAO;AAAA,MACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAgBA,MAAM,WACJ,UACA,QACA,SACA,WACA,WACA,QACiC;AACjC,cAAM,aAAa,UAAU,QAAQ,OAAO,UAA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;","names":["AppError","Guards","TOKENS","Result","AppError","Result","ERROR_CODES","Guards","STATUS_CODES","AppError","Result","ERROR_CODE_MESSAGES","ERROR_CODES","STATUS_CODES","AppError","Result","Guards","Guards","AppError","Result","Guards","AppError","Result","Guards","AppError","Result","Guards","AppError","Result","Guards","AppError","Result","Guards","GuidHelper","AppError","Result","Result","Guards","Result","Result","Guards","Result","GUEST","GuidHelper","Guards","Guards","LOG_LEVEL","Guards","LOG_LEVEL","Guards","LOG_LEVEL","LOG_LEVEL","Guards","LOG_LEVEL","TOKENS","ConsoleLogger","SentryLoggerFactory","PinoLoggerFactory","Guards","Guards","Guards","Guards","TOKENS","InMemoryCacheExtended","RedisCacheFactory","Guards","Guards","Guards","Guards","StringHelper","Guards","StringHelper","Guards","Guards","GuidHelper","StringHelper","AppError","Guards","Guards","AppError","Guards","Guards","AsyncLocalStorage","drizzle","Guards","Guards","TOKENS","Guards","PolicyRegistry","RoleAuthorizationStrategy","PermissionAuthorizationStrategy","UserAuthorizationStrategy","TenantAuthorizationStrategy","AuthorizationPipeline","SupabaseServerAuthFactory","ClaimsIdentityMapper","GateKeeper","DbSqlLiteClientFactory","DbClientFactory","AppError","Guards","Guards","TOKENS","DbUtils","TransactionState","UnitOfWork","NodeAxiosFactory","Guards","TOKENS","CockatielResilienceFactory","AllowOrigin","HttpUtils","Guards","TOKENS","ZodValidatorFactory","SchemaValidationStrategy","ValidationPipeline","IDEMPOTENCY_CONSTANTS","Guards","TOKENS","IdempotencyStore","IdempotencyPipeline","ConcurrencyRetryPipeline","CacheUtils","QueryCachingPipeline","TOKENS","Mediator","ExceptionPipeline","LoggerUtils","LoggingPipeline","PerformancePipeline","Guards","AuthUtils","ValidationUtils","CacheUtils","PipelineUtils","CompositePipeline","GuidHelper","HttpHelper","ERROR_CODE_MESSAGES","ERROR_CODES","GuidHelper","HttpHelper","STATUS_CODES","ERROR_CODE_MESSAGES","ERROR_CODES","GuidHelper","HttpHelper","STATUS_CODES","GuidHelper","HttpHelper","STATUS_CODES","Guards","ERROR_CODE_MESSAGES","ERROR_CODES","Guards","GuidHelper","HttpHelper","STATUS_CODES","Guards","Guards","HttpHelper","STATUS_CODES","ERROR_CODE_MESSAGES","ERROR_CODES","Guards","GuidHelper","HttpHelper","STATUS_CODES","Guards","ERROR_CODE_MESSAGES","ERROR_CODES","GUEST","GuidHelper","HttpHelper","STATUS_CODES","Guards","Guards","TOKENS","NoAuthGateKeeper","SupabaseSsrTokenExtractor","BearerTokenExtractor","HttpCookieExtractor","HttpHeaderExtractor","LoggerUtils","ClientIpResolver","RequestContextMiddleware","AllowOrigin","AllowOriginMiddleware","OptionsMiddleware","CORSMiddleware","AllowMethodFactory","MethodCheckMiddleware","AuthenticationMiddleware","CacheUtils","RateLimitKeyBuilder","RateLimitMiddleware","CsrfTokenService","CsrfCookieMiddleware","CsrfMiddleware","CompositeMiddleware","TOKENS","ServiceScopeFactory","NodeRequestContextFactory","UserContextFactory","Guards","LOG_LEVEL","TOKENS","Guards","Guards","TOKENS","LOG_LEVEL","Guards","LoggerUtils","CacheUtils","AuthUtils","DbModule","PLimitConcurrencyService","HttpCoreModule","HttpOriginModule","CqrsModule","MiddlewareModule","ContextModule","AppError","Result","AppError","Result","Guards","AppError","Result","Guards"]}
1
+ {"version":3,"sources":["../src/application/containers/container.utils.ts","../src/application/containers/index.ts","../src/application/cqrs/base-handler.ts","../src/application/cqrs/mediator.ts","../src/application/cqrs/pipelines/authorization.pipeline.ts","../src/application/cqrs/pipelines/composite.pipeline.ts","../src/application/cqrs/pipelines/concurrency-retry.pipeline.ts","../src/application/cqrs/pipelines/exception.pipeline.ts","../src/application/cqrs/pipelines/idempotency.pipeline.ts","../src/application/cqrs/pipelines/logging.pipeline.ts","../src/application/cqrs/pipelines/performance.pipeline.ts","../src/application/cqrs/pipelines/pipeline_strategies/auth/base-authorization.strategy.ts","../src/application/cqrs/pipelines/pipeline_strategies/auth/permission-authorization.strategy.ts","../src/application/cqrs/pipelines/pipeline_strategies/auth/role-authorization.strategy.ts","../src/application/cqrs/pipelines/pipeline_strategies/auth/tenant-authorization.strategy.ts","../src/application/cqrs/pipelines/pipeline_strategies/auth/user-authorization.strategy.ts","../src/application/cqrs/pipelines/pipeline_strategies/auth/index.ts","../src/application/cqrs/pipelines/pipeline_strategies/validation/schema-validation.strategy.ts","../src/application/cqrs/pipelines/pipeline_strategies/validation/index.ts","../src/application/cqrs/pipelines/pipeline_strategies/index.ts","../src/application/cqrs/pipelines/query-caching.pipeline.ts","../src/application/cqrs/pipelines/validation.pipeline.ts","../src/application/cqrs/pipelines/index.ts","../src/application/cqrs/index.ts","../src/application/gate_keepers/gate-keeper.ts","../src/application/gate_keepers/noauth.gate-keeper.ts","../src/application/gate_keepers/index.ts","../src/application/mappers/claims-identity.mapper.ts","../src/application/mappers/index.ts","../src/application/policies/policy-registry.ts","../src/application/policies/index.ts","../src/application/specifications/specification.ts","../src/application/specifications/index.ts","../src/application/index.ts","../src/infrastructure/loggers/console.logger.ts","../src/infrastructure/loggers/sentry.logger.ts","../src/infrastructure/factories/sentry-logger.factory.ts","../src/infrastructure/loggers/pino.logger.ts","../src/infrastructure/factories/pino-logger.factory.ts","../src/infrastructure/modules/utils/logger.utils.ts","../src/infrastructure/cache/inmemory.cache.ts","../src/infrastructure/cache/redis.cache.ts","../src/infrastructure/factories/redis-cache.factory.ts","../src/infrastructure/modules/utils/cache.utils.ts","../src/infrastructure/services/allow_methods/allow-method.service.ts","../src/infrastructure/services/allow_methods/index.ts","../src/infrastructure/services/allow_origins/allow-origin.http.ts","../src/infrastructure/services/allow_origins/index.ts","../src/infrastructure/services/concurrency/p-limit.service.ts","../src/infrastructure/services/concurrency/index.ts","../src/infrastructure/services/crypto/crypto.service.ts","../src/infrastructure/services/crypto/index.ts","../src/infrastructure/services/csrf/csrf-token.service.ts","../src/infrastructure/services/csrf/index.ts","../src/infrastructure/services/extractors/extract-bearer.extractor.ts","../src/infrastructure/services/extractors/extract-ssr-bearer.extractor.ts","../src/infrastructure/services/extractors/http-cookie.extractor.ts","../src/infrastructure/services/extractors/http-header.extractor.ts","../src/infrastructure/services/extractors/index.ts","../src/infrastructure/services/resiliences/resilience.service.ts","../src/infrastructure/services/resiliences/index.ts","../src/infrastructure/services/resolver/utils/socket.utils.ts","../src/infrastructure/services/resolver/utils/index.ts","../src/infrastructure/services/resolver/client-ip.resolver.ts","../src/infrastructure/services/resolver/index.ts","../src/infrastructure/services/index.ts","../src/infrastructure/factories/allow-method.factory.ts","../src/infrastructure/factories/axios.factory.ts","../src/infrastructure/factories/cockatiel-resilience.factory.ts","../src/infrastructure/factories/db-client.factory.ts","../src/infrastructure/context/request-context.ts","../src/infrastructure/factories/request-context.factory.ts","../src/infrastructure/factories/service-scope.factory.ts","../src/infrastructure/factories/sql-light-db-client.factory.ts","../src/infrastructure/factories/supabase.factory.ts","../src/infrastructure/factories/user-context.factory.ts","../src/infrastructure/factories/zod-validator.factory.ts","../src/infrastructure/factories/index.ts","../src/infrastructure/modules/utils/auth.utils.ts","../src/infrastructure/modules/utils/db.utils.ts","../src/infrastructure/transaction/transaction-state.ts","../src/infrastructure/transaction/unit-of-work.ts","../src/infrastructure/modules/db.module.ts","../src/infrastructure/modules/utils/http.utils.ts","../src/infrastructure/modules/http-core.module.ts","../src/infrastructure/modules/utils/validation.utils.ts","../src/infrastructure/idempotency/idempotency-store.ts","../src/infrastructure/modules/utils/pipeline.utils.ts","../src/infrastructure/modules/cqrs.module.ts","../src/presentation/controllers/base.controller.ts","../src/presentation/controllers/index.ts","../src/presentation/middlewares/allow-method.middleware.ts","../src/presentation/middlewares/allow-origin.middleware.ts","../src/presentation/middlewares/auth.middleware.ts","../src/presentation/middlewares/composite.middleware.ts","../src/presentation/middlewares/cors.middleware.ts","../src/presentation/middlewares/csrf.middleware.ts","../src/presentation/middlewares/csrf-cookie.middleware.ts","../src/presentation/middlewares/options.middleware.ts","../src/presentation/middlewares/rate-limiter.middleware.ts","../src/presentation/mappers/context.mapper.ts","../src/presentation/middlewares/request.middleware.ts","../src/presentation/middlewares/index.ts","../src/presentation/index.ts","../src/infrastructure/cache/rate-limit-key-builder.cache.ts","../src/infrastructure/cache/index.ts","../src/infrastructure/modules/middleware.module.ts","../src/infrastructure/modules/context.module.ts","../src/index.ts","../src/infrastructure/builder/app.builder.ts","../src/infrastructure/configuration/configuration.ts","../src/infrastructure/container/service-container.ts","../src/infrastructure/index.ts","../src/infrastructure/context/index.ts","../src/infrastructure/datasources/base-postgressql.datasource.ts","../src/infrastructure/datasources/base-sqllite.datasource.ts","../src/infrastructure/datasources/remote.datasource.ts","../src/infrastructure/idempotency/index.ts","../src/infrastructure/loggers/index.ts","../src/infrastructure/modules/index.ts","../src/infrastructure/modules/utils/index.ts","../src/infrastructure/repositories/read-dao.ts","../src/infrastructure/repositories/repository.ts","../src/infrastructure/transaction/index.ts","../src/infrastructure/db/drizzle.types.ts"],"sourcesContent":["import {\r\n Guards,\r\n type HttpHeaders,\r\n type HttpMethod,\r\n type Optional,\r\n type ResponseDto,\r\n TOKENS,\r\n} from '@xeno-js/shared'\r\n\r\nimport type { ApplicationRegistry, IServiceContainer, IServiceScope } from '@/domain'\r\n\r\n/**\r\n * Utils that provide utility functions for interacting with the service container and managing scoped service resolution.\r\n */\r\nexport const ContainerUtils = Object.freeze({\r\n /**\r\n * Resolves a scoped service from the container using the provided token.\r\n * @param token * The token to resolve from the registry.\r\n * @param container * The container to resolve the service from.\r\n *\r\n * @returns The resolved service instance.\r\n * @throws Error if the active service scope is not available.\r\n */\r\n resolveServiceScoped<K extends keyof T, T extends ApplicationRegistry>(\r\n token: K,\r\n container: IServiceContainer<T>,\r\n ) {\r\n const scope = container.resolve(TOKENS.SERVICE_SCOPE_ACCESSOR).getScope()\r\n if (!Guards.isDefined(scope)) {\r\n throw new Error('Active service scope is required to execute Scoped service.')\r\n }\r\n\r\n const service = (scope as IServiceScope<T>).resolve(token)\r\n return service\r\n },\r\n\r\n /**\r\n * Executes a service action within the context of a scoped service.\r\n * @param endpoint * The endpoint to execute the action on.\r\n * @param method * The HTTP method to use for the action.\r\n * @param headers * The headers to include in the request.\r\n * @param transport * The transport object containing the request and response objects.\r\n * @param container * The container to resolve the service from.\r\n * @param action * The action to execute within the scoped service.\r\n *\r\n * @returns Promise<ResponseDto<TResponse>> A promise that resolves to the response DTO of the executed action.\r\n * @throws Error If the active service scope is not available.\r\n * @throws Error If the service is not found in the container.\r\n * @throws Error If the service is not a scoped service.\r\n */\r\n async runExecute<TResponse, T extends ApplicationRegistry, TRes, TReq>(\r\n endpoint: string,\r\n method: Optional<string>,\r\n headers: HttpHeaders,\r\n transport: { res: TRes; req: TReq },\r\n container: IServiceContainer<T>,\r\n action: () => Promise<ResponseDto<TResponse>>,\r\n ): Promise<ResponseDto<TResponse>> {\r\n const middleware = container.resolve(TOKENS.MIDDLEWARE)\r\n\r\n return await middleware.execute(\r\n { path: endpoint, method: (method as HttpMethod) ?? 'GET', transport },\r\n { ...headers },\r\n async () => {\r\n return await action()\r\n },\r\n )\r\n },\r\n})\r\n","export * from './container.utils'\r\n","import {\r\n AppError,\r\n type IFactory,\r\n type IHandler,\r\n type IRequest,\r\n type Optional,\r\n type ResultType,\r\n type UserContext,\r\n} from '@xeno-js/shared'\r\n\r\n/**\r\n * BaseHandler is an abstract class that implements the IHandler interface.\r\n * It provides a base implementation for handling requests and executing strategies.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport abstract class BaseHandler<\r\n TRequest extends IRequest<TResponse>,\r\n TResponse,\r\n> implements IHandler<TRequest, TResponse> {\r\n constructor(private readonly _identityFactory: IFactory<void, UserContext>) {}\r\n\r\n public async handle(request: TRequest, signal: AbortSignal): Promise<ResultType<TResponse>> {\r\n AppError.throwIfAborted(signal, this.constructor.name)\r\n\r\n return await this.executeAsync(request)\r\n }\r\n\r\n /**\r\n * Executes the strategy for the given request.\r\n * @param request - The request to be handled.\r\n * @param signal - (Optional) The abort signal for the request.\r\n * @throws {AppError} If the strategy execution fails.\r\n * @protected - This method should be overridden by subclasses.\r\n * @abstract - This method must be implemented by subclasses.\r\n * @async - This method is asynchronous.\r\n * @template TRequest - The type of the request.\r\n * @template TResponse - The type of the response.\r\n * @returns {Promise<ResultType<TResponse>>} A promise that resolves to the result of the strategy execution.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n protected abstract executeAsync(\r\n request: TRequest,\r\n signal?: Optional<AbortSignal>,\r\n ): Promise<ResultType<TResponse>>\r\n\r\n /**\r\n * Gets the current context.\r\n * @returns {UserContext} The current context.\r\n * {@link UserContext}\r\n */\r\n protected _getCurrentContext(): UserContext {\r\n return this._identityFactory.create()\r\n }\r\n}\r\n","import type {\r\n Delegate,\r\n ICommand,\r\n IHandler,\r\n IMediator,\r\n IPipelineBehavior,\r\n IQuery,\r\n IRequest,\r\n ResultType,\r\n} from '@xeno-js/shared'\r\nimport { AppError, Result } from '@xeno-js/shared'\r\nimport { ERROR_CODE_MESSAGES, ERROR_CODES, Guards, STATUS_CODES, TOKENS } from '@xeno-js/shared'\r\n\r\nimport type { ApplicationRegistry, IServiceScopeAccessor } from '@/domain'\r\n\r\n/**\r\n * @description Mediator implementation for CQRS pattern. It is responsible for sending commands and executing queries by delegating them to the appropriate handlers, while also applying any registered pipeline behaviors (middlewares).\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class Mediator<\r\n TRegistry extends ApplicationRegistry<unknown> = ApplicationRegistry<unknown>,\r\n> implements IMediator {\r\n /**\r\n * @param _factoryScope - An instance of IServiceScopeAccessor used to access the current service scope, which is necessary for resolving handlers and pipeline behaviors for processing requests.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n constructor(private readonly _factoryScope: IServiceScopeAccessor<TRegistry>) {}\r\n\r\n /**\r\n * @inheritdoc\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n async send<TResponse>(\r\n request: ICommand<TResponse>,\r\n signal: AbortSignal,\r\n ): Promise<ResultType<TResponse>> {\r\n return this.process<TResponse>(request, TOKENS.COMMAND_PIPELINES_BEHAVIOR, signal)\r\n }\r\n\r\n /**\r\n * @inheritdoc\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n async query<TResponse>(\r\n request: IQuery<TResponse>,\r\n signal: AbortSignal,\r\n ): Promise<ResultType<TResponse>> {\r\n return this.process<TResponse>(request, TOKENS.QUERY_PIPELINES_BEHAVIOR, signal)\r\n }\r\n\r\n /**\r\n * @description Internal method to process both commands and queries. It resolves the appropriate handler for the request and applies the registered pipeline behaviors in the correct order.\r\n * @param request The command or query to be processed.\r\n * @param pipelineToken The token used to resolve the pipeline behaviors for the request.\r\n * @param signal An optional AbortSignal to allow cancellation of the request.\r\n * @returns A promise that resolves to the result of processing the request.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n private async process<TResponse>(\r\n request: IRequest<TResponse>,\r\n pipelineToken: keyof ApplicationRegistry<unknown>,\r\n signal: AbortSignal,\r\n ): Promise<ResultType<TResponse>> {\r\n if (Guards.isDefined(signal) && signal.aborted)\r\n return Result.fail(AppError.aborted(request.intent))\r\n\r\n const scope = this._factoryScope.getScope()\r\n\r\n if (!Guards.isDefined(scope))\r\n return Result.fail(\r\n AppError.create({\r\n code: ERROR_CODES.SCOPE_NOT_AVAILABLE,\r\n status: STATUS_CODES.INTERNAL_SERVER_ERROR,\r\n name: request.intent,\r\n message: ERROR_CODE_MESSAGES[ERROR_CODES.SCOPE_NOT_AVAILABLE],\r\n cause: new Error('Service scope is required to process the request.'),\r\n }),\r\n )\r\n\r\n const pipelines = scope.resolve(pipelineToken) as unknown as IPipelineBehavior<\r\n IRequest<TResponse>,\r\n TResponse\r\n >\r\n\r\n if (!Guards.isDefined(pipelines) || !Guards.hasMethod(pipelines, 'handle')) {\r\n return Result.fail(\r\n AppError.create({\r\n code: ERROR_CODES.PIPELINE_NOT_AVAILABLE,\r\n status: STATUS_CODES.INTERNAL_SERVER_ERROR,\r\n name: request.intent,\r\n message: ERROR_CODE_MESSAGES[ERROR_CODES.PIPELINE_NOT_AVAILABLE],\r\n cause: new Error('Pipeline behavior is required to process the request.'),\r\n }),\r\n )\r\n }\r\n\r\n const next: Delegate<TResponse> = () => {\r\n const handler = scope.resolve(request.intent as keyof TRegistry) as IHandler<\r\n IRequest<TResponse>,\r\n TResponse\r\n >\r\n\r\n if (!Guards.isDefined(handler) || !Guards.hasMethod(handler, 'handle')) {\r\n AppError.throw({\r\n code: ERROR_CODES.HANDLER_NOT_FOUND,\r\n status: STATUS_CODES.INTERNAL_SERVER_ERROR,\r\n name: request.intent,\r\n message: ERROR_CODE_MESSAGES[ERROR_CODES.HANDLER_NOT_FOUND],\r\n cause: new Error('Handler is required to process the request.'),\r\n })\r\n }\r\n return handler.handle(request, signal)\r\n }\r\n\r\n return pipelines.handle(request, next)\r\n }\r\n}\r\n","import type { Delegate, IPipelineBehavior, IRequest, IStrategy, ResultType } from '@xeno-js/shared'\r\nimport { Result } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description Middleware che gestisce l'autenticazione e l'autorizzazione dei comandi.\r\n * Intercetta i comandi che implementano ISecureCommand e verifica se l'utente è autenticato e ha i ruoli necessari.\r\n * Se il comando non richiede autorizzazione, delega semplicemente al prossimo middleware.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class AuthorizationPipeline<\r\n TInput extends IRequest<TResult>,\r\n TResult,\r\n> implements IPipelineBehavior<TInput, TResult> {\r\n /**\r\n * @description Costruisce una nuova istanza di AuthorizationPipeline, accettando un array di strategie di autorizzazione. Ogni strategia rappresenta una regola o un criterio specifico per determinare se un comando è autorizzato o meno. Durante l'esecuzione del pipeline, ogni strategia viene valutata in ordine, e se una qualsiasi strategia determina che il comando non è autorizzato, il pipeline restituisce un risultato di fallimento con l'errore corrispondente. Se tutte le strategie passano, il pipeline delega al prossimo comportamento nella catena.\r\n * @param _strategies Un array di oggetti che implementano l'interfaccia IStrategy, utilizzati per valutare l'autorizzazione dei comandi.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n constructor(private readonly _strategies: IStrategy<TInput>[]) {}\r\n\r\n public async handle(request: TInput, next: Delegate<TResult>): Promise<ResultType<TResult>> {\r\n for (const strategy of this._strategies) {\r\n const result = await strategy.execute(request)\r\n if (!result.isOk()) {\r\n return Result.fail(result.getErrorOrThrow())\r\n }\r\n }\r\n\r\n return next()\r\n }\r\n}\r\n","import type { Delegate, IPipelineBehavior, IRequest, ResultType } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description A composite pipeline behavior that allows for the combination of multiple pipeline behaviors into a single pipeline. This class takes an array of IPipelineBehavior instances and executes them in the order they were provided, allowing for a structured and modular approach to handling requests in a CQRS architecture. Each behavior can perform specific actions before and after invoking the next behavior in the pipeline, enabling cross-cutting concerns to be applied consistently across all requests.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class CompositePipeline<\r\n TInput extends IRequest<TResult>,\r\n TResult,\r\n> implements IPipelineBehavior<TInput, TResult> {\r\n /**\r\n * @description Constructs a new instance of the CompositePipeline class, which takes an optional array of IPipelineBehavior instances. If no behaviors are provided, it initializes with an empty array. The composite pipeline will execute each behavior in the order they were provided, allowing for a flexible and modular approach to handling requests in a CQRS architecture.\r\n * @param _pipelines An optional array of IPipelineBehavior instances that represent the individual behaviors to be combined into the composite pipeline.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n constructor(private readonly _pipelines: readonly IPipelineBehavior<TInput, TResult>[] = []) {}\r\n\r\n async handle(request: TInput, next: Delegate<TResult>): Promise<ResultType<TResult>> {\r\n let currentNext = next\r\n\r\n for (let i = this._pipelines.length - 1; i >= 0; i--) {\r\n const currentBehavior = this._pipelines[i]\r\n const previousNext = currentNext\r\n\r\n currentNext = () => currentBehavior.handle(request, previousNext)\r\n }\r\n\r\n return currentNext()\r\n }\r\n}\r\n","import type { Delegate, ICommand, IPipelineBehavior, ResultType } from '@xeno-js/shared'\r\nimport type { Optional } from '@xeno-js/shared'\r\nimport { AppError, Result } from '@xeno-js/shared'\r\nimport {\r\n DEFAULT_CONCURRENCY,\r\n ERROR_CODES,\r\n Guards,\r\n PromiseHelper,\r\n STATUS_CODES,\r\n} from '@xeno-js/shared'\r\n\r\n/**\r\n * @description A pipeline behavior that implements a retry mechanism for handling concurrency conflicts in the CQRS pipelines. When a request results in a concurrency conflict error, this behavior will automatically retry the request up to a specified maximum number of attempts, with an exponential backoff strategy and added jitter to prevent thundering herd problems. If the maximum number of retry attempts is exceeded, it returns a failed Result with an AppError indicating the concurrency conflict.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class ConcurrencyRetryPipeline<\r\n TInput extends ICommand<TResult>,\r\n TResult,\r\n> implements IPipelineBehavior<TInput, TResult> {\r\n /**\r\n * @description Configuration for the retry mechanism, including the base delay and maximum jitter for calculating the delay between retry attempts, as well as the maximum number of retry attempts allowed before giving up and returning a failed Result with an AppError indicating the concurrency conflict.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n private readonly _delayConfig: { baseDelayMs: number; maxJitterMs: number }\r\n /**\r\n * @description Maximum number of retry attempts for handling concurrency conflicts. If the number of attempts exceeds this value, the pipeline will return a failed Result with an AppError indicating that the maximum retry attempts have been exceeded due to concurrency conflicts.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n private readonly _maxRetries: number\r\n\r\n /**\r\n * @description Constructs a new instance of the ConcurrencyRetryBehavior class, which takes an optional maximum number of retry attempts and an optional delay configuration for the exponential backoff strategy. The delay configuration includes a base delay in milliseconds and a maximum jitter in milliseconds to be added to the base delay for each retry attempt. The constructor validates the input parameters to ensure that they are positive integers and throws an error if they are not.\r\n * @param maxRetries An optional parameter that specifies the maximum number of retry attempts for handling concurrency conflicts. The default value is DEFAULT_CONCURRENCY.MAX_RETRIES. It must be a positive integer.\r\n * @param delayConfig An optional parameter that specifies the delay configuration for the exponential backoff strategy, including a base delay in milliseconds and a maximum jitter in milliseconds. The default values are DEFAULT_CONCURRENCY.BASE_DELAY for the base delay and DEFAULT_CONCURRENCY.MAX_JITTER for the maximum jitter. Both values must be non-negative integers.\r\n * @throws Will throw an error if the provided maxRetries value is not a positive integer or if the provided delayConfig values are not valid non-negative integers.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n constructor(\r\n maxRetries: number = DEFAULT_CONCURRENCY.MAX_RETRIES,\r\n delayConfig: Optional<{ baseDelayMs: number; maxJitterMs: number }> = {\r\n baseDelayMs: DEFAULT_CONCURRENCY.BASE_DELAY,\r\n maxJitterMs: DEFAULT_CONCURRENCY.MAX_JITTER,\r\n },\r\n ) {\r\n const values = [maxRetries, delayConfig?.baseDelayMs, delayConfig?.maxJitterMs]\r\n const errorMessages = [\r\n `Invalid maxRetries value: ${maxRetries}. It must be a positive integer.`,\r\n `Invalid baseDelayMs value: ${delayConfig.baseDelayMs}. It must be a non-negative integer.`,\r\n `Invalid maxJitterMs value: ${delayConfig.maxJitterMs}. It must be a non-negative integer.`,\r\n ]\r\n\r\n values.forEach((value, index) => {\r\n Guards.throwIfNotInteger(value, errorMessages[index])\r\n Guards.throwIfNegative(value, errorMessages[index])\r\n if (index === 0 && value === 0) {\r\n throw new Error(errorMessages[index])\r\n }\r\n })\r\n\r\n this._maxRetries = maxRetries\r\n this._delayConfig = delayConfig\r\n }\r\n\r\n /**\r\n * @description Handles the request by implementing a retry mechanism for concurrency conflicts. It retries the request up to the maximum number of attempts with an exponential backoff strategy and added jitter. If the request succeeds or fails with an error that is not a concurrency conflict, it returns the result immediately. If the maximum number of retry attempts is exceeded due to concurrency conflicts, it returns a failed Result with an AppError indicating the concurrency conflict.\r\n * @param request The input request to be handled, which must extend ICommand.\r\n * @param next The delegate function that represents the next behavior or handler in the pipeline.\r\n * @returns A Promise that resolves to a ResultType containing either the successful result or a failed AppError if the maximum retry attempts are exceeded due to concurrency conflicts.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n public async handle(request: TInput, next: Delegate<TResult>): Promise<ResultType<TResult>> {\r\n let attempts = 0\r\n\r\n while (true) {\r\n attempts++\r\n\r\n const result = await next()\r\n\r\n if (result.isOk() || !this.isConcurrencyError(result.getErrorOrThrow())) return result\r\n\r\n if (attempts >= this._maxRetries)\r\n return Result.fail(\r\n AppError.conflict(\r\n request.intent,\r\n `Maximum retry attempts (${this._maxRetries}) exceeded due to concurrency conflicts.`,\r\n ),\r\n )\r\n\r\n const { baseDelayMs, maxJitterMs } = this._delayConfig\r\n\r\n await PromiseHelper.delayWithJitter(baseDelayMs, maxJitterMs)\r\n }\r\n }\r\n\r\n /**\r\n * @description Checks if the given error is a concurrency conflict error.\r\n * @param error The error to be checked.\r\n * @returns A boolean indicating whether the error is a concurrency conflict error.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n private isConcurrencyError(error: AppError): boolean {\r\n return error.code === ERROR_CODES.CONFLICT && error.status === STATUS_CODES.CONFLICT\r\n }\r\n}\r\n","import type { Delegate, IPipelineBehavior, IRequest, ResultType } from '@xeno-js/shared'\r\nimport { AppError, Result } from '@xeno-js/shared'\r\nimport { ERROR_CODE_MESSAGES, ERROR_CODES, STATUS_CODES } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description A pipeline behavior that handles exceptions thrown during the execution of a request in the CQRS pattern. It catches any unhandled exceptions, wraps them in an AppError with a standardized error code and message, and returns a failed Result containing the AppError. This ensures that exceptions are consistently handled and logged across the application, providing a clear mechanism for error reporting and debugging in the context of CQRS pipelines.\r\n * @template TInput - The type of the input request, which must extend IRequest.\r\n * @template TResult - The type of the result returned by the pipeline, which can be any type.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class ExceptionPipeline<\r\n TInput extends IRequest<TResult>,\r\n TResult,\r\n> implements IPipelineBehavior<TInput, TResult> {\r\n public async handle(request: TInput, next: Delegate<TResult>): Promise<ResultType<TResult>> {\r\n try {\r\n return await next()\r\n } catch (error: unknown) {\r\n if (error instanceof AppError) return Result.fail(error)\r\n\r\n const appError = AppError.create({\r\n code: ERROR_CODES.SYSTEM_ERROR,\r\n message: ERROR_CODE_MESSAGES[ERROR_CODES.SYSTEM_ERROR],\r\n status: STATUS_CODES.INTERNAL_SERVER_ERROR,\r\n name: request.intent,\r\n cause: error,\r\n })\r\n return Result.fail(appError)\r\n }\r\n }\r\n}\r\n","import type {\r\n Delegate,\r\n ICommand,\r\n IIdempotencyStore,\r\n INetworkContextAccessor,\r\n IPipelineBehavior,\r\n ResultType,\r\n} from '@xeno-js/shared'\r\nimport { AppError, Result } from '@xeno-js/shared'\r\nimport { Guards, IDEMPOTENCY_CONSTANTS } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description A pipeline behavior that implements idempotency for command requests in the CQRS architecture. This behavior ensures that if multiple requests with the same command ID are received, only one of them will be processed, and the others will receive the same result without reprocessing the command. The pipeline uses an IIdempotencyStore to manage locks and store results for processed commands, allowing it to handle concurrent requests safely and efficiently while preventing duplicate processing of commands. The behavior checks if the incoming request is a command and if it has a valid ID. If the command has already been processed, it retrieves the stored result and returns it. If the command is currently being processed by another request, it returns an error indicating that the command is locked. If the command has not been processed and is not locked, it acquires a lock, processes the command, stores the result, and releases the lock accordingly. The pipeline also includes error handling to ensure that locks are released in case of exceptions during command processing.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class IdempotencyPipeline<\r\n TInput extends ICommand<TResult>,\r\n TResult,\r\n> implements IPipelineBehavior<TInput, TResult> {\r\n /** @description TTL (time-to-live) in seconds for locks acquired in the idempotency mechanism. This value determines how long a lock will be held for a given command ID when it is being processed. If a lock is not released within this time frame, it will automatically expire, allowing other instances of the command to be processed. The default value is set to 300 seconds (5 minutes), which provides a reasonable balance between allowing sufficient time for command processing and preventing long-term locks that could lead to delays in processing subsequent commands with the same ID. This value can be overridden by providing a different lockTtlSeconds value when constructing the IdempotencyPipeline instance.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n private readonly _lockTtlSeconds: number\r\n /** @description TTL (time-to-live) in seconds for processed command results stored in the idempotency mechanism. This value determines how long the result of a processed command will be stored and available for retrieval when subsequent requests with the same command ID are received. If a result is not retrieved within this time frame, it will automatically expire and be removed from the store, meaning that subsequent requests with the same command ID will not be able to retrieve the previous result and may need to reprocess the command. The default value is set to 86400 seconds (24 hours), which allows for a reasonable window of time for clients to retrieve results of processed commands while also ensuring that stale results do not persist indefinitely in the store. This value can be overridden by providing a different processedTtlSeconds value when constructing the IdempotencyPipeline instance.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n private readonly _processedTtlSeconds: number\r\n\r\n /**\r\n * @description Constructs a new instance of the IdempotencyPipeline class, which requires an IIdempotencyStore for managing locks and storing results of processed commands. The constructor also accepts optional parameters for configuring the TTL (time-to-live) values for locks and processed results, allowing for customization of the idempotency behavior based on the specific needs of the application. The constructor validates the input parameters to ensure that they are positive integers and throws an error if they are not, ensuring that the pipeline is configured with valid TTL values for proper functioning of the idempotency mechanism.\r\n * @param idempotencyStore An instance of IIdempotencyStore used for managing locks and storing results of processed commands in the idempotency mechanism. This store is essential for ensuring that commands with the same ID are processed in an idempotent manner, allowing the pipeline to handle concurrent requests safely and efficiently while preventing duplicate processing of commands.\r\n * @param lockTtlSeconds TTL (time-to-live) in seconds for locks acquired in the idempotency mechanism. This value determines how long a lock will be held for a given command ID when it is being processed. If a lock is not released within this time frame, it will automatically expire, allowing other instances of the command to be processed. The default value is set to 300 seconds (5 minutes), which provides a reasonable balance between allowing sufficient time for command processing and preventing long-term locks that could lead to delays in processing subsequent commands with the same ID. This value can be overridden by providing a different lockTtlSeconds value when constructing the IdempotencyPipeline instance.\r\n * @param processedTtlSeconds TTL (time-to-live) in seconds for processed command results stored in the idempotency mechanism. This value determines how long the result of a processed command will be stored and available for retrieval when subsequent requests with the same command ID are received. If a result is not retrieved within this time frame, it will automatically expire and be removed from the store, meaning that subsequent requests with the same command ID will not be able to retrieve the previous result and may need to reprocess the command. The default value is set to 86400 seconds (24 hours), which allows for a reasonable window of time for clients to retrieve results of processed commands while also ensuring that stale results do not persist indefinitely in the store. This value can be overridden by providing a different processedTtlSeconds value when constructing the IdempotencyPipeline instance.\r\n * @throws Will throw an error if the provided lockTtlSeconds or processedTtlSeconds values are not positive integers, ensuring that the pipeline is configured with valid TTL values for proper functioning of the idempotency mechanism.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n constructor(\r\n private readonly _requestContextFactory: INetworkContextAccessor,\r\n private readonly _idempotencyStore: IIdempotencyStore,\r\n lockTtlSeconds: number = IDEMPOTENCY_CONSTANTS.DEFAULT_IDEMPOTENCY_LOCK_TTL_SECONDS,\r\n processedTtlSeconds: number = IDEMPOTENCY_CONSTANTS.DEFAULT_TTL_SECONDS,\r\n ) {\r\n const values: number[] = [lockTtlSeconds, processedTtlSeconds]\r\n const errorMessages = [\r\n `Invalid lockTtlSeconds value: ${lockTtlSeconds}. It must be a positive integer.`,\r\n `Invalid processedTtlSeconds value: ${processedTtlSeconds}. It must be a positive integer.`,\r\n ]\r\n values.forEach((value, index) => {\r\n Guards.throwIfNotInteger(value, errorMessages[index])\r\n Guards.throwIfNegative(value, errorMessages[index])\r\n if (value === 0) {\r\n throw new Error(errorMessages[index])\r\n }\r\n })\r\n\r\n this._lockTtlSeconds = lockTtlSeconds\r\n this._processedTtlSeconds = processedTtlSeconds\r\n }\r\n\r\n public async handle(request: TInput, next: Delegate<TResult>): Promise<ResultType<TResult>> {\r\n const network = this._requestContextFactory.getNetworkContext()\r\n if (!Guards.isDefined(network))\r\n return Result.fail(\r\n AppError.conflict(\r\n request.intent,\r\n `Network context is not defined for request ${request.intent}`,\r\n ),\r\n )\r\n\r\n try {\r\n const alreadyProcessed = await this._idempotencyStore.hasBeenProcessed(network.requestId)\r\n if (alreadyProcessed) {\r\n const payload = await this._idempotencyStore.getPayload<TResult>(network.requestId)\r\n if (Guards.isDefined(payload)) {\r\n return Result.ok(payload)\r\n } else {\r\n return Result.fail(\r\n AppError.conflict(\r\n request.intent,\r\n `Idempotency store indicates request has been processed but no payload found for request ID ${network.requestId}`,\r\n ),\r\n )\r\n }\r\n }\r\n\r\n const lockAcquired = await this._idempotencyStore.acquireLock(\r\n network.requestId,\r\n this._lockTtlSeconds,\r\n )\r\n\r\n if (!lockAcquired) {\r\n return Result.fail(\r\n AppError.conflict(\r\n request.intent,\r\n `Failed to acquire lock for request ID ${network.requestId}`,\r\n ),\r\n )\r\n }\r\n\r\n const result = await next()\r\n\r\n if (result.isOk()) {\r\n await this._idempotencyStore.markAsProcessed(\r\n network.requestId,\r\n result.getValueOrThrow(),\r\n this._processedTtlSeconds,\r\n )\r\n } else {\r\n await this._idempotencyStore.releaseLock(network.requestId)\r\n }\r\n\r\n return result\r\n } catch (error: unknown) {\r\n await this._idempotencyStore.releaseLock(network.requestId)\r\n\r\n throw error\r\n }\r\n }\r\n}\r\n","import type { Delegate, ILogger, IPipelineBehavior, IRequest, ResultType } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description A pipeline behavior that logs the handling of commands and queries, including their success or failure, along with contextual information such as request ID, correlation ID, and user ID.\r\n * This pipeline can be used to enhance observability and debugging capabilities in the application by providing detailed logs for each request processed through the CQRS pipeline.\r\n *\r\n * @template TInput - The type of the input request, which must extend the IRequest interface.\r\n * @template TResult - The type of the result returned by the request handler.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class LoggingPipeline<\r\n TInput extends IRequest<TResult>,\r\n TResult,\r\n> implements IPipelineBehavior<TInput, TResult> {\r\n /**\r\n * @description Constructs a new instance of the LoggingPipeline class, which requires an ILogger for logging. The pipeline will use this dependency to log relevant information about each request being handled, including any errors that occur during processing.\r\n * @param _logger An instance of ILogger used for logging informational messages and errors related to the handling of requests.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n constructor(private readonly _logger: ILogger) {}\r\n\r\n public async handle(request: TInput, next: Delegate<TResult>): Promise<ResultType<TResult>> {\r\n this._logger.info(`Handling ${request.type} ${request.intent}`)\r\n\r\n try {\r\n const result = await next()\r\n\r\n if (!result.isOk()) {\r\n const error = result.getErrorOrThrow()\r\n this._logger.error(\r\n `Failed to handle ${request.type} ${request.intent}: ${error.message}`,\r\n error,\r\n )\r\n } else {\r\n this._logger.info(`Successfully handled ${request.type} ${request.intent}`)\r\n }\r\n\r\n return result\r\n } catch (error: unknown) {\r\n this._logger.error(`Exception while handling ${request.type} ${request.intent}`, error)\r\n throw error\r\n }\r\n }\r\n}\r\n","import type { Delegate, ILogger, IPipelineBehavior, IRequest, ResultType } from '@xeno-js/shared'\r\nimport { Guards } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description Default threshold in milliseconds for logging performance warnings. If a request takes longer than this threshold to execute, a warning will be logged. This value can be overridden by providing a different thresholdMs value when constructing the PerformancePipeline instance.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nconst defaultThresholdMs = 500\r\n\r\n/**\r\n * @description A pipeline behavior that measures the execution time of commands and queries, logging a warning if the execution time exceeds a specified threshold. This pipeline can be used to identify performance bottlenecks in the application and ensure that requests are processed within acceptable time limits.\r\n *\r\n * @template TInput - The type of the input request, which must extend the IRequest interface.\r\n * @template TResult - The type of the result returned by the request handler.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class PerformancePipeline<\r\n TInput extends IRequest<TResult>,\r\n TResult,\r\n> implements IPipelineBehavior<TInput, TResult> {\r\n /**\r\n * @description Threshold in milliseconds for logging performance warnings. If a request takes longer than this threshold to execute, a warning will be logged. This value is set through the constructor and must be a positive integer.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n private readonly _thresholdMs: number\r\n\r\n /**\r\n * @description Constructs a new instance of the PerformancePipeline class, which requires an ILogger for logging. The pipeline will use this dependency to log performance-related information about each request being handled, including any warnings when execution times exceed the specified threshold.\r\n * @param _logger An instance of ILogger used for logging performance warnings related to the handling of requests.\r\n * @param thresholdMs An optional parameter that specifies the execution time threshold in milliseconds. If a request takes longer than this threshold to execute, a warning will be logged. The default value is 500ms.\r\n * @throws Will throw an error if the provided thresholdMs value is not a positive integer.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n constructor(\r\n private readonly _logger: ILogger,\r\n thresholdMs: number = defaultThresholdMs,\r\n ) {\r\n const message = `Invalid thresholdMs value: ${thresholdMs}. It must be a positive integer.`\r\n Guards.throwIfNegative(thresholdMs, message)\r\n if (thresholdMs === 0) {\r\n throw new Error(message)\r\n }\r\n this._thresholdMs = thresholdMs\r\n }\r\n\r\n public async handle(request: TInput, next: Delegate<TResult>): Promise<ResultType<TResult>> {\r\n const startTime = performance.now()\r\n try {\r\n return await next()\r\n } finally {\r\n const endTime = performance.now()\r\n const duration = endTime - startTime\r\n\r\n if (duration > this._thresholdMs) {\r\n this._logger.warn(`Performance warning: ${request.intent} took ${duration.toFixed(2)}ms`)\r\n }\r\n }\r\n }\r\n}\r\n","import type {\r\n IContextAccessor,\r\n Identity,\r\n IRequest,\r\n IStrategy,\r\n RequestContext,\r\n ResultType,\r\n} from '@xeno-js/shared'\r\nimport { AppError, Result } from '@xeno-js/shared'\r\nimport { Guards } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description Abstract base class for authorization strategies in the CQRS pipeline. This class implements the IStrategy interface and provides a common structure for performing authorization checks based on the identity of the authenticated user. It defines an abstract method performAuthorizationCheck that must be implemented by concrete authorization strategies to specify the logic for checking if the user has the necessary permissions to execute a given request. The execute method retrieves the user's identity from the request context and ensures that the user is authenticated before delegating to the performAuthorizationCheck method for further authorization validation. If the user is not authenticated, it returns a failed Result with an appropriate AppError indicating that authentication is required.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport abstract class BaseAuthorizationStrategy<\r\n TInput extends IRequest,\r\n> implements IStrategy<TInput> {\r\n /**\r\n * @description Constructs a new instance of the BaseAuthorizationStrategy class, which serves as an abstract base for specific authorization strategies in the CQRS pipeline. It takes an IRequestContext as a parameter, which is used to retrieve the identity of the currently authenticated user during the authorization process. This context is essential for performing the authorization checks based on the user's identity when executing requests that require specific permissions.\r\n * @param requestContext An instance of IRequestContext used to access the identity of the currently authenticated user. This context is essential for performing the authorization checks based on the user's identity when executing requests that require specific permissions.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n constructor(private readonly _requestContext: IContextAccessor<RequestContext>) {}\r\n\r\n public async execute(request: IRequest): Promise<ResultType<void>> {\r\n const context = this._requestContext.getContext()\r\n\r\n if (!Guards.isDefined(context)) {\r\n return Result.fail(AppError.unauthorized(request.intent, 'User is not authenticated.'))\r\n }\r\n\r\n return await this.performAuthorizationCheck(request, context.identity)\r\n }\r\n\r\n /**\r\n * @description Abstract method that must be implemented by concrete authorization strategies to perform the actual authorization check. This method is called after the user's identity has been retrieved and verified. It receives the request and the user's identity as parameters and should return a Result indicating whether the authorization check passed or failed.\r\n * @param request The incoming request for which the authorization check is being performed. This request contains information about the action being attempted and any relevant data needed for the authorization logic.\r\n * @param auth The identity of the currently authenticated user, which includes information such as the user's ID, tenant ID, and roles. This context is used to determine if the user has the necessary permissions to execute the request.\r\n * @returns A Result indicating the outcome of the authorization check. If the check passes, it should return a successful Result with a void value. If the check fails, it should return a failed Result with an appropriate AppError describing the reason for the failure.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n protected abstract performAuthorizationCheck(\r\n request: IRequest,\r\n auth: Identity,\r\n ): Promise<ResultType<void>>\r\n}\r\n","import type {\r\n IContextAccessor,\r\n Identity,\r\n IPolicyRegistry,\r\n IRequest,\r\n RequestContext,\r\n} from '@xeno-js/shared'\r\nimport { AppError, Result } from '@xeno-js/shared'\r\nimport { Guards } from '@xeno-js/shared'\r\n\r\nimport { BaseAuthorizationStrategy } from './base-authorization.strategy'\r\n\r\n/**\r\n * @description Authorization strategy that checks if the authenticated user has at least one of the required permissions specified in the command. It extends the BaseAuthorizationStrategy and implements the performAuthorizationCheck method to verify if the user's permissions match any of the required permissions for the command. If the user is not authenticated or does not have the necessary permissions, it returns a failed Result with an appropriate AppError.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class PermissionAuthorizationStrategy extends BaseAuthorizationStrategy<IRequest> {\r\n /** @description Constructs a new instance of the PermissionAuthorizationStrategy class, which is responsible for checking if the authenticated user has the required permissions specified in the command. It takes an IRequestContext as a parameter, which is used to retrieve the identity of the currently authenticated user during the authorization process.\r\n * @param _policy An instance of IPolicyRegistry used to retrieve the authorization policy associated with the command's intent. This policy contains the required permissions that the user must have to execute the command.\r\n * @param requestContext An instance of IRequestContext used to access the identity of the currently authenticated user. This context is essential for performing the authorization checks based on the user's permissions when executing commands that require specific permission-based access.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n constructor(\r\n private readonly _policy: IPolicyRegistry,\r\n requestContext: IContextAccessor<RequestContext>,\r\n ) {\r\n super(requestContext)\r\n }\r\n\r\n protected async performAuthorizationCheck(\r\n command: IRequest,\r\n auth: Identity,\r\n ): Promise<Result<void, AppError>> {\r\n const policy = this._policy.getPolicy(command.intent)\r\n\r\n if (!Guards.isNullOrEmpty(policy?.permissions)) {\r\n const permissions = auth.permissions ?? []\r\n const hasRequiredPermission = policy.permissions?.some((permission) =>\r\n permissions.includes(permission),\r\n )\r\n if (!hasRequiredPermission)\r\n return Result.fail(\r\n AppError.forbidden(command.intent, 'User does not have the required permissions.'),\r\n )\r\n }\r\n\r\n return Result.ok()\r\n }\r\n}\r\n","import type {\r\n IContextAccessor,\r\n Identity,\r\n IPolicyRegistry,\r\n IRequest,\r\n RequestContext,\r\n} from '@xeno-js/shared'\r\nimport { AppError, Result } from '@xeno-js/shared'\r\nimport { Guards } from '@xeno-js/shared'\r\n\r\nimport { BaseAuthorizationStrategy } from './base-authorization.strategy'\r\n\r\n/**\r\n * @description Authorization strategy that checks if the authenticated user has at least one of the required roles specified in the command. It extends the BaseAuthorizationStrategy and implements the performAuthorizationCheck method to verify if the user's roles match any of the required roles for the command. If the user is not authenticated or does not have the necessary roles, it returns a failed Result with an appropriate AppError.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class RoleAuthorizationStrategy extends BaseAuthorizationStrategy<IRequest> {\r\n /** @description Constructs a new instance of the RoleAuthorizationStrategy class, which is responsible for checking if the authenticated user has the required roles specified in the command. It takes an IRequestContext as a parameter, which is used to retrieve the identity of the currently authenticated user during the authorization process.\r\n * @param requestContext An instance of IRequestContext used to access the identity of the currently authenticated user. This context is essential for performing the authorization checks based on the user's roles when executing commands that require specific role-based permissions.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n constructor(\r\n private readonly _policy: IPolicyRegistry,\r\n requestContext: IContextAccessor<RequestContext>,\r\n ) {\r\n super(requestContext)\r\n }\r\n\r\n protected async performAuthorizationCheck(\r\n command: IRequest,\r\n auth: Identity,\r\n ): Promise<Result<void, AppError>> {\r\n const policy = this._policy.getPolicy(command.intent)\r\n\r\n if (!Guards.isNullOrEmpty(policy?.roles)) {\r\n const roles = auth.roles ?? []\r\n const hasRequiredRole = policy.roles?.some((role) => roles.includes(role))\r\n if (!hasRequiredRole)\r\n return Result.fail(\r\n AppError.forbidden(command.intent, 'User does not have the required roles.'),\r\n )\r\n }\r\n\r\n return Result.ok()\r\n }\r\n}\r\n","import type {\r\n IContextAccessor,\r\n Identity,\r\n IPolicyRegistry,\r\n IRequest,\r\n RequestContext,\r\n} from '@xeno-js/shared'\r\nimport { AppError, Result } from '@xeno-js/shared'\r\nimport { Guards, GuidHelper } from '@xeno-js/shared'\r\n\r\nimport { BaseAuthorizationStrategy } from './base-authorization.strategy'\r\n\r\n/**\r\n * @description Authorization strategy that checks if the authenticated tenant has the required tenant ID specified in the command. It extends the BaseAuthorizationStrategy and implements the performAuthorizationCheck method to verify if the tenant's ID matches the required tenant ID for the command. If the tenant is not authenticated or does not have the necessary tenant ID, it returns a failed Result with an appropriate AppError.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class TenantAuthorizationStrategy extends BaseAuthorizationStrategy<IRequest> {\r\n /** @description Constructs a new instance of the TenantAuthorizationStrategy class, which is responsible for checking if the authenticated tenant has the required tenant ID specified in the command. It takes an IContextAccessor as a parameter, which is used to retrieve the identity of the currently authenticated tenant during the authorization process.\r\n * @param requestContext An instance of IContextAccessor used to access the identity of the currently authenticated tenant. This context is essential for performing the authorization checks based on the tenant's ID when executing commands that require specific tenant-based permissions.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n constructor(\r\n private readonly _policy: IPolicyRegistry,\r\n requestContext: IContextAccessor<RequestContext>,\r\n ) {\r\n super(requestContext)\r\n }\r\n\r\n protected async performAuthorizationCheck(\r\n command: IRequest,\r\n auth: Identity,\r\n ): Promise<Result<void, AppError>> {\r\n const policy = this._policy.getPolicy(command.intent)\r\n\r\n if (Guards.isDefined(policy?.tenantId)) {\r\n if (Guards.isNullOrEmpty(auth.tenantId) || !GuidHelper.isValidGuid(auth.tenantId))\r\n return Result.fail(AppError.unauthorized(command.intent, 'Tenant is not authenticated.'))\r\n }\r\n\r\n return Result.ok()\r\n }\r\n}\r\n","import type {\r\n IContextAccessor,\r\n Identity,\r\n IPolicyRegistry,\r\n IRequest,\r\n RequestContext,\r\n} from '@xeno-js/shared'\r\nimport { AppError, Result } from '@xeno-js/shared'\r\nimport { Guards, GuidHelper } from '@xeno-js/shared'\r\n\r\nimport { BaseAuthorizationStrategy } from './base-authorization.strategy'\r\n\r\n/**\r\n * @description Authorization strategy that checks if the authenticated user has the required user ID specified in the command. It extends the BaseAuthorizationStrategy and implements the performAuthorizationCheck method to verify if the user's ID matches the required user ID for the command. If the user is not authenticated or does not have the necessary user ID, it returns a failed Result with an appropriate AppError.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class UserAuthorizationStrategy extends BaseAuthorizationStrategy<IRequest> {\r\n /** @description Constructs a new instance of the UserAuthorizationStrategy class, which is responsible for checking if the authenticated user has the required user ID specified in the command. It takes an IContextAccessor as a parameter, which is used to retrieve the identity of the currently authenticated user during the authorization process.\r\n * @param requestContext An instance of IContextAccessor used to access the identity of the currently authenticated user. This context is essential for performing the authorization checks based on the user's ID when executing commands that require specific user-based permissions.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n constructor(\r\n private readonly _policy: IPolicyRegistry,\r\n requestContext: IContextAccessor<RequestContext>,\r\n ) {\r\n super(requestContext)\r\n }\r\n\r\n protected async performAuthorizationCheck(\r\n command: IRequest,\r\n auth: Identity,\r\n ): Promise<Result<void, AppError>> {\r\n const policy = this._policy.getPolicy(command.intent)\r\n\r\n if (Guards.isDefined(policy?.userId)) {\r\n if (Guards.isNullOrEmpty(auth.userId) || !GuidHelper.isValidGuid(auth.userId))\r\n return Result.fail(AppError.unauthorized(command.intent, 'User is not authenticated.'))\r\n }\r\n\r\n return Result.ok()\r\n }\r\n}\r\n","export * from './base-authorization.strategy'\r\nexport * from './permission-authorization.strategy'\r\nexport * from './role-authorization.strategy'\r\nexport * from './tenant-authorization.strategy'\r\nexport * from './user-authorization.strategy'\r\n","import type { IRequest, IStrategy, IValidatorService, ResultType } from '@xeno-js/shared'\r\nimport { AppError, Result } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description Strategy that validates incoming requests against predefined schemas. It implements the IStrategy interface and uses a schema registry to determine if a schema exists for the given request type. If a schema is found, it validates the request against the schema using a safe parsing method. If the validation fails, it returns a failed Result with an appropriate AppError indicating a validation error. If the validation succeeds, it returns a successful Result with a boolean value of true.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class SchemaValidationStrategy implements IStrategy<IRequest, boolean> {\r\n /**\r\n * @description Constructs a new instance of the SchemaValidationStrategy class, which takes an IValidatorService as a parameter. This service is used to check for the existence of validation schemas and to perform the actual validation of requests against those schemas. The constructor initializes the strategy with the provided validator service, allowing it to execute the validation logic when handling requests in the CQRS pipeline.\r\n * @param _validator An instance of IValidatorService that provides methods to check for the existence of validation schemas and to validate data against those schemas. This service is essential for performing the schema validation logic in this strategy.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n constructor(private readonly _validator: IValidatorService) {}\r\n\r\n public async execute(request: IRequest): Promise<ResultType<boolean>> {\r\n const key = request.intent\r\n const parseResult = await this._validator.validate(key, request)\r\n\r\n if (!parseResult.isOk())\r\n return Result.fail(\r\n AppError.validationError(\r\n request.intent,\r\n `Validation failed: ${parseResult.getErrorOrThrow().message}`,\r\n ),\r\n )\r\n\r\n return Result.ok(true)\r\n }\r\n}\r\n","export * from './schema-validation.strategy'\r\n","export * from './auth/index'\r\nexport * from './validation/index'\r\n","import type {\r\n Delegate,\r\n ICache,\r\n ICacheKeyBuilder,\r\n ILogger,\r\n IPipelineBehavior,\r\n IQuery,\r\n ResultType,\r\n} from '@xeno-js/shared'\r\nimport { Result } from '@xeno-js/shared'\r\nimport { Guards } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description A pipeline behavior that implements caching for query requests in the CQRS architecture. This behavior checks if the incoming request is a query and if it implements the IQuery interface. If so, it attempts to retrieve the response from the cache using the provided cache key. If a cached response is found, it returns it immediately. If not, it delegates control to the next handler in the pipeline to execute the query and retrieve the data from the database. After successfully retrieving the data, it stores the result in the cache with the specified TTL (time-to-live) for future requests. This behavior also includes error handling for cache read/write operations, ensuring that any cache-related errors do not disrupt the normal flow of query execution and that appropriate warnings are logged.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class QueryCachingPipeline<\r\n TInput extends IQuery<TResult>,\r\n TResult,\r\n> implements IPipelineBehavior<TInput, TResult> {\r\n /**\r\n * @description Constructs a new instance of the QueryCachingPipeline class, which requires an ICache implementation for interacting with the cache and an ILogger for logging cache-related operations and errors. The constructor initializes the dependencies needed for the caching behavior to function properly within the CQRS pipeline.\r\n * @param _cacheService An instance of ICache used for interacting with the cache, including retrieving and storing cached responses based on cache keys.\r\n * @param _logger An instance of ILogger used for logging cache-related operations, such as cache hits, cache misses, and any errors that occur during cache read/write operations.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n constructor(\r\n private readonly _cacheService: ICache,\r\n private readonly _cacheKeyBuilder: ICacheKeyBuilder,\r\n private readonly _logger: ILogger,\r\n ) {}\r\n\r\n public async handle(request: TInput, next: Delegate<TResult>): Promise<ResultType<TResult>> {\r\n if (\r\n Guards.isNullOrEmpty(request.cacheOptions) ||\r\n Guards.isNullOrEmpty(request.cacheOptions.cacheKey)\r\n )\r\n return next()\r\n\r\n const bypass =\r\n request.cacheOptions.bypassCache === true || request.cacheOptions.consistentRead === true\r\n\r\n const key = request.cacheOptions.isUserScoped\r\n ? this._cacheKeyBuilder.buildUserScopedKey(request.cacheOptions.cacheKey)\r\n : this._cacheKeyBuilder.buildContextualKey(request.cacheOptions.cacheKey)\r\n // 1. Read (Cache Hit)\r\n if (!bypass) {\r\n try {\r\n const cachedResponse = await this._cacheService.get<TResult>(key)\r\n if (Guards.isDefined(cachedResponse)) {\r\n this._logger.debug(\r\n `[Cache HIT] Returning data from cache for: ${request.cacheOptions.cacheKey}`,\r\n )\r\n return Result.ok(cachedResponse)\r\n }\r\n } catch (error) {\r\n // If Redis fails, we don't crash the app. Log and proceed to the DB.\r\n this._logger.warn(\r\n `[Cache ERROR] Unable to read cache for: ${request.cacheOptions.cacheKey}. Proceeding to DB. Error: ${error instanceof Error ? error.message : String(error)}`,\r\n )\r\n }\r\n }\r\n\r\n // 2. Cache Miss: Delegate control to the Handler that queries the DB\r\n const result = await next()\r\n\r\n // 3. Write: If the Handler succeeded, save the result in cache\r\n if (result.isOk()) {\r\n try {\r\n await this._cacheService.set(key, result.getValueOrThrow(), request.cacheOptions.ttl)\r\n this._logger.debug(`[Cache SET] Data saved in cache for: ${key}`)\r\n } catch (error) {\r\n this._logger.warn(\r\n `[Cache ERROR] Unable to save cache for: ${key}. Error: ${error instanceof Error ? error.message : String(error)}`,\r\n )\r\n }\r\n }\r\n\r\n return result\r\n }\r\n}\r\n","import type { Delegate, IPipelineBehavior, IRequest, IStrategy, ResultType } from '@xeno-js/shared'\r\nimport { Result } from '@xeno-js/shared'\r\n/**\r\n * @description A pipeline behavior that performs validation on the incoming request in a CQRS architecture. It checks if the request has a validate method and, if so, invokes it to perform validation. If the validation fails, it returns a failed Result containing the validation error. If the validation succeeds or if there is no validate method, it proceeds to the next behavior in the pipeline. This allows for a structured approach to ensuring that requests meet certain criteria before being processed further in the CQRS pipeline.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class ValidationPipeline<\r\n TInput extends IRequest<TResult>,\r\n TResult,\r\n> implements IPipelineBehavior<TInput, TResult> {\r\n /** @description Constructs a new instance of the ValidationPipeline class, which takes an array of IStrategy instances as validators. These validators are used to perform validation checks on the incoming requests. The constructor initializes the pipeline with the provided validators, allowing it to execute the validation logic when handling requests in the CQRS pipeline.\r\n * @param _validators An array of IStrategy instances that represent the validation strategies to be applied to incoming requests. Each strategy should implement the isApplicable method to determine if it should be applied to a given request and the execute method to perform the actual validation logic, returning a Result indicating the success or failure of the validation.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n constructor(private readonly _validators: readonly IStrategy<TInput, boolean>[]) {}\r\n\r\n public async handle(request: TInput, next: Delegate<TResult>): Promise<ResultType<TResult>> {\r\n for (const validator of this._validators) {\r\n const validationResult = await validator.execute(request)\r\n if (!validationResult.isOk()) {\r\n return Result.fail(validationResult.getErrorOrThrow())\r\n }\r\n }\r\n return next()\r\n }\r\n}\r\n","export * from './authorization.pipeline'\r\nexport * from './composite.pipeline'\r\nexport * from './concurrency-retry.pipeline'\r\nexport * from './exception.pipeline'\r\nexport * from './idempotency.pipeline'\r\nexport * from './logging.pipeline'\r\nexport * from './performance.pipeline'\r\nexport * from './pipeline_strategies/index'\r\nexport * from './query-caching.pipeline'\r\nexport * from './validation.pipeline'\r\n","export * from './base-handler'\r\nexport * from './mediator'\r\nexport * from './pipelines/index'\r\n","import type {\r\n IBaseAuthService,\r\n IBaseMapper,\r\n Identity,\r\n IGateKeeper,\r\n ResultType,\r\n} from '@xeno-js/shared'\r\nimport type { AuthClaims, Optional } from '@xeno-js/shared'\r\nimport { Result } from '@xeno-js/shared'\r\nimport { Guards, GUEST } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description The GateKeeper class is responsible for authenticating users based on their identity and permissions. It provides a method to authenticate a user using a token and returns their identity. If the token is invalid or missing, it returns a guest identity.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class GateKeeper implements IGateKeeper {\r\n constructor(\r\n private readonly _authService: IBaseAuthService,\r\n private readonly _mapper: IBaseMapper<AuthClaims, Identity>,\r\n ) {}\r\n\r\n public async authenticate(token: Optional<string>): Promise<ResultType<Identity>> {\r\n const guest = GUEST as unknown as Identity\r\n\r\n if (!Guards.isNullOrEmpty(token)) {\r\n const authResult = await this._authService.authenticate(token)\r\n if (authResult.isOk()) {\r\n const claims = authResult.getValueOrThrow()\r\n if (Guards.isDefined(claims)) return Result.ok(this._mapper.map(claims))\r\n }\r\n }\r\n\r\n const userResult = await this._authService.getUser()\r\n\r\n if (userResult.isOk()) {\r\n const user = userResult.getValueOrThrow()\r\n if (Guards.isDefined(user)) {\r\n return Result.ok(this._mapper.map(user))\r\n }\r\n }\r\n\r\n return Result.ok(guest)\r\n\r\n return Result.ok(guest)\r\n }\r\n}\r\n","import type { Identity, IGateKeeper, ResultType } from '@xeno-js/shared'\r\nimport type { Optional } from '@xeno-js/shared'\r\nimport { Result } from '@xeno-js/shared'\r\nimport { GUEST } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description The NoAuthGateKeeper class is a specialized implementation of the IGateKeeper interface that bypasses authentication and authorization checks. It is designed for scenarios where authentication is not required, such as public endpoints or testing environments. The authenticate method returns a guest identity, effectively granting access without requiring a valid token.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class NoAuthGateKeeper implements IGateKeeper {\r\n public async authenticate(_token: Optional<string>): Promise<ResultType<Identity>> {\r\n const guest = GUEST as unknown as Identity\r\n\r\n return Result.ok(guest)\r\n }\r\n}\r\n","export * from './gate-keeper'\r\nexport * from './noauth.gate-keeper'\r\n","import type { IBaseMapper, Identity } from '@xeno-js/shared'\r\nimport type { AuthClaims } from '@xeno-js/shared'\r\nimport { GuidHelper } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description ClaimsIdentityMapper is responsible for mapping authentication claims (AuthClaims) to an Identity object. This mapper takes the claims extracted from a token (such as a JWT) and transforms them into a structured Identity that can be used throughout the application for authentication and authorization purposes. The mapping includes parsing the user ID and tenant ID from the claims, as well as extracting roles and permissions.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class ClaimsIdentityMapper implements IBaseMapper<AuthClaims, Identity> {\r\n public map(claims: AuthClaims): Identity {\r\n return {\r\n userId: GuidHelper.parse(claims.sub),\r\n email: claims.email,\r\n name: claims.name,\r\n tenantId: GuidHelper.parse(claims.tenantId),\r\n roles: claims.roles,\r\n permissions: claims.permissions,\r\n }\r\n }\r\n}\r\n","export * from './claims-identity.mapper'\r\n","import type { IPolicyRegistry } from '@xeno-js/shared'\r\nimport type { AuthPolicy, Optional } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description The PolicyRegistry class is an implementation of the IPolicyRegistry interface that manages role-based access control policies. It provides methods to add policies for certain intents and to retrieve the access control policy for a given intent. The policies are stored in a cache, allowing for efficient retrieval and management of access control policies across the application.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class PolicyRegistry implements IPolicyRegistry {\r\n /**\r\n * @description Constructs a new instance of the PolicyRegistry class, which is responsible for managing role-based access control policies. It takes an ICache instance as a parameter, which is used to store and retrieve policies for specific intents. The cache allows for efficient management of access control policies across the application.\r\n * @param _cache An instance of ICache used to store and retrieve policies for specific intents. This cache is essential for efficient management of access control policies across the application.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n constructor(private readonly _cache: Map<string, AuthPolicy> = new Map()) {}\r\n\r\n public addPolicy(intent: string, policy: AuthPolicy): this {\r\n const key = this.getKey(intent)\r\n this._cache.set(key, policy)\r\n return this\r\n }\r\n\r\n public getPolicy(intent: string): Optional<AuthPolicy> {\r\n const key = this.getKey(intent)\r\n return this._cache.get(key)\r\n }\r\n\r\n private getKey(intent: string): string {\r\n return `policy:${intent.toLowerCase()}`\r\n }\r\n}\r\n","export * from './policy-registry'\r\n","import type { ISpecification } from '@xeno-js/shared'\r\n\r\n/**\r\n * Base class for specifications, providing default implementations for logical operations (AND, OR, NOT).\r\n *\r\n * @template T - The type of the candidate object that the specification will evaluate.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport abstract class Specification<T> implements ISpecification<T> {\r\n /**\r\n * Determines if the candidate satisfies the specification criteria.\r\n *\r\n * @param candidate - The object to evaluate against the specification.\r\n * @returns A boolean indicating whether the candidate satisfies the specification.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n public abstract isSatisfiedBy(candidate: T): boolean\r\n\r\n /**\r\n * Combines this specification with another specification using a logical AND operation.\r\n *\r\n * @param other - Another specification to combine with this specification.\r\n * @returns A new specification that represents the logical AND of this and the other specification.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n public and(other: ISpecification<T>): ISpecification<T> {\r\n return new AndSpecification<T>(this, other)\r\n }\r\n\r\n /**\r\n * Combines this specification with another specification using a logical OR operation.\r\n *\r\n * @param other - Another specification to combine with this specification.\r\n * @returns A new specification that represents the logical OR of this and the other specification.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n public or(other: ISpecification<T>): ISpecification<T> {\r\n return new OrSpecification<T>(this, other)\r\n }\r\n\r\n /**\r\n * Inverts this specification using a logical NOT operation.\r\n *\r\n * @returns A new specification that represents the logical NOT of this specification.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n public not(): ISpecification<T> {\r\n return new NotSpecification<T>(this)\r\n }\r\n}\r\n\r\n/**\r\n * A specification that represents the logical AND of two specifications. It evaluates to true if both specifications are satisfied by the candidate.\r\n *\r\n * @template T - The type of the candidate object that the specification will evaluate.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nclass AndSpecification<T> extends Specification<T> {\r\n constructor(\r\n private _left: ISpecification<T>,\r\n private _right: ISpecification<T>,\r\n ) {\r\n super()\r\n }\r\n public isSatisfiedBy(candidate: T): boolean {\r\n return this._left.isSatisfiedBy(candidate) && this._right.isSatisfiedBy(candidate)\r\n }\r\n}\r\n\r\n/**\r\n * A specification that represents the logical OR of two specifications. It evaluates to true if at least one of the specifications is satisfied by the candidate.\r\n *\r\n * @template T - The type of the candidate object that the specification will evaluate.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nclass OrSpecification<T> extends Specification<T> {\r\n constructor(\r\n private _left: ISpecification<T>,\r\n private _right: ISpecification<T>,\r\n ) {\r\n super()\r\n }\r\n public isSatisfiedBy(candidate: T): boolean {\r\n return this._left.isSatisfiedBy(candidate) || this._right.isSatisfiedBy(candidate)\r\n }\r\n}\r\n\r\n/**\r\n * A specification that represents the logical NOT of another specification. It evaluates to true if the original specification is not satisfied by the candidate.\r\n *\r\n * @template T - The type of the candidate object that the specification will evaluate.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nclass NotSpecification<T> extends Specification<T> {\r\n constructor(private _spec: ISpecification<T>) {\r\n super()\r\n }\r\n public isSatisfiedBy(candidate: T): boolean {\r\n return !this._spec.isSatisfiedBy(candidate)\r\n }\r\n}\r\n","export * from './specification'\r\n","export * from './containers/index'\r\nexport * from './cqrs/index'\r\nexport * from './gate_keepers/index'\r\nexport * from './mappers/index'\r\nexport * from './policies/index'\r\nexport * from './specifications/index'\r\n","import type { ILoggerClient } from '@xeno-js/shared'\r\nimport type { LogLevel, Optional } from '@xeno-js/shared'\r\nimport { Guards, LOG_LEVEL } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description Concrete implementation of ILoggerClient that uses the built-in console for logging. This class serves as a simple logging provider that can be used for development and debugging purposes, allowing log messages to be output to the console with different log levels (e.g., error, warning, info, debug) and optional context and error information.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class ConsoleLogger implements ILoggerClient {\r\n /**\r\n * 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.\r\n * @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.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n constructor(private readonly _minLevel: LogLevel = LOG_LEVEL.DEBUG) {}\r\n\r\n public track<T>(\r\n level: LogLevel,\r\n message: string,\r\n context: T,\r\n error: Optional<unknown> = undefined,\r\n ): void {\r\n if (level < this._minLevel) return\r\n\r\n const logMessage = `[${level}] ${message}`\r\n const payload = Guards.isDefined(error) ? { ...context, error } : context\r\n switch (level) {\r\n case LOG_LEVEL.ERROR:\r\n console.error(logMessage, payload ?? {})\r\n break\r\n case LOG_LEVEL.WARN:\r\n console.warn(logMessage, payload ?? {})\r\n break\r\n case LOG_LEVEL.DEBUG:\r\n console.debug(logMessage, payload ?? {})\r\n break\r\n default:\r\n console.info(logMessage, payload ?? {})\r\n break\r\n }\r\n }\r\n}\r\n","import type * as Sentry from '@sentry/node'\r\nimport type { ILoggerClient } from '@xeno-js/shared'\r\nimport type { Dictionary, LogLevel, Optional } from '@xeno-js/shared'\r\nimport { Guards, LOG_LEVEL } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description Concrete implementation of ILoggerClient that uses Sentry as the error tracking system. This class acts as an adapter between the ILoggerClient interface and the Sentry library, allowing the use of Sentry as a logging provider within the application's architecture without directly coupling the code to the specific tracking framework.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class SentryLogger implements ILoggerClient {\r\n constructor(\r\n private readonly _client: typeof Sentry,\r\n public readonly _minLevel: LogLevel,\r\n ) {}\r\n\r\n public track<T>(\r\n level: LogLevel,\r\n message: string,\r\n context: Optional<T extends Dictionary<unknown> ? T : never> = undefined,\r\n error: Optional<unknown> = undefined,\r\n ): void {\r\n if (level < this._minLevel) return\r\n\r\n if (level === LOG_LEVEL.ERROR || level === LOG_LEVEL.WARN) {\r\n this._client.withScope((scope) => {\r\n if (Guards.isDefined(context)) scope.setExtras(context)\r\n\r\n if (Guards.isDefined(error)) {\r\n this._client.captureException(error)\r\n } else {\r\n this._client.captureMessage(message, 'warning')\r\n }\r\n })\r\n }\r\n }\r\n}\r\n","import * as Sentry from '@sentry/node'\r\nimport type { IFactory, ILoggerClient } from '@xeno-js/shared'\r\nimport { Guards, LOG_LEVEL } from '@xeno-js/shared'\r\n\r\nimport type { LoggerConfig } from '@/domain'\r\n\r\nimport { SentryLogger } from '../loggers/sentry.logger'\r\nimport type { XenoRegistry } from '../xeno-registry'\r\n\r\n/**\r\n * @description Factory class responsible for creating instances of SentryLogger based on the provided configuration. It implements the IFactory interface, allowing for easy integration with dependency injection systems. The factory encapsulates the creation logic for the SentryLogger, including the initialization of the underlying Sentry instance with the specified configuration options such as DSN and environment. This design promotes separation of concerns and allows for flexibility in managing SentryLogger instances across the application.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class SentryLoggerFactory<TRegistry extends XenoRegistry = XenoRegistry> implements IFactory<\r\n LoggerConfig<TRegistry>,\r\n ILoggerClient\r\n> {\r\n public create(config: LoggerConfig<TRegistry>): ILoggerClient {\r\n const level = config.level ?? LOG_LEVEL.WARN\r\n const sentryConfig = config.sentry?.config\r\n\r\n const env = sentryConfig?.environment ?? process.env.NODE_ENV ?? 'development'\r\n\r\n if (!Guards.isDefined(sentryConfig))\r\n throw new Error('Sentry configuration is required when Sentry logging is enabled.')\r\n\r\n if (!Guards.isDefined(sentryConfig.dsn))\r\n throw new Error('Sentry DSN is required when Sentry logging is enabled.')\r\n\r\n Sentry.init({\r\n dsn: sentryConfig.dsn,\r\n environment: env,\r\n tracesSampleRate: env === 'production' ? 0.1 : 1.0,\r\n integrations: [Sentry.httpIntegration()],\r\n beforeSend(event, hint) {\r\n const error = hint.originalException\r\n\r\n if (error instanceof Error && error.name === 'ZodError') {\r\n return null\r\n }\r\n\r\n return event\r\n },\r\n })\r\n\r\n return new SentryLogger(Sentry, level)\r\n }\r\n}\r\n","import type { ILoggerClient } from '@xeno-js/shared'\r\nimport type { LogLevel, Optional } from '@xeno-js/shared'\r\nimport { Guards, LOG_LEVEL } from '@xeno-js/shared'\r\nimport type { Logger } from 'pino'\r\n\r\n/**\r\n * @description Class that implements the ILoggerClient interface using the Pino logging library. This class serves as an adapter between the ILoggerClient interface and the Pino logging library, allowing the use of Pino as a logging provider within the application's architecture without directly coupling the code to the specific logging framework.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class PinoLogger implements ILoggerClient {\r\n /**\r\n * 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.\r\n * @param _logger The Pino logger instance used for logging messages.\r\n * @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.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n constructor(\r\n private readonly _logger: Logger,\r\n private readonly _minLevel: LogLevel = LOG_LEVEL.DEBUG,\r\n ) {}\r\n\r\n public track<T>(\r\n level: LogLevel,\r\n message: string,\r\n context: T,\r\n error: Optional<unknown> = undefined,\r\n ): void {\r\n if (level < this._minLevel) return\r\n\r\n const payload = Guards.isDefined(error) ? { ...context, error } : context\r\n\r\n switch (level) {\r\n case LOG_LEVEL.ERROR:\r\n this._logger.error(payload ?? {}, message)\r\n break\r\n case LOG_LEVEL.WARN:\r\n this._logger.warn(payload ?? {}, message)\r\n break\r\n case LOG_LEVEL.DEBUG:\r\n this._logger.debug(payload ?? {}, message)\r\n break\r\n default:\r\n this._logger.info(payload ?? {}, message)\r\n break\r\n }\r\n }\r\n}\r\n","import type { IFactory, ILoggerClient } from '@xeno-js/shared'\r\nimport { LOG_LEVEL } from '@xeno-js/shared'\r\nimport type { DestinationStream, LoggerOptions } from 'pino'\r\nimport pino from 'pino'\r\n\r\nimport type { LoggerConfig } from '@/domain'\r\n\r\nimport { PinoLogger } from '../loggers/pino.logger'\r\nimport type { XenoRegistry } from '../xeno-registry'\r\n\r\n/**\r\n * @description Factory class responsible for creating instances of PinoLogger based on the provided configuration. It implements the IFactory interface, allowing for easy integration with dependency injection systems. The factory encapsulates the creation logic for the PinoLogger, including the initialization of the underlying Pino instance with the specified configuration options such as log level. This design promotes separation of concerns and allows for flexibility in managing PinoLogger instances across the application.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class PinoLoggerFactory<TRegistry extends XenoRegistry = XenoRegistry> implements IFactory<\r\n LoggerConfig<TRegistry>,\r\n ILoggerClient\r\n> {\r\n public create(config: LoggerConfig<TRegistry>): ILoggerClient {\r\n const level = config.level ?? LOG_LEVEL.DEBUG\r\n\r\n const env = config.pino.config?.env ?? process.env.NODE_ENV ?? 'development'\r\n const destinationType = config.pino.config?.destination ?? 'stdout'\r\n const filePath = config.pino.config?.filePath ?? 'logs/app.log'\r\n const prettyPrint = config.pino.config?.prettyPrint ?? env === 'development'\r\n\r\n const options: LoggerOptions = {\r\n level: 'trace',\r\n\r\n serializers: {\r\n err: pino.stdSerializers.err,\r\n },\r\n\r\n timestamp: pino.stdTimeFunctions.isoTime,\r\n\r\n redact: {\r\n paths: ['password', 'token', 'secret', 'authorization', 'headers.authorization'],\r\n censor: '***',\r\n },\r\n }\r\n\r\n if (prettyPrint) {\r\n return new PinoLogger(\r\n pino({\r\n ...options,\r\n transport: {\r\n target: 'pino-pretty',\r\n options: {\r\n colorize: true,\r\n ignore: 'pid,hostname',\r\n translateTime: 'SYS:standard',\r\n },\r\n },\r\n }),\r\n level,\r\n )\r\n }\r\n\r\n if (destinationType === 'file') {\r\n const destination: DestinationStream = pino.destination({ dest: filePath, sync: false })\r\n return new PinoLogger(pino(options, destination), level)\r\n } else {\r\n const stream = pino.destination({ dest: 1, sync: false })\r\n return new PinoLogger(pino(options, stream), level)\r\n }\r\n }\r\n}\r\n","import type { ILoggerClient } from '@xeno-js/shared'\r\nimport type { KeysOfType, Optional } from '@xeno-js/shared'\r\n\r\nimport type { IServiceContainer, IServiceScope, LoggerConfig } from '@/domain'\r\n\r\nimport type { XenoRegistry } from '../../xeno-registry'\r\n/**\r\n * @description LoggerUtils is a utility object that provides helper functions for the CoreModule. It includes the addLogger function, which is responsible for configuring and registering the logging services in the dependency injection container based on the provided LoggerConfig options. This function 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.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport const LoggerUtils = Object.freeze({\r\n /**\r\n * @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.\r\n *\r\n * @param container - The service container to register logging services with.\r\n * @param opts - The LoggerConfig options to determine which loggers to enable and their configurations.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n async addLogger<TRegistry extends XenoRegistry = XenoRegistry>(\r\n container: IServiceContainer<TRegistry>,\r\n opts: Optional<LoggerConfig<XenoRegistry>>,\r\n ): Promise<void> {\r\n const loggerDependencies: KeysOfType<XenoRegistry, ILoggerClient>[] = []\r\n\r\n const { Guards, LOG_LEVEL, TOKENS } = await import('@xeno-js/shared')\r\n\r\n if (!Guards.isDefined(opts) || opts.console) {\r\n const { ConsoleLogger } = await import('../../loggers/console.logger')\r\n container.addSingleton(TOKENS.CONSOLE_LOGGER, () => new ConsoleLogger(opts?.level))\r\n loggerDependencies.push(TOKENS.CONSOLE_LOGGER)\r\n }\r\n\r\n const customLoggerFactories: ((c: IServiceScope<TRegistry>) => ILoggerClient)[] = []\r\n\r\n if (Guards.isDefined(opts)) {\r\n if (Guards.isDefined(opts.sentry.config)) {\r\n const { SentryLoggerFactory } = await import('../../factories/sentry-logger.factory')\r\n container.addSingleton(TOKENS.SENTRY_LOGGER, () => {\r\n const factory = new SentryLoggerFactory()\r\n return factory.create(opts)\r\n })\r\n loggerDependencies.push(TOKENS.SENTRY_LOGGER)\r\n }\r\n\r\n if (Guards.isDefined(opts.pino.config)) {\r\n const { PinoLoggerFactory } = await import('../../factories/pino-logger.factory')\r\n container.addSingleton(TOKENS.PINO_LOGGER, () => {\r\n const factory = new PinoLoggerFactory()\r\n return factory.create(opts)\r\n })\r\n loggerDependencies.push(TOKENS.PINO_LOGGER)\r\n }\r\n\r\n if (!Guards.isNullOrEmpty(opts.customLoggers)) {\r\n const customLoggers = opts.customLoggers\r\n customLoggers.forEach((f) => {\r\n if (Guards.isDefined(f)) {\r\n customLoggerFactories.push(f)\r\n }\r\n })\r\n }\r\n }\r\n\r\n const { BaseLogger } = await import('@xeno-js/shared')\r\n container.addSingleton(TOKENS.LOGGER, (c) => {\r\n const context = c.resolve(TOKENS.CONTEXT_ACCESSOR)\r\n const resolvedDependencies = [\r\n ...loggerDependencies.map((token) => c.resolve(token)),\r\n ...customLoggerFactories.map((factory) => factory(c)),\r\n ]\r\n return new BaseLogger(context, opts?.level ?? LOG_LEVEL.DEBUG, resolvedDependencies)\r\n })\r\n },\r\n} as const)\r\n","import { Guards, InMemoryCache, type Optional } from '@xeno-js/shared'\r\n\r\nimport type { IAtomicCache } from '@/domain'\r\n\r\n/**\r\n * @description The InMemoryCacheExtended class extends the InMemoryCache class and implements the IAtomicCache interface. It provides an implementation of the increment method, which increments the value associated with the given key in the cache. If the key does not exist, it is created with an initial value of 1. The method returns a Promise that resolves to the incremented value.\r\n */\r\nexport class InMemoryCacheExtended extends InMemoryCache implements IAtomicCache {\r\n public async increment(key: string, ttlSeconds: Optional<string | number>): Promise<number> {\r\n const current = (await this.get<number>(key)) ?? 0\r\n const next = Number(current) + 1\r\n const ttl = Guards.isDefined(ttlSeconds) ? Number(ttlSeconds) : 60\r\n await this.set(key, next, ttl)\r\n return next\r\n }\r\n}\r\n","import type { Optional } from '@xeno-js/shared'\r\nimport { Guards, StringHelper } from '@xeno-js/shared'\r\nimport type { Redis } from 'ioredis'\r\n\r\nimport type { IAtomicCache } from '@/domain'\r\n\r\n/**\r\n * @description The RedisCache class provides an implementation of the ICache interface using Redis as the underlying caching mechanism. This class allows for storing, retrieving, and managing cached values in a Redis database, supporting features such as time-to-live (TTL) for cache entries and atomic operations for setting values only if they do not already exist. The RedisCache class abstracts away the details of interacting with Redis, providing a simple and consistent interface for caching operations within the application.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class RedisCache implements IAtomicCache {\r\n /**\r\n * @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.\r\n * @param _redisClient An instance of the Redis client from the ioredis library, used to perform caching operations in the Redis database.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n constructor(private readonly _redisClient: Redis) {}\r\n\r\n public async increment(key: string, ttlSeconds: Optional<number | string>): Promise<number> {\r\n const multi = this._redisClient.multi()\r\n multi.incr(key)\r\n multi.expire(key, ttlSeconds ?? 60)\r\n const results = await multi.exec()\r\n return (results?.[0]?.[1] as number) ?? 1\r\n }\r\n\r\n public async get<T>(key: string): Promise<Optional<T>> {\r\n const value: string | null = await this._redisClient.get(key)\r\n if (!Guards.isDefined(value)) {\r\n return undefined\r\n }\r\n return JSON.parse(value) as T\r\n }\r\n\r\n public async set<T>(key: string, value: T, ttl: Optional<number>): Promise<void> {\r\n const stringValue = StringHelper.safeStringify(value)\r\n const ttlOption = Guards.isDefined(ttl) ? ttl : 86400 // Default TTL of 1 day if not provided\r\n\r\n await this._redisClient.set(key, stringValue, 'EX', ttlOption)\r\n }\r\n\r\n public async setIfAbsent<T>(key: string, value: T, ttl: Optional<number>): Promise<boolean> {\r\n const stringValue = StringHelper.safeStringify(value)\r\n const ttlOption = Guards.isDefined(ttl) ? ttl : 300 // Default TTL of 5 minutes for locks if not provided\r\n const result = await this._redisClient.set(key, stringValue, 'EX', ttlOption, 'NX')\r\n return result === 'OK'\r\n }\r\n\r\n public async remove(key: string): Promise<void> {\r\n await this._redisClient.del(key)\r\n }\r\n\r\n public async has(key: string): Promise<boolean> {\r\n const exists = await this._redisClient.exists(key)\r\n return exists === 1\r\n }\r\n\r\n public async clear(): Promise<void> {\r\n await this._redisClient.flushdb()\r\n }\r\n}\r\n","import type { CacheClientConfig, IFactory } from '@xeno-js/shared'\r\nimport { Guards } from '@xeno-js/shared'\r\nimport type { RedisOptions } from 'ioredis'\r\nimport { Redis } from 'ioredis'\r\n\r\nimport type { IAtomicCache } from '@/domain'\r\n\r\nimport { RedisCache } from '../cache/redis.cache'\r\n\r\n/**\r\n * @description Factory class responsible for creating instances of RedisCache based on the provided configuration. It implements the IFactory interface, allowing for easy integration with dependency injection systems. The factory encapsulates the creation logic for the RedisCache, including the initialization of the underlying Redis instance with the specified configuration options such as host, port, and authentication settings. This design promotes separation of concerns and allows for flexibility in managing RedisCache instances across the application.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class RedisCacheFactory implements IFactory<CacheClientConfig, IAtomicCache> {\r\n public create(config: CacheClientConfig): IAtomicCache {\r\n const host = config?.host ?? 'localhost'\r\n const port = config?.port ?? 6379\r\n const password = config?.password\r\n const username = config?.username\r\n const useTls = config?.tls ?? false\r\n const maxRetries = config?.maxRetriesPerRequest ?? 3\r\n\r\n const redisOptions: RedisOptions = {\r\n host,\r\n port,\r\n maxRetriesPerRequest: maxRetries,\r\n\r\n // Strategia di riconnessione esponenziale per garantire resilienza\r\n retryStrategy(times) {\r\n const delay = Math.min(times * 50, 2000)\r\n return delay\r\n },\r\n }\r\n\r\n if (Guards.isDefined(password)) {\r\n redisOptions.password = password\r\n }\r\n\r\n if (Guards.isDefined(username)) {\r\n redisOptions.username = username\r\n }\r\n\r\n if (useTls) {\r\n redisOptions.tls = {}\r\n }\r\n\r\n const nativeRedisInstance = new Redis(redisOptions)\r\n\r\n nativeRedisInstance.on('error', (err) => {\r\n console.error('❌ [Redis Error]:', err.message)\r\n })\r\n\r\n return new RedisCache(nativeRedisInstance)\r\n }\r\n}\r\n","import type { CacheConfig } from '@xeno-js/shared'\r\n\r\nimport type { IServiceContainer } from '@/domain'\r\n\r\nimport type { XenoRegistry } from '../../xeno-registry'\r\n\r\n/**\r\n * @description Utility functions for configuring caching in the service container.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport const CacheUtils = Object.freeze({\r\n /**\r\n * @description Checks if the provided cache configuration requires any cache strategies.\r\n * @param container The service container to which the cache strategies will be added.\r\n * @param opts The cache configuration options.\r\n * @returns True if any cache strategies are required, false otherwise.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n async addCache<TRegistry extends XenoRegistry = XenoRegistry>(\r\n container: IServiceContainer<TRegistry>,\r\n opts: CacheConfig,\r\n ): Promise<void> {\r\n const { Guards, TOKENS } = await import('@xeno-js/shared')\r\n if (!opts.inMemory && !Guards.isDefined(opts.redis)) {\r\n throw new Error(\r\n 'No cache strategies are configured. Please provide at least one cache strategy.',\r\n )\r\n }\r\n\r\n const { CacheKeyBuilder } = await import('@xeno-js/shared')\r\n container.addSingleton(\r\n TOKENS.CACHE_KEY_BUILDER,\r\n (c) => new CacheKeyBuilder(c.resolve(TOKENS.IDENTITY_ACCESSOR)),\r\n )\r\n\r\n if (opts.inMemory || !Guards.isDefined(opts.redis)) {\r\n const { InMemoryCacheExtended } = await import('../../cache/inmemory.cache')\r\n container.addSingleton(TOKENS.CACHE, () => new InMemoryCacheExtended())\r\n return\r\n }\r\n\r\n if (Guards.isDefined(opts.redis)) {\r\n const { RedisCacheFactory } = await import('../../factories/redis-cache.factory')\r\n container.addSingleton(TOKENS.CACHE, () => {\r\n const config = opts.redis\r\n return new RedisCacheFactory().create(config!)\r\n })\r\n }\r\n },\r\n} as const)\r\n","import { Guards, type HttpMethod, type Optional } from '@xeno-js/shared'\r\n\r\nimport type { IAllowMethod } from '@/domain'\r\n\r\ninterface DynamicRoute {\r\n pattern: RegExp\r\n methods: HttpMethod[]\r\n}\r\n\r\nexport class AllowMethodRegistry implements IAllowMethod {\r\n private readonly _staticRoutes = new Map<string, HttpMethod[]>()\r\n private readonly _dynamicRoutes: DynamicRoute[] = []\r\n\r\n public add(path: string, methods: HttpMethod[]): void {\r\n const normalizedPath = this.normalizePath(path)\r\n\r\n if (this.isDynamicPath(normalizedPath)) {\r\n const pattern = this.createRoutePattern(normalizedPath)\r\n this._dynamicRoutes.push({ pattern, methods })\r\n } else {\r\n this._staticRoutes.set(normalizedPath, methods)\r\n }\r\n }\r\n\r\n public check(path: string, method: HttpMethod): boolean {\r\n const cleanPath = this.normalizePath(path.split('?')[0].split('#')[0])\r\n\r\n const staticMethods = this._staticRoutes.get(cleanPath)\r\n if (Guards.isDefined(staticMethods)) return staticMethods.includes(method)\r\n\r\n for (const route of this._dynamicRoutes) {\r\n if (route.pattern.test(cleanPath)) return route.methods.includes(method)\r\n }\r\n\r\n return false\r\n }\r\n\r\n public getMethods(path: string): string {\r\n const cleanPath = this.normalizePath(path.split('?')[0].split('#')[0])\r\n const methods = this.findMethods(cleanPath)\r\n\r\n return Guards.isDefined(methods) ? methods.join(', ').toUpperCase() : ''\r\n }\r\n\r\n private findMethods(cleanPath: string): Optional<HttpMethod[]> {\r\n const staticMethods = this._staticRoutes.get(cleanPath)\r\n if (Guards.isDefined(staticMethods)) return staticMethods\r\n\r\n for (const route of this._dynamicRoutes) if (route.pattern.test(cleanPath)) return route.methods\r\n\r\n return undefined\r\n }\r\n\r\n private isDynamicPath(path: string): boolean {\r\n return path.includes(':') || (path.includes('{') && path.includes('}'))\r\n }\r\n\r\n private normalizePath(path: string): string {\r\n const trimmed = path.trim()\r\n const withLeadingSlash = trimmed.startsWith('/') ? trimmed : `/${trimmed}`\r\n if (withLeadingSlash === '/') return '/'\r\n return withLeadingSlash.replace(/\\/+$/, '')\r\n }\r\n\r\n private createRoutePattern(path: string): RegExp {\r\n const segments = path.split('/').filter(Boolean)\r\n\r\n const regexSegments = segments.map((segment) => {\r\n if (segment.startsWith(':') || (segment.startsWith('{') && segment.endsWith('}')))\r\n return '([^/]+)'\r\n return segment.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\r\n })\r\n\r\n return new RegExp(`^\\\\/${regexSegments.join('\\\\/')}\\\\/?$`)\r\n }\r\n}\r\n","export * from './allow-method.service'\r\n","import type { Optional } from '@xeno-js/shared'\r\nimport { Guards } from '@xeno-js/shared'\r\n\r\nimport type { IAllowOrigin } from '@/domain'\r\n\r\n/**\r\n * @description A class that implements the IAllowOrigin interface.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class AllowOrigin implements IAllowOrigin {\r\n constructor(private readonly _list: string[]) {}\r\n\r\n public isAllowed(origin: Optional<string>): boolean {\r\n if (Guards.isNullOrEmpty(origin)) return true\r\n\r\n const cleanOrigin = origin.trim().toLowerCase()\r\n\r\n for (const pattern of this._list) {\r\n const cleanPattern = pattern.trim().toLowerCase()\r\n\r\n if (cleanPattern === '*') return true\r\n\r\n if (cleanPattern === cleanOrigin) return true\r\n\r\n if (cleanPattern.startsWith('*.')) {\r\n const domainSuffix = cleanPattern.substring(1)\r\n if (cleanOrigin.endsWith(domainSuffix)) {\r\n const prefix = cleanOrigin.slice(0, cleanOrigin.length - domainSuffix.length)\r\n if (!Guards.isNullOrEmpty(prefix) && !prefix.includes('.')) return true\r\n }\r\n }\r\n }\r\n\r\n return false\r\n }\r\n}\r\n","export * from './allow-origin.http'\r\n","import type { IConcurrencyService } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description Concrete implementation of IConcurrencyService utilizing the 'p-limit' library.\r\n * This service ensures that no matter how many tasks are submitted, only the specified 'concurrencyLimit' number of tasks will be in a pending state simultaneously.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class PLimitConcurrencyService implements IConcurrencyService {\r\n public async executeInParallel<T>(\r\n tasks: (() => Promise<T>)[],\r\n concurrencyLimit: number,\r\n ): Promise<T[]> {\r\n const { default: pLimit } = await import('p-limit')\r\n\r\n const limit = pLimit(concurrencyLimit)\r\n\r\n const promises = tasks.map((task) => limit(task))\r\n\r\n return Promise.all(promises)\r\n }\r\n}\r\n","export * from './p-limit.service'\r\n","import type { ICryptoService } from '@/domain'\r\n\r\n/**\r\n * @description The EdgeCryptoService class implements the ICryptoService interface, providing a concrete implementation for cryptographic operations using the Web Cryptography API.\r\n *\r\n */\r\nexport class EdgeCryptoService implements ICryptoService {\r\n public randomBytes(size: number): Uint8Array {\r\n const buffer = new Uint8Array(size)\r\n crypto.getRandomValues(buffer)\r\n return buffer\r\n }\r\n\r\n public async hmacSha256(secret: string, data: string): Promise<string> {\r\n const encoder = new TextEncoder()\r\n const keyData = encoder.encode(secret)\r\n const messageData = encoder.encode(data)\r\n\r\n const cryptoKey = await crypto.subtle.importKey(\r\n 'raw',\r\n keyData,\r\n { name: 'HMAC', hash: 'SHA-256' },\r\n false,\r\n ['sign'],\r\n )\r\n\r\n const signature = await crypto.subtle.sign('HMAC', cryptoKey, messageData)\r\n\r\n // Converte l'ArrayBuffer risultante in una stringa base64url compatibile\r\n return btoa(String.fromCharCode(...new Uint8Array(signature)))\r\n .replace(/\\+/g, '-')\r\n .replace(/\\//g, '_')\r\n .replace(/=/g, '')\r\n }\r\n\r\n public timingSafeEqual(a: Uint8Array, b: Uint8Array): boolean {\r\n if (a.length !== b.length) {\r\n return false\r\n }\r\n let mismatch = 0\r\n for (let i = 0; i < a.length; i++) {\r\n mismatch |= a[i] ^ b[i]\r\n }\r\n return mismatch === 0\r\n }\r\n}\r\n","export * from './crypto.service'\r\n","import { Guards } from '@xeno-js/shared'\r\n\r\nimport type { ICryptoService, ICsrfTokenService } from '@/domain'\r\n\r\n/**\r\n * @description Service for generating and validating CSRF tokens\r\n */\r\nexport class CsrfTokenService implements ICsrfTokenService {\r\n constructor(\r\n private readonly _secret: string,\r\n private readonly _cryptoService: ICryptoService,\r\n ) {}\r\n\r\n public async generate(subject: string): Promise<string> {\r\n const randomBuffer = this._cryptoService.randomBytes(32)\r\n const nonce = btoa(String.fromCharCode(...randomBuffer))\r\n .replace(/\\+/g, '-')\r\n .replace(/\\//g, '_')\r\n .replace(/=/g, '')\r\n\r\n const signature = await this._cryptoService.hmacSha256(this._secret, `${subject}.${nonce}`)\r\n\r\n return `${nonce}.${signature}`\r\n }\r\n\r\n public async validate(token: string, subject: string): Promise<boolean> {\r\n const separatorIndex = token.indexOf('.')\r\n\r\n if (separatorIndex <= 0) return false\r\n\r\n const nonce = token.slice(0, separatorIndex)\r\n const signature = token.slice(separatorIndex + 1)\r\n\r\n if (Guards.isNullOrEmpty(nonce) || Guards.isNullOrEmpty(signature)) return false\r\n\r\n const expected = await this._cryptoService.hmacSha256(this._secret, `${subject}.${nonce}`)\r\n\r\n const encoder = new TextEncoder()\r\n const actualBuffer = encoder.encode(signature)\r\n const expectedBuffer = encoder.encode(expected)\r\n\r\n if (actualBuffer.length !== expectedBuffer.length) return false\r\n\r\n return this._cryptoService.timingSafeEqual(actualBuffer, expectedBuffer)\r\n }\r\n}\r\n","export * from './csrf-token.service'\r\n","import type { HttpHeaders, IServiceExtractor, Optional } from '@xeno-js/shared'\r\nimport { Guards, StringHelper } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description The BearerTokenExtractor class implements the IExtractor interface, providing a concrete implementation for extracting Bearer tokens from the Authorization header of an incoming HTTP request. The extract method checks for the presence of the Authorization header, verifies that it starts with the \"Bearer \" prefix, and returns the token value if valid. If the header is missing or does not conform to the expected format, it returns undefined, allowing for consistent handling of authentication tokens in the application.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class BearerTokenExtractor implements IServiceExtractor<HttpHeaders, Optional<string>> {\r\n extract(headers: HttpHeaders): Optional<string> {\r\n const authHeader = StringHelper.getSingleValue(headers['authorization'])\r\n if (!Guards.isDefined(authHeader)) {\r\n return undefined\r\n }\r\n\r\n if (authHeader.toLowerCase().startsWith('bearer ')) {\r\n return authHeader.substring(7)\r\n }\r\n\r\n const cookieHeader = StringHelper.getSingleValue(headers['cookie'])\r\n if (Guards.isDefined(cookieHeader)) {\r\n const match = /sb-access-token=([^;]+)/.exec(cookieHeader)\r\n if (!Guards.isNullOrEmpty(match) && Guards.isDefined(match[1])) {\r\n return match[1].trim()\r\n }\r\n }\r\n\r\n return undefined\r\n }\r\n}\r\n","import {\r\n Guards,\r\n type HttpHeaders,\r\n type IServiceExtractor,\r\n type Optional,\r\n StringHelper,\r\n} from '@xeno-js/shared'\r\n\r\n/**\r\n * @description The SupabaseSsrTokenExtractor class is a specialized implementation of the IServiceExtractor interface that extracts the Supabase SSR token from the HTTP headers. It is designed to work with Supabase's server-side rendering (SSR) functionality, where the token is stored in the HTTP headers for server-side rendering purposes. The extract method retrieves the token from the headers and returns it as a string.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class SupabaseSsrTokenExtractor implements IServiceExtractor<HttpHeaders, Optional<string>> {\r\n extract(headers: HttpHeaders): Optional<string> {\r\n const authHeader = StringHelper.getSingleValue(headers['authorization'])\r\n if (Guards.isDefined(authHeader) && authHeader.toLowerCase().startsWith('bearer ')) {\r\n return authHeader.substring(7)\r\n }\r\n\r\n const cookieHeader = StringHelper.getSingleValue(headers['cookie'])\r\n if (Guards.isNullOrEmpty(cookieHeader)) return undefined\r\n\r\n const cookies = cookieHeader.split(';').map((c) => c.trim())\r\n const tokenChunks: Record<number, string> = {}\r\n let unchunkedToken: Optional<string>\r\n\r\n for (const cookie of cookies) {\r\n const [name, ...rest] = cookie.split('=')\r\n if (!Guards.isDefined(name) || Guards.isNullOrEmpty(rest)) continue\r\n const value = decodeURIComponent(rest.join('='))\r\n\r\n if (Guards.isDefined(/^sb-[a-z0-9]+-auth-token$/.exec(name))) {\r\n unchunkedToken = value\r\n } else {\r\n const match = /^sb-[a-z0-9]+-auth-token\\.(\\d+)$/.exec(name)\r\n if (Guards.isDefined(match)) tokenChunks[parseInt(match[1], 10)] = value\r\n }\r\n }\r\n\r\n let fullTokenString = unchunkedToken\r\n if (!Guards.isDefined(fullTokenString) && Object.keys(tokenChunks).length > 0) {\r\n const indices = Object.keys(tokenChunks)\r\n .map(Number)\r\n .sort((a, b) => a - b)\r\n fullTokenString = indices.map((i) => tokenChunks[i]).join('')\r\n }\r\n\r\n if (Guards.isNullOrEmpty(fullTokenString)) return undefined\r\n\r\n try {\r\n const parsed = StringHelper.safeParse(fullTokenString)\r\n if (Guards.isDefined(parsed) && Guards.isObject(parsed) && 'access_token' in parsed) {\r\n const accessToken = parsed['access_token']\r\n if (Guards.isString(accessToken)) return accessToken\r\n }\r\n } catch {\r\n return undefined\r\n }\r\n }\r\n}\r\n","import { Guards, type IServiceExtractor, type Optional } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description The HttpCookieExtractor class implements the IServiceExtractor interface, providing a concrete implementation for extracting HTTP cookie values from an incoming HttpRequest. The extract method retrieves the value of a specified cookie, handling both string and array formats for cookie values. If the cookie is not present or if the cookies object is null or empty, it returns undefined, allowing for consistent handling of missing cookies in the application.\r\n */\r\nexport class HttpCookieExtractor implements IServiceExtractor<\r\n {\r\n header: Optional<string>\r\n name: string\r\n },\r\n Optional<string>\r\n> {\r\n extract(cookie: { header: Optional<string>; name: string }): Optional<string> {\r\n if (!Guards.isDefined(cookie.header)) return undefined\r\n\r\n for (const rawCookie of cookie.header.split(';')) {\r\n const separatorIndex = rawCookie.indexOf('=')\r\n\r\n if (separatorIndex <= 0) continue\r\n\r\n const name = rawCookie.slice(0, separatorIndex).trim()\r\n\r\n if (name !== cookie.name) continue\r\n\r\n const value = rawCookie.slice(separatorIndex + 1).trim()\r\n\r\n try {\r\n return decodeURIComponent(value)\r\n } catch {\r\n return undefined\r\n }\r\n }\r\n\r\n return undefined\r\n }\r\n}\r\n","import type { IServiceExtractor } from '@xeno-js/shared'\r\nimport type { Metadata } from '@xeno-js/shared'\r\nimport {\r\n Guards,\r\n GuidHelper,\r\n type HttpHeaders,\r\n HttpHelper,\r\n MathHelper,\r\n type Optional,\r\n StringHelper,\r\n} from '@xeno-js/shared'\r\n\r\n/**\r\n * @description The HttpHeaderExtractor class implements the IServiceExtractor interface, providing a concrete implementation for extracting HTTP header values from an incoming HttpRequest. The extract method retrieves the value of a specified header, handling both string and array formats for header values. If the header is not present or if the headers object is null or empty, it returns undefined, allowing for consistent handling of missing headers in the application.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class HttpHeaderExtractor implements IServiceExtractor<HttpHeaders, Metadata> {\r\n /**\r\n * @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.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n constructor(\r\n private readonly _bearerExtractor: IServiceExtractor<HttpHeaders, Optional<string>>,\r\n private readonly _cookieExtractor: IServiceExtractor<\r\n {\r\n header: Optional<string>\r\n name: string\r\n },\r\n Optional<string>\r\n >,\r\n private readonly _trustedIp: Optional<string>,\r\n private readonly _cookieName: string,\r\n ) {}\r\n\r\n extract(headers: HttpHeaders): Metadata {\r\n const correlationId = GuidHelper.parse(StringHelper.getSingleValue(headers['x-correlation-id']))\r\n const requestId = GuidHelper.parse(StringHelper.getSingleValue(headers['x-request-id']))\r\n const token = this._bearerExtractor.extract(headers)\r\n const clientIp =\r\n StringHelper.getSingleValue(headers[this._trustedIp?.toLowerCase() ?? 'x-forwarded-for']) ??\r\n StringHelper.getSingleValue(headers['x-real-ip'])\r\n const spanId = GuidHelper.parse(StringHelper.getSingleValue(headers['x-span-id']))\r\n const parentSpanId = StringHelper.getSingleValue(headers['x-parent-span-id'])\r\n const acceptHeader = StringHelper.getSingleValue(headers['accept'])\r\n const contentTypeHeader = StringHelper.getSingleValue(headers['content-type'])\r\n const userAgent = StringHelper.getSingleValue(headers['user-agent'])\r\n const returnAddress = StringHelper.getSingleValue(headers['x-return-address'])\r\n const sequenceId = StringHelper.getSingleValue(headers['x-sequence-id'])\r\n const position = StringHelper.getSingleValue(headers['x-sequence-position'])\r\n const size = StringHelper.getSingleValue(headers['x-sequence-size'])\r\n const expiration = StringHelper.getSingleValue(headers['x-expiration'])\r\n\r\n const csrf = StringHelper.getSingleValue(headers['x-csrf-token'])\r\n const cookieHeader = StringHelper.getSingleValue(headers['cookie'])\r\n const csrfCookie = this._cookieExtractor.extract({\r\n header: cookieHeader,\r\n name: this._cookieName,\r\n })\r\n const origin = StringHelper.getSingleValue(headers['origin'])\r\n const cleanOrigin = HttpHelper.sanitizeOriginUrl(origin)\r\n const referer = StringHelper.getSingleValue(headers['referer'])\r\n const cleanReferer = HttpHelper.sanitizeOriginUrl(referer)\r\n\r\n const accept = acceptHeader === '*/*' ? undefined : acceptHeader\r\n const formatIndicator = accept ?? contentTypeHeader ?? 'application/json'\r\n\r\n const metadata: Metadata = {\r\n correlationId,\r\n requestId,\r\n token,\r\n clientIp,\r\n spanId,\r\n parentSpanId,\r\n formatIndicator,\r\n userAgent,\r\n returnAddress,\r\n csrf,\r\n csrfCookie,\r\n origin: cleanOrigin,\r\n referer: cleanReferer,\r\n sequence: {\r\n sequenceId,\r\n position: Guards.isDefined(position) ? MathHelper.toNumber(position) : undefined,\r\n size: Guards.isDefined(size) ? MathHelper.toNumber(size) : undefined,\r\n },\r\n expiration: Guards.isDefined(expiration) ? MathHelper.toNumber(expiration) : undefined,\r\n }\r\n\r\n return metadata\r\n }\r\n}\r\n","export * from './extract-bearer.extractor'\r\nexport * from './extract-ssr-bearer.extractor'\r\nexport * from './http-cookie.extractor'\r\nexport * from './http-header.extractor'\r\n","import type { IServiceResilience, Optional } from '@xeno-js/shared'\r\nimport { AppError } from '@xeno-js/shared'\r\nimport type { IPolicy } from 'cockatiel'\r\n\r\n/**\r\n * @description The ServiceResilience class implements the IServiceResilience interface, providing a concrete implementation of resilience features for service calls. This class is designed to enhance the reliability of service interactions by automatically handling transient faults and preventing cascading failures in distributed systems. The execute method allows for the execution of asynchronous operations with built-in support for retries, timeouts, and circuit breakers, ensuring that service calls are more resilient to failures and can recover gracefully from errors.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class ServiceResilience implements IServiceResilience {\r\n constructor(private readonly policy: IPolicy) {}\r\n\r\n public async execute<T>(operation: () => Promise<T>, signal: Optional<AbortSignal>): Promise<T> {\r\n AppError.throwIfAborted(signal, 'ServiceResilience.execute')\r\n\r\n return this.policy.execute(() => operation(), signal)\r\n }\r\n}\r\n","export * from './resilience.service'\r\n","import type { Optional } from '@xeno-js/shared'\r\nimport { Guards } from '@xeno-js/shared'\r\n\r\ninterface HasRemoteSocket {\r\n readonly socket?: {\r\n readonly remoteAddress?: string\r\n }\r\n readonly connection?: {\r\n readonly remoteAddress?: string\r\n }\r\n}\r\n\r\n/**\r\n * @description SocketIpExtractor extracts the IP address of the remote socket from an incoming request. It checks for the presence of a 'socket' or 'connection' property in the request object and returns the 'remoteAddress' value if available. If the request object is not defined or not an object, it returns undefined.\r\n */\r\nexport const SocketIpExtractor = Object.freeze({\r\n /**\r\n * @description Extracts the IP address of the remote socket from an incoming request.\r\n * @param req The incoming request object.\r\n * @returns The IP address of the remote socket, or undefined if not available.\r\n */\r\n extract<T>(req: T): Optional<string> {\r\n if (Guards.isDefined(req) && Guards.isObject(req)) {\r\n const candidate = req as HasRemoteSocket\r\n return candidate.socket?.remoteAddress ?? candidate.connection?.remoteAddress\r\n }\r\n return undefined\r\n },\r\n} as const)\r\n","export * from './socket.utils'\r\n","import type { Optional } from '@xeno-js/shared'\r\nimport { Guards } from '@xeno-js/shared'\r\n\r\nimport type { IIPResolver } from '@/domain'\r\n\r\nimport { SocketIpExtractor } from './utils'\r\n\r\n/**\r\n * @description ClientIpResolver is a resolver that extracts the client IP address from the network context or the socket IP address.\r\n */\r\nexport class ClientIpResolver implements IIPResolver {\r\n constructor(private readonly _trustedProxies: string[] = []) {}\r\n\r\n public resolve<T>(req: T, clientIp: Optional<string>): Optional<string> {\r\n const socketIp = SocketIpExtractor.extract(req)\r\n\r\n if (!Guards.isDefined(socketIp))\r\n return !Guards.isNullOrEmpty(clientIp) ? clientIp.split(',')[0].trim() : undefined\r\n\r\n const isTrustedProxy = this._trustedProxies.includes(socketIp)\r\n if (!isTrustedProxy) return socketIp\r\n\r\n if (Guards.isDefined(clientIp)) return clientIp.split(',')[0].trim()\r\n\r\n return socketIp\r\n }\r\n}\r\n","export * from './client-ip.resolver'\r\n","export * from './allow_methods/index'\r\nexport * from './allow_origins/index'\r\nexport * from './concurrency/index'\r\nexport * from './crypto/index'\r\nexport * from './csrf/index'\r\nexport * from './extractors/index'\r\nexport * from './resiliences/index'\r\nexport * from './resolver/index'\r\n","import type { Dictionary, HttpMethod, IFactory } from '@xeno-js/shared'\r\n\r\nimport type { IAllowMethod } from '@/domain'\r\n\r\nimport { AllowMethodRegistry } from '../services'\r\n\r\n/**\r\n * @description Factory class responsible for creating instances of ZodValidatorService based on the provided configuration. It implements the IFactory interface, allowing for easy integration with dependency injection systems. The factory encapsulates the creation logic for the ZodValidatorService, including the initialization of the underlying ZodValidatorService instance with the specified configuration options such as URL and API key. This design promotes separation of concerns and allows for flexibility in managing ZodValidatorService instances across the application.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class AllowMethodFactory implements IFactory<Dictionary<HttpMethod[]>, IAllowMethod> {\r\n public create(opts: Dictionary<HttpMethod[]>): IAllowMethod {\r\n const allowMethodService = new AllowMethodRegistry()\r\n\r\n // 2. Iteriamo sugli schemi passati nella configurazione e li registriamo (Ora in modo sincrono!)\r\n for (const [intentKey, schema] of Object.entries(opts)) {\r\n allowMethodService.add(intentKey, schema)\r\n }\r\n\r\n return allowMethodService\r\n }\r\n}\r\n","import http from 'node:http'\r\nimport https from 'node:https'\r\n\r\nimport type { HttpClientConfig, IHttpClient } from '@xeno-js/shared'\r\nimport { AxiosFactory, AxiosHttpClient } from '@xeno-js/shared'\r\nimport axios from 'axios'\r\n\r\nexport class NodeAxiosFactory extends AxiosFactory {\r\n public override create(config: HttpClientConfig): IHttpClient {\r\n const isKeepAlive = config.keepAlive ?? true\r\n const maxSockets = config.maxSockets ?? 100\r\n\r\n const httpAgent = new http.Agent({\r\n keepAlive: isKeepAlive,\r\n maxSockets,\r\n scheduling: 'lifo',\r\n })\r\n\r\n const httpsAgent = new https.Agent({\r\n keepAlive: isKeepAlive,\r\n maxSockets,\r\n scheduling: 'lifo',\r\n })\r\n\r\n const axiosInstance = axios.create({\r\n baseURL: config.baseURL,\r\n headers: config.defaultHeaders,\r\n timeout: config.timeoutMs,\r\n httpAgent,\r\n httpsAgent,\r\n maxRedirects: config.maxRedirects ?? 5,\r\n decompress: config.decompress ?? true,\r\n proxy: config.proxy,\r\n withCredentials: config.withCredentials,\r\n })\r\n\r\n return new AxiosHttpClient(axiosInstance)\r\n }\r\n}\r\n","import type { IFactory, IServiceResilience, Optional } from '@xeno-js/shared'\r\nimport { AppError, Guards, RESILIENCE_DEFAULTS } from '@xeno-js/shared'\r\nimport {\r\n bulkhead,\r\n circuitBreaker,\r\n ConsecutiveBreaker,\r\n ExponentialBackoff,\r\n handleWhen,\r\n retry,\r\n wrap,\r\n} from 'cockatiel'\r\n\r\nimport type { ResilienceConfig } from '@/domain'\r\n\r\nimport { ServiceResilience } from '../services/resiliences/resilience.service'\r\n\r\ninterface HttpErrorLike {\r\n code?: string\r\n status?: number\r\n config?: {\r\n method?: string\r\n }\r\n}\r\n\r\n/**\r\n * @description Factory class responsible for creating instances of ServiceResilience based on the provided configuration. It implements the IFactory interface, allowing for easy integration with dependency injection systems. The factory encapsulates the creation logic for the ServiceResilience, including the initialization of the underlying resilience policies with the specified configuration options such as retry, circuit breaker, and bulkhead. This design promotes separation of concerns and allows for flexibility in managing ServiceResilience instances across the application.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class CockatielResilienceFactory implements IFactory<ResilienceConfig, IServiceResilience> {\r\n public create(config: ResilienceConfig): IServiceResilience {\r\n const message =\r\n 'The resilience configuration provided is invalid. Please ensure that all values are non-negative numbers.'\r\n const normalizedConfig = {\r\n retry: {\r\n attempts: this.checkConfigValue(\r\n config.retry.attempts,\r\n RESILIENCE_DEFAULTS.RETRY.ATTEMPTS,\r\n message,\r\n ),\r\n baseDelayMs: this.checkConfigValue(\r\n config.retry.baseDelayMs,\r\n RESILIENCE_DEFAULTS.RETRY.BASE_DELAY_MS,\r\n message,\r\n ),\r\n maxDelayMs: this.checkConfigValue(\r\n config.retry.maxDelayMs,\r\n RESILIENCE_DEFAULTS.RETRY.MAX_DELAY_MS,\r\n message,\r\n ),\r\n },\r\n circuitBreaker: {\r\n consecutiveFailures: this.checkConfigValue(\r\n config.circuitBreaker.consecutiveFailures,\r\n RESILIENCE_DEFAULTS.CIRCUIT_BREAKER.CONSECUTIVE_FAILURES,\r\n message,\r\n ),\r\n halfOpenTimeoutMs: this.checkConfigValue(\r\n config.circuitBreaker.halfOpenTimeoutMs,\r\n RESILIENCE_DEFAULTS.CIRCUIT_BREAKER.HALF_OPEN_TIMEOUT_MS,\r\n message,\r\n ),\r\n },\r\n bulkhead: {\r\n maxConcurrent: this.checkConfigValue(\r\n config.bulkhead.maxConcurrent,\r\n RESILIENCE_DEFAULTS.BULKHEAD.MAX_CONCURRENT,\r\n message,\r\n ),\r\n },\r\n }\r\n\r\n const retryPolicy = retry(\r\n handleWhen((error: unknown) => this.isTransientAndIdempotent(error)),\r\n {\r\n maxAttempts: normalizedConfig.retry.attempts,\r\n backoff: new ExponentialBackoff({\r\n initialDelay: normalizedConfig.retry.baseDelayMs,\r\n maxDelay: normalizedConfig.retry.maxDelayMs,\r\n }),\r\n },\r\n )\r\n\r\n const circuitBreakerPolicy = circuitBreaker(\r\n handleWhen((error: unknown) => this.isTransientError(error)),\r\n {\r\n breaker: new ConsecutiveBreaker(normalizedConfig.circuitBreaker.consecutiveFailures),\r\n halfOpenAfter: normalizedConfig.circuitBreaker.halfOpenTimeoutMs,\r\n },\r\n )\r\n\r\n const bulkheadPolicy = bulkhead(normalizedConfig.bulkhead.maxConcurrent)\r\n\r\n return new ServiceResilience(wrap(bulkheadPolicy, circuitBreakerPolicy, retryPolicy))\r\n }\r\n\r\n private isTransientError(error: unknown): boolean {\r\n if (!Guards.isDefined(error) || !Guards.isObject(error)) return false\r\n\r\n let status: number | undefined\r\n let isNetworkError = false\r\n\r\n if (error instanceof AppError) {\r\n status = error.status\r\n const cause = error.cause as HttpErrorLike\r\n if (Guards.isDefined(cause) && Guards.isString(cause.code)) {\r\n isNetworkError = [\r\n 'ECONNABORTED',\r\n 'ECONNRESET',\r\n 'ETIMEDOUT',\r\n 'ENOTFOUND',\r\n 'ECONNREFUSED',\r\n ].includes(cause.code.toUpperCase())\r\n }\r\n } else {\r\n const err = error as HttpErrorLike\r\n status = err.status\r\n if (Guards.isString(err.code)) {\r\n isNetworkError = [\r\n 'ECONNABORTED',\r\n 'ECONNRESET',\r\n 'ETIMEDOUT',\r\n 'ENOTFOUND',\r\n 'ECONNREFUSED',\r\n ].includes(err.code.toUpperCase())\r\n }\r\n }\r\n\r\n if (isNetworkError) return true\r\n\r\n if (Guards.isDefined(status)) {\r\n // 408 Request Timeout, 429 Too Many Requests, and Server Errors (5xx)\r\n return status === 408 || status === 429 || (status >= 500 && status < 600)\r\n }\r\n\r\n return false\r\n }\r\n\r\n private isTransientAndIdempotent(error: unknown): boolean {\r\n if (!this.isTransientError(error)) return false\r\n\r\n let method: string | undefined\r\n\r\n if (error instanceof AppError) {\r\n const cause = error.cause as HttpErrorLike\r\n if (\r\n Guards.isDefined(cause) &&\r\n Guards.isDefined(cause.config) &&\r\n Guards.isString(cause.config.method)\r\n ) {\r\n method = cause.config.method.toUpperCase()\r\n }\r\n } else {\r\n const err = error as HttpErrorLike\r\n if (Guards.isDefined(err.config) && Guards.isString(err.config.method)) {\r\n method = err.config.method.toUpperCase()\r\n }\r\n }\r\n\r\n if (Guards.isNullOrEmpty(method)) return false\r\n\r\n const idempotentMethods = ['GET', 'PUT', 'DELETE', 'HEAD', 'OPTIONS']\r\n return idempotentMethods.includes(method)\r\n }\r\n\r\n private checkConfigValue(value: Optional<number>, defaultValue: number, message: string): number {\r\n if (Guards.isDefined(value)) {\r\n Guards.throwIfNegative(value, message)\r\n return value\r\n }\r\n return defaultValue\r\n }\r\n}\r\n","import type { DbConfig, IFactory } from '@xeno-js/shared'\r\nimport type { Dictionary } from '@xeno-js/shared'\r\nimport { drizzle } from 'drizzle-orm/node-postgres'\r\nimport { Pool } from 'pg'\r\n\r\nimport type { DbContext } from '../db/db.types'\r\n\r\n/**\r\n * @description Factory class responsible for creating instances of IDbClient based on the provided configuration. It implements the IFactory interface, allowing for easy integration with dependency injection systems. The factory encapsulates the creation logic for the IDbClient, including the initialization of the underlying database client with the specified configuration options such as connection string and table mappings. This design promotes separation of concerns and allows for flexibility in managing IDbClient instances across the application.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class DbClientFactory implements IFactory<DbConfig, DbContext<Dictionary>> {\r\n public create(opts: DbConfig): DbContext<Dictionary> {\r\n const pool = new Pool({\r\n connectionString: opts.connectionString,\r\n })\r\n\r\n return drizzle({ client: pool })\r\n }\r\n}\r\n","import type { AsyncLocalStorage } from 'node:async_hooks'\r\n\r\nimport type { Identity, IFactory, NetworkContext, Optional, RequestContext } from '@xeno-js/shared'\r\nimport { Guards } from '@xeno-js/shared'\r\n\r\nimport type { ExecutionContext, IRequestContext, IServiceScope } from '@/domain'\r\n\r\nimport type { XenoRegistry } from '../xeno-registry'\r\n\r\n/**\r\n * @description The NodeRequestContext class is an implementation of the IRequestContext interface that utilizes Node.js's AsyncLocalStorage to manage and access request-specific context data, such as user identity information, across asynchronous operations. This class provides methods to run asynchronous functions within a specific context and to retrieve the current identity information from the context when needed. By leveraging AsyncLocalStorage, the NodeRequestContext ensures that the context data is properly propagated across asynchronous calls, allowing for seamless access to identity information throughout the execution flow of a request.\r\n * @template TCtx - The type of the context data that will be stored and accessed using this request context implementation. This typically includes user identity information, such as user ID, roles, and correlation ID, which can be used for authentication and authorization purposes within the application.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class NodeRequestContext<\r\n TRegistry extends XenoRegistry = XenoRegistry,\r\n> implements IRequestContext<RequestContext, TRegistry> {\r\n /**\r\n * @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.\r\n * @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.\r\n * @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.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n constructor(\r\n private readonly _storage: AsyncLocalStorage<ExecutionContext<TRegistry>>,\r\n private readonly _factoryScope: IFactory<void, IServiceScope<TRegistry>>,\r\n ) {}\r\n\r\n public async runAsync<T>(context: RequestContext, fn: () => Promise<T>): Promise<T> {\r\n const scope = this._factoryScope.create()\r\n try {\r\n return await this._storage.run({ context, scope }, fn)\r\n } finally {\r\n await scope.dispose()\r\n }\r\n }\r\n\r\n public updateIdentity(identity: Identity): void {\r\n const store = this._storage.getStore()\r\n if (Guards.isDefined(store) && Guards.isDefined(store.context)) {\r\n store.context = Object.freeze({\r\n ...store.context,\r\n identity: Object.freeze(identity),\r\n })\r\n }\r\n }\r\n\r\n public getContext(): Optional<RequestContext> {\r\n const store = this._storage.getStore()\r\n if (!Guards.isDefined(store)) return undefined\r\n const context = store.context\r\n return Object.freeze(context)\r\n }\r\n\r\n public getIdentity(): Optional<Identity> {\r\n const store = this._storage.getStore()\r\n if (!Guards.isDefined(store)) return undefined\r\n return Object.freeze(store.context?.identity)\r\n }\r\n\r\n public getScope(): Optional<IServiceScope<TRegistry>> {\r\n const store = this._storage.getStore()\r\n if (!Guards.isDefined(store)) return undefined\r\n return store.scope\r\n }\r\n\r\n public getNetworkContext(): Optional<NetworkContext> {\r\n const store = this._storage.getStore()\r\n if (!Guards.isDefined(store)) return undefined\r\n return Object.freeze(store.context?.network)\r\n }\r\n}\r\n","import { AsyncLocalStorage } from 'node:async_hooks'\r\n\r\nimport type { IFactory, RequestContext } from '@xeno-js/shared'\r\n\r\nimport type { ExecutionContext, IRequestContext, IServiceScope } from '@/domain'\r\n\r\nimport { NodeRequestContext } from '../context/request-context'\r\nimport type { XenoRegistry } from '../xeno-registry'\r\n\r\n/**\r\n * @description Factory class responsible for creating instances of NodeRequestContext. It implements the IFactory interface, allowing for easy integration with dependency injection systems. The factory encapsulates the creation logic for the NodeRequestContext, promoting separation of concerns and flexibility in managing request context instances across the application.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class NodeRequestContextFactory<TRegistry extends XenoRegistry> implements IFactory<\r\n void,\r\n IRequestContext<RequestContext, TRegistry>\r\n> {\r\n private _store: AsyncLocalStorage<ExecutionContext<TRegistry>> = new AsyncLocalStorage<\r\n ExecutionContext<TRegistry>\r\n >()\r\n\r\n constructor(private readonly _factoryScope: IFactory<void, IServiceScope<TRegistry>>) {}\r\n\r\n public create(): IRequestContext<RequestContext, TRegistry> {\r\n return new NodeRequestContext<TRegistry>(this._store, this._factoryScope)\r\n }\r\n}\r\n","import type { IFactory } from '@xeno-js/shared'\r\n\r\nimport type { IServiceContainer, IServiceScope } from '@/domain'\r\n\r\nimport type { XenoRegistry } from '../xeno-registry'\r\n\r\n/**\r\n * @description Factory class responsible for creating instances of IServiceScope. It implements the IFactory interface, allowing for easy integration with dependency injection systems. The factory encapsulates the creation logic for the IServiceScope, promoting separation of concerns and allowing for flexibility in managing IServiceScope instances across the application.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class ServiceScopeFactory<T extends XenoRegistry = XenoRegistry> implements IFactory<\r\n void,\r\n IServiceScope<T>\r\n> {\r\n constructor(private readonly _container: IServiceContainer<T>) {}\r\n\r\n public create(): IServiceScope<T> {\r\n return this._container.createScope()\r\n }\r\n}\r\n","import { createClient } from '@libsql/client'\r\nimport type { DbConfig, IFactory } from '@xeno-js/shared'\r\nimport type { Dictionary } from '@xeno-js/shared'\r\nimport { drizzle } from 'drizzle-orm/libsql'\r\n\r\nimport type { DbContext } from '../db/db.types'\r\n\r\n/**\r\n * @description Factory class responsible for creating instances of IDbClient based on the provided configuration. It implements the IFactory interface, allowing for easy integration with dependency injection systems. The factory encapsulates the creation logic for the IDbClient, including the initialization of the underlying database client with the specified configuration options such as connection string and table mappings. This design promotes separation of concerns and allows for flexibility in managing IDbClient instances across the application.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class DbSqlLiteClientFactory implements IFactory<DbConfig, DbContext<Dictionary>> {\r\n public create(opts: DbConfig): DbContext<Dictionary> {\r\n const client = createClient({ url: opts.connectionString })\r\n return drizzle({ client })\r\n }\r\n}\r\n","import { createServerClient } from '@supabase/ssr'\r\nimport type { SupabaseClientOptions } from '@supabase/supabase-js'\r\nimport type { IExtendendService, IFactory } from '@xeno-js/shared'\r\nimport {\r\n Guards,\r\n SupabaseAuthService,\r\n SupabaseClaimsMapper,\r\n SupabaseSessionMapper,\r\n} from '@xeno-js/shared'\r\n\r\nimport type { AuthSsrConfig, IServiceContainer } from '@/domain'\r\n\r\nimport type { XenoRegistry } from '../xeno-registry'\r\n\r\ninterface SupabaseServerAuthFactoryInput<TRegistry extends XenoRegistry> {\r\n config: AuthSsrConfig<SupabaseClientOptions<'public'>>\r\n container: IServiceContainer<TRegistry>\r\n}\r\n\r\nexport class SupabaseServerAuthFactory<\r\n TRegistry extends XenoRegistry = XenoRegistry,\r\n> implements IFactory<SupabaseServerAuthFactoryInput<TRegistry>, IExtendendService> {\r\n public create({\r\n config,\r\n container,\r\n }: SupabaseServerAuthFactoryInput<TRegistry>): IExtendendService {\r\n if (!Guards.isDefined(config.ssrOpts)) {\r\n throw new Error('ISsrCookieHandler is required for @supabase/ssr initialization.')\r\n }\r\n\r\n const cookieService = config.ssrOpts(container)\r\n const client = createServerClient(config.url, config.key, {\r\n ...config.opts,\r\n cookies: {\r\n getAll() {\r\n return cookieService.getAll()\r\n },\r\n setAll(cookiesToSet) {\r\n // Mappa array di cookie in entrata verso il gestore agnostico del backend\r\n cookieService.setAll(cookiesToSet)\r\n },\r\n },\r\n })\r\n\r\n const mapper = new SupabaseClaimsMapper()\r\n const sessionMapper = new SupabaseSessionMapper(mapper)\r\n\r\n return new SupabaseAuthService(client, mapper, sessionMapper, config)\r\n }\r\n}\r\n","import type { IFactory, IIdentityAccessor } from '@xeno-js/shared'\r\nimport type { Guid, Optional, UserContext } from '@xeno-js/shared'\r\nimport { Guards } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description Factory class responsible for creating instances of UserContext. It implements the IFactory interface, allowing for easy integration with dependency injection systems. The factory encapsulates the creation logic for the UserContext, promoting separation of concerns and flexibility in managing user context instances across the application.\r\n *\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class UserContextFactory implements IFactory<void, UserContext> {\r\n /**\r\n * @description Constructs an instance of UserContextFactory.\r\n * @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.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n constructor(private readonly _identityFactory: IIdentityAccessor) {}\r\n\r\n public create(): UserContext {\r\n const output: { userId: Optional<Guid>; tenantId: Optional<Guid> } = {\r\n userId: undefined,\r\n tenantId: undefined,\r\n }\r\n\r\n const identity = this._identityFactory.getIdentity()\r\n\r\n if (Guards.isDefined(identity)) {\r\n output.userId = identity.userId\r\n output.tenantId = identity.tenantId\r\n }\r\n\r\n return output\r\n }\r\n}\r\n","import type { IFactory, ILogger, IValidatorService } from '@xeno-js/shared'\r\nimport { ZodValidatorService } from '@xeno-js/shared'\r\nimport type { ZodType } from 'zod'\r\n\r\nimport type { SchemaConfig } from '@/domain'\r\n\r\n/**\r\n * @description Factory class responsible for creating instances of ZodValidatorService based on the provided configuration. It implements the IFactory interface, allowing for easy integration with dependency injection systems. The factory encapsulates the creation logic for the ZodValidatorService, including the initialization of the underlying ZodValidatorService instance with the specified configuration options such as URL and API key. This design promotes separation of concerns and allows for flexibility in managing ZodValidatorService instances across the application.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class ZodValidatorFactory implements IFactory<\r\n SchemaConfig<ZodType> & { logger: ILogger },\r\n IValidatorService\r\n> {\r\n public create(opts: SchemaConfig<ZodType> & { logger: ILogger }): IValidatorService {\r\n const validatorService = new ZodValidatorService(new Map(), opts.logger)\r\n\r\n // 2. Iteriamo sugli schemi passati nella configurazione e li registriamo (Ora in modo sincrono!)\r\n for (const [intentKey, schema] of Object.entries(opts.schemas)) {\r\n validatorService.addSchema(intentKey, schema)\r\n }\r\n\r\n return validatorService\r\n }\r\n}\r\n","export * from './allow-method.factory'\r\nexport * from './axios.factory'\r\nexport * from './cockatiel-resilience.factory'\r\nexport * from './db-client.factory'\r\nexport * from './pino-logger.factory'\r\nexport * from './redis-cache.factory'\r\nexport * from './request-context.factory'\r\nexport * from './sentry-logger.factory'\r\nexport * from './service-scope.factory'\r\nexport * from './sql-light-db-client.factory'\r\nexport * from './supabase.factory'\r\nexport * from './user-context.factory'\r\nexport * from './zod-validator.factory'\r\n","import type { SupabaseClientOptions } from '@supabase/supabase-js'\r\nimport type { IRequest, IStrategy } from '@xeno-js/shared'\r\nimport type { ZodType } from 'zod'\r\n\r\nimport type { AuthSsrConfig, IServiceContainer, PipelineConfig } from '@/domain'\r\nimport type { XenoRegistry } from '@/infrastructure'\r\n\r\n/**\r\n * @description Utility functions for configuring authentication and authorization in the service container.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport const AuthUtils = Object.freeze({\r\n /**\r\n * @description Checks if the provided authorization configuration requires any authorization strategies.\r\n * @param authorizationConfig The authorization configuration to check.\r\n * @returns True if any authorization strategies are required, false otherwise.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n\r\n async addAuthZ<TRegistry extends XenoRegistry = XenoRegistry>(\r\n container: IServiceContainer<TRegistry>,\r\n opts: PipelineConfig<TRegistry, ZodType>['authorization'],\r\n ): Promise<(keyof TRegistry)[]> {\r\n const { TOKENS } = await import('@xeno-js/shared')\r\n const pipelines: (keyof TRegistry)[] = []\r\n type StrategiesToken = keyof TRegistry\r\n const strategies: StrategiesToken[] = []\r\n\r\n const { Guards } = await import('@xeno-js/shared')\r\n if (Guards.isDefined(opts.policies)) {\r\n const { PolicyRegistry } = await import('@/application')\r\n container.addSingleton(TOKENS.POLICY_REGISTRY, () => new PolicyRegistry())\r\n\r\n const policyRegistry = opts.policies\r\n const registryInstance = container.resolve(TOKENS.POLICY_REGISTRY)\r\n const Policies = new Set<string>()\r\n for (const [intent, policy] of Object.entries(policyRegistry)) {\r\n const intentLower = intent.toLowerCase()\r\n registryInstance.addPolicy(intentLower, policy)\r\n\r\n if (!Guards.isNullOrEmpty(policy.roles)) {\r\n Policies.add('roles')\r\n }\r\n\r\n if (!Guards.isNullOrEmpty(policy.permissions)) {\r\n Policies.add('permissions')\r\n }\r\n\r\n if (!Guards.isNullOrEmpty(policy.userId)) {\r\n Policies.add('userId')\r\n }\r\n\r\n if (!Guards.isNullOrEmpty(policy.tenantId)) {\r\n Policies.add('tenantId')\r\n }\r\n }\r\n\r\n if (Policies.has('roles')) {\r\n const { RoleAuthorizationStrategy } = await import('@/application')\r\n container.addSingleton(\r\n TOKENS.ROLE_AUTHORIZATION_PIPELINE,\r\n (c) =>\r\n new RoleAuthorizationStrategy(\r\n c.resolve(TOKENS.POLICY_REGISTRY),\r\n c.resolve(TOKENS.CONTEXT_ACCESSOR),\r\n ),\r\n )\r\n strategies.push(TOKENS.ROLE_AUTHORIZATION_PIPELINE)\r\n }\r\n\r\n if (Policies.has('permissions')) {\r\n const { PermissionAuthorizationStrategy } = await import('@/application')\r\n container.addSingleton(\r\n TOKENS.PERMISSION_AUTHORIZATION_PIPELINE,\r\n (c) =>\r\n new PermissionAuthorizationStrategy(\r\n c.resolve(TOKENS.POLICY_REGISTRY),\r\n c.resolve(TOKENS.CONTEXT_ACCESSOR),\r\n ),\r\n )\r\n strategies.push(TOKENS.PERMISSION_AUTHORIZATION_PIPELINE)\r\n }\r\n\r\n if (Policies.has('userId')) {\r\n const { UserAuthorizationStrategy } = await import('@/application')\r\n container.addSingleton(\r\n TOKENS.USER_AUTHORIZATION_PIPELINE,\r\n (c) =>\r\n new UserAuthorizationStrategy(\r\n c.resolve(TOKENS.POLICY_REGISTRY),\r\n c.resolve(TOKENS.CONTEXT_ACCESSOR),\r\n ),\r\n )\r\n strategies.push(TOKENS.USER_AUTHORIZATION_PIPELINE)\r\n }\r\n\r\n if (Policies.has('tenantId')) {\r\n const { TenantAuthorizationStrategy } = await import('@/application')\r\n container.addSingleton(\r\n TOKENS.TENANT_AUTHORIZATION_PIPELINE,\r\n (c) =>\r\n new TenantAuthorizationStrategy(\r\n c.resolve(TOKENS.POLICY_REGISTRY),\r\n c.resolve(TOKENS.CONTEXT_ACCESSOR),\r\n ),\r\n )\r\n strategies.push(TOKENS.TENANT_AUTHORIZATION_PIPELINE)\r\n }\r\n }\r\n\r\n if (!Guards.isNullOrEmpty(opts.customAuthorizationStrategy)) {\r\n const customStrategies = opts.customAuthorizationStrategy\r\n customStrategies.forEach((strategyToken, index) => {\r\n if (Guards.isDefined(strategyToken)) {\r\n const token = `CUSTOM_AUTHORIZATION_STRATEGY_${index}` as keyof TRegistry\r\n\r\n container.addSingleton(token, (c) => {\r\n return strategyToken(c) as unknown as TRegistry[typeof token]\r\n })\r\n strategies.push(token)\r\n }\r\n })\r\n }\r\n\r\n const { AuthorizationPipeline } = await import('@/application')\r\n container.addSingleton(TOKENS.AUTHORIZATION_PIPELINE, (c) => {\r\n const resolvedStrategies = strategies.map(\r\n (strategy) => c.resolve(strategy) as unknown as IStrategy<IRequest, void>,\r\n )\r\n return new AuthorizationPipeline(resolvedStrategies)\r\n })\r\n pipelines.push(TOKENS.AUTHORIZATION_PIPELINE)\r\n return pipelines\r\n },\r\n\r\n /**\r\n * @description Configures the authentication service and gatekeeper in the service container.\r\n * @param container The service container to configure.\r\n * @param opts The authentication configuration options.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n async addAuthN<TRegistry extends XenoRegistry = XenoRegistry>(\r\n container: IServiceContainer<TRegistry>,\r\n opts: AuthSsrConfig<SupabaseClientOptions<'public'>>,\r\n ): Promise<void> {\r\n const { TOKENS } = await import('@xeno-js/shared')\r\n const _t = opts\r\n const { SupabaseServerAuthFactory } = await import('../../factories')\r\n container.addScoped(TOKENS.AUTH_SERVICE, () => {\r\n const factory = new SupabaseServerAuthFactory()\r\n return factory.create({ config: opts, container })\r\n })\r\n\r\n container.addSingleton(TOKENS.BASE_AUTH_SERVICE, () => {\r\n const factory = new SupabaseServerAuthFactory()\r\n return factory.create({ config: opts, container })\r\n })\r\n\r\n const { ClaimsIdentityMapper } = await import('@/application')\r\n container.addSingleton(TOKENS.CLAIMS_IDENTITY_MAPPER, () => new ClaimsIdentityMapper())\r\n\r\n const { GateKeeper } = await import('@/application')\r\n container.addSingleton(TOKENS.GATE_KEEPER, (c) => {\r\n return new GateKeeper(\r\n c.resolve(TOKENS.BASE_AUTH_SERVICE),\r\n c.resolve(TOKENS.CLAIMS_IDENTITY_MAPPER),\r\n )\r\n })\r\n },\r\n} as const)\r\n","import type { DbConfig } from '@xeno-js/shared'\r\nimport type { Dictionary } from '@xeno-js/shared'\r\n\r\nimport type { DbContext } from '../../db/db.types'\r\n\r\n/**\r\n * @description Utility functions for database operations, including the creation of database clients based on configuration options. These utilities provide a convenient way to initialize and manage database connections, supporting both SQLite and other database engines as specified in the configuration.\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport const DbUtils = Object.freeze({\r\n /**\r\n * @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.\r\n *\r\n * @param opts - The database configuration options, including the connection string and any other relevant settings required for establishing a connection to the SQLite database.\r\n * @returns A new instance of a database client configured for SQLite, ready for use in the application.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n async addSqlLite(opts: DbConfig): Promise<DbContext<Dictionary>> {\r\n const { DbSqlLiteClientFactory } = await import('../../factories/sql-light-db-client.factory')\r\n return new DbSqlLiteClientFactory().create(opts)\r\n },\r\n\r\n /**\r\n * @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.\r\n * @param opts - The database configuration options, including the connection string and any other relevant settings required for establishing a connection to the database.\r\n * @returns A new instance of a database client, ready for use in the application.\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n async addDbClient(opts: DbConfig): Promise<DbContext<Dictionary>> {\r\n const { DbClientFactory } = await import('../../factories/db-client.factory')\r\n return new DbClientFactory().create(opts)\r\n },\r\n})\r\n","import type { ITransactionState, Maybe } from '@xeno-js/shared'\r\n\r\n/**\r\n * @file transaction-state.ts\r\n * @description This file contains the definition of the TransactionState class.\r\n * @version 1.0.0\r\n * @author Xeno\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class TransactionState<T> implements ITransactionState<T> {\r\n /**\r\n * The current state of the transaction, which can be either a specific transaction type or null.\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n private _state: Maybe<T> = null\r\n\r\n /**\r\n * Creates an instance of TransactionState.\r\n * @param initialState - The initial state of the transaction, which can be either a specific transaction type or null.\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n constructor(initialState: Maybe<T> = null) {\r\n this._state = initialState\r\n }\r\n\r\n get state(): Maybe<T> {\r\n return this._state\r\n }\r\n\r\n set state(value: Maybe<T>) {\r\n this._state = value\r\n }\r\n}\r\n","import type { IDisposable, ITransactionState, IUnitOfWork } from '@xeno-js/shared'\r\nimport { AppError } from '@xeno-js/shared'\r\nimport { Guards, type Optional } from '@xeno-js/shared'\r\n\r\nimport type { DbContext, DbTransaction } from '../db/db.types'\r\n\r\n/**\r\n * @file unit-of-work.ts\r\n * @description This file contains the implementation of the Unit of Work pattern.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class UnitOfWork implements IUnitOfWork, IDisposable {\r\n /**\r\n * Creates an instance of UnitOfWork.\r\n * @param _dbContext - The database context used for managing transactions.\r\n * @param _ttx - The transaction state, which can be either a specific transaction type or null.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n constructor(\r\n private readonly _dbContext: DbContext,\r\n private readonly _ttx: ITransactionState<DbTransaction>,\r\n ) {}\r\n\r\n async runInTransaction<T>(callback: () => Promise<T>, signal: Optional<AbortSignal>): Promise<T> {\r\n AppError.throwIfAborted(signal, 'UnitOfWork.runInTransaction')\r\n\r\n return this._dbContext.transaction(async (tx) => {\r\n this._ttx.state = tx\r\n try {\r\n const result = await callback()\r\n return result\r\n } finally {\r\n this._ttx.state = null\r\n }\r\n })\r\n }\r\n\r\n async dispose(): Promise<void> {\r\n if (Guards.isDefined(this._ttx.state)) {\r\n try {\r\n if (Guards.hasMethod(this._ttx.state, 'rollback')) {\r\n await (this._ttx.state as DbContext & { rollback: () => Promise<void> }).rollback()\r\n }\r\n } finally {\r\n this._ttx.state = null\r\n }\r\n }\r\n }\r\n}\r\n","import type { DbConfig } from '@xeno-js/shared'\r\n\r\nimport type { IModule, IServiceContainer } from '@/domain'\r\n\r\nimport type { DbContext, DbTransaction } from '../db/db.types'\r\nimport type { XenoRegistry } from '../xeno-registry'\r\n\r\n/**\r\n * @description The DbModule class is responsible for configuring the database module within the application. It implements the IModule interface, allowing it to be integrated into the application's dependency injection system. The configure method registers a singleton factory for creating an IDbClient instance using the provided configuration options. This design promotes modularity and allows for easy management of database connections and operations throughout the application.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class DbModule<TRegistry extends XenoRegistry = XenoRegistry> implements IModule<\r\n TRegistry,\r\n DbConfig\r\n> {\r\n async configure(container: IServiceContainer<TRegistry>, opts: DbConfig): Promise<void> {\r\n const { Guards, TOKENS } = await import('@xeno-js/shared')\r\n\r\n const { DbUtils } = await import('./utils/db.utils')\r\n const db = opts.enableSqlLite ? await DbUtils.addSqlLite(opts) : await DbUtils.addDbClient(opts)\r\n\r\n const { TransactionState } = await import('../transaction/transaction-state')\r\n\r\n container.addScoped(TOKENS.TRANSACTION_STATE, () => {\r\n return new TransactionState<DbTransaction>()\r\n })\r\n\r\n const { UnitOfWork } = await import('../transaction/unit-of-work')\r\n container.addScoped(TOKENS.UNIT_OF_WORK, (c) => {\r\n const ttx = c.resolve(TOKENS.TRANSACTION_STATE)\r\n return new UnitOfWork(db, ttx)\r\n })\r\n\r\n container.addScoped(TOKENS.DB_CONTEXT, (c) => {\r\n const ttx = c.resolve(TOKENS.TRANSACTION_STATE)\r\n\r\n return new Proxy(db, {\r\n get(_target, prop, receiver) {\r\n const activeState = ttx.state\r\n if (Guards.isDefined(activeState)) {\r\n if (prop === 'transaction') {\r\n return activeState.transaction.bind(activeState)\r\n }\r\n return Reflect.get(activeState, prop, receiver) as DbContext\r\n }\r\n return Reflect.get(db, prop, receiver) as DbContext\r\n },\r\n })\r\n })\r\n }\r\n}\r\n","import type { HttpConfig, IServiceContainer, ResilienceConfig } from '@/domain'\r\n\r\nimport type { XenoRegistry } from '../../xeno-registry'\r\n\r\n/**\r\n * @description Utility functions for configuring HTTP clients and resilience features in the service container.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport const HttpUtils = Object.freeze({\r\n /**\r\n * @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.\r\n * @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.\r\n * @returns A string representing the encoded query string that can be appended to a URL for making HTTP requests.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n async addAxios<TRegistry extends XenoRegistry = XenoRegistry>(\r\n container: IServiceContainer<TRegistry>,\r\n opts: HttpConfig<TRegistry>,\r\n ): Promise<void> {\r\n const { NodeAxiosFactory } = await import('../../factories')\r\n const { Guards } = await import('@xeno-js/shared')\r\n if (!Guards.isDefined(opts.token)) {\r\n throw new Error('HttpConfig.token is required and must be defined.')\r\n }\r\n\r\n container.addSingleton(opts.token, () => {\r\n const factory = new NodeAxiosFactory()\r\n const instance = factory.create(opts.client)\r\n if (\r\n !Guards.hasMethod(instance, 'get') ||\r\n !Guards.hasMethod(instance, 'post') ||\r\n !Guards.hasMethod(instance, 'put') ||\r\n !Guards.hasMethod(instance, 'patch') ||\r\n !Guards.hasMethod(instance, 'delete')\r\n ) {\r\n throw new Error(\r\n 'The created HTTP client instance does not implement the required methods of IHttpClient.',\r\n )\r\n }\r\n return instance as unknown as TRegistry[typeof opts.token]\r\n })\r\n },\r\n /**\r\n * @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.\r\n * @param container - The service container to register the resilience client with.\r\n * @param opts - The ResilienceConfig options that determine whether resilience features are enabled and provide the necessary settings for implementing resilience strategies.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n async addResilience<TRegistry extends XenoRegistry = XenoRegistry>(\r\n container: IServiceContainer<TRegistry>,\r\n opts: ResilienceConfig,\r\n ): Promise<void> {\r\n const { TOKENS } = await import('@xeno-js/shared')\r\n const { CockatielResilienceFactory } = await import('../../factories')\r\n container.addSingleton(TOKENS.RESILIENCE_CLIENT, () => {\r\n const factory = new CockatielResilienceFactory()\r\n return factory.create(opts)\r\n })\r\n },\r\n\r\n async addAllowOrigin<TRegistry extends XenoRegistry = XenoRegistry>(\r\n container: IServiceContainer<TRegistry>,\r\n opts: string[],\r\n ): Promise<void> {\r\n const { Guards } = await import('@xeno-js/shared')\r\n if (Guards.isNullOrEmpty(opts)) throw new Error('At least an allow origin must be passed')\r\n\r\n const { TOKENS } = await import('@xeno-js/shared')\r\n const { AllowOrigin } = await import('../../services')\r\n const allowOrigin: string[] = []\r\n\r\n opts.forEach((x) => {\r\n allowOrigin.push(x.trim().toLowerCase())\r\n })\r\n\r\n container.addSingleton(TOKENS.ALLOW_ORIGIN, () => new AllowOrigin(allowOrigin))\r\n },\r\n} as const)\r\n","import type { HttpCoreConfig, IModule, IServiceContainer } from '@/domain'\r\n\r\nimport type { XenoRegistry } from '../xeno-registry'\r\n\r\n/**\r\n * @description HttpCoreModule is responsible for configuring the core HTTP functionalities of the application. It implements the IModule interface, allowing it to be integrated into the application's dependency injection system. The configure method registers essential services such as the HTTP client and resilience features based on the provided configuration options. This design promotes modularity and allows for easy management of HTTP-related operations throughout the application.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class HttpCoreModule<TRegistry extends XenoRegistry = XenoRegistry> implements IModule<\r\n TRegistry,\r\n HttpCoreConfig<TRegistry>\r\n> {\r\n async configure(\r\n container: IServiceContainer<TRegistry>,\r\n opts: HttpCoreConfig<TRegistry>,\r\n ): Promise<void> {\r\n const { HttpUtils } = await import('./utils/http.utils')\r\n await HttpUtils.addAxios(container, opts.http)\r\n await HttpUtils.addResilience(container, opts.resilience)\r\n }\r\n}\r\n\r\nexport class HttpOriginModule<TRegistry extends XenoRegistry = XenoRegistry> implements IModule<\r\n TRegistry,\r\n string[]\r\n> {\r\n async configure(container: IServiceContainer<TRegistry>, opts: string[]): Promise<void> {\r\n const { HttpUtils } = await import('./utils/http.utils')\r\n await HttpUtils.addAllowOrigin(container, opts)\r\n }\r\n}\r\n","import type { ILogger, IRequest, IStrategy } from '@xeno-js/shared'\r\nimport type { KeysOfType } from '@xeno-js/shared'\r\nimport type { ZodType } from 'zod'\r\n\r\nimport type {\r\n ApplicationRegistry,\r\n IServiceContainer,\r\n IServiceScope,\r\n PipelineConfig,\r\n} from '@/domain'\r\n\r\nimport type { XenoRegistry } from '../../xeno-registry'\r\n\r\n/**\r\n * @description ValidationUtils is a utility class that provides methods for adding validation strategies to the dependency injection container based on the provided configuration. It checks if the validation configuration is defined and, if so, it registers the appropriate validation strategies (such as Zod schema validation) in the container and adds them to the pipeline behaviors. This allows for flexible and configurable validation of requests in the application.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport const ValidationUtils = Object.freeze({\r\n /**\r\n * @description Checks if the provided validation configuration requires any validation strategies.\r\n * @param validationConfig The validation configuration to check.\r\n * @returns True if any validation strategies are required, false otherwise.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n\r\n async addValidation<TRegistry extends XenoRegistry = XenoRegistry>(\r\n container: IServiceContainer<TRegistry>,\r\n opts: PipelineConfig<TRegistry, ZodType>['validation'],\r\n logger: ILogger,\r\n ): Promise<(keyof TRegistry)[]> {\r\n const { Guards, TOKENS } = await import('@xeno-js/shared')\r\n\r\n if (!Guards.isDefined(opts.zod) && Guards.isNullOrEmpty(opts.customValidationStrategy)) {\r\n return []\r\n }\r\n\r\n const pipelines: (keyof TRegistry)[] = []\r\n const validationStrategies: KeysOfType<\r\n ApplicationRegistry<unknown>,\r\n IStrategy<IRequest, boolean>\r\n >[] = []\r\n\r\n if (Guards.isDefined(opts.zod)) {\r\n const config = opts.zod\r\n const { ZodValidatorFactory } = await import('../../factories/zod-validator.factory')\r\n container.addSingleton(TOKENS.ZOD_VALIDATOR, () => {\r\n return new ZodValidatorFactory().create({ ...config, logger })\r\n })\r\n\r\n const { SchemaValidationStrategy } = await import('@/application')\r\n container.addSingleton(\r\n TOKENS.SCHEMA_VALIDATION_STRATEGY,\r\n (c) => new SchemaValidationStrategy(c.resolve(TOKENS.ZOD_VALIDATOR)),\r\n )\r\n validationStrategies.push(TOKENS.SCHEMA_VALIDATION_STRATEGY)\r\n }\r\n const customValidationFactory: ((\r\n c: IServiceScope<TRegistry>,\r\n ) => IStrategy<IRequest, boolean>)[] = []\r\n\r\n if (!Guards.isNullOrEmpty(opts.customValidationStrategy)) {\r\n for (const strategyToken of opts.customValidationStrategy) {\r\n if (Guards.isDefined(strategyToken)) {\r\n customValidationFactory.push(strategyToken)\r\n }\r\n }\r\n }\r\n\r\n const { ValidationPipeline } = await import('@/application')\r\n container.addSingleton(TOKENS.VALIDATION_PIPELINE, (c) => {\r\n const resolvedStrategies = [\r\n ...validationStrategies.map((token) => c.resolve(token)),\r\n ...customValidationFactory.map((factory) => factory(c)),\r\n ]\r\n return new ValidationPipeline(resolvedStrategies)\r\n })\r\n\r\n pipelines.push(TOKENS.VALIDATION_PIPELINE)\r\n return pipelines\r\n },\r\n} as const)\r\n","import type { ICache, ICacheKeyBuilder, IIdempotencyStore } from '@xeno-js/shared'\r\nimport type { Optional } from '@xeno-js/shared'\r\nimport { IDEMPOTENCY_CONSTANTS } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description The IdempotencyStore class provides an implementation of the IIdempotencyStore interface, utilizing a caching mechanism to manage locks and processed command results for idempotent operations. This class is designed to ensure that commands with the same ID are processed only once, preventing duplicate processing and allowing for retrieval of results from previously processed commands. The IdempotencyStore uses the IRequestContext to build contextual keys for storing locks and results in a multi-tenant environment, following the AWS SaaS Factory Pattern for logical partitioning. By leveraging the ICache interface, the IdempotencyStore can efficiently manage locks and stored results with configurable time-to-live (TTL) values, ensuring that stale data is automatically cleaned up over time.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class IdempotencyStore implements IIdempotencyStore {\r\n /**\r\n * @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.\r\n * @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.\r\n * @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.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n constructor(\r\n private readonly _cache: ICache,\r\n private readonly _cacheKeyBuilder: ICacheKeyBuilder,\r\n ) {}\r\n\r\n public async acquireLock(requestId: string, ttlSeconds: number): Promise<boolean> {\r\n const key = this._cacheKeyBuilder.buildContextualKey(`command:${requestId}`)\r\n return await this._cache.setIfAbsent(\r\n `${IDEMPOTENCY_CONSTANTS.LOCK_KEY_PREFIX}${key}`,\r\n IDEMPOTENCY_CONSTANTS.LOCKED_VALUE,\r\n ttlSeconds,\r\n )\r\n }\r\n\r\n public async hasBeenProcessed(commandId: string): Promise<boolean> {\r\n const key = this._cacheKeyBuilder.buildContextualKey(`command:${commandId}`)\r\n return await this._cache.has(`${IDEMPOTENCY_CONSTANTS.PROCESSED_KEY_PREFIX}${key}`)\r\n }\r\n\r\n public async markAsProcessed<T>(\r\n commandId: string,\r\n payload: T,\r\n ttlSeconds: number,\r\n ): Promise<void> {\r\n const key = this._cacheKeyBuilder.buildContextualKey(`command:${commandId}`)\r\n await this._cache.set(\r\n `${IDEMPOTENCY_CONSTANTS.PROCESSED_KEY_PREFIX}${key}`,\r\n payload,\r\n ttlSeconds,\r\n )\r\n }\r\n\r\n public async getPayload<T>(commandId: string): Promise<Optional<T>> {\r\n const key = this._cacheKeyBuilder.buildContextualKey(`command:${commandId}`)\r\n const payload = await this._cache.get<T>(`${IDEMPOTENCY_CONSTANTS.PROCESSED_KEY_PREFIX}${key}`)\r\n\r\n return payload\r\n }\r\n\r\n public async releaseLock(commandId: string): Promise<void> {\r\n const key = this._cacheKeyBuilder.buildContextualKey(`command:${commandId}`)\r\n await this._cache.remove(`${IDEMPOTENCY_CONSTANTS.LOCK_KEY_PREFIX}${key}`)\r\n }\r\n}\r\n","import type { IServiceContainer, PipelineConfig } from '@/domain'\r\n\r\nimport type { XenoRegistry } from '../../xeno-registry'\r\n\r\n/**\r\n * @description Utility functions for configuring command and query pipelines in the service container.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport const PipelineUtils = Object.freeze({\r\n /**\r\n * @description Checks if the provided command configuration requires any command strategies.\r\n * @param commandConfig The command configuration to check.\r\n * @returns True if any command strategies are required, false otherwise.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n async addCommand<TRegistry extends XenoRegistry = XenoRegistry>(\r\n container: IServiceContainer<TRegistry>,\r\n opts: PipelineConfig<TRegistry>['commandBus'] & { isCache: boolean },\r\n ): Promise<(keyof TRegistry)[]> {\r\n const pipelines: (keyof TRegistry)[] = []\r\n const { Guards, TOKENS } = await import('@xeno-js/shared')\r\n if (Guards.isDefined(opts.idempotency)) {\r\n const { IdempotencyStore } = await import('../../idempotency/idempotency-store')\r\n container.addSingleton(\r\n TOKENS.IDEMPOTENCY_STORE,\r\n (c) => new IdempotencyStore(c.resolve(TOKENS.CACHE), c.resolve(TOKENS.CACHE_KEY_BUILDER)),\r\n )\r\n\r\n const { IdempotencyPipeline } = await import('@/application')\r\n container.addSingleton(TOKENS.IDEMPOTENCY_PIPELINE, (c) => {\r\n const requestContext = c.resolve(TOKENS.NETWORK_CONTEXT_ACCESSOR)\r\n const idempotencyStore = c.resolve(TOKENS.IDEMPOTENCY_STORE)\r\n const config = opts.idempotency\r\n return new IdempotencyPipeline(\r\n requestContext,\r\n idempotencyStore,\r\n config?.lockTtlSeconds,\r\n config?.processedTtlSeconds,\r\n )\r\n })\r\n pipelines.push(TOKENS.IDEMPOTENCY_PIPELINE)\r\n }\r\n\r\n if (Guards.isDefined(opts.concurrency)) {\r\n const { ConcurrencyRetryPipeline } = await import('@/application')\r\n container.addSingleton(TOKENS.CONCURRENCY_RETRY_PIPELINE, () => {\r\n const config = opts.concurrency\r\n return new ConcurrencyRetryPipeline(config?.maxRetries, config?.delayConfig)\r\n })\r\n pipelines.push(TOKENS.CONCURRENCY_RETRY_PIPELINE)\r\n }\r\n return pipelines\r\n },\r\n /**\r\n * @description Checks if the provided query configuration requires any query strategies.\r\n * @param queryConfig The query configuration to check.\r\n * @returns True if any query strategies are required, false otherwise.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n async addQuery<TRegistry extends XenoRegistry = XenoRegistry>(\r\n container: IServiceContainer<TRegistry>,\r\n opts: { isCache: boolean },\r\n ): Promise<(keyof TRegistry)[]> {\r\n const { TOKENS } = await import('@xeno-js/shared')\r\n const pipelines: (keyof TRegistry)[] = []\r\n\r\n if (!opts.isCache) {\r\n const { CacheUtils } = await import('./cache.utils')\r\n await CacheUtils.addCache(container, { inMemory: true, redis: undefined })\r\n }\r\n\r\n const { QueryCachingPipeline } = await import('@/application')\r\n container.addSingleton(\r\n TOKENS.QUERY_CACHING_PIPELINE,\r\n (c) =>\r\n new QueryCachingPipeline(\r\n c.resolve(TOKENS.CACHE),\r\n c.resolve(TOKENS.CACHE_KEY_BUILDER),\r\n c.resolve(TOKENS.LOGGER),\r\n ),\r\n )\r\n pipelines.push(TOKENS.QUERY_CACHING_PIPELINE)\r\n return pipelines\r\n },\r\n} as const)\r\n","import type { ICommand, IPipelineBehavior, IQuery } from '@xeno-js/shared'\r\nimport type { ZodType } from 'zod'\r\n\r\nimport type { IModule, IServiceContainer, IServiceScopeAccessor, PipelineConfig } from '@/domain'\r\n\r\nimport type { XenoRegistry } from '../xeno-registry'\r\n\r\n/**\r\n * @description CqrsModule is responsible for configuring and registering the necessary services and dependencies related to the Command Query Responsibility Segregation (CQRS) pattern in the application. It sets up the Mediator service, which acts as a central hub for handling commands and queries, allowing for a clean separation of concerns between the command and query sides of the application. By registering the Mediator in the dependency injection container, it enables other parts of the application to easily resolve and utilize its functionality for processing commands and queries.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class CqrsModule<TRegistry extends XenoRegistry = XenoRegistry> implements IModule<\r\n TRegistry,\r\n PipelineConfig<TRegistry, ZodType>\r\n> {\r\n async configure(\r\n container: IServiceContainer<TRegistry>,\r\n opts: PipelineConfig<TRegistry, ZodType> & { isLogger: boolean; isCache: boolean },\r\n ): Promise<void> {\r\n const { TOKENS } = await import('@xeno-js/shared')\r\n let isCache = opts.isCache\r\n\r\n const { Mediator } = await import('@/application')\r\n container.addSingleton(TOKENS.MEDIATOR, (c) => {\r\n const serviceScopeAccessor = c.resolve(TOKENS.SERVICE_SCOPE_ACCESSOR)\r\n return new Mediator<TRegistry>(serviceScopeAccessor as IServiceScopeAccessor<TRegistry>)\r\n })\r\n\r\n const { ExceptionPipeline } = await import('@/application')\r\n container.addSingleton(TOKENS.EXCEPTION_PIPELINE, () => new ExceptionPipeline())\r\n if (!opts.isLogger) {\r\n const { LoggerUtils } = await import('./utils/logger.utils')\r\n await LoggerUtils.addLogger(container, undefined)\r\n }\r\n\r\n const { LoggingPipeline } = await import('@/application')\r\n container.addSingleton(\r\n TOKENS.LOGGING_PIPELINE,\r\n (c) => new LoggingPipeline(c.resolve(TOKENS.LOGGER)),\r\n )\r\n const pipelines: (keyof TRegistry)[] = [TOKENS.EXCEPTION_PIPELINE, TOKENS.LOGGING_PIPELINE]\r\n\r\n const { PerformancePipeline } = await import('@/application')\r\n container.addSingleton(TOKENS.PERFORMANCE_PIPELINE, (c) => {\r\n const logger = c.resolve(TOKENS.LOGGER)\r\n const thresholdMs = opts.performance?.thresholdMs\r\n return new PerformancePipeline(logger, thresholdMs)\r\n })\r\n pipelines.push(TOKENS.PERFORMANCE_PIPELINE)\r\n\r\n const { Guards } = await import('@xeno-js/shared')\r\n if (\r\n Guards.isDefined(opts.authorization.policies) ||\r\n Guards.isDefined(opts.authorization.customAuthorizationStrategy)\r\n ) {\r\n const { AuthUtils } = await import('./utils/auth.utils')\r\n const authPipelines = await AuthUtils.addAuthZ(container, opts.authorization)\r\n pipelines.push(...authPipelines)\r\n }\r\n\r\n if (\r\n Guards.isDefined(opts.validation.zod) ||\r\n Guards.isDefined(opts.validation.customValidationStrategy)\r\n ) {\r\n const { ValidationUtils } = await import('./utils/validation.utils')\r\n const logger = container.resolve(TOKENS.LOGGER)\r\n const validationPipelines = await ValidationUtils.addValidation(\r\n container,\r\n opts.validation,\r\n logger,\r\n )\r\n pipelines.push(...validationPipelines)\r\n }\r\n\r\n const commandPipelines = pipelines\r\n const queryPipelines = pipelines\r\n\r\n if (\r\n (Guards.isDefined(opts.commandBus.idempotency) || opts.queryBus.isEnabled) &&\r\n opts.isCache\r\n ) {\r\n const { CacheUtils } = await import('./utils/cache.utils')\r\n await CacheUtils.addCache(container, { inMemory: true, redis: undefined })\r\n }\r\n\r\n if (\r\n Guards.isDefined(opts.commandBus.idempotency) ||\r\n Guards.isDefined(opts.commandBus.concurrency)\r\n ) {\r\n const { PipelineUtils } = await import('./utils/pipeline.utils')\r\n const newCommandPipelines = await PipelineUtils.addCommand(container, {\r\n ...opts.commandBus,\r\n isCache,\r\n })\r\n isCache = true\r\n commandPipelines.push(...newCommandPipelines)\r\n }\r\n\r\n if (opts.queryBus.isEnabled) {\r\n const { PipelineUtils } = await import('./utils/pipeline.utils')\r\n const newQueryPipelines = await PipelineUtils.addQuery(container, { isCache })\r\n queryPipelines.push(...newQueryPipelines)\r\n }\r\n\r\n const { CompositePipeline } = await import('@/application')\r\n container.addSingleton(TOKENS.COMMAND_PIPELINES_BEHAVIOR, (c) => {\r\n const resolvedCommandPipelines = commandPipelines.map((token) => {\r\n return c.resolve(token) as IPipelineBehavior<ICommand<unknown>, unknown>\r\n })\r\n return new CompositePipeline<ICommand<unknown>, unknown>(resolvedCommandPipelines)\r\n })\r\n\r\n container.addSingleton(TOKENS.QUERY_PIPELINES_BEHAVIOR, (c) => {\r\n const resolvedQueryPipelines = queryPipelines.map(\r\n (token) => c.resolve(token) as IPipelineBehavior<IQuery<unknown>, unknown>,\r\n )\r\n return new CompositePipeline<IQuery<unknown>, unknown>(resolvedQueryPipelines)\r\n })\r\n }\r\n}\r\n","import type {\r\n AppError,\r\n ICommand,\r\n IContextAccessor,\r\n IController,\r\n IMediator,\r\n IQuery,\r\n RequestContext,\r\n ResultType,\r\n} from '@xeno-js/shared'\r\nimport type { Dictionary, Optional, ResponseDto } from '@xeno-js/shared'\r\nimport { GuidHelper, HttpHelper } from '@xeno-js/shared'\r\n\r\n/**\r\n * BaseController is an abstract class that implements the IController interface. It provides a foundation for creating specific controllers that handle incoming requests and return responses. The class requires a mediator to facilitate communication between different parts of the application.\r\n * @template TRequest - The type of the request object that the controller will handle.\r\n * @template TResponse - The type of the response object that the controller will return.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport abstract class BaseController<TRequest, TResponse> implements IController<\r\n TRequest,\r\n TResponse\r\n> {\r\n /**\r\n * Constructs a new instance of the BaseController class.\r\n * @param _requestContext - An instance of IContextAccessor used to manage the execution context for requests.\r\n * @param _mediator - An instance of IMediator used to facilitate communication between different parts of the application.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n constructor(\r\n private readonly _requestContext: IContextAccessor<RequestContext>,\r\n private readonly _mediator: IMediator,\r\n ) {}\r\n\r\n abstract handle(request: TRequest): Promise<ResponseDto<TResponse>>\r\n\r\n /**\r\n * Helper to return a successful 200/201 response.\r\n * @param data - The data to include in the response.\r\n * @param status - The HTTP status code (default is 200).\r\n * @param meta - Optional metadata to include in the response.\r\n * @param headers - Optional headers to include in the response.\r\n * @returns A ResponseDto containing the data and status.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n protected ok<T>(\r\n data: T,\r\n status = 200,\r\n meta: Optional<Dictionary> = {},\r\n headers: Optional<Dictionary<string[]>> = {},\r\n ): ResponseDto<T> {\r\n return HttpHelper.success(data, status, meta, headers)\r\n }\r\n\r\n /**\r\n * Helper to automatically map a failed Result (from the CQRS pipeline)\r\n * into a standardized ErrorResponseDto.\r\n * @param error - The AppError instance representing the error.\r\n * @param details - Optional additional details about the error.\r\n * @param headers - Optional headers to include in the error response.\r\n * @returns A ResponseDto representing the error response.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n protected fail(\r\n error: AppError,\r\n details: Optional<string> = undefined,\r\n headers: Optional<Dictionary<string[]>> = {},\r\n ): ResponseDto<TResponse> {\r\n const context = this._requestContext.getContext()\r\n\r\n const customHeaders = error['header'] as Optional<Dictionary<string[]>>\r\n\r\n return HttpHelper.error<TResponse>(\r\n {\r\n success: false,\r\n error: {\r\n code: error.code,\r\n message: error.message,\r\n path: context?.network.path,\r\n details: details ?? error.message,\r\n },\r\n correlationId: context?.tracing.correlationId ?? GuidHelper.generate(),\r\n requestId: context?.network.requestId ?? GuidHelper.generate(),\r\n spanId: context?.tracing.spanId ?? GuidHelper.generate(),\r\n timestamp: new Date().toISOString(),\r\n },\r\n error.status,\r\n {\r\n 'Content-Type': [context?.network.formatIndicator ?? 'application/json'],\r\n ...customHeaders,\r\n ...headers,\r\n },\r\n )\r\n }\r\n\r\n /**\r\n * Helper to send a query through the mediator and return the result.\r\n * @param request - The IQuery instance to be sent.\r\n * @returns A promise resolving to the result of the query.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n protected _query(request: IQuery<TResponse>): Promise<ResultType<TResponse>> {\r\n const signal = new AbortController().signal\r\n return this._mediator.query(request, signal)\r\n }\r\n\r\n /**\r\n * Helper to send a command through the mediator and return the result.\r\n * @param request - The ICommand instance to be sent.\r\n * @returns A promise resolving to the result of the command.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n protected _send(request: ICommand<TResponse>): Promise<ResultType<TResponse>> {\r\n const signal = new AbortController().signal\r\n return this._mediator.send(request, signal)\r\n }\r\n\r\n protected getContext(): Optional<RequestContext> {\r\n return this._requestContext.getContext()\r\n }\r\n}\r\n","export * from './base.controller'\r\n","import type {\r\n HttpHeaders,\r\n HttpMethod,\r\n IMiddleware,\r\n RequestContext,\r\n ResponseDto,\r\n} from '@xeno-js/shared'\r\nimport {\r\n ERROR_CODE_MESSAGES,\r\n ERROR_CODES,\r\n GuidHelper,\r\n HttpHelper,\r\n STATUS_CODES,\r\n} from '@xeno-js/shared'\r\n\r\nimport type { ApplicationRegistry, IAllowMethod, IRequestContext } from '@/domain'\r\n\r\n/**\r\n * @description Middleware that checks if the requested method is allowed for the given path. If the method is not allowed, it returns a 405\r\n * status code with an error message.\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n * @param {IAllowMethod} _allowMethod - The allow method service to check if the method is allowed.\r\n * @param {IRequestContext<RequestContext, ApplicationRegistry<unknown>>} _requestContext - The request context to get the request context.\r\n * @returns {IMiddleware<HttpHeaders>} - The middleware function that checks if the method is allowed.\r\n * @throws {Error} - If the method is not allowed, it throws an error with a 405 status code and an error message.\r\n * @see {@link IAllowMethod} - The allow method service.\r\n * @see {@link IRequestContext} - The request context.\r\n * @see {@link IMiddleware} - The middleware interface.\r\n * @see {@link IResponseDto} - The response DTO.\r\n */\r\nexport class MethodCheckMiddleware implements IMiddleware<HttpHeaders> {\r\n constructor(\r\n private readonly _requestContext: IRequestContext<RequestContext, ApplicationRegistry<unknown>>,\r\n private readonly _allowMethod: IAllowMethod,\r\n ) {}\r\n\r\n public async execute<T, TRes, TReq>(\r\n req: { method: HttpMethod; path: string; transport: { req: TRes; res: TReq } },\r\n _headers: HttpHeaders,\r\n next: () => Promise<ResponseDto<T>>,\r\n ): Promise<ResponseDto<T>> {\r\n const isAllowed = this._allowMethod.check(req.path, req.method)\r\n\r\n if (!isAllowed) {\r\n const { network, tracing } = this._requestContext.getContext() ?? {}\r\n\r\n return HttpHelper.error(\r\n {\r\n success: false,\r\n error: {\r\n code: ERROR_CODES.NOT_ALLOWED,\r\n message: ERROR_CODE_MESSAGES[ERROR_CODES.NOT_ALLOWED],\r\n details: `Operation blocked by allow method middleware`,\r\n path: req.path,\r\n },\r\n correlationId: tracing?.correlationId ?? GuidHelper.generate(),\r\n requestId: network?.requestId ?? GuidHelper.generate(),\r\n spanId: tracing?.spanId ?? GuidHelper.generate(),\r\n timestamp: new Date().toISOString(),\r\n },\r\n STATUS_CODES.NOT_ALLOWED,\r\n {\r\n Allow: this._allowMethod.getMethods(req.path),\r\n },\r\n )\r\n }\r\n\r\n return await next()\r\n }\r\n}\r\n","import type {\r\n HttpHeaders,\r\n HttpMethod,\r\n IContextAccessor,\r\n ILogger,\r\n IMiddleware,\r\n RequestContext,\r\n ResponseDto,\r\n} from '@xeno-js/shared'\r\nimport {\r\n ERROR_CODE_MESSAGES,\r\n ERROR_CODES,\r\n GuidHelper,\r\n HttpHelper,\r\n STATUS_CODES,\r\n} from '@xeno-js/shared'\r\n\r\nimport type { IAllowOrigin } from '@/domain'\r\n\r\n/**\r\n * @description A middleware that checks if the origin of the request is allowed.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class AllowOriginMiddleware implements IMiddleware<HttpHeaders> {\r\n constructor(\r\n private readonly _allowOrigin: IAllowOrigin,\r\n private readonly _requestContext: IContextAccessor<RequestContext>,\r\n private readonly _logger: ILogger,\r\n ) {}\r\n\r\n public async execute<T, TRes, TReq>(\r\n req: { method: HttpMethod; path: string; transport: { req: TRes; res: TReq } },\r\n _headers: HttpHeaders,\r\n next: () => Promise<ResponseDto<T>>,\r\n ): Promise<ResponseDto<T>> {\r\n const { network, tracing } = this._requestContext.getContext() ?? {}\r\n const origin = network?.origin\r\n\r\n if (!this._allowOrigin.isAllowed(origin)) {\r\n this._logger.warn(`Access denied by AllowOrigin policy for origin: ${origin ?? 'unknown'}`)\r\n\r\n return HttpHelper.error(\r\n {\r\n success: false,\r\n error: {\r\n code: ERROR_CODES.FORBIDDEN,\r\n message: ERROR_CODE_MESSAGES[ERROR_CODES.FORBIDDEN],\r\n details: `The origin '${origin ?? 'unknown'}' is not allowed to access this resource.`,\r\n path: req.path,\r\n },\r\n correlationId: tracing?.correlationId ?? GuidHelper.generate(),\r\n requestId: network?.requestId ?? GuidHelper.generate(),\r\n spanId: tracing?.spanId ?? GuidHelper.generate(),\r\n timestamp: new Date().toISOString(),\r\n },\r\n STATUS_CODES.FORBIDDEN,\r\n )\r\n }\r\n\r\n return next()\r\n }\r\n}\r\n","import type {\r\n HttpHeaders,\r\n HttpMethod,\r\n IGateKeeper,\r\n ILogger,\r\n IMiddleware,\r\n IServiceExtractor,\r\n Optional,\r\n RequestContext,\r\n ResponseDto,\r\n} from '@xeno-js/shared'\r\nimport { GuidHelper, HttpHelper, STATUS_CODES } from '@xeno-js/shared'\r\n\r\nimport type { ApplicationRegistry, IRequestContext } from '@/domain'\r\n\r\n/**\r\n * @description Middleware that checks if the request is authenticated. If the request is not authenticated, it returns a 401\r\n * status code with an error message.\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @param {IRequestContext<RequestContext, ApplicationRegistry<unknown>>} _requestContext - The request context to use for resolving services.\r\n * @param {IGateKeeper} _gateKeeper - The gate keeper to use for authentication.\r\n * @param {ILogger} _logger - The logger to use for logging.\r\n * @param {IServiceExtractor<HttpHeaders, Optional<string>>} _tokenExtractor - The token extractor to use for extracting the token from the request.\r\n * @returns {IMiddleware<HttpHeaders>} - The middleware function.\r\n * @link https://github.com/xeno-js/xeno-js\r\n *\r\n * @see {@link IRequestContext} - The request context interface.\r\n * @see {@link IGateKeeper} - The gate keeper interface.\r\n * @see {@link ILogger} - The logger interface.\r\n * @see {@link IServiceExtractor} - The service extractor interface.\r\n */\r\nexport class AuthenticationMiddleware implements IMiddleware<HttpHeaders> {\r\n constructor(\r\n private readonly _requestContext: IRequestContext<RequestContext, ApplicationRegistry<unknown>>,\r\n private readonly _tokenExtractor: IServiceExtractor<HttpHeaders, Optional<string>>,\r\n private readonly _gateKeeper: IGateKeeper,\r\n private readonly _logger: ILogger,\r\n ) {}\r\n\r\n public async execute<T, TRes, TReq>(\r\n req: { method: HttpMethod; path: string; transport: { req: TRes; res: TReq } },\r\n headers: HttpHeaders,\r\n next: () => Promise<ResponseDto<T>>,\r\n ): Promise<ResponseDto<T>> {\r\n const token = this._tokenExtractor.extract(headers)\r\n const authResult = await this._gateKeeper.authenticate(token)\r\n\r\n if (!authResult.isOk()) {\r\n const error = authResult.getErrorOrThrow()\r\n this._logger.warn(\r\n `Authentication failed for request on path: ${req.path}. Code: ${error.code}. Error: ${error}`,\r\n )\r\n\r\n const { network, tracing } = this._requestContext.getContext() ?? {}\r\n\r\n return HttpHelper.error(\r\n {\r\n success: false,\r\n error: {\r\n code: error.code,\r\n message: error.message,\r\n details: `[Authentication Error] Failed to authenticate request on path: ${req.path}`,\r\n path: req.path,\r\n },\r\n correlationId: tracing?.correlationId ?? GuidHelper.generate(),\r\n requestId: network?.requestId ?? GuidHelper.generate(),\r\n spanId: tracing?.spanId ?? GuidHelper.generate(),\r\n timestamp: new Date().toISOString(),\r\n },\r\n error.status ?? STATUS_CODES.UNAUTHORIZED,\r\n { 'Content-Type': [network?.formatIndicator ?? 'application/json'] },\r\n )\r\n }\r\n\r\n this._requestContext.updateIdentity(authResult.getValueOrThrow()!)\r\n\r\n return next()\r\n }\r\n}\r\n","import type { HttpHeaders, HttpMethod, IMiddleware, ResponseDto } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description A middleware that executes a list of middlewares in a chain.\r\n *\r\n * @author Xeno\r\n * @version 1.0.1\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class CompositeMiddleware implements IMiddleware<HttpHeaders> {\r\n constructor(private readonly _middlewares: IMiddleware<HttpHeaders>[]) {}\r\n\r\n public async execute<T, TRes, TReq>(\r\n req: { method: HttpMethod; path: string; transport: { req: TRes; res: TReq } },\r\n headers: HttpHeaders,\r\n next: () => Promise<ResponseDto<T>>,\r\n ): Promise<ResponseDto<T>> {\r\n let currentNext = next\r\n\r\n for (let i = this._middlewares.length - 1; i >= 0; i--) {\r\n const currentBehavior = this._middlewares[i]\r\n const previousNext = currentNext\r\n currentNext = () => currentBehavior.execute(req, headers, previousNext)\r\n }\r\n\r\n return currentNext()\r\n }\r\n}\r\n","import type {\r\n HttpHeaders,\r\n HttpMethod,\r\n IContextAccessor,\r\n IMiddleware,\r\n RequestContext,\r\n ResponseDto,\r\n} from '@xeno-js/shared'\r\nimport { Guards } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description A cors middleware that checks if the origin of the request is allowed.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class CORSMiddleware implements IMiddleware<HttpHeaders> {\r\n constructor(\r\n private readonly _requestContext: IContextAccessor<RequestContext>,\r\n private readonly _withCredentials: 'true' | 'false' = 'false',\r\n ) {}\r\n\r\n public async execute<T, TRes, TReq>(\r\n _req: { method: HttpMethod; path: string; transport: { req: TRes; res: TReq } },\r\n _headers: HttpHeaders,\r\n next: () => Promise<ResponseDto<T>>,\r\n ): Promise<ResponseDto<T>> {\r\n const { network } = this._requestContext.getContext() ?? {}\r\n const origin = network?.origin\r\n\r\n const response = await next()\r\n if (Guards.isDefined(origin))\r\n response.headers = {\r\n ...(response.headers ?? {}),\r\n 'Access-Control-Allow-Origin': origin,\r\n 'Access-Control-Allow-Credentials': this._withCredentials,\r\n 'Vary': 'Origin',\r\n }\r\n return response\r\n }\r\n}\r\n","import type { HttpHeaders, HttpMethod, RequestContext, ResponseDto } from '@xeno-js/shared'\r\nimport {\r\n ERROR_CODE_MESSAGES,\r\n ERROR_CODES,\r\n Guards,\r\n GuidHelper,\r\n HttpHelper,\r\n STATUS_CODES,\r\n} from '@xeno-js/shared'\r\n\r\nimport type { ApplicationRegistry, ICsrfTokenService, IRequestContext } from '@/domain'\r\n\r\n/**\r\n * @description The CsrfMiddleware class implements the IMiddleware interface, providing a concrete implementation for handling CSRF token validation. It checks the incoming request for a valid CSRF token and returns an error response if the token is missing or invalid.\r\n */\r\nexport class CsrfMiddleware {\r\n constructor(\r\n private readonly _requestContext: IRequestContext<RequestContext, ApplicationRegistry<unknown>>,\r\n private readonly _csrfTokenService: ICsrfTokenService,\r\n ) {}\r\n\r\n public async execute<T, TRes, TReq>(\r\n req: { method: HttpMethod; path: string; transport: { req: TRes; res: TReq } },\r\n _headers: HttpHeaders,\r\n next: () => Promise<ResponseDto<T>>,\r\n ): Promise<ResponseDto<T>> {\r\n const method = req.method.toUpperCase()\r\n const isStateChanging = ['POST', 'PUT', 'DELETE', 'PATCH'].includes(method)\r\n\r\n if (isStateChanging) {\r\n const { network, tracing, identity } = this._requestContext.getContext() ?? {}\r\n const headerToken = network?.csrf\r\n const cookieToken = network?.csrfCookie\r\n\r\n if (!Guards.isDefined(headerToken) || !Guards.isDefined(cookieToken)) {\r\n return HttpHelper.error(\r\n {\r\n success: false,\r\n error: {\r\n code: ERROR_CODES.FORBIDDEN,\r\n message: ERROR_CODE_MESSAGES[ERROR_CODES.FORBIDDEN],\r\n details: 'CSRF token missing',\r\n path: req.path,\r\n },\r\n correlationId: tracing?.correlationId ?? GuidHelper.generate(),\r\n requestId: network?.requestId ?? GuidHelper.generate(),\r\n spanId: tracing?.spanId ?? GuidHelper.generate(),\r\n timestamp: new Date().toISOString(),\r\n },\r\n STATUS_CODES.FORBIDDEN,\r\n {\r\n 'Content-Type': [network?.formatIndicator ?? 'application/json'],\r\n },\r\n )\r\n }\r\n\r\n if (headerToken !== cookieToken) {\r\n return HttpHelper.error(\r\n {\r\n success: false,\r\n error: {\r\n code: ERROR_CODES.FORBIDDEN,\r\n message: ERROR_CODE_MESSAGES[ERROR_CODES.FORBIDDEN],\r\n details: 'CSRF token mismatch',\r\n path: req.path,\r\n },\r\n correlationId: tracing?.correlationId ?? GuidHelper.generate(),\r\n requestId: network?.requestId ?? GuidHelper.generate(),\r\n spanId: tracing?.spanId ?? GuidHelper.generate(),\r\n timestamp: new Date().toISOString(),\r\n },\r\n STATUS_CODES.FORBIDDEN,\r\n {\r\n 'Content-Type': [network?.formatIndicator ?? 'application/json'],\r\n },\r\n )\r\n }\r\n\r\n if (\r\n !Guards.isDefined(identity?.userId) ||\r\n !(await this._csrfTokenService.validate(headerToken, identity?.userId))\r\n ) {\r\n return HttpHelper.error(\r\n {\r\n success: false,\r\n error: {\r\n code: ERROR_CODES.FORBIDDEN,\r\n message: ERROR_CODE_MESSAGES[ERROR_CODES.FORBIDDEN],\r\n details: 'CSRF token invalid',\r\n path: req.path,\r\n },\r\n correlationId: tracing?.correlationId ?? GuidHelper.generate(),\r\n requestId: network?.requestId ?? GuidHelper.generate(),\r\n spanId: tracing?.spanId ?? GuidHelper.generate(),\r\n timestamp: new Date().toISOString(),\r\n },\r\n STATUS_CODES.FORBIDDEN,\r\n {\r\n 'Content-Type': [network?.formatIndicator ?? 'application/json'],\r\n },\r\n )\r\n }\r\n }\r\n\r\n return await next()\r\n }\r\n}\r\n","import type {\r\n HttpHeaders,\r\n HttpMethod,\r\n IContextAccessor,\r\n IMiddleware,\r\n RequestContext,\r\n ResponseDto,\r\n} from '@xeno-js/shared'\r\nimport { Guards } from '@xeno-js/shared'\r\n\r\nimport type { ICsrfTokenService, MiddlewareConfig } from '@/domain'\r\n\r\n/**\r\n * @description The CsrfCookieMiddleware class implements the IMiddleware interface, providing a concrete implementation for handling CSRF token validation and cookie management. It checks the incoming request for a valid CSRF token and sets a CSRF cookie if necessary.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n * @license MIT\r\n */\r\nexport class CsrfCookieMiddleware implements IMiddleware<HttpHeaders> {\r\n constructor(\r\n private readonly _requestContext: IContextAccessor<RequestContext>,\r\n private readonly _csrfTokenService: ICsrfTokenService,\r\n private readonly _csrf: NonNullable<MiddlewareConfig['csrf']>,\r\n ) {}\r\n\r\n public async execute<T, TRes, TReq>(\r\n _req: {\r\n method: HttpMethod\r\n path: string\r\n transport: {\r\n req: TRes\r\n res: TReq\r\n }\r\n },\r\n _headers: HttpHeaders,\r\n next: () => Promise<ResponseDto<T>>,\r\n ): Promise<ResponseDto<T>> {\r\n const response = await next()\r\n\r\n const context = this._requestContext.getContext()\r\n const identity = context?.identity\r\n const network = context?.network\r\n\r\n if (!Guards.isDefined(identity?.userId)) return response\r\n\r\n if (Guards.isDefined(network?.csrfCookie)) return response\r\n\r\n const token = await this._csrfTokenService.generate(identity.userId)\r\n\r\n const cookieName = this._csrf.cookieName ?? '__Host-xeno-csrf'\r\n const maxAge = this._csrf.cookieMaxAgeSeconds ?? 3600\r\n const sameSite = this._csrf.sameSite ?? 'lax'\r\n\r\n const cookie =\r\n `${cookieName}=${encodeURIComponent(token)}; ` +\r\n `Path=/; ` +\r\n `Secure; ` +\r\n `SameSite=${sameSite}; ` +\r\n `Max-Age=${maxAge}`\r\n\r\n const existingCookies = response.headers['Set-Cookie']\r\n\r\n response.headers = {\r\n ...(response.headers ?? {}),\r\n 'Set-Cookie': [...(existingCookies ?? []), cookie],\r\n }\r\n\r\n return response\r\n }\r\n}\r\n","import type { HttpHeaders, HttpMethod, INetworkContextAccessor, ResponseDto } from '@xeno-js/shared'\r\nimport { Guards, HttpHelper, STATUS_CODES } from '@xeno-js/shared'\r\n\r\nimport type { IAllowMethod } from '@/domain'\r\n\r\n/**\r\n * @description A middleware that handles OPTIONS requests.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class OptionsMiddleware {\r\n constructor(\r\n private readonly _requestContext: INetworkContextAccessor,\r\n private readonly _alloewMethod: IAllowMethod,\r\n private readonly _allowHeaders: string[] = [],\r\n private readonly _withCredentials: 'true' | 'false' = 'false',\r\n ) {}\r\n\r\n public async execute<T, TRes, TReq>(\r\n req: { method: HttpMethod; path: string; transport: { req: TRes; res: TReq } },\r\n _headers: HttpHeaders,\r\n next: () => Promise<ResponseDto<T>>,\r\n ): Promise<ResponseDto<T>> {\r\n if (req.method.toUpperCase() === 'OPTIONS') {\r\n const network = this._requestContext.getNetworkContext()\r\n const origin = network?.origin\r\n\r\n const headers: HttpHeaders = {}\r\n if (Guards.isDefined(origin)) {\r\n headers['Access-Control-Allow-Origin'] = origin\r\n headers['Access-Control-Allow-Credentials'] = this._withCredentials\r\n headers['Vary'] = 'Origin'\r\n }\r\n headers['Access-Control-Allow-Methods'] = this._alloewMethod.getMethods(req.path)\r\n headers['Access-Control-Allow-Headers'] = this._allowHeaders.join(', ')\r\n\r\n return HttpHelper.success(null as T, STATUS_CODES.NO_CONTENT, {}, headers)\r\n }\r\n\r\n return await next()\r\n }\r\n}\r\n","import type {\r\n HttpHeaders,\r\n HttpMethod,\r\n IContextAccessor,\r\n ILogger,\r\n IMiddleware,\r\n RequestContext,\r\n ResponseDto,\r\n} from '@xeno-js/shared'\r\nimport {\r\n ERROR_CODE_MESSAGES,\r\n ERROR_CODES,\r\n Guards,\r\n GuidHelper,\r\n HttpHelper,\r\n STATUS_CODES,\r\n} from '@xeno-js/shared'\r\n\r\nimport type { IAtomicCache, IRateLimitKeyBuilder } from '@/domain'\r\n\r\n/**\r\n * @description The RateLimitMiddleware class implements the IMiddleware interface and provides rate limiting functionality for incoming requests. It uses an IAtomicCache instance to track the number of requests made by each client within a specified time window. If the number of requests exceeds the maximum allowed, the middleware returns a 429 Too Many Requests response. Otherwise it calls the next middleware in the chain.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 1.0.0\r\n * @param {IContextAccessor<RequestContext>} _ctxAccessor - The context accessor for the request.\r\n * @param {IAtomicCache} _cache - The cache used to store the request counts.\r\n * @param {ILogger} _logger - The logger used to log messages.\r\n * @param {number} _opts.maxRequests - The maximum number of requests allowed within the time window.\r\n * @param {number} _opts.windowSeconds - The time window in seconds within which the maximum number of requests is allowed.\r\n * @link https://github.com/xenowits/xeno-js\r\n */\r\nexport class RateLimitMiddleware implements IMiddleware<HttpHeaders> {\r\n constructor(\r\n private readonly _ctxAccessor: IContextAccessor<RequestContext>,\r\n private readonly _cache: IAtomicCache,\r\n private readonly _keyBuilder: IRateLimitKeyBuilder,\r\n private readonly _logger: ILogger,\r\n private readonly _opts: {\r\n maxRequests: number\r\n windowSeconds: number\r\n },\r\n ) {}\r\n\r\n public async execute<T, TRes, TReq>(\r\n req: { method: HttpMethod; path: string; transport: { req: TRes; res: TReq } },\r\n _headers: HttpHeaders,\r\n next: () => Promise<ResponseDto<T>>,\r\n ): Promise<ResponseDto<T>> {\r\n const cacheKey = this._keyBuilder.buildRateLimitKey(req.path)\r\n const { network, tracing } = this._ctxAccessor.getContext() ?? {}\r\n\r\n if (!Guards.isDefined(cacheKey))\r\n return HttpHelper.error(\r\n {\r\n success: false,\r\n error: {\r\n code: ERROR_CODES.SYSTEM_ERROR,\r\n message: ERROR_CODE_MESSAGES[ERROR_CODES.SYSTEM_ERROR],\r\n details: `Bad Request: Unable to identify client context for rate limiting.`,\r\n path: req.path,\r\n },\r\n correlationId: tracing?.correlationId ?? GuidHelper.generate(),\r\n requestId: network?.requestId ?? GuidHelper.generate(),\r\n spanId: tracing?.spanId ?? GuidHelper.generate(),\r\n timestamp: new Date().toISOString(),\r\n },\r\n STATUS_CODES.SERVICE_UNAVAILABLE,\r\n {\r\n 'Content-Type': [network?.formatIndicator ?? 'application/json'],\r\n 'Retry-After': [String(this._opts.windowSeconds)],\r\n },\r\n )\r\n\r\n const currentHits = await this._cache.increment(cacheKey, this._opts.windowSeconds)\r\n\r\n if (currentHits > this._opts.maxRequests) {\r\n this._logger.warn(`[RateLimit] key ${cacheKey} has been blocked on ${req.path}`)\r\n\r\n return HttpHelper.error(\r\n {\r\n success: false,\r\n error: {\r\n code: ERROR_CODES.TOO_MANY_REQUESTS,\r\n message: ERROR_CODE_MESSAGES[ERROR_CODES.TOO_MANY_REQUESTS],\r\n details: `Rate limit exceeded. Key ${cacheKey} throttled.`,\r\n path: req.path,\r\n },\r\n correlationId: tracing?.correlationId ?? GuidHelper.generate(),\r\n requestId: network?.requestId ?? GuidHelper.generate(),\r\n spanId: tracing?.spanId ?? GuidHelper.generate(),\r\n timestamp: new Date().toISOString(),\r\n },\r\n STATUS_CODES.TOO_MANY_REQUESTS,\r\n {\r\n 'Content-Type': [network?.formatIndicator ?? 'application/json'],\r\n 'Retry-After': [String(this._opts.windowSeconds)],\r\n },\r\n )\r\n }\r\n\r\n return next()\r\n }\r\n}\r\n","import type {\r\n IBaseMapper,\r\n Identity,\r\n MessagingContext,\r\n NetworkContext,\r\n RequestContext,\r\n TracingContext,\r\n} from '@xeno-js/shared'\r\nimport { Guards, type Metadata, type Optional } from '@xeno-js/shared'\r\n\r\ninterface ContextMapperSource {\r\n readonly metadata: Metadata\r\n readonly identity: Identity\r\n readonly path: string\r\n readonly transport: { req: unknown; res: unknown }\r\n}\r\n\r\nexport const ContextMapper: IBaseMapper<ContextMapperSource, RequestContext> = Object.freeze({\r\n /**\r\n * @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.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n map: (source: ContextMapperSource): RequestContext => {\r\n const { metadata, identity, path, transport } = source\r\n\r\n const network: NetworkContext = {\r\n requestId: metadata.requestId!,\r\n clientIp: metadata.clientIp,\r\n userAgent: metadata.userAgent,\r\n formatIndicator: metadata.formatIndicator,\r\n path,\r\n transport,\r\n csrf: metadata.csrf,\r\n csrfCookie: metadata.csrfCookie,\r\n origin: metadata.origin,\r\n }\r\n const tracing: TracingContext = {\r\n correlationId: metadata.correlationId!,\r\n startTime: Date.now(),\r\n spanId: metadata.spanId,\r\n parentSpanId: metadata.parentSpanId,\r\n referer: metadata.referer,\r\n }\r\n const messaging = _buildMessagingContext(metadata)\r\n\r\n const requestContext: RequestContext = {\r\n identity,\r\n network,\r\n tracing,\r\n messaging,\r\n }\r\n\r\n return requestContext\r\n },\r\n} as const)\r\n\r\n/**\r\n * @description Builds the MessagingContext based on the provided Metadata. It checks for the presence of sequence data, expiration, and return address in the metadata to determine if a MessagingContext should be created. If any of these properties are defined, it constructs a MessagingContext object with the relevant information; otherwise, it returns undefined. This method encapsulates the logic for determining whether messaging-related context is available and ensures that the resulting MessagingContext is properly structured.\r\n * @param meta The Metadata object extracted from the HTTP request headers, containing information such as correlation ID, request ID, authentication token, client IP, user agent, format indicator, return address, expiration, and sequence data. This metadata is used to determine whether a MessagingContext should be created and what properties it should contain.\r\n * @returns An Optional<MessagingContext> object that contains messaging-related context information if available; otherwise, it returns undefined. The MessagingContext includes properties such as return address, expiration time, and sequence information (sequence ID, position, and size) if they are present in the metadata.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nfunction _buildMessagingContext(meta: Metadata): Optional<MessagingContext> {\r\n const hasSequenceData =\r\n Guards.isDefined(meta.sequence?.sequenceId) ||\r\n Guards.isDefined(meta.sequence?.position) ||\r\n Guards.isDefined(meta.sequence?.size)\r\n\r\n const hasMessagingData =\r\n hasSequenceData || Guards.isDefined(meta.expiration) || Guards.isDefined(meta.returnAddress)\r\n\r\n const messaging: Optional<MessagingContext> = hasMessagingData\r\n ? {\r\n returnAddress: meta.returnAddress,\r\n expiration: meta.expiration,\r\n sequence: hasSequenceData ? meta.sequence : undefined,\r\n }\r\n : undefined\r\n return messaging\r\n}\r\n","import type {\r\n Identity,\r\n ILogger,\r\n IMiddleware,\r\n IServiceExtractor,\r\n RequestContext,\r\n} from '@xeno-js/shared'\r\nimport type { Guid, HttpHeaders, HttpMethod, Metadata, ResponseDto } from '@xeno-js/shared'\r\nimport {\r\n ERROR_CODE_MESSAGES,\r\n ERROR_CODES,\r\n GUEST,\r\n GuidHelper,\r\n HttpHelper,\r\n STATUS_CODES,\r\n} from '@xeno-js/shared'\r\n\r\nimport type { ApplicationRegistry, IIPResolver, IRequestContext } from '@/domain'\r\n\r\nimport { ContextMapper } from '../mappers/context.mapper'\r\n\r\n/**\r\n * @description The RequestContextMiddleware class is responsible for extracting metadata from incoming HTTP requests, performing authentication using the provided authentication middleware, and composing an ExecutionContext that includes identity, network, and tracing information. It implements the IMiddleware interface, allowing it to be used as part of a middleware chain in the request processing pipeline. The middleware ensures that the ExecutionContext is properly set up for downstream handlers, controllers, or use cases to access necessary contextual information for processing the request.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class RequestContextMiddleware implements IMiddleware<HttpHeaders> {\r\n /**\r\n * @description Constructs a new instance of the RequestContextMiddleware class, which is responsible for handling the request context in the middleware chain. It takes several dependencies as parameters, including an IRequestContext for managing the execution context, an IServiceExtractor for extracting metadata from HTTP headers, an IGateKeeper for performing authentication, and an IServiceContainer for managing service scopes and dependencies. These dependencies are essential for the middleware to function correctly, allowing it to extract necessary information from incoming requests, authenticate users, and set up the execution context for downstream processing.\r\n * @param _requestContext An instance of IRequestContext used to manage the execution context for the request. This context allows the middleware to set and retrieve contextual information that can be accessed by downstream handlers, controllers, or use cases during the processing of the request.\r\n * @param _extractor An instance of IServiceExtractor used to extract metadata from the incoming HTTP request headers. This extractor is responsible for parsing the headers and retrieving relevant information such as correlation IDs, request IDs, authentication tokens, client IP addresses, and tracing span IDs, which are essential for building the ExecutionContext.\r\n * @param _logger\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n constructor(\r\n private readonly _requestContext: IRequestContext<RequestContext, ApplicationRegistry<unknown>>,\r\n private readonly _extractor: IServiceExtractor<HttpHeaders, Metadata>,\r\n private readonly _resolver: IIPResolver,\r\n private readonly _logger: ILogger,\r\n ) {}\r\n\r\n public async execute<T, TRes, TReq>(\r\n req: { method: HttpMethod; path: string; transport: { req: TRes; res: TReq } },\r\n headers: HttpHeaders,\r\n next: () => Promise<ResponseDto<T>>,\r\n ): Promise<ResponseDto<T>> {\r\n const correlationId = GuidHelper.generate()\r\n const requestId = GuidHelper.generate()\r\n const spanId: Guid = correlationId\r\n const formatIndicator = 'application/json'\r\n\r\n try {\r\n const meta = this._extractor.extract(headers)\r\n\r\n const clientIp = this._resolver.resolve(req.transport.req, meta.clientIp)\r\n\r\n const metadata: Metadata = {\r\n ...meta,\r\n clientIp,\r\n correlationId: meta.correlationId ?? correlationId,\r\n requestId: meta.requestId ?? requestId,\r\n spanId: meta.spanId ?? spanId,\r\n formatIndicator: meta.formatIndicator,\r\n }\r\n\r\n const tmpContext = ContextMapper.map({\r\n metadata,\r\n identity: GUEST as unknown as Identity,\r\n path: req.path,\r\n transport: req.transport,\r\n })\r\n\r\n const result = await this._requestContext.runAsync(tmpContext, async () => {\r\n return next()\r\n })\r\n if (!result.ok && !result.data.success)\r\n this._logger.error(result.data.error.message, result.data)\r\n\r\n return result\r\n } catch (error) {\r\n this._logger.error('RequestContextMiddleware encountered an error', error)\r\n return HttpHelper.error(\r\n {\r\n success: false,\r\n error: {\r\n code: ERROR_CODES.SYSTEM_ERROR,\r\n message: ERROR_CODE_MESSAGES[ERROR_CODES.SYSTEM_ERROR],\r\n details: `[Fatal System Error] Exception caught during request handling on path: ${req.path}`,\r\n path: req.path,\r\n },\r\n correlationId,\r\n requestId,\r\n spanId,\r\n timestamp: new Date().toISOString(),\r\n },\r\n STATUS_CODES.INTERNAL_SERVER_ERROR,\r\n { 'Content-Type': [formatIndicator] },\r\n )\r\n }\r\n }\r\n}\r\n","export * from './allow-method.middleware'\r\nexport * from './allow-origin.middleware'\r\nexport * from './auth.middleware'\r\nexport * from './composite.middleware'\r\nexport * from './cors.middleware'\r\nexport * from './csrf.middleware'\r\nexport * from './csrf-cookie.middleware'\r\nexport * from './options.middleware'\r\nexport * from './rate-limiter.middleware'\r\nexport * from './request.middleware'\r\n","export * from './controllers/index'\r\nexport * from './middlewares/index'\r\n","import type { Optional, RequestContext } from '@xeno-js/shared'\r\nimport { Guards } from '@xeno-js/shared'\r\n\r\nimport type { ApplicationRegistry, IRateLimitKeyBuilder, IRequestContext } from '@/domain'\r\n\r\n/**\r\n * @description The RateLimitKeyBuilder class implements the IRateLimitKeyBuilder interface, providing a method to build rate limit keys based on the user's identity. This class utilizes an instance of IIdentityAccessor to retrieve the current user's identity, allowing for the creation of tenant-specific rate limit keys in multi-tenant applications. If a tenant ID is present in the identity, the rate limit key is prefixed with the tenant ID; otherwise, it defaults to a public rate limit key. This approach ensures that rate limit data is appropriately scoped to the user's context, preventing data leakage between tenants.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-vue\r\n * @copyright Xeno\r\n * @license MIT\r\n */\r\nexport class RateLimitKeyBuilder implements IRateLimitKeyBuilder {\r\n constructor(\r\n private readonly _contextAccessor: IRequestContext<\r\n RequestContext,\r\n ApplicationRegistry<unknown>\r\n >,\r\n ) {}\r\n\r\n public buildRateLimitKey(resource: string): Optional<string> {\r\n const ctx = this._contextAccessor.getContext()\r\n\r\n const tenantId = ctx?.identity?.tenantId\r\n const userId = ctx?.identity?.userId\r\n const clientIp = ctx?.network?.clientIp\r\n\r\n if (!Guards.isNullOrEmpty(tenantId) && !Guards.isNullOrEmpty(userId))\r\n return `ratelimit:tenant:${tenantId}:user:${userId}:${resource}`\r\n\r\n if (!Guards.isNullOrEmpty(tenantId) && !Guards.isNullOrEmpty(clientIp))\r\n return `ratelimit:tenant:${tenantId}:ip:${clientIp}:${resource}`\r\n\r\n if (!Guards.isNullOrEmpty(userId)) return `ratelimit:user:${userId}:${resource}`\r\n\r\n if (!Guards.isNullOrEmpty(clientIp)) return `ratelimit:ip:${clientIp}:${resource}`\r\n\r\n return undefined\r\n }\r\n}\r\n","export * from './inmemory.cache'\r\nexport * from './rate-limit-key-builder.cache'\r\nexport * from './redis.cache'\r\n","import { Guards, type HttpHeaders, type IGateKeeper, type IMiddleware } from '@xeno-js/shared'\r\n\r\nimport type { IModule, IServiceContainer, MiddlewareConfig } from '@/domain'\r\n\r\nimport type { XenoRegistry } from '../xeno-registry'\r\n\r\n/**\r\n * @description MiddlewareModule is responsible for registering essential services and middlewares that are fundamental to the application's operation. This includes setting up the logging infrastructure and the request context middleware. By implementing the IModule interface, MiddlewareModule can be easily integrated into the application's dependency injection container, allowing it to configure necessary services and middlewares during the application startup phase.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class MiddlewareModule<TRegistry extends XenoRegistry = XenoRegistry> implements IModule<\r\n TRegistry,\r\n MiddlewareConfig & {\r\n isAuth: boolean\r\n isLogger: boolean\r\n isCache: boolean\r\n }\r\n> {\r\n async configure(\r\n container: IServiceContainer<TRegistry>,\r\n opts: MiddlewareConfig & {\r\n isAuth: boolean\r\n isLogger: boolean\r\n isCache: boolean\r\n },\r\n ): Promise<void> {\r\n const { TOKENS } = await import('@xeno-js/shared')\r\n\r\n if (!opts.isAuth) {\r\n const { NoAuthGateKeeper } = await import('@/application')\r\n container.addSingleton(TOKENS.GATE_KEEPER, (): IGateKeeper => new NoAuthGateKeeper())\r\n }\r\n\r\n if (opts.isSSR) {\r\n const { SupabaseSsrTokenExtractor } = await import('../services')\r\n container.addSingleton(TOKENS.BEARER_TOKEN_EXTRACTOR, () => new SupabaseSsrTokenExtractor())\r\n } else {\r\n const { BearerTokenExtractor } = await import('../services')\r\n container.addSingleton(TOKENS.BEARER_TOKEN_EXTRACTOR, () => new BearerTokenExtractor())\r\n }\r\n\r\n const { HttpCookieExtractor } = await import('../services')\r\n container.addSingleton('COOKIE_EXTRACTOR', () => new HttpCookieExtractor())\r\n\r\n const { HttpHeaderExtractor } = await import('../services')\r\n container.addSingleton(\r\n TOKENS.SERVICE_EXTRACTOR,\r\n (c) =>\r\n new HttpHeaderExtractor(\r\n c.resolve(TOKENS.BEARER_TOKEN_EXTRACTOR),\r\n c.resolve('COOKIE_EXTRACTOR'),\r\n opts.trustedIpHeader,\r\n opts.csrf?.cookieName ?? '__Host-xeno-csrf',\r\n ),\r\n )\r\n\r\n if (!opts.isLogger) {\r\n const { LoggerUtils } = await import('./utils/logger.utils')\r\n await LoggerUtils.addLogger(container, undefined)\r\n }\r\n\r\n const { ClientIpResolver } = await import('../services')\r\n container.addSingleton('IP_RESOLVER', () => new ClientIpResolver(opts.trustedProxies))\r\n\r\n const middlewares: (keyof TRegistry)[] = [TOKENS.REQUEST_CONTEXT_MIDDLEWARE]\r\n\r\n const { RequestContextMiddleware } = await import('@/presentation')\r\n container.addSingleton(\r\n TOKENS.REQUEST_CONTEXT_MIDDLEWARE,\r\n (c) =>\r\n new RequestContextMiddleware(\r\n c.resolve(TOKENS.REQUEST_CONTEXT),\r\n c.resolve(TOKENS.SERVICE_EXTRACTOR),\r\n c.resolve('IP_RESOLVER'),\r\n c.resolve(TOKENS.LOGGER),\r\n ),\r\n )\r\n\r\n if (!Guards.isNullOrEmpty(opts.allowOrigins)) {\r\n if (opts.withCredentials && opts.allowOrigins.includes('*'))\r\n throw new Error(\r\n 'Wildcard CORS origin is not allowed when withCredentials is set to true in addHttpCore',\r\n )\r\n\r\n const { AllowOrigin } = await import('../services')\r\n container.addSingleton('ALLOW_ORIGIN', () => {\r\n return new AllowOrigin(opts.allowOrigins!)\r\n })\r\n\r\n const { AllowOriginMiddleware } = await import('@/presentation')\r\n container.addSingleton(TOKENS.ALLOW_ORIGIN_MIDDLEWARE, (c) => {\r\n return new AllowOriginMiddleware(\r\n c.resolve(TOKENS.ALLOW_ORIGIN),\r\n c.resolve(TOKENS.CONTEXT_ACCESSOR),\r\n c.resolve(TOKENS.LOGGER),\r\n )\r\n })\r\n middlewares.push(TOKENS.ALLOW_ORIGIN_MIDDLEWARE)\r\n }\r\n\r\n const withCredentials = opts.withCredentials ? 'true' : 'false'\r\n if (opts.optionsMiddleware) {\r\n const { OptionsMiddleware } = await import('@/presentation')\r\n container.addSingleton(\r\n TOKENS.OPTIONS_MIDDLEWARE,\r\n (c) =>\r\n new OptionsMiddleware(\r\n c.resolve(TOKENS.NETWORK_CONTEXT_ACCESSOR),\r\n c.resolve(TOKENS.ALLOW_METHOD),\r\n opts.allowHeaders,\r\n withCredentials,\r\n ),\r\n )\r\n middlewares.push(TOKENS.OPTIONS_MIDDLEWARE)\r\n }\r\n\r\n if (opts.cors) {\r\n const { CORSMiddleware } = await import('@/presentation')\r\n container.addSingleton(TOKENS.CORS_MIDDLEWARE, (c) => {\r\n return new CORSMiddleware(c.resolve(TOKENS.CONTEXT_ACCESSOR), withCredentials)\r\n })\r\n middlewares.push(TOKENS.CORS_MIDDLEWARE)\r\n }\r\n\r\n if (Guards.isDefined(opts.routeRegistry)) {\r\n const registry = opts.routeRegistry\r\n const { AllowMethodFactory } = await import('../factories')\r\n container.addSingleton(TOKENS.ALLOW_METHOD, () => new AllowMethodFactory().create(registry))\r\n\r\n const { MethodCheckMiddleware } = await import('@/presentation')\r\n container.addSingleton(\r\n TOKENS.METHOD_CHECK_MIDDLEWARE,\r\n (c) =>\r\n new MethodCheckMiddleware(\r\n c.resolve(TOKENS.REQUEST_CONTEXT),\r\n c.resolve(TOKENS.ALLOW_METHOD),\r\n ),\r\n )\r\n middlewares.push(TOKENS.METHOD_CHECK_MIDDLEWARE)\r\n }\r\n\r\n const { AuthenticationMiddleware } = await import('@/presentation')\r\n container.addSingleton(TOKENS.AUTH_MIDDLEWARE, (c) => {\r\n return new AuthenticationMiddleware(\r\n c.resolve(TOKENS.REQUEST_CONTEXT),\r\n c.resolve(TOKENS.BEARER_TOKEN_EXTRACTOR),\r\n c.resolve(TOKENS.GATE_KEEPER),\r\n c.resolve(TOKENS.LOGGER),\r\n )\r\n })\r\n middlewares.push(TOKENS.AUTH_MIDDLEWARE)\r\n\r\n if (\r\n Guards.isDefined(opts.rateLimite.maxRequests) ||\r\n Guards.isDefined(opts.rateLimite.windowSeconds)\r\n ) {\r\n const maxRequests = opts.rateLimite.maxRequests ?? 30\r\n Guards.throwIfNegative(maxRequests, 'MaxRequests must be positive')\r\n Guards.throwIfNotInteger(maxRequests, 'MaxRequests must be an integer')\r\n const windowSeconds = opts.rateLimite.windowSeconds ?? 30\r\n Guards.throwIfNegative(windowSeconds, 'WindowSeconds must be positive')\r\n Guards.throwIfNotInteger(windowSeconds, 'WindowSeconds must be an integer')\r\n\r\n if (!opts.isCache) {\r\n const { CacheUtils } = await import('./utils/cache.utils')\r\n await CacheUtils.addCache(container, { inMemory: true, redis: undefined })\r\n }\r\n\r\n const { RateLimitKeyBuilder } = await import('../cache')\r\n container.addSingleton(\r\n 'RATE_LIMIT_KEY_BUILDER',\r\n (c) => new RateLimitKeyBuilder(c.resolve(TOKENS.REQUEST_CONTEXT)),\r\n )\r\n\r\n const { RateLimitMiddleware } = await import('@/presentation')\r\n container.addSingleton(TOKENS.RATE_LIMITER_MIDDLEWARE, (c) => {\r\n return new RateLimitMiddleware(\r\n c.resolve(TOKENS.CONTEXT_ACCESSOR),\r\n c.resolve(TOKENS.CACHE),\r\n c.resolve('RATE_LIMIT_KEY_BUILDER'),\r\n c.resolve(TOKENS.LOGGER),\r\n {\r\n maxRequests,\r\n windowSeconds,\r\n },\r\n )\r\n })\r\n middlewares.push(TOKENS.RATE_LIMITER_MIDDLEWARE)\r\n }\r\n\r\n if (Guards.isDefined(opts.csrf)) {\r\n const csrf = opts.csrf\r\n const { CsrfTokenService } = await import('../services')\r\n container.addSingleton('CSRF_TOKEN_SERVICE', (c) => {\r\n return new CsrfTokenService(csrf.secret, c.resolve('CRYPTO_SERVICE'))\r\n })\r\n\r\n const { CsrfCookieMiddleware } = await import('@/presentation')\r\n container.addSingleton('CSRF_COOKIE_MIDDLEWARE', (c) => {\r\n return new CsrfCookieMiddleware(\r\n c.resolve(TOKENS.REQUEST_CONTEXT),\r\n c.resolve('CSRF_TOKEN_SERVICE'),\r\n csrf,\r\n )\r\n })\r\n middlewares.push('CSRF_COOKIE_MIDDLEWARE')\r\n\r\n const { CsrfMiddleware } = await import('@/presentation')\r\n container.addSingleton(TOKENS.CSRF_MIDDLEWARE, (c) => {\r\n return new CsrfMiddleware(\r\n c.resolve(TOKENS.REQUEST_CONTEXT),\r\n c.resolve('CSRF_TOKEN_SERVICE'),\r\n )\r\n })\r\n middlewares.push(TOKENS.CSRF_MIDDLEWARE)\r\n }\r\n\r\n const { CompositeMiddleware } = await import('@/presentation')\r\n container.addSingleton(TOKENS.MIDDLEWARE, (c) => {\r\n const resolvedMiddleware = middlewares.map(\r\n (token) => c.resolve(token) as IMiddleware<HttpHeaders>,\r\n )\r\n return new CompositeMiddleware(resolvedMiddleware)\r\n })\r\n }\r\n}\r\n","import type { IFactory } from '@xeno-js/shared'\r\n\r\nimport type { IModule, IServiceContainer, IServiceScope } from '@/domain'\r\n\r\nimport type { XenoRegistry } from '../xeno-registry'\r\n\r\n/**\r\n * @description ContextModule is responsible for configuring and registering the necessary services and dependencies related to the request context in the application. It sets up the RequestContext service, which provides a way to manage and access contextual information related to a specific request or operation. By registering the RequestContext in the dependency injection container, it enables other parts of the application to easily resolve and utilize its functionality for managing request-specific data and state.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class ContextModule<TRegistry extends XenoRegistry = XenoRegistry> implements IModule<\r\n TRegistry,\r\n void\r\n> {\r\n async configure(container: IServiceContainer<TRegistry>): Promise<void> {\r\n const { TOKENS } = await import('@xeno-js/shared')\r\n const { ServiceScopeFactory } = await import('../factories/service-scope.factory')\r\n container.addSingleton(TOKENS.SERVICE_SCOPE_FACTORY, () => {\r\n const factory = new ServiceScopeFactory<TRegistry>(container)\r\n return factory\r\n })\r\n\r\n const { NodeRequestContextFactory } = await import('../factories/request-context.factory')\r\n container.addSingleton(TOKENS.REQUEST_CONTEXT, (c) => {\r\n return new NodeRequestContextFactory<TRegistry>(\r\n c.resolve(TOKENS.SERVICE_SCOPE_FACTORY) as IFactory<void, IServiceScope<TRegistry>>,\r\n ).create()\r\n })\r\n\r\n container.addSingleton(TOKENS.CONTEXT_ACCESSOR, (c) => c.resolve(TOKENS.REQUEST_CONTEXT))\r\n container.addSingleton(TOKENS.IDENTITY_ACCESSOR, (c) => c.resolve(TOKENS.REQUEST_CONTEXT))\r\n container.addSingleton(TOKENS.SERVICE_SCOPE_ACCESSOR, (c) => c.resolve(TOKENS.REQUEST_CONTEXT))\r\n container.addSingleton(TOKENS.NETWORK_CONTEXT_ACCESSOR, (c) =>\r\n c.resolve(TOKENS.REQUEST_CONTEXT),\r\n )\r\n const { UserContextFactory } = await import('../factories/user-context.factory')\r\n container.addSingleton(TOKENS.USER_CONTEXT_FACTORY, (c) => {\r\n const requestContext = c.resolve(TOKENS.REQUEST_CONTEXT)\r\n return new UserContextFactory(requestContext)\r\n })\r\n }\r\n}\r\n","export {\r\n BaseAuthorizationStrategy,\r\n BaseHandler,\r\n ContainerUtils,\r\n Specification,\r\n} from './application'\r\nexport type * from './domain'\r\nexport type { XenoRegistry } from './infrastructure'\r\nexport { AppBuilder, BasePostgresSqlDataSource, BaseSqliteSqlDataSource, ReadDao, Repository, SupabaseServerAuthFactory } from './infrastructure'\r\nexport type * from './infrastructure/db/db.types'\r\nexport type { Query } from './infrastructure/db/drizzle.types'\r\nexport * from './infrastructure/db/drizzle.types'\r\nexport { BaseController } from './presentation'\r\nexport * from '@xeno-js/shared'\r\nexport { Query as BaseQuery } from '@xeno-js/shared'\r\n","import type { SupabaseClientOptions } from '@supabase/supabase-js'\r\nimport type { CacheConfig, DbConfig, IConfigurationService } from '@xeno-js/shared'\r\nimport type { Optional, SetupAction } from '@xeno-js/shared'\r\nimport { Guards, LOG_LEVEL, TOKENS } from '@xeno-js/shared'\r\nimport type { ZodType } from 'zod'\r\n\r\nimport type {\r\n ApplicationRegistry,\r\n AuthSsrConfig,\r\n HttpCoreConfig,\r\n IModule,\r\n IServiceContainer,\r\n LoggerConfig,\r\n MiddlewareConfig,\r\n PipelineConfig,\r\n} from '@/domain'\r\n\r\nimport { EnvironmentConfigurationService } from '../configuration'\r\nimport { ServiceContainer } from '../container/service-container'\r\nimport type { XenoRegistry } from '../xeno-registry'\r\n\r\n/**\r\n * @description The AppBuilder class provides a fluent, .NET-style API for configuring and bootstrapping the application. It orchestrates the registration of various modules (CQRS, HTTP, Database, Logging, Auth) into the ServiceContainer.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\ninterface QueuedModule {\r\n priority: number\r\n name: string\r\n action: () => Promise<void>\r\n}\r\n\r\n/**\r\n * @description The AppBuilder class provides a fluent, .NET-style API for configuring and bootstrapping the application.\r\n * It orchestrates the registration of various modules (CQRS, HTTP, Database, Logging, Auth) into the ServiceContainer.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport class AppBuilder<TRegistry extends XenoRegistry = XenoRegistry> {\r\n private readonly _container: IServiceContainer<TRegistry> = new ServiceContainer<TRegistry>()\r\n private readonly _configuration: IConfigurationService\r\n\r\n constructor(container?: IServiceContainer<TRegistry>) {\r\n this._container = container ?? new ServiceContainer<TRegistry>()\r\n\r\n this._container.addSingleton(\r\n TOKENS.CONFIGURATION_SERVICE,\r\n () => new EnvironmentConfigurationService(),\r\n )\r\n this._configuration = this._container.resolve(TOKENS.CONFIGURATION_SERVICE)\r\n this._middlewareConfig.allowOrigins?.push(\r\n this._configuration.get('APP_URL') ??\r\n `http://localhost:${this._configuration.getNumber('PORT', 3000)}`,\r\n )\r\n }\r\n\r\n // --- Module Configurations ---\r\n private readonly _modules: QueuedModule[] = []\r\n\r\n // --- Specific Configurations ---\r\n private _pipelineConfig: PipelineConfig<TRegistry, ZodType> = {\r\n performance: { thresholdMs: 500 },\r\n authorization: {\r\n policies: undefined,\r\n customAuthorizationStrategy: undefined,\r\n },\r\n validation: {\r\n zod: undefined,\r\n customValidationStrategy: undefined,\r\n },\r\n commandBus: {\r\n idempotency: undefined,\r\n concurrency: undefined,\r\n },\r\n queryBus: { isEnabled: false },\r\n }\r\n private _config: CacheConfig = { inMemory: true, redis: undefined }\r\n private _middlewareConfig: MiddlewareConfig = {\r\n isSSR: false,\r\n rateLimite: {\r\n maxRequests: 3,\r\n windowSeconds: 100,\r\n },\r\n csrf: undefined,\r\n optionsMiddleware: false,\r\n routeRegistry: undefined,\r\n trustedIpHeader: undefined,\r\n trustedProxies: [],\r\n allowOrigins: [],\r\n allowHeaders: [],\r\n cors: true,\r\n withCredentials: true,\r\n }\r\n private readonly _httpConfig: HttpCoreConfig<TRegistry> = {\r\n dataSourceToken: undefined,\r\n http: {\r\n token: undefined,\r\n client: {\r\n defaultHeaders: undefined,\r\n baseURL: undefined,\r\n timeoutMs: undefined,\r\n keepAlive: undefined,\r\n maxSockets: undefined,\r\n maxRedirects: undefined,\r\n decompress: undefined,\r\n withCredentials: undefined,\r\n proxy: false,\r\n },\r\n },\r\n resilience: { retry: {}, circuitBreaker: {}, bulkhead: {} },\r\n } as unknown as HttpCoreConfig<TRegistry>\r\n\r\n // --- Module Queuing Flags ---\r\n private _isContextModuleQueued = false\r\n private _isMiddlewareModuleQueued = false\r\n private _isPipelineModuleQueued = false\r\n private _isLoggerModuleQueued = false\r\n private _isAuthModuleQueued = false\r\n private _isDbContextModuleQueued = false\r\n private _isConcurrencyServiceQueued = false\r\n private _isCacheModuleQueued = false\r\n\r\n // ─────────────────────────────────────────────────────────────────────────────\r\n // Application Modules Configuration\r\n // ─────────────────────────────────────────────────────────────────────────────\r\n\r\n /**\r\n * @description Enables the use of middlewares in the application. Middlewares can be used for cross-cutting concerns such as logging, authentication, and request/response manipulation.\r\n * @returns The current instance of AppBuilder for method chaining.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n public addMiddlewares(setupAction: SetupAction<MiddlewareConfig, IConfigurationService>): this {\r\n setupAction(this._middlewareConfig, this._configuration)\r\n this._queueMiddlewareModule()\r\n return this\r\n }\r\n\r\n /**\r\n * @description Enables the use of context in the application. Context can be used to store and manage request-specific data, such as user information, correlation IDs, and other metadata that needs to be accessible throughout the request lifecycle.\r\n * @returns The current instance of AppBuilder for method chaining.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n public addContext(): this {\r\n this._queueContextModule()\r\n return this\r\n }\r\n\r\n /**\r\n * @description Configures the logger for the application. This method allows you to set up logging options such as log level, console logging, and integration with external logging services like Sentry or Pino.\r\n * @param setupAction A callback function that receives a LoggerConfig object to configure the logger settings.\r\n * @returns The current instance of AppBuilder for method chaining.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n public addLogger(\r\n setupAction?: SetupAction<LoggerConfig<TRegistry>, IConfigurationService>,\r\n ): this {\r\n if (this._isLoggerModuleQueued) return this\r\n this._isLoggerModuleQueued = true\r\n const config = {\r\n level: LOG_LEVEL.DEBUG,\r\n console: true,\r\n sentry: { config: undefined },\r\n pino: { config: undefined },\r\n customLoggers: undefined,\r\n } as unknown as Optional<LoggerConfig<ApplicationRegistry<unknown>>>\r\n if (Guards.isDefined(setupAction) && Guards.isDefined(config))\r\n setupAction(config, this._configuration)\r\n\r\n this._modules.push({\r\n priority: 3,\r\n name: 'LoggerModule',\r\n action: async () => {\r\n const { LoggerUtils } = await import('../modules/utils/logger.utils')\r\n await LoggerUtils.addLogger(this._container, config)\r\n },\r\n })\r\n return this\r\n }\r\n\r\n /**\r\n * @description Configures the caching settings for the application. This method allows you to set up caching options such as Redis configuration or in-memory caching.\r\n * @param setupAction A callback function that receives a CacheConfig object to configure the caching settings.\r\n * @returns The current instance of AppBuilder for method chaining.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n public addCache(setupAction?: SetupAction<CacheConfig, IConfigurationService>): this {\r\n if (this._isCacheModuleQueued) return this\r\n this._isCacheModuleQueued = true\r\n if (Guards.isDefined(setupAction)) setupAction(this._config, this._configuration)\r\n\r\n this._modules.push({\r\n priority: 3,\r\n name: 'CacheModule',\r\n action: async () => {\r\n const { CacheUtils } = await import('../modules/utils/cache.utils')\r\n await CacheUtils.addCache(this._container, this._config)\r\n },\r\n })\r\n return this\r\n }\r\n\r\n /**\r\n * @description Configures the authentication client for the application. This method allows you to set up authentication options such as the authentication server URL, API key, and additional options.\r\n * @param setupAction A callback function that receives an AuthClientConfig object to configure the authentication client settings.\r\n * @returns The current instance of AppBuilder for method chaining.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n public addAuth(\r\n setupAction: SetupAction<AuthSsrConfig<SupabaseClientOptions<'public'>>, IConfigurationService>,\r\n ): this {\r\n if (this._isAuthModuleQueued) return this\r\n this._isAuthModuleQueued = true\r\n const config: AuthSsrConfig<SupabaseClientOptions<'public'>> = {\r\n url: '',\r\n key: '',\r\n opts: undefined,\r\n redirectTo: '',\r\n storageOpts: { type: 'memory', cookieOpts: undefined, storage: undefined },\r\n ssrOpts: undefined,\r\n }\r\n setupAction(config, this._configuration)\r\n this._modules.push({\r\n priority: 2,\r\n name: 'AuthModule',\r\n action: async () => {\r\n const { AuthUtils } = await import('../modules/utils/auth.utils')\r\n await AuthUtils.addAuthN(this._container, config)\r\n },\r\n })\r\n return this\r\n }\r\n\r\n /**\r\n * @description Configures the database settings for the application. This method allows you to set up database options such as enabling/disabling the database, connection string, and table definitions.\r\n * @param setupAction A callback function that receives a DbConfig object to configure the database settings.\r\n * @returns The current instance of AppBuilder for method chaining.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n public addDb(setupAction: SetupAction<DbConfig, IConfigurationService>): this {\r\n if (this._isDbContextModuleQueued) return this\r\n this._isDbContextModuleQueued = true\r\n const config = { connectionString: '', enableSqlLite: false }\r\n setupAction(config, this._configuration)\r\n this._modules.push({\r\n priority: 4,\r\n name: 'DbModule',\r\n action: async () => {\r\n const { DbModule } = await import('../modules/db.module')\r\n const dbModule = new DbModule()\r\n await dbModule.configure(this._container, config)\r\n },\r\n })\r\n return this\r\n }\r\n\r\n /**\r\n * @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.\r\n * @returns The current instance of AppBuilder for method chaining.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n public addConcurrencyService(): this {\r\n if (this._isConcurrencyServiceQueued) return this\r\n this._isConcurrencyServiceQueued = true\r\n this._modules.push({\r\n priority: 40,\r\n name: 'ConcurrencyServiceModule',\r\n action: async () => {\r\n const { PLimitConcurrencyService } = await import('../services/concurrency')\r\n this._container.addSingleton('CONCURRENCY_SERVICE', () => new PLimitConcurrencyService())\r\n },\r\n })\r\n return this\r\n }\r\n\r\n // ─────────────────────────────────────────────────────────────────────────────\r\n // CQRS Pipeline Configuration\r\n // ─────────────────────────────────────────────────────────────────────────────\r\n\r\n /**\r\n * @description Configures the CQRS pipeline settings for the application. This method allows you to set up various aspects of the CQRS pipeline, including performance monitoring, authorization, validation, command bus settings, and query bus settings.\r\n * @param setupAction A callback function that receives a PipelineConfig object to configure the CQRS pipeline settings.\r\n * @returns The current instance of AppBuilder for method chaining.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n public addPipeline(\r\n setupAction?: SetupAction<PipelineConfig<TRegistry>, IConfigurationService>,\r\n ): this {\r\n if (Guards.isDefined(setupAction)) {\r\n setupAction(this._pipelineConfig, this._configuration)\r\n }\r\n this._queuePipelineModule()\r\n return this\r\n }\r\n\r\n // ─────────────────────────────────────────────────────────────────────────────\r\n // HTTP & Resilience Configuration\r\n // ─────────────────────────────────────────────────────────────────────────────\r\n\r\n /**\r\n * @description Configures the HTTP core settings for the application. This method allows you to set up HTTP core options such as data source token, HTTP client configuration, and resilience settings.\r\n * @param setupAction A callback function that receives an HttpCoreConfig object to configure the HTTP core settings.\r\n * @returns The current instance of AppBuilder for method chaining.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n public addHttpCore(\r\n setupAction: SetupAction<HttpCoreConfig<TRegistry>, IConfigurationService>,\r\n ): this {\r\n setupAction(this._httpConfig, this._configuration)\r\n this._modules.push({\r\n priority: 30,\r\n name: 'HttpCoreModule',\r\n action: async () => {\r\n const { HttpCoreModule } = await import('../modules/http-core.module')\r\n const coreModule = new HttpCoreModule<TRegistry>()\r\n await coreModule.configure(this._container, this._httpConfig)\r\n },\r\n })\r\n return this\r\n }\r\n\r\n public addAllowOrigin(setupAction: SetupAction<string[], IConfigurationService>): this {\r\n const config: string[] = []\r\n setupAction(config, this._configuration)\r\n this._modules.push({\r\n priority: 30,\r\n name: 'HttpCoreModule',\r\n action: async () => {\r\n const { HttpOriginModule } = await import('../modules/http-core.module')\r\n const httpOriginModule = new HttpOriginModule()\r\n await httpOriginModule.configure(this._container, config)\r\n },\r\n })\r\n return this\r\n }\r\n\r\n // ─────────────────────────────────────────────────────────────────────────────\r\n // Dependency Injection Pass-through Methods\r\n // ─────────────────────────────────────────────────────────────────────────────\r\n\r\n /**\r\n * @description Registers services in the application. This method allows you to add custom services to the dependency injection container, enabling modular and organized configuration of services.\r\n * @param setupAction A callback function that receives the IServiceContainer to register services.\r\n * @returns The current instance of AppBuilder for method chaining.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n public addServices(\r\n setupAction: SetupAction<IServiceContainer<TRegistry>, IConfigurationService>,\r\n ): this {\r\n this._modules.push({\r\n priority: 99,\r\n name: 'ClientServicesModule',\r\n action: async () => {\r\n setupAction(this._container, this._configuration)\r\n },\r\n })\r\n return this\r\n }\r\n\r\n /**\r\n * @description Registers a module in the application. A module is a self-contained unit of functionality that can configure services and dependencies in the service container. This method allows you to add custom modules to the application, enabling modular and organized configuration of services.\r\n * @param factory A factory function that creates the module instance.\r\n * @param opts Optional configuration options for the module.\r\n * @returns The current instance of AppBuilder for method chaining.\r\n *\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n public addModule<T>(name: string, factory: () => Promise<IModule<TRegistry, T>>, opts?: T): this {\r\n this._modules.push({\r\n priority: 50,\r\n name,\r\n action: async () => {\r\n const module = await factory()\r\n await module.configure(this._container, opts)\r\n },\r\n })\r\n return this\r\n }\r\n\r\n /**\r\n * @description Resolves a service from the dependency injection container.\r\n * @param token The injection token used to identify the service.\r\n * @returns The resolved service instance.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n public resolve<K extends keyof TRegistry>(token: K): TRegistry[K] {\r\n return this._container.resolve(token)\r\n }\r\n\r\n // ─────────────────────────────────────────────────────────────────────────────\r\n // Build\r\n // ─────────────────────────────────────────────────────────────────────────────\r\n\r\n /**\r\n * @description Finalizes the configuration and initializes all registered modules in the container.\r\n * @returns The fully configured ServiceContainer.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n public async build(): Promise<IServiceContainer<TRegistry>> {\r\n console.info('⚙️ Bootstrapping application modules...')\r\n const sortedModules = this._modules.sort((a, b) => a.priority - b.priority)\r\n for (const queued of sortedModules) {\r\n try {\r\n await queued.action()\r\n } catch (error) {\r\n const errorMessage = error instanceof Error ? error.message : String(error)\r\n\r\n console.error(`\\n❌ [AppBuilder Fatal Error]`)\r\n console.error(`An error occurred while initializing the module:`)\r\n console.error(`👉 Module: **${queued.name}**`)\r\n console.error(`📝 Reason: ${errorMessage}\\n`)\r\n\r\n if (error instanceof Error && Guards.isDefined(error.stack)) {\r\n console.error(error.stack)\r\n }\r\n\r\n throw new Error(`Bootstrap failed at [${queued.name}]: ${errorMessage}`, { cause: error })\r\n }\r\n }\r\n console.info('✅ Application modules bootstrapped successfully.')\r\n return this._container\r\n }\r\n\r\n // ─────────────────────────────────────────────────────────────────────────────\r\n // Private Helper Methods\r\n // ─────────────────────────────────────────────────────────────────────────────\r\n\r\n /**\r\n * @description Queues the configuration of the CQRS pipeline module if it has not already been queued. This method ensures that the pipeline module is only added once, even if multiple pipeline-related configurations are made.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n private _queuePipelineModule(): void {\r\n if (this._isPipelineModuleQueued) return\r\n this._isPipelineModuleQueued = true\r\n\r\n this._queueContextModule()\r\n\r\n this._modules.push({\r\n priority: 5,\r\n name: 'CqrsModule',\r\n action: async () => {\r\n const { CqrsModule } = await import('../modules/cqrs.module')\r\n const pipelineModule = new CqrsModule<TRegistry>()\r\n await pipelineModule.configure(this._container, {\r\n ...this._pipelineConfig,\r\n isLogger: this._isLoggerModuleQueued || this._isMiddlewareModuleQueued,\r\n isCache: !this._isCacheModuleQueued,\r\n })\r\n },\r\n })\r\n }\r\n\r\n /**\r\n * @description Queues the configuration of the middleware module if it has not already been queued. This method ensures that the middleware module is only added once, even if multiple middleware-related configurations are made.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n private _queueMiddlewareModule(): void {\r\n if (this._isMiddlewareModuleQueued) return\r\n this._isMiddlewareModuleQueued = true\r\n\r\n this._queueContextModule()\r\n\r\n this._modules.push({\r\n priority: 3,\r\n name: 'MiddlewareModule',\r\n action: async () => {\r\n const { MiddlewareModule } = await import('../modules/middleware.module')\r\n const middlewareModule = new MiddlewareModule()\r\n await middlewareModule.configure(this._container, {\r\n ...this._middlewareConfig,\r\n isAuth: this._isAuthModuleQueued,\r\n isLogger: this._isLoggerModuleQueued,\r\n isCache: this._isCacheModuleQueued || this._isPipelineModuleQueued,\r\n })\r\n },\r\n })\r\n }\r\n\r\n /**\r\n * @description Queues the configuration of the context module if it has not already been queued. This method ensures that the context module is only added once, even if multiple context-related configurations are made.\r\n \r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\n private _queueContextModule(): void {\r\n if (this._isContextModuleQueued) return\r\n this._isContextModuleQueued = true\r\n\r\n this._modules.push({\r\n priority: 0,\r\n name: 'ContextModule',\r\n action: async () => {\r\n const { ContextModule } = await import('../modules/context.module')\r\n const contextModule = new ContextModule<TRegistry>()\r\n await contextModule.configure(this._container)\r\n },\r\n })\r\n }\r\n}\r\n","import type { IConfigurationService } from '@xeno-js/shared'\r\nimport type { Dictionary, Optional } from '@xeno-js/shared'\r\nimport { Guards } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description\r\n * This class implements the IConfigurationService interface and provides methods to retrieve configuration values from environment variables.\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class EnvironmentConfigurationService implements IConfigurationService {\r\n /**\r\n * @description Internal dictionary to hold environment variables.\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n private readonly _env: Dictionary<Optional<string>>\r\n\r\n /**\r\n * @description Constructs an instance of EnvironmentConfigurationService and initializes the internal environment variable dictionary.\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n constructor() {\r\n this._env = process.env\r\n }\r\n\r\n public get(key: string, defaultValue?: string): Optional<string> {\r\n const value = this._env[key]\r\n if (Guards.isNullOrEmpty(value)) {\r\n return defaultValue\r\n }\r\n return value\r\n }\r\n\r\n public getNumber(key: string, defaultValue?: number): Optional<number> {\r\n const value = this.get(key)\r\n if (!Guards.isDefined(value)) {\r\n return defaultValue\r\n }\r\n const parsed = Number(value)\r\n if (isNaN(parsed)) {\r\n throw new Error(\r\n `[Configuration Error]: Key \"${key}\" with value \"${value}\" is not a valid number.`,\r\n )\r\n }\r\n return parsed\r\n }\r\n\r\n public getBoolean(key: string, defaultValue?: boolean): Optional<boolean> {\r\n const value = this.get(key)\r\n if (!Guards.isDefined(value)) {\r\n return defaultValue\r\n }\r\n const normalized = value.toLowerCase().trim()\r\n if (normalized === 'true' || normalized === '1') return true\r\n if (normalized === 'false' || normalized === '0') return false\r\n\r\n throw new Error(\r\n `[Configuration Error]: Key \"${key}\" with value \"${value}\" is not a valid boolean.`,\r\n )\r\n }\r\n\r\n public getOrThrow(key: string): string {\r\n const value = this.get(key)\r\n if (!Guards.isDefined(value)) {\r\n throw new Error(\r\n `[Configuration Error]: Required configuration key \"${key}\" is missing in the environment.`,\r\n )\r\n }\r\n return value\r\n }\r\n}\r\n","import { AsyncLocalStorage } from 'node:async_hooks'\r\n\r\nimport type { Factory, IDisposable } from '@xeno-js/shared'\r\nimport { Guards } from '@xeno-js/shared'\r\n\r\nimport type { ApplicationRegistry, IServiceContainer, IServiceScope, Lifetime } from '@/domain'\r\n\r\nimport type { DbContext } from '../db'\r\n\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n\r\n/**\r\n * @description Represents a registration entry in the service container, encapsulating the token, lifetime, and factory function for creating instances of the service.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\ninterface RegistrationEntry<\r\n T,\r\n Registry extends ApplicationRegistry<DbContext> = ApplicationRegistry<DbContext>,\r\n> {\r\n /**\r\n * The unique injection token that identifies the service registration.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n token: keyof Registry\r\n /**\r\n * The lifetime of the service registration, indicating how instances are managed and reused.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n lifetime: Lifetime\r\n /**\r\n * The factory function responsible for creating instances of the service.\r\n * It receives the current service scope as an argument, allowing for dependency resolution within that scope.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n factory: Factory<T, [IServiceScope<Registry>]>\r\n}\r\n\r\n/**\r\n * @description Represents the context of service resolution, including the stack of tokens being resolved and the active lifetime of the current resolution.\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\ninterface ResolutionContext<Registry> {\r\n /**\r\n * A set of tokens currently being resolved, used to detect circular dependencies.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n stack: Set<keyof Registry>\r\n /**\r\n * The active lifetime of the current resolution, indicating whether we are constructing a singleton, scoped, or transient service.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n activeLifetime?: Lifetime\r\n}\r\n\r\n/**\r\n * @description Concrete implementation of {@link IServiceScope}, representing a logical scope for resolving scoped services within the service container.\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nclass ContainerScope<\r\n Registry extends ApplicationRegistry<DbContext> = ApplicationRegistry<DbContext>,\r\n> implements IServiceScope<Registry> {\r\n private readonly scopedInstances = new Map<keyof Registry, unknown>()\r\n private readonly trackedDisposables: unknown[] = []\r\n private isDisposed = false\r\n\r\n constructor(\r\n private readonly container: ServiceContainer<Registry>,\r\n private readonly parentScope?: ContainerScope<Registry>,\r\n ) {}\r\n\r\n public resolve<K extends keyof Registry>(token: K): Registry[K] {\r\n if (this.isDisposed) {\r\n throw new Error(\r\n `[DI Container Error]: Unable to resolve '${token as string}'. The scope has been closed.`,\r\n )\r\n }\r\n return this.container.internalExecuteInContext(() =>\r\n this.container.internalResolveInternal(token, this),\r\n )\r\n }\r\n\r\n public getScopedInstance<K extends keyof Registry>(token: K): Registry[K] | undefined {\r\n return this.scopedInstances.get(token) as Registry[K] | undefined\r\n }\r\n\r\n public setScopedInstance<K extends keyof Registry>(token: K, instance: Registry[K]): void {\r\n this.scopedInstances.set(token, instance)\r\n if (isDisposable.check(instance)) {\r\n this.trackedDisposables.push(instance)\r\n }\r\n }\r\n\r\n public trackInstance(instance: unknown): void {\r\n if (isDisposable.check(instance) && !this.trackedDisposables.includes(instance)) {\r\n this.trackedDisposables.push(instance)\r\n }\r\n }\r\n\r\n public async dispose(): Promise<void> {\r\n if (this.isDisposed) return\r\n this.isDisposed = true\r\n\r\n for (let i = this.trackedDisposables.length - 1; i >= 0; i--) {\r\n const disposable = this.trackedDisposables[i]\r\n if (isDisposable.check(disposable)) {\r\n try {\r\n await disposable.dispose()\r\n } catch (err) {\r\n console.error(`[DI Container Dispose Error]: Failed to dispose resource`, err)\r\n }\r\n }\r\n }\r\n\r\n this.scopedInstances.clear()\r\n this.trackedDisposables.length = 0\r\n }\r\n}\r\n\r\n/**\r\n * @description Concrete implementation of {@link IServiceContainer}.\r\n *\r\n * Supports three registration lifetimes:\r\n * - **singleton** — one shared instance per container.\r\n * - **transient** — a new instance on every {@link resolve} call.\r\n * - **scoped** — one instance per {@link IServiceScope}; must be resolved\r\n * through a scope obtained via {@link createScope}.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport class ServiceContainer<\r\n Registry extends ApplicationRegistry<DbContext> = ApplicationRegistry<DbContext>,\r\n> implements IServiceContainer<Registry> {\r\n private readonly registrations = new Map<keyof Registry, RegistrationEntry<unknown, Registry>>()\r\n private readonly singletonInstances = new Map<keyof Registry, unknown>()\r\n private readonly rootScope: ContainerScope<Registry>\r\n private readonly resolutionStack = new AsyncLocalStorage<ResolutionContext<Registry>>()\r\n\r\n constructor() {\r\n this.rootScope = new ContainerScope<Registry>(this)\r\n }\r\n\r\n public addSingleton<K extends keyof Registry>(\r\n token: K,\r\n factory: Factory<Registry[K], [IServiceScope<Registry>]>,\r\n ): this {\r\n this.register(token, 'singleton', factory)\r\n return this\r\n }\r\n\r\n public addScoped<K extends keyof Registry>(\r\n token: K,\r\n factory: Factory<Registry[K], [IServiceScope<Registry>]>,\r\n ): this {\r\n this.register(token, 'scoped', factory)\r\n return this\r\n }\r\n\r\n public addTransient<K extends keyof Registry>(\r\n token: K,\r\n factory: Factory<Registry[K], [IServiceScope<Registry>]>,\r\n ): this {\r\n this.register(token, 'transient', factory)\r\n return this\r\n }\r\n\r\n private register<K extends keyof Registry>(\r\n token: K,\r\n lifetime: Lifetime,\r\n factory: Factory<Registry[K], [IServiceScope<Registry>]>,\r\n ): void {\r\n if (this.registrations.has(token)) {\r\n const tokenName = token.toString()\r\n throw new Error(\r\n `[DI Container Error]: The token '${tokenName}' is already registered in the container.`,\r\n )\r\n }\r\n this.registrations.set(token, { token, lifetime, factory })\r\n }\r\n\r\n public resolve<K extends keyof Registry>(token: K): Registry[K] {\r\n return this.internalExecuteInContext(() => this.rootScope.resolve(token))\r\n }\r\n\r\n public createScope(): IServiceScope<Registry> {\r\n return new ContainerScope<Registry>(this, this.rootScope)\r\n }\r\n\r\n /**\r\n * Executes a callback function within the context of the service container's resolution stack.\r\n * This method ensures that the resolution stack is properly managed, allowing for circular dependency detection and lifetime tracking during service resolution.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n internalExecuteInContext<T>(callback: () => T): T {\r\n const currentStack = this.resolutionStack.getStore()\r\n if (!Guards.isDefined(currentStack)) {\r\n const initialContext: ResolutionContext<Registry> = {\r\n stack: new Set<keyof Registry>(),\r\n }\r\n return this.resolutionStack.run(initialContext, callback)\r\n }\r\n return callback()\r\n }\r\n\r\n /**\r\n * Resolve the service for the given token within the provided scope.\r\n * @param token The injection token to resolve.\r\n * @param currentScope The current service scope for resolving scoped services.\r\n * @returns The resolved service instance of type `T`.\r\n * @throws An error if no registration is found for the given token.\r\n * @throws An error if a circular dependency is detected.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n internalResolveInternal<K extends keyof Registry>(\r\n token: K,\r\n currentScope: ContainerScope<Registry>,\r\n ): Registry[K] {\r\n const registration = this.registrations.get(token)\r\n if (!Guards.isDefined(registration)) {\r\n const tokenName = token.toString()\r\n throw new Error(\r\n `[DI Container Error]: Registration not found for token '${tokenName}'. Ensure the service is registered before resolving.`,\r\n )\r\n }\r\n\r\n const currentStack = this.resolutionStack.getStore()\r\n if (!Guards.isDefined(currentStack)) {\r\n throw new Error(`[DI Container Error]: Execution outside the IoC container context.`)\r\n }\r\n\r\n if (currentStack.stack.has(token)) {\r\n const cyclePath = [...currentStack.stack, token].map((t) => t.toString()).join(' -> ')\r\n const tokenName = token.toString()\r\n throw new Error(\r\n `[DI Circular Dependency Error]: Detected circular dependency while resolving '${tokenName}'. Resolution path: ${cyclePath}`,\r\n )\r\n }\r\n\r\n if (currentStack.activeLifetime === 'singleton' && registration.lifetime === 'scoped') {\r\n const captivePath = [...currentStack.stack, token].map((t) => t.toString()).join(' -> ')\r\n throw new Error(\r\n `[DI Captive Dependency Error]: Attempted to resolve a scoped service '${token.toString()}' from a singleton context. This can lead to captive dependencies. Resolution path: ${captivePath}`,\r\n )\r\n }\r\n\r\n const executeWithStackIsolation = (\r\n targetLifetime: Lifetime,\r\n factoryFn: () => Registry[K],\r\n ): Registry[K] => {\r\n const previousLifetime = currentStack.activeLifetime\r\n currentStack.stack.add(token)\r\n\r\n currentStack.activeLifetime =\r\n registration.lifetime === 'singleton' ? 'singleton' : previousLifetime\r\n try {\r\n return factoryFn()\r\n } finally {\r\n currentStack.stack.delete(token)\r\n currentStack.activeLifetime = previousLifetime\r\n }\r\n }\r\n\r\n if (registration.lifetime === 'singleton') {\r\n if (this.singletonInstances.has(token)) {\r\n return this.singletonInstances.get(token) as Registry[K]\r\n }\r\n\r\n return executeWithStackIsolation('singleton', () => {\r\n const instance = registration.factory(currentScope) as Registry[K]\r\n this.singletonInstances.set(token, instance)\r\n this.rootScope.trackInstance(instance)\r\n return instance\r\n })\r\n }\r\n\r\n if (registration.lifetime === 'scoped') {\r\n const existingInstance = currentScope.getScopedInstance(token)\r\n if (Guards.isDefined(existingInstance)) {\r\n return existingInstance\r\n }\r\n\r\n return executeWithStackIsolation('scoped', () => {\r\n const instance = registration.factory(currentScope) as Registry[K]\r\n currentScope.setScopedInstance(token, instance)\r\n return instance\r\n })\r\n }\r\n\r\n return executeWithStackIsolation('transient', () => {\r\n const instance = registration.factory(currentScope) as Registry[K]\r\n if (isDisposable.check(instance)) {\r\n currentScope.trackInstance(instance)\r\n }\r\n return instance\r\n })\r\n }\r\n\r\n public async dispose(): Promise<void> {\r\n await this.rootScope.dispose()\r\n this.singletonInstances.clear()\r\n this.registrations.clear()\r\n }\r\n}\r\n\r\nconst isDisposable = Object.freeze({\r\n check: (obj: unknown): obj is IDisposable => {\r\n return (\r\n Guards.isDefined(obj) &&\r\n Guards.isObject(obj) &&\r\n 'dispose' in obj &&\r\n Guards.hasMethod(obj, 'dispose')\r\n )\r\n },\r\n} as const)\r\n","export * from './builder/index'\r\nexport * from './cache/index'\r\nexport * from './configuration/index'\r\nexport * from './container/index'\r\nexport * from './context/index'\r\nexport * from './datasources'\r\nexport type * from './db/index'\r\nexport * from './factories/index'\r\nexport * from './idempotency/index'\r\nexport * from './loggers/index'\r\nexport * from './modules/index'\r\nexport * from './repositories/index'\r\nexport * from './services/index'\r\nexport * from './transaction/index'\r\nexport type * from './xeno-registry/index'\r\n","export * from './request-context'\r\n","import type { Dictionary } from '@xeno-js/shared'\r\nimport type { NodePgDatabase } from 'drizzle-orm/node-postgres'\r\n\r\nimport type { DbContext } from '../db'\r\n\r\n/**\r\n * @description BasePostgresSqlDataSource is an abstract class that serves as a foundation for creating data sources that interact with a PostgreSQL database. It provides a common interface for accessing the database connection and ensures that the database connection is properly initialized and managed. By extending this class, developers can easily create data sources that are tailored to their specific use cases.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport abstract class BasePostgresSqlDataSource<TSchema extends Dictionary = Dictionary> {\r\n constructor(\r\n private readonly _db: DbContext<TSchema>,\r\n ) { }\r\n\r\n /**\r\n * @description Returns the database connection.\r\n * @returns {NodePgDatabase<TSchema>} The database connection.\r\n */\r\n protected get db(): NodePgDatabase<TSchema> {\r\n return this._db as NodePgDatabase<TSchema>\r\n }\r\n}","import type { Dictionary } from '@xeno-js/shared'\r\nimport type { LibSQLDatabase } from 'drizzle-orm/libsql'\r\n\r\nimport type { DbContext } from '../db'\r\n\r\n/**\r\n * @description BaseSqliteSqlDataSource is an abstract class that serves as a foundation for creating data sources that interact with a SQLite / libSQL database.\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport abstract class BaseSqliteSqlDataSource<TSchema extends Dictionary = Dictionary> {\r\n constructor(\r\n private readonly _db: DbContext<TSchema>,\r\n ) { }\r\n\r\n /**\r\n * @description Returns the SQLite database connection.\r\n * @returns {LibSQLDatabase<TSchema>} The database connection.\r\n */\r\n protected get db(): LibSQLDatabase<TSchema> {\r\n return this._db as LibSQLDatabase<TSchema>\r\n }\r\n}","import type {\r\n HttpBaseRequest,\r\n HttpMethod,\r\n HttpRequest,\r\n IHttpClient,\r\n IRemoteDataSource,\r\n IServiceResilience,\r\n Optional,\r\n ResultType,\r\n} from '@xeno-js/shared'\r\nimport { AppError, Result } from '@xeno-js/shared'\r\n\r\n/**\r\n * @description Concrete implementation of the IRemoteDataSource contract that utilizes an agnostic HTTP client and a resilience service to fetch data from remote endpoints. The RemoteDataSource class is responsible for sending HTTP requests based on the provided HttpClientRequest parameters, while leveraging the resilience features of the IServiceResilience to ensure reliable communication with external services. This implementation abstracts away the details of how HTTP requests are made and how resilience is handled, allowing for flexibility in choosing different HTTP clients and resilience strategies without affecting the consumers of the IRemoteDataSource interface.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\nexport abstract class RemoteDataSource implements IRemoteDataSource {\r\n /** The constructor of the RemoteDataSource class takes two dependencies: an instance of an agnostic HTTP client that implements the IHttpClient interface, and an instance of a resilience service that implements the IServiceResilience interface.\r\n * These dependencies are injected into the class, allowing for greater flexibility and testability.\r\n * The HTTP client is used to send requests to remote endpoints, while the resilience service is used to execute these requests with built-in support for retries, timeouts, and circuit breakers, ensuring that the remote calls are more resilient to failures and can recover gracefully from errors.\r\n * @param _httpClient An instance of an agnostic HTTP client that implements the IHttpClient interface, used for sending HTTP requests to remote endpoints.\r\n * @param _resilienceService An instance of a resilience service that implements the IServiceResilience interface, used for executing HTTP requests with built-in support for retries, timeouts, and circuit breakers to enhance the reliability of remote calls.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n constructor(\r\n private readonly _httpClient: IHttpClient,\r\n private readonly _resilienceService: IServiceResilience,\r\n ) {}\r\n\r\n /** @description Private method that sends an HTTP request to a specified endpoint using the provided HttpRequest options. The method utilizes the resilience service to execute the request, ensuring that it is performed with built-in support for retries, timeouts, and circuit breakers. The response from the HTTP client is then wrapped in a ResultType, which encapsulates either the successful response data or an error, providing a consistent way to handle both success and failure cases.\r\n * @param endpoint The URL or endpoint to which the HTTP request is sent.\r\n * @param options The HttpRequest options that specify the HTTP method, headers, query parameters, body, and other request configurations.\r\n * @returns A Promise that resolves to a ResultType containing either the successful response data or an error if the request fails.\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n private async send<TResponse, TBody = unknown>(\r\n endpoint: string,\r\n options: HttpRequest<TBody>,\r\n ): Promise<ResultType<TResponse>> {\r\n const response = await this._resilienceService.execute(async () => {\r\n switch (options.method) {\r\n case 'GET':\r\n return await this._httpClient.get<TResponse>(endpoint, options)\r\n case 'POST':\r\n return await this._httpClient.post<TResponse, TBody>(endpoint, options.body, options)\r\n case 'PUT':\r\n return await this._httpClient.put<TResponse, TBody>(endpoint, options.body, options)\r\n case 'PATCH':\r\n return await this._httpClient.patch<TResponse, TBody>(endpoint, options.body, options)\r\n case 'DELETE':\r\n return await this._httpClient.delete<TResponse>(endpoint, options)\r\n default:\r\n throw AppError.notSupported(\r\n this.constructor.name,\r\n `Unsupported HTTP method: ${options.method}`,\r\n )\r\n }\r\n }, options.signal)\r\n\r\n return Result.ok(response.data)\r\n }\r\n\r\n protected setOptions<T>(\r\n request: Optional<HttpBaseRequest>,\r\n method: HttpMethod,\r\n body: Optional<T> = undefined,\r\n ): HttpRequest<T> {\r\n return {\r\n query: request?.query,\r\n signal: request?.signal,\r\n timeoutMs: request?.timeoutMs,\r\n headers: request?.headers,\r\n responseType: request?.responseType,\r\n method,\r\n body,\r\n }\r\n }\r\n\r\n public async get<TResponse>(\r\n endpoint: string,\r\n request?: HttpBaseRequest,\r\n ): Promise<ResultType<TResponse>> {\r\n const options = this.setOptions(request, 'GET')\r\n\r\n return await this.send<TResponse>(endpoint, options)\r\n }\r\n\r\n public async post<TResponse, TBody = unknown>(\r\n endpoint: string,\r\n body: TBody,\r\n request?: HttpBaseRequest,\r\n ): Promise<ResultType<TResponse>> {\r\n const options = this.setOptions(request, 'POST', body)\r\n\r\n return await this.send<TResponse, TBody>(endpoint, options)\r\n }\r\n\r\n public async put<TResponse, TBody = unknown>(\r\n endpoint: string,\r\n body: TBody,\r\n request?: HttpBaseRequest,\r\n ): Promise<ResultType<TResponse>> {\r\n const options = this.setOptions(request, 'PUT', body)\r\n\r\n return await this.send<TResponse, TBody>(endpoint, options)\r\n }\r\n\r\n public async patch<TResponse, TBody = unknown>(\r\n endpoint: string,\r\n body: TBody,\r\n request?: HttpBaseRequest,\r\n ): Promise<ResultType<TResponse>> {\r\n const options = this.setOptions(request, 'PATCH', body)\r\n\r\n return await this.send<TResponse, TBody>(endpoint, options)\r\n }\r\n\r\n public async delete<TResponse>(\r\n endpoint: string,\r\n request?: HttpBaseRequest,\r\n ): Promise<ResultType<TResponse>> {\r\n const options = this.setOptions(request, 'DELETE')\r\n\r\n return await this.send<TResponse>(endpoint, options)\r\n }\r\n}\r\n","export * from './idempotency-store'\r\n","export * from './console.logger'\r\nexport * from './pino.logger'\r\nexport * from './sentry.logger'\r\n","export * from './context.module'\r\nexport * from './cqrs.module'\r\nexport * from './db.module'\r\nexport * from './http-core.module'\r\nexport * from './middleware.module'\r\nexport * from './utils/index'\r\n","export * from './auth.utils'\r\nexport * from './cache.utils'\r\nexport * from './db.utils'\r\nexport * from './http.utils'\r\nexport * from './logger.utils'\r\nexport * from './pipeline.utils'\r\nexport * from './validation.utils'\r\n","import type { IMapper, IReadDao, IReadDataSource, ResultType } from '@xeno-js/shared'\r\nimport type { Optional, UserContext } from '@xeno-js/shared'\r\nimport { AppError, Result } from '@xeno-js/shared'\r\nimport { Guards } from '@xeno-js/shared'\r\n\r\n/**\r\n * An abstract generic read-only DAO that provides basic read operations for entities of type T, using a Data Transfer Object (DTO) of type TDto for data access. This class relies on an IReadDataSource to perform database operations and an IMapper to convert between entities and DTOs.\r\n * @template T - The type of the entity that the DAO will manage.\r\n * @template TDto - The type of the Data Transfer Object (DTO) used for data access.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport abstract class ReadDao<T, TDto> implements IReadDao<T> {\r\n /**\r\n * Constructs a new ReadDao instance.\r\n * @param _dataSource An instance of IReadDataSource used to execute SQL queries and commands for data access.\r\n * @param _mapper An instance of IMapper used to convert between entities and DTOs.\r\n *\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n constructor(\r\n private readonly _dataSource: IReadDataSource<TDto>,\r\n private readonly _mapper: IMapper<T, TDto>,\r\n ) {}\r\n\r\n public async findById(\r\n id: string | number,\r\n ctx: UserContext,\r\n signal: Optional<AbortSignal>,\r\n ): Promise<ResultType<Optional<T>>> {\r\n AppError.throwIfAborted(signal, 'ReadDao.findById')\r\n const result = await this._dataSource.findById(id, ctx, signal)\r\n if (Guards.isNullOrEmpty(result)) return Result.ok()\r\n\r\n const entity = this._mapper.toEntity(result)\r\n return Result.ok(entity)\r\n }\r\n\r\n public async findAll(ctx: UserContext, signal: Optional<AbortSignal>): Promise<ResultType<T[]>> {\r\n AppError.throwIfAborted(signal, 'ReadDao.findAll')\r\n const results = await this._dataSource.findAll(ctx, signal)\r\n const entities = results.map((result) => this._mapper.toEntity(result))\r\n return Result.ok(entities)\r\n }\r\n}\r\n","import type { IMapper, IRepository, IWriteDataSource, ResultType } from '@xeno-js/shared'\r\nimport type { Optional, UserContext } from '@xeno-js/shared'\r\nimport { AppError, Result } from '@xeno-js/shared'\r\nimport { Guards } from '@xeno-js/shared'\r\n\r\n/**\r\n * An abstract generic repository that provides basic CRUD operations for entities of type T, using a Data Transfer Object (DTO) of type TDto for data access. This class relies on an IWriteDataSource to perform database operations and an IMapper to convert between entities and DTOs.\r\n * @template T - The type of the entity that the repository will manage.\r\n * @template TDto - The type of the Data Transfer Object (DTO) used for data access.\r\n\r\n * \r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js \r\n */\r\nexport abstract class Repository<T, TDto> implements IRepository<T> {\r\n /**\r\n * Constructs a new Repository instance.\r\n * @param _dataSource An instance of IWriteDataSource used to execute SQL queries and commands for data access.\r\n * @param _mapper An instance of IMapper used to convert between entities and DTOs.\r\n *\r\n *\r\n * @author Xeno\r\n * @version 1.0.0\r\n * @since 2025-09-30\r\n * @link https://github.com/xeno-js/xeno-js\r\n */\r\n constructor(\r\n private readonly _dataSource: IWriteDataSource<TDto>,\r\n private readonly _mapper: IMapper<T, TDto>,\r\n ) {}\r\n\r\n public async findById(\r\n id: string | number,\r\n ctx: UserContext,\r\n signal: Optional<AbortSignal>,\r\n ): Promise<ResultType<Optional<T>>> {\r\n AppError.throwIfAborted(signal, 'Repository.findById')\r\n\r\n const result = await this._dataSource.findById(id, ctx, signal)\r\n if (Guards.isNullOrEmpty(result)) return Result.ok()\r\n\r\n const entity = this._mapper.toEntity(result)\r\n return Result.ok(entity)\r\n }\r\n\r\n public async findAll(ctx: UserContext, signal: Optional<AbortSignal>): Promise<ResultType<T[]>> {\r\n AppError.throwIfAborted(signal, 'Repository.findAll')\r\n\r\n const results = await this._dataSource.findAll(ctx, signal)\r\n const entities = results.map((result) => this._mapper.toEntity(result))\r\n return Result.ok(entities)\r\n }\r\n\r\n public async save(entity: T, signal: Optional<AbortSignal>): Promise<ResultType<void>> {\r\n const dto = this._mapper.toDto(entity)\r\n\r\n AppError.throwIfAborted(signal, 'Repository.save')\r\n\r\n await this._dataSource.insert(dto, signal)\r\n return Result.ok()\r\n }\r\n\r\n public async delete(\r\n entity: T,\r\n ctx: UserContext,\r\n signal: Optional<AbortSignal>,\r\n ): Promise<ResultType<void>> {\r\n const dto = this._mapper.toDto(entity)\r\n\r\n AppError.throwIfAborted(signal, 'Repository.delete')\r\n\r\n await this._dataSource.delete(dto, ctx, signal)\r\n return Result.ok()\r\n }\r\n\r\n public async update(\r\n id: string | number,\r\n entity: Partial<T>,\r\n ctx: UserContext,\r\n signal: Optional<AbortSignal>,\r\n ): Promise<ResultType<void>> {\r\n const dto = this._mapper.toPartialDto(entity)\r\n\r\n AppError.throwIfAborted(signal, 'Repository.update')\r\n\r\n await this._dataSource.update(id, dto, ctx, signal)\r\n return Result.ok()\r\n }\r\n}\r\n","export * from './unit-of-work'\r\n","export * from 'drizzle-orm'\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,EACE;AAAA,EAKA;AAAA,OACK;AAPP,IAca;AAdb;AAAA;AAAA;AAcO,IAAM,iBAAiB,OAAO,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAS1C,qBACE,OACA,WACA;AACA,cAAM,QAAQ,UAAU,QAAQ,OAAO,sBAAsB,EAAE,SAAS;AACxE,YAAI,CAAC,OAAO,UAAU,KAAK,GAAG;AAC5B,gBAAM,IAAI,MAAM,6DAA6D;AAAA,QAC/E;AAEA,cAAM,UAAW,MAA2B,QAAQ,KAAK;AACzD,eAAO;AAAA,MACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAgBA,MAAM,WACJ,UAC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mBAAmB;AAEnD,UAAM,KAAK,YAAY,OAAO,KAAK,KAAK,MAAM;AAC9C,WAAOC,SAAO,GAAG;AAAA,EACnB;AAAA,EAEA,MAAa,OACX,IACA,QACA,KACA,QAC2B;AAC3B,UAAM,MAAM,KAAK,QAAQ,aAAa,MAAM;AAE5C,IAAAD,WAAS,eAAe,QAAQ,mBAAmB;AAEnD,UAAM,KAAK,YAAY,OAAO,IAAI,KAAK,KAAK,MAAM;AAClD,WAAOC,SAAO,GAAG;AAAA,EACnB;AACF;;;AV9EA;;;AWZA;;;ACAA;AAAA;AAAA,kCAAc;;;AhBWd,0BAAc;AACd;AACA,cAAc;AACd,SAAkB,aAAiB;","names":["AppError","Guards","TOKENS","Result","AppError","Result","ERROR_CODES","Guards","STATUS_CODES","AppError","Result","ERROR_CODE_MESSAGES","ERROR_CODES","STATUS_CODES","AppError","Result","Guards","Guards","AppError","Result","Guards","AppError","Result","Guards","AppError","Result","Guards","AppError","Result","Guards","AppError","Result","Guards","GuidHelper","AppError","Result","Result","Guards","Result","Result","Guards","Result","GUEST","GuidHelper","Guards","Guards","LOG_LEVEL","Guards","LOG_LEVEL","Guards","LOG_LEVEL","LOG_LEVEL","Guards","LOG_LEVEL","TOKENS","ConsoleLogger","SentryLoggerFactory","PinoLoggerFactory","Guards","Guards","Guards","Guards","TOKENS","InMemoryCacheExtended","RedisCacheFactory","Guards","Guards","Guards","Guards","StringHelper","Guards","StringHelper","Guards","Guards","GuidHelper","StringHelper","AppError","Guards","Guards","AppError","Guards","Guards","AsyncLocalStorage","drizzle","Guards","Guards","TOKENS","Guards","PolicyRegistry","RoleAuthorizationStrategy","PermissionAuthorizationStrategy","UserAuthorizationStrategy","TenantAuthorizationStrategy","AuthorizationPipeline","SupabaseServerAuthFactory","ClaimsIdentityMapper","GateKeeper","DbSqlLiteClientFactory","DbClientFactory","AppError","Guards","Guards","TOKENS","DbUtils","TransactionState","UnitOfWork","NodeAxiosFactory","Guards","TOKENS","CockatielResilienceFactory","AllowOrigin","HttpUtils","Guards","TOKENS","ZodValidatorFactory","SchemaValidationStrategy","ValidationPipeline","IDEMPOTENCY_CONSTANTS","Guards","TOKENS","IdempotencyStore","IdempotencyPipeline","ConcurrencyRetryPipeline","CacheUtils","QueryCachingPipeline","TOKENS","Mediator","ExceptionPipeline","LoggerUtils","LoggingPipeline","PerformancePipeline","Guards","AuthUtils","ValidationUtils","CacheUtils","PipelineUtils","CompositePipeline","GuidHelper","HttpHelper","ERROR_CODE_MESSAGES","ERROR_CODES","GuidHelper","HttpHelper","STATUS_CODES","ERROR_CODE_MESSAGES","ERROR_CODES","GuidHelper","HttpHelper","STATUS_CODES","GuidHelper","HttpHelper","STATUS_CODES","Guards","ERROR_CODE_MESSAGES","ERROR_CODES","Guards","GuidHelper","HttpHelper","STATUS_CODES","Guards","Guards","HttpHelper","STATUS_CODES","ERROR_CODE_MESSAGES","ERROR_CODES","Guards","GuidHelper","HttpHelper","STATUS_CODES","Guards","ERROR_CODE_MESSAGES","ERROR_CODES","GUEST","GuidHelper","HttpHelper","STATUS_CODES","Guards","Guards","TOKENS","NoAuthGateKeeper","SupabaseSsrTokenExtractor","BearerTokenExtractor","HttpCookieExtractor","HttpHeaderExtractor","LoggerUtils","ClientIpResolver","RequestContextMiddleware","AllowOrigin","AllowOriginMiddleware","OptionsMiddleware","CORSMiddleware","AllowMethodFactory","MethodCheckMiddleware","AuthenticationMiddleware","CacheUtils","RateLimitKeyBuilder","RateLimitMiddleware","CsrfTokenService","CsrfCookieMiddleware","CsrfMiddleware","CompositeMiddleware","TOKENS","ServiceScopeFactory","NodeRequestContextFactory","UserContextFactory","Guards","LOG_LEVEL","TOKENS","Guards","Guards","TOKENS","LOG_LEVEL","Guards","LoggerUtils","CacheUtils","AuthUtils","DbModule","PLimitConcurrencyService","HttpCoreModule","HttpOriginModule","CqrsModule","MiddlewareModule","ContextModule","AppError","Result","AppError","Result","Guards","AppError","Result","Guards"]}