@xeno-js/core 5.0.2 → 5.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +580 -527
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -2
- package/dist/index.d.ts +4 -2
- package/dist/index.js +122 -68
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/infrastructure/services/concurrency/p-limit.service.ts","../src/infrastructure/services/concurrency/index.ts","../src/infrastructure/context/request-context.ts","../src/infrastructure/factories/request-context.factory.ts","../src/application/cqrs/base-handler.ts","../src/application/cqrs/command/command.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/validation/schema-validation.strategy.ts","../src/application/cqrs/pipelines/query-caching.pipeline.ts","../src/application/cqrs/pipelines/validation.pipeline.ts","../src/application/cqrs/query/query.ts","../src/application/gate_keepers/gate-keeper.ts","../src/application/gate_keepers/noauth.gate-keeper.ts","../src/application/loggers/base.logger.ts","../src/application/loggers/utils/logger-context.utils.ts","../src/application/mappers/claims-identity.mapper.ts","../src/application/policies/policy-registry.ts","../src/application/specifications/specification.ts","../src/infrastructure/builder/app.builder.ts","../src/infrastructure/configuration/node.configuration.ts","../src/infrastructure/configuration/vite.configuration.ts","../src/infrastructure/container/service-container.ts","../src/infrastructure/modules/auth.module.ts","../src/infrastructure/services/allow_methods/allow-method.service.ts","../src/infrastructure/services/allow_origins/allow-origin.http.ts","../src/infrastructure/services/index.ts","../src/infrastructure/services/cookies/cookies.service.ts","../src/infrastructure/services/crypto/crypto.service.ts","../src/infrastructure/services/csrf/csrf-token.service.ts","../src/infrastructure/services/extractors/extract-bearer.extractor.ts","../src/infrastructure/services/extractors/http-cookie.extractor.ts","../src/infrastructure/services/extractors/http-header.extractor.ts","../src/infrastructure/services/resolver/client-ip.resolver.ts","../src/infrastructure/modules/cache.module.ts","../src/infrastructure/cache/inmemory.cache.ts","../src/infrastructure/cache/key-builder.cache.ts","../src/infrastructure/cache/rate-limit-key-builder.cache.ts","../src/infrastructure/modules/utils/auth.utils.ts","../src/infrastructure/modules/utils/cache.utils.ts","../src/infrastructure/modules/utils/logger.utils.ts","../src/infrastructure/loggers/console.logger.ts","../src/infrastructure/modules/context.module.ts","../src/infrastructure/events/event.dispatcher.ts","../src/infrastructure/factories/allow-method.factory.ts","../src/infrastructure/factories/index.ts","../src/infrastructure/factories/service-scope.factory.ts","../src/infrastructure/factories/user-context.factory.ts","../src/infrastructure/http/adapter.http.ts","../src/infrastructure/http/url-builder.http.ts","../src/infrastructure/services/service_proxy/services.proxy.ts","../src/infrastructure/modules/cqrs.module.ts","../src/application/cqrs/pipelines/cache-invalidation.pipeline.ts","../src/infrastructure/idempotency/idempotency-store.ts","../src/infrastructure/pipeline_setup/setup.pipeline.ts","../src/infrastructure/modules/db.module.ts","../src/infrastructure/transaction/unit-of-work.ts","../src/infrastructure/transaction/transaction-state.ts","../src/infrastructure/modules/http-server.module.ts","../src/infrastructure/factories/route-matcher.factory.ts","../src/infrastructure/http/route-matcher.http.ts","../src/infrastructure/factories/server-options.factory.ts","../src/infrastructure/modules/logger.module.ts","../src/infrastructure/loggers/setup.logger.ts","../src/infrastructure/modules/middleware.module.ts","../src/presentation/controllers/base.controller.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/cookie-response.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/middlewares/request.middleware.ts","../src/presentation/mappers/context.mapper.ts","../src/infrastructure/http/dispatcher.http.ts","../src/infrastructure/modules/route.module.ts","../src/infrastructure/plugin/define.plugin.ts","../src/infrastructure/plugin/auth.plugin.ts","../src/infrastructure/plugin/authz.plugin.ts","../src/infrastructure/plugin/concurrency.plugin.ts","../src/infrastructure/plugin/http.plugin.ts","../src/infrastructure/modules/http-core.module.ts","../src/infrastructure/datasources/remote.datasource.ts","../src/infrastructure/factories/http.factory.ts","../src/infrastructure/services/resiliences/resilience.service.ts","../src/infrastructure/plugin/idempotency.plugin.ts","../src/infrastructure/plugin/logger.plugin.ts","../src/infrastructure/plugin/performance.plugin.ts","../src/infrastructure/plugin/query.plugin.ts","../src/infrastructure/plugin/validation.plugin.ts","../src/infrastructure/xeno_application/xeno.application.ts","../src/infrastructure/repositories/read-dao.ts","../src/infrastructure/repositories/repository.ts","../src/infrastructure/http/native-route.helper.ts","../src/index.ts"],"sourcesContent":["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 { AsyncLocalStorage } from 'node:async_hooks'\n\nimport type {\n Identity,\n IFactory,\n NetworkContext,\n Optional,\n RequestContext,\n TracingContext,\n} from '@xeno-js/shared'\nimport type {\n ExecutionContext,\n IRequestContext,\n IServiceScope,\n XenoRegistry,\n} from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\n/**\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.\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.\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 NodeRequestContext<\n TRegistry extends XenoRegistry = XenoRegistry,\n> implements IRequestContext<RequestContext, TRegistry> {\n /**\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.\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.\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.\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 constructor(\n private readonly _storage: AsyncLocalStorage<ExecutionContext<TRegistry>>,\n private readonly _factoryScope: IFactory<void, IServiceScope<TRegistry>>,\n ) {}\n\n public async runAsync<T>(context: RequestContext, fn: () => Promise<T>): Promise<T> {\n const scope = this._factoryScope.create()\n try {\n return await this._storage.run({ context, scope }, fn)\n } finally {\n await scope.dispose()\n }\n }\n\n public updateIdentity(identity: Identity): void {\n const store = this._storage.getStore()\n if (Guards.isDefined(store) && Guards.isDefined(store.context)) {\n store.context = Object.freeze({\n ...store.context,\n identity: Object.freeze(identity),\n })\n }\n }\n\n public getContext(): Optional<RequestContext> {\n const store = this._storage.getStore()\n if (!Guards.isDefined(store)) return undefined\n const context = store.context\n return Object.freeze(context)\n }\n\n public getIdentity(): Optional<Identity> {\n const store = this._storage.getStore()\n if (!Guards.isDefined(store)) return undefined\n return Object.freeze(store.context?.identity)\n }\n\n public getScope(): Optional<IServiceScope<TRegistry>> {\n const store = this._storage.getStore()\n if (!Guards.isDefined(store)) return undefined\n return store.scope\n }\n\n public getNetworkContext(): Optional<NetworkContext> {\n const store = this._storage.getStore()\n if (!Guards.isDefined(store)) return undefined\n return Object.freeze(store.context?.network)\n }\n\n public getTracingContext(): Optional<TracingContext> {\n const store = this._storage.getStore()\n if (!Guards.isDefined(store)) return undefined\n return Object.freeze(store.context?.tracing)\n }\n}\n","import { AsyncLocalStorage } from 'node:async_hooks'\n\nimport type { IFactory, RequestContext } from '@xeno-js/shared'\nimport type {\n ExecutionContext,\n IRequestContext,\n IServiceScope,\n XenoRegistry,\n} from '@xeno-js/shared'\n\nimport { NodeRequestContext } from '../context/request-context'\n\n/**\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.\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 NodeRequestContextFactory<\n TRegistry extends XenoRegistry = XenoRegistry,\n> implements IFactory<void, IRequestContext<RequestContext, TRegistry>> {\n private _store: AsyncLocalStorage<ExecutionContext<TRegistry>> = new AsyncLocalStorage<\n ExecutionContext<TRegistry>\n >()\n\n constructor(private readonly _factoryScope: IFactory<void, IServiceScope<TRegistry>>) {}\n\n public create(): IRequestContext<RequestContext, TRegistry> {\n return new NodeRequestContext<TRegistry>(this._store, this._factoryScope)\n }\n}\n","import type {\n IFactory,\n IHandler,\n IRequest,\n Optional,\n ResultType,\n UserContext,\n} from '@xeno-js/shared'\nimport { AppError } from '@xeno-js/shared'\n\n/**\n * BaseHandler is an abstract class that implements the IHandler interface.\n * It provides a base implementation for handling requests and executing strategies.\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 abstract class BaseHandler<\n TRequest extends IRequest<TResponse>,\n TResponse,\n> implements IHandler<TRequest, TResponse> {\n constructor(private readonly _identityFactory: IFactory<void, UserContext>) {}\n\n public async handle(\n request: TRequest,\n signal: Optional<AbortSignal>,\n ): Promise<ResultType<TResponse>> {\n AppError.throwIfAborted(signal, this.constructor.name)\n\n return await this.executeAsync(request, signal)\n }\n\n /**\n * Executes the strategy for the given request.\n * @param request - The request to be handled.\n * @param signal - (Optional) The abort signal for the request.\n * @throws {AppError} If the strategy execution fails.\n * @protected - This method should be overridden by subclasses.\n * @abstract - This method must be implemented by subclasses.\n * @async - This method is asynchronous.\n * @template TRequest - The type of the request.\n * @template TResponse - The type of the response.\n * @returns {Promise<ResultType<TResponse>>} A promise that resolves to the result of the strategy execution.\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 protected abstract executeAsync(\n request: TRequest,\n signal?: Optional<AbortSignal>,\n ): Promise<ResultType<TResponse>>\n\n /**\n * Gets the current context.\n * @returns {UserContext} The current context.\n * {@link UserContext}\n */\n protected _getCurrentContext(): UserContext {\n return this._identityFactory.create()\n }\n}\n","import type { ICommand, Optional, RequestType } from '@xeno-js/shared'\nimport { REQUEST_TYPE } from '@xeno-js/shared'\n\n/**\n * @description Base class for all commands.\n * @author Xeno\n * @version 1.0.0\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-js\n */\nexport abstract class Command<TResponse = unknown> implements ICommand<TResponse> {\n public readonly type: RequestType = REQUEST_TYPE.COMMAND\n public readonly cacheInvalidation: Optional<{\n keys?: string[]\n patterns?: string[]\n }> = undefined\n\n constructor(\n readonly intent: string,\n cacheInvalidation?: {\n keys?: string[]\n patterns?: string[]\n },\n ) {\n this.cacheInvalidation = cacheInvalidation\n }\n}\n","import type {\n Delegate,\n ICommand,\n IHandler,\n IMediator,\n IPipelineBehavior,\n IQuery,\n IRequest,\n Optional,\n ResultType,\n} from '@xeno-js/shared'\nimport type { IServiceScopeAccessor, XenoRegistry } from '@xeno-js/shared'\nimport { AppError, Result } from '@xeno-js/shared'\nimport { ERROR_CODE_MESSAGES, ERROR_CODES, Guards, STATUS_CODES } from '@xeno-js/shared'\nimport { TOKENS } from '@xeno-js/shared'\n\n/**\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).\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 Mediator<TRegistry extends XenoRegistry = XenoRegistry> implements IMediator {\n /**\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.\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 constructor(private readonly _factoryScope: IServiceScopeAccessor<TRegistry>) {}\n\n /**\n * @inheritdoc\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 async send<TResponse>(\n request: ICommand<TResponse>,\n signal: Optional<AbortSignal>,\n ): Promise<ResultType<TResponse>> {\n return this.process<TResponse>(request, TOKENS.COMMAND_PIPELINES_BEHAVIOR, signal)\n }\n\n /**\n * @inheritdoc\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 async query<TResponse>(\n request: IQuery<TResponse>,\n signal: Optional<AbortSignal>,\n ): Promise<ResultType<TResponse>> {\n return this.process<TResponse>(request, TOKENS.QUERY_PIPELINES_BEHAVIOR, signal)\n }\n\n /**\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.\n * @param request The command or query to be processed.\n * @param pipelineToken The token used to resolve the pipeline behaviors for the request.\n * @param signal An optional AbortSignal to allow cancellation of the request.\n * @returns A promise that resolves to the result of processing the request.\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 async process<TResponse>(\n request: IRequest<TResponse>,\n pipelineToken: keyof XenoRegistry,\n signal: Optional<AbortSignal>,\n ): Promise<ResultType<TResponse>> {\n if (Guards.isDefined(signal) && signal.aborted)\n return Result.fail(AppError.aborted(request.intent))\n\n const scope = this._factoryScope.getScope()\n\n if (!Guards.isDefined(scope))\n return Result.fail(\n AppError.create({\n code: ERROR_CODES.SCOPE_NOT_AVAILABLE,\n status: STATUS_CODES.INTERNAL_SERVER_ERROR,\n name: request.intent,\n message: ERROR_CODE_MESSAGES[ERROR_CODES.SCOPE_NOT_AVAILABLE],\n cause: new Error('Service scope is required to process the request.'),\n }),\n )\n\n const pipelines = scope.resolve(pipelineToken) as unknown as IPipelineBehavior<\n IRequest<TResponse>,\n TResponse\n >\n\n if (!Guards.isDefined(pipelines) || !Guards.hasMethod(pipelines, 'handle')) {\n return Result.fail(\n AppError.create({\n code: ERROR_CODES.PIPELINE_NOT_AVAILABLE,\n status: STATUS_CODES.INTERNAL_SERVER_ERROR,\n name: request.intent,\n message: ERROR_CODE_MESSAGES[ERROR_CODES.PIPELINE_NOT_AVAILABLE],\n cause: new Error('Pipeline behavior is required to process the request.'),\n }),\n )\n }\n\n const next: Delegate<TResponse> = () => {\n const handler = scope.resolve(request.intent as keyof TRegistry) as IHandler<\n IRequest<TResponse>,\n TResponse\n >\n\n if (!Guards.isDefined(handler) || !Guards.hasMethod(handler, 'handle')) {\n AppError.throw({\n code: ERROR_CODES.HANDLER_NOT_FOUND,\n status: STATUS_CODES.INTERNAL_SERVER_ERROR,\n name: request.intent,\n message: ERROR_CODE_MESSAGES[ERROR_CODES.HANDLER_NOT_FOUND],\n cause: new Error('Handler is required to process the request.'),\n })\n }\n return handler.handle(request, signal)\n }\n\n return pipelines.handle(request, next)\n }\n}\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","/* eslint-disable @typescript-eslint/naming-convention */\nimport type { Delegate, ICommand, IPipelineBehavior, Optional, ResultType } from '@xeno-js/shared'\nimport type { ConcurrencyOptions } from '@xeno-js/shared'\nimport {\n AppError,\n DEFAULT_CONCURRENCY,\n ERROR_CODES,\n PromiseHelper,\n Result,\n STATUS_CODES,\n} from '@xeno-js/shared'\n\n/**\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.\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 ConcurrencyRetryPipeline<\n TInput extends ICommand<TResult>,\n TResult,\n> implements IPipelineBehavior<TInput, TResult> {\n private static readonly DEFAULT_MAX_RETRIES = DEFAULT_CONCURRENCY.MAX_RETRIES\n private static readonly DEFAULT_BASE_DELAY_MS = DEFAULT_CONCURRENCY.BASE_DELAY\n private static readonly DEFAULT_MAX_JITTER_MS = DEFAULT_CONCURRENCY.MAX_JITTER\n\n /**\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.\n * @param _options Optional configuration options for the behavior, including the maximum number of retry attempts and the delay configuration for the exponential backoff strategy.\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 constructor(private readonly _options: Optional<ConcurrencyOptions> = undefined) {}\n\n /**\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.\n * @param request The input request to be handled, which must extend ICommand.\n * @param next The delegate function that represents the next behavior or handler in the pipeline.\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.\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 handle(request: TInput, next: Delegate<TResult>): Promise<ResultType<TResult>> {\n const intentConfig = this._options?.intentRegistry?.[request.intent]\n\n const maxRetries =\n intentConfig?.maxRetries ??\n this._options?.maxRetries ??\n ConcurrencyRetryPipeline.DEFAULT_MAX_RETRIES\n\n const baseDelay =\n intentConfig?.delayConfig?.baseDelayMs ??\n this._options?.delayConfig?.baseDelayMs ??\n ConcurrencyRetryPipeline.DEFAULT_BASE_DELAY_MS\n\n const jitter =\n intentConfig?.delayConfig?.maxJitterMs ??\n this._options?.delayConfig?.maxJitterMs ??\n ConcurrencyRetryPipeline.DEFAULT_MAX_JITTER_MS\n\n let attempts = 0\n\n while (true) {\n attempts++\n\n const result = await next()\n\n if (result.isOk() || !this.isConcurrencyError(result.getErrorOrThrow())) return result\n\n if (attempts >= maxRetries)\n return Result.fail(\n AppError.conflict(\n request.intent,\n `Maximum retry attempts (${maxRetries}) exceeded due to concurrency conflicts.`,\n ),\n )\n\n await PromiseHelper.delayWithJitter(baseDelay, jitter)\n }\n }\n\n /**\n * @description Checks if the given error is a concurrency conflict error.\n * @param error The error to be checked.\n * @returns A boolean indicating whether the error is a concurrency conflict error.\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 isConcurrencyError(error: AppError): boolean {\n return error.code === ERROR_CODES.CONFLICT && error.status === STATUS_CODES.CONFLICT\n }\n}\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","/* eslint-disable @typescript-eslint/naming-convention */\nimport type {\n Delegate,\n ICommand,\n IIdempotencyStore,\n INetworkContextAccessor,\n IPipelineBehavior,\n Optional,\n ResultType,\n} from '@xeno-js/shared'\nimport type { IdempotencyOptions } from '@xeno-js/shared'\nimport { AppError, Result } from '@xeno-js/shared'\nimport { Guards, IDEMPOTENCY_CONSTANTS } from '@xeno-js/shared'\n\n/**\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.\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 IdempotencyPipeline<\n TInput extends ICommand<TResult>,\n TResult,\n> implements IPipelineBehavior<TInput, TResult> {\n private static readonly DEFAULT_LOCK_TTL =\n IDEMPOTENCY_CONSTANTS.DEFAULT_IDEMPOTENCY_LOCK_TTL_SECONDS\n private static readonly DEFAULT_PROCESSED_TTL = IDEMPOTENCY_CONSTANTS.DEFAULT_TTL_SECONDS\n\n /**\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.\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.\n * @param _options Optional configuration options for the idempotency pipeline, including the TTL values for locks and processed results. These options allow for customization of the idempotency behavior based on the specific needs of the application. The constructor validates the input options 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.\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 constructor(\n private readonly _requestContextFactory: INetworkContextAccessor,\n private readonly _idempotencyStore: IIdempotencyStore,\n private readonly _options: Optional<IdempotencyOptions> = undefined,\n ) {}\n\n public async handle(request: TInput, next: Delegate<TResult>): Promise<ResultType<TResult>> {\n const network = this._requestContextFactory.getNetworkContext()\n if (!Guards.isDefined(network))\n return Result.fail(\n AppError.conflict(\n request.intent,\n `network context is not defined for request ${request.intent}`,\n ),\n )\n\n const intentConfig = this._options?.intentRegistry?.[request.intent]\n const lockTtl =\n intentConfig?.lockTtlSeconds ??\n this._options?.lockTtlSeconds ??\n IdempotencyPipeline.DEFAULT_LOCK_TTL\n\n const processedTtl =\n intentConfig?.processedTtlSeconds ??\n this._options?.processedTtlSeconds ??\n IdempotencyPipeline.DEFAULT_PROCESSED_TTL\n\n try {\n const alreadyProcessed = await this._idempotencyStore.hasBeenProcessed(network.requestId)\n if (alreadyProcessed) {\n const payload = await this._idempotencyStore.getPayload<TResult>(network.requestId)\n if (Guards.isDefined(payload)) {\n return Result.ok(payload)\n } else {\n return Result.fail(\n AppError.conflict(\n request.intent,\n `Idempotency store indicates request has been processed but no payload found for request ID ${network.requestId}`,\n ),\n )\n }\n }\n\n const lockAcquired = await this._idempotencyStore.acquireLock(network.requestId, lockTtl)\n\n if (!lockAcquired) {\n return Result.fail(\n AppError.conflict(\n request.intent,\n `Failed to acquire lock for request ID ${network.requestId}`,\n ),\n )\n }\n\n const result = await next()\n\n if (result.isOk()) {\n await this._idempotencyStore.markAsProcessed(\n network.requestId,\n result.getValueOrThrow() ?? { success: true },\n processedTtl,\n )\n } else {\n await this._idempotencyStore.releaseLock(network.requestId)\n }\n\n return result\n } catch (error: unknown) {\n await this._idempotencyStore.releaseLock(network.requestId)\n\n throw error\n }\n }\n}\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 {\n Delegate,\n Dictionary,\n ILogger,\n IPipelineBehavior,\n IRequest,\n ResultType,\n} from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\n/**\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.\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 */\nconst defaultThresholdMs = 500\n\n/**\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.\n *\n * @template TInput - The type of the input request, which must extend the IRequest interface.\n * @template TResult - The type of the result returned by the request handler.\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 PerformancePipeline<\n TInput extends IRequest<TResult>,\n TResult,\n> implements IPipelineBehavior<TInput, TResult> {\n /**\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.\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 readonly _thresholdMs: number\n\n private readonly _intentThresholdMS: Dictionary<{ thresholdMs: number }>\n\n /**\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.\n * @param _logger An instance of ILogger used for logging performance warnings related to the handling of requests.\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.\n * @throws Will throw an error if the provided thresholdMs value is not a positive integer.\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 constructor(\n private readonly _logger: ILogger,\n intentThresholdMS: Dictionary<{ thresholdMs: number }> = {},\n thresholdMs: number = defaultThresholdMs,\n ) {\n const message = `Invalid thresholdMs value: ${thresholdMs}. It must be a positive integer.`\n Guards.throwIfNegative(thresholdMs, message)\n if (thresholdMs === 0) {\n throw new Error(message)\n }\n this._thresholdMs = thresholdMs\n\n for (const [intent, val] of Object.entries(intentThresholdMS)) {\n const intentMessage = `Invalid thresholdMs value for intent '${intent}': ${val.thresholdMs}. It must be a positive integer.`\n Guards.throwIfNegative(val.thresholdMs, intentMessage)\n Guards.throwIfNotInteger(val.thresholdMs, intentMessage)\n if (val.thresholdMs === 0) {\n throw new Error(intentMessage)\n }\n }\n this._intentThresholdMS = intentThresholdMS\n }\n\n public async handle(request: TInput, next: Delegate<TResult>): Promise<ResultType<TResult>> {\n const startTime = performance.now()\n try {\n return await next()\n } finally {\n const endTime = performance.now()\n const duration = endTime - startTime\n\n const thresholdMs =\n this._intentThresholdMS?.[request.intent]?.thresholdMs ?? this._thresholdMs\n if (duration > thresholdMs) {\n this._logger.warn(`Performance warning: ${request.intent} took ${duration.toFixed(2)}ms`)\n }\n }\n }\n}\n","import type {\n IContextAccessor,\n Identity,\n IPolicyRegistry,\n IRequest,\n IStrategy,\n RequestContext,\n ResultType,\n} from '@xeno-js/shared'\nimport { AppError, Result } from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\n/**\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.\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 abstract class BaseAuthorizationStrategy<\n TInput extends IRequest,\n> implements IStrategy<TInput> {\n /**\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.\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.\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 constructor(\n protected readonly _policy: IPolicyRegistry,\n private readonly _requestContext: IContextAccessor<RequestContext>,\n ) {}\n\n public async execute(request: IRequest): Promise<ResultType<void>> {\n const context = this._requestContext.getContext()\n\n if (!Guards.isDefined(context)) {\n return Result.fail(AppError.unauthorized(request.intent, 'User is not authenticated.'))\n }\n\n const superadmin = this._policy.getPolicy('superadmin')\n if (!Guards.isNullOrEmpty(superadmin?.roles)) {\n const auth = context?.identity\n const roles = auth?.roles ?? []\n const hasRequiredRole = superadmin.roles?.some((role) => roles.includes(role))\n if (hasRequiredRole) return Result.ok()\n }\n\n return await this.performAuthorizationCheck(request, context.identity)\n }\n\n /**\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.\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.\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.\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.\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 protected abstract performAuthorizationCheck(\n request: IRequest,\n auth: Identity,\n ): Promise<ResultType<void>>\n}\n","import type {\n IContextAccessor,\n Identity,\n IPolicyRegistry,\n IRequest,\n RequestContext,\n} from '@xeno-js/shared'\nimport { AppError, Result } from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\nimport { BaseAuthorizationStrategy } from './base-authorization.strategy'\n\n/**\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.\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 PermissionAuthorizationStrategy extends BaseAuthorizationStrategy<IRequest> {\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.\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.\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.\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 constructor(policy: IPolicyRegistry, requestContext: IContextAccessor<RequestContext>) {\n super(policy, requestContext)\n }\n\n protected async performAuthorizationCheck(\n command: IRequest,\n auth: Identity,\n ): Promise<Result<void, AppError>> {\n const policy = this._policy.getPolicy(command.intent)\n\n if (!Guards.isNullOrEmpty(policy?.permissions)) {\n const permissions = auth.permissions ?? []\n const hasRequiredPermission = policy.permissions?.some((permission) =>\n permissions.includes(permission),\n )\n if (!hasRequiredPermission)\n return Result.fail(\n AppError.forbidden(command.intent, 'User does not have the required permissions.'),\n )\n }\n\n return Result.ok()\n }\n}\n","import type {\n IContextAccessor,\n Identity,\n IPolicyRegistry,\n IRequest,\n RequestContext,\n} from '@xeno-js/shared'\nimport { AppError, Result } from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\nimport { BaseAuthorizationStrategy } from './base-authorization.strategy'\n\n/**\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.\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 RoleAuthorizationStrategy extends BaseAuthorizationStrategy<IRequest> {\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.\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.\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 constructor(policy: IPolicyRegistry, requestContext: IContextAccessor<RequestContext>) {\n super(policy, requestContext)\n }\n\n protected async performAuthorizationCheck(\n command: IRequest,\n auth: Identity,\n ): Promise<Result<void, AppError>> {\n const policy = this._policy.getPolicy(command.intent)\n\n if (!Guards.isNullOrEmpty(policy?.roles)) {\n const roles = auth.roles ?? []\n const hasRequiredRole = policy.roles?.some((role) => roles.includes(role))\n if (!hasRequiredRole)\n return Result.fail(\n AppError.forbidden(command.intent, 'User does not have the required roles.'),\n )\n }\n\n return Result.ok()\n }\n}\n","import type {\n IContextAccessor,\n Identity,\n IPolicyRegistry,\n IRequest,\n RequestContext,\n} from '@xeno-js/shared'\nimport { AppError, Result } from '@xeno-js/shared'\nimport { Guards, GuidHelper } from '@xeno-js/shared'\n\nimport { BaseAuthorizationStrategy } from './base-authorization.strategy'\n\n/**\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.\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 TenantAuthorizationStrategy extends BaseAuthorizationStrategy<IRequest> {\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.\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.\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 constructor(policy: IPolicyRegistry, requestContext: IContextAccessor<RequestContext>) {\n super(policy, requestContext)\n }\n\n protected async performAuthorizationCheck(\n command: IRequest,\n auth: Identity,\n ): Promise<Result<void, AppError>> {\n const policy = this._policy.getPolicy(command.intent)\n\n if (Guards.isDefined(policy?.tenantId)) {\n if (Guards.isNullOrEmpty(auth.tenantId) || !GuidHelper.isValidGuid(auth.tenantId))\n return Result.fail(AppError.unauthorized(command.intent, 'Tenant is not authenticated.'))\n }\n\n return Result.ok()\n }\n}\n","import type {\n IContextAccessor,\n Identity,\n IPolicyRegistry,\n IRequest,\n RequestContext,\n} from '@xeno-js/shared'\nimport { AppError, Result } from '@xeno-js/shared'\nimport { Guards, GuidHelper } from '@xeno-js/shared'\n\nimport { BaseAuthorizationStrategy } from './base-authorization.strategy'\n\n/**\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.\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 UserAuthorizationStrategy extends BaseAuthorizationStrategy<IRequest> {\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.\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.\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 constructor(policy: IPolicyRegistry, requestContext: IContextAccessor<RequestContext>) {\n super(policy, requestContext)\n }\n\n protected async performAuthorizationCheck(\n command: IRequest,\n auth: Identity,\n ): Promise<Result<void, AppError>> {\n const policy = this._policy.getPolicy(command.intent)\n\n if (Guards.isDefined(policy?.userId)) {\n if (Guards.isNullOrEmpty(auth.userId) || !GuidHelper.isValidGuid(auth.userId))\n return Result.fail(AppError.unauthorized(command.intent, 'User is not authenticated.'))\n }\n\n return Result.ok()\n }\n}\n","import type { IRequest, IStrategy, IValidatorService, ResultType } from '@xeno-js/shared'\nimport { AppError, Result } from '@xeno-js/shared'\n\n/**\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.\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 SchemaValidationStrategy implements IStrategy<IRequest, boolean> {\n /**\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.\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.\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 constructor(private readonly _validator: IValidatorService) {}\n\n public async execute(request: IRequest): Promise<ResultType<boolean>> {\n const key = request.intent\n const parseResult = await this._validator.validate(key, request)\n\n if (!parseResult.isOk()) {\n const validatorError = parseResult.getErrorOrThrow()\n const details =\n validatorError.cause instanceof Error\n ? validatorError.cause.message\n : validatorError.message\n\n return Result.fail(\n Object.assign(AppError.validationError(request.intent, `Validation failed: ${details}`), {\n validatorError,\n }),\n )\n }\n\n return Result.ok(true)\n }\n}\n","import type {\n Delegate,\n ICache,\n ICacheKeyBuilder,\n ILogger,\n IPipelineBehavior,\n IQuery,\n ResultType,\n} from '@xeno-js/shared'\nimport { Result } from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\n/**\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.\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 QueryCachingPipeline<\n TInput extends IQuery<TResult>,\n TResult,\n> implements IPipelineBehavior<TInput, TResult> {\n /**\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.\n * @param _cacheService An instance of ICache used for interacting with the cache, including retrieving and storing cached responses based on cache keys.\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.\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 constructor(\n private readonly _cacheService: ICache,\n private readonly _cacheKeyBuilder: ICacheKeyBuilder,\n private readonly _logger: ILogger,\n ) {}\n\n public async handle(request: TInput, next: Delegate<TResult>): Promise<ResultType<TResult>> {\n if (\n Guards.isNullOrEmpty(request.cacheOptions) ||\n Guards.isNullOrEmpty(request.cacheOptions.cacheKey)\n )\n return next()\n\n const bypass =\n request.cacheOptions.bypassCache === true || request.cacheOptions.consistentRead === true\n\n const key = request.cacheOptions.isUserScoped\n ? this._cacheKeyBuilder.buildUserScopedKey(request.cacheOptions.cacheKey)\n : this._cacheKeyBuilder.buildContextualKey(request.cacheOptions.cacheKey)\n\n if (!bypass) {\n try {\n const cachedResponse = await this._cacheService.get<TResult>(key)\n if (Guards.isDefined(cachedResponse)) {\n this._logger.debug(\n `[Cache HIT] Returning data from cache for: ${request.cacheOptions.cacheKey}`,\n )\n return Result.ok(cachedResponse)\n }\n } catch (error) {\n this._logger.warn(\n `[Cache ERROR] Unable to read cache for: ${request.cacheOptions.cacheKey}. Proceeding to DB. Error: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n }\n\n const result = await next()\n\n if (result.isOk()) {\n try {\n await this._cacheService.set(key, result.getValueOrThrow(), request.cacheOptions.ttl)\n this._logger.debug(`[Cache SET] Data saved in cache for: ${key}`)\n } catch (error) {\n this._logger.warn(\n `[Cache ERROR] Unable to save cache for: ${key}. Error: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n }\n\n return result\n }\n}\n","import type { Delegate, IPipelineBehavior, IRequest, IStrategy, ResultType } from '@xeno-js/shared'\nimport { Result } from '@xeno-js/shared'\n/**\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.\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 ValidationPipeline<\n TInput extends IRequest<TResult>,\n TResult,\n> implements IPipelineBehavior<TInput, TResult> {\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.\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.\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 constructor(private readonly _validators: readonly IStrategy<TInput, boolean>[]) {}\n\n public async handle(request: TInput, next: Delegate<TResult>): Promise<ResultType<TResult>> {\n for (const validator of this._validators) {\n const validationResult = await validator.execute(request)\n if (!validationResult.isOk()) {\n return Result.fail(validationResult.getErrorOrThrow())\n }\n }\n return next()\n }\n}\n","import type { ICacheableOptions, IQuery, RequestType } from '@xeno-js/shared'\nimport { REQUEST_TYPE } from '@xeno-js/shared'\n\n/**\n * @description Base class for all queries.\n * @author Xeno\n * @version 1.0.0\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-js\n */\nexport abstract class Query<TResponse = unknown> implements IQuery<TResponse> {\n public readonly type: RequestType = REQUEST_TYPE.QUERY\n\n constructor(\n readonly intent: string,\n readonly cacheOptions: ICacheableOptions,\n ) {}\n}\n","import type {\n IBaseAuthService,\n IBaseMapper,\n Identity,\n IGateKeeper,\n ResultType,\n} from '@xeno-js/shared'\nimport type { AuthClaims, Optional } from '@xeno-js/shared'\nimport { Result } from '@xeno-js/shared'\nimport { Guards, GUEST } from '@xeno-js/shared'\n\n/**\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.\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 GateKeeper implements IGateKeeper {\n constructor(\n private readonly _authServiceResolver: () => IBaseAuthService,\n private readonly _mapper: IBaseMapper<AuthClaims, Identity>,\n ) {}\n\n public async authenticate(token: Optional<string>): Promise<ResultType<Identity>> {\n const guest = GUEST as unknown as Identity\n const authService = this._authServiceResolver()\n if (!Guards.isNullOrEmpty(token)) {\n const authResult = await authService.authenticate(token)\n\n if (!authResult.isOk()) return Result.fail(authResult.getErrorOrThrow())\n\n const claims = authResult.getValueOrThrow()\n if (!Guards.isNullOrEmpty(claims)) return Result.ok(this._mapper.map(claims))\n\n return Result.ok(guest)\n }\n\n const userResult = await authService.getUser()\n\n if (userResult.isOk()) {\n const user = userResult.getValueOrThrow()\n if (Guards.isDefined(user)) {\n return Result.ok(this._mapper.map(user))\n }\n }\n\n return Result.ok(guest)\n }\n}\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","import type { IContextAccessor, ILogger, ILoggerClient, RequestContext } from '@xeno-js/shared'\nimport type { LogLevel, Optional } from '@xeno-js/shared'\nimport { LOG_LEVEL, LOG_LEVEL_NAMES } from '@xeno-js/shared'\n\nimport { LoggerUtils } from './utils'\n\n/**\n * @description Concrete implementation of the ILogger interface that serves as a central logging service within the application. This class is designed to broadcast log messages to multiple logging clients (implementations of ILoggerClient) that are injected via the constructor. The BaseLogger class provides methods for logging messages at different levels (info, warn, debug, error) and ensures that only messages that meet or exceed the specified minimum log level are forwarded to the registered logging clients. This design allows for flexibility in logging, enabling the use of various logging providers (e.g., Sentry, Pino) without coupling the application code to specific logging frameworks.\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 BaseLogger implements ILogger {\n // ─── Private Fields ─────────────────────────────────────────────────────────\n private readonly _minLevel: LogLevel\n private readonly _loggers: ILoggerClient[]\n\n /**\n * @description Constructs a new instance of the BaseLogger class, which takes an array of ILoggerClient instances and an optional minimum log level. The ILoggerClient instances represent the various logging providers that will receive log messages from this logger. The minimum log level determines the threshold for logging messages, where messages with a log level below the specified minimum will not be forwarded to the logging clients. This allows for efficient logging by filtering out less critical log messages based on the configured log level.\n * @param _requestContext The request context that provides contextual information for log messages, such as request-specific data or metadata.\n * @param config The minimum log level for this logger instance. Only messages with a log level equal to or higher than this level will be processed and forwarded to the logging clients.\n * @param loggers An array of ILoggerClient instances that will receive log messages from this logger. Each ILoggerClient represents a different logging provider or destination (e.g., console, file, external service).\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 constructor(\n private readonly _requestContext: IContextAccessor<RequestContext>,\n config: LogLevel,\n loggers: ILoggerClient[],\n ) {\n this._minLevel = config\n this._loggers = loggers\n }\n\n public info(message: string): void {\n this.broadcast(LOG_LEVEL.INFO, message)\n }\n\n public warn(message: string): void {\n this.broadcast(LOG_LEVEL.WARN, message)\n }\n\n public debug(message: string): void {\n this.broadcast(LOG_LEVEL.DEBUG, message)\n }\n\n public error(message: string, error: unknown): void {\n this.broadcast(LOG_LEVEL.ERROR, message, error)\n }\n\n /**\n * @description Private method to broadcast log messages to all registered ILoggerClient instances. This method checks if the log level of the message meets or exceeds the configured minimum log level before forwarding the message to the logging clients. It iterates through the array of ILoggerClient instances and calls their track method with the appropriate parameters (log level, message, context, and error if applicable). This design allows for efficient logging by ensuring that only relevant log messages are processed and forwarded to the logging clients based on the configured log level.\n * @param level The log level of the message.\n * @param message The log message.\n * @param context Optional context information to include with the log message.\n * @param error Optional error object to include with the log message.\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 broadcast(level: LogLevel, message: string, error: Optional<unknown> = undefined): void {\n if (level < this._minLevel) return\n\n const logMessage = `[${LOG_LEVEL_NAMES[level]}] ${message}`\n const context = this._requestContext.getContext()\n const safeContext = LoggerUtils.toSafeContext(context)\n for (const logger of this._loggers) {\n logger.track(level, logMessage, safeContext, error)\n }\n }\n}\n","import type { Dictionary, Optional, RequestContext } from '@xeno-js/shared'\nimport { Guards, HttpHelper, StringHelper } from '@xeno-js/shared'\n\n/**\n * @description LoggerUtils provides utility functions for working with LoggerContext objects.\n */\nexport const LoggerUtils = Object.freeze({\n /**\n * @description toSafeContext converts a RequestContext object to a LoggerContext object, ensuring that only the necessary fields are included.\n * @param ctx The RequestContext object to convert.\n * @returns The converted LoggerContext object.\n */\n toSafeContext(ctx: Optional<RequestContext>): Dictionary {\n const context = {\n identity: {\n userId: ctx?.identity?.userId,\n tenantId: ctx?.identity?.tenantId,\n },\n network: {\n requestId: ctx?.network?.requestId,\n path: ctx?.network?.path,\n origin: ctx?.network?.origin,\n clientIp: HttpHelper.maskIp(ctx?.network?.clientIp),\n },\n tracing: {\n correlationId: ctx?.tracing?.correlationId,\n spanId: ctx?.tracing?.spanId,\n startTime: ctx?.tracing?.startTime,\n parentSpanId: ctx?.tracing.parentSpanId,\n },\n messaging: ctx?.messaging,\n }\n return StringHelper.safeStringifyObject(context)\n },\n\n toNormalizeError(error: unknown): unknown {\n if (error instanceof Error) {\n return {\n message: error.message,\n name: error.name,\n stack: error.stack,\n cause: error.cause,\n }\n }\n const errorString = Guards.isString(error) ? error : StringHelper.safeStringify(error)\n const customError = new Error(errorString)\n\n if (Guards.isObject(error) && Guards.isDefined(error)) {\n Object.assign(customError, error)\n }\n\n return customError\n },\n} as const)\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","import type { IPolicyRegistry } from '@xeno-js/shared'\nimport type { AuthPolicy, Optional } from '@xeno-js/shared'\n\n/**\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.\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 PolicyRegistry implements IPolicyRegistry {\n /**\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.\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.\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 constructor(private readonly _cache: Map<string, AuthPolicy> = new Map()) {}\n\n public addPolicy(intent: string, policy: AuthPolicy): this {\n const key = this.getKey(intent)\n this._cache.set(key, policy)\n return this\n }\n\n public setSuperadminRoles(roles: string[]): this {\n const key = this.getKey('superadmin')\n this._cache.set(key, { roles })\n return this\n }\n\n public getPolicy(intent: string): Optional<AuthPolicy> {\n const key = this.getKey(intent)\n return this._cache.get(key)\n }\n\n private getKey(intent: string): string {\n return `policy:${intent.toLowerCase()}`\n }\n}\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","import type {\n AuthModuleOptions,\n AuthPlugin,\n CacheConfig,\n CachePlugin,\n ContextPlugin,\n DbPlugin,\n HttpConfig,\n HttpPlugin,\n HttpServerPlugin,\n IAppBuilder,\n IConfigurationService,\n IModule,\n IServiceContainer,\n LoggerConfig,\n LoggerPlugin,\n MiddlewareConfig,\n NativeRouteDefinition,\n Nullable,\n PipelinePlugin,\n SetupAction,\n XenoRegistry,\n} from '@xeno-js/shared'\nimport { Guards, LOG_LEVEL, TOKENS } from '@xeno-js/shared'\n\nimport { EnvironmentConfigurationService } from '../configuration'\nimport { ViteConfigurationService } from '../configuration/vite.configuration'\nimport { ServiceContainer } from '../container/service-container'\nimport {\n CacheModule,\n ContextModule,\n CqrsModule,\n LoggerModule,\n MiddlewareModule,\n RouteModule,\n} from '../modules'\nimport { withAuth, withCustomHttp } from '../plugin'\nimport { XenoApplication } from '../xeno_application/xeno.application'\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 * @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 * @author Xeno\n * @version 1.0.0\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-js\n */\nexport class XenoAppBuilder<\n TRegistry extends XenoRegistry = XenoRegistry,\n TApp extends XenoApplication<TRegistry> = XenoApplication<TRegistry>,\n> implements IAppBuilder<TRegistry, TApp> {\n protected _container: IServiceContainer<TRegistry> = new ServiceContainer<TRegistry>()\n protected readonly _configuration: IConfigurationService\n protected _buildPromise: Nullable<Promise<TApp>> = null\n private _pipelinePlugins: PipelinePlugin<TRegistry>[] = []\n private _appFactory: Nullable<(container: IServiceContainer<TRegistry>) => TApp> = null\n\n constructor(\n container?: IServiceContainer<TRegistry>,\n configurationService?: 'vite' | 'node' | IConfigurationService,\n ) {\n this._container = container ?? new ServiceContainer<TRegistry>()\n\n this._configuration = this._getConfigurationService(configurationService)\n this._container.addSingleton(TOKENS.CONFIGURATION_SERVICE, () => this._configuration)\n }\n\n private _getConfigurationService(service?: 'vite' | 'node' | IConfigurationService) {\n if (!Guards.isDefined(service) || service === 'node')\n return new EnvironmentConfigurationService()\n\n if (service === 'vite') return new ViteConfigurationService()\n\n return service\n }\n\n // --- Module Configurations ---\n protected readonly _modules: QueuedModule[] = []\n\n // --- Specific Configurations ---\n private _middlewareConfig: MiddlewareConfig = {\n isSSR: false,\n cors: {\n enabled: true,\n enablePreflight: true,\n withCredentials: true,\n allowOrigins: [],\n allowHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'Accept', 'Origin'],\n },\n rateLimit: {\n enabled: true,\n maxRequests: 100,\n windowSeconds: 60,\n },\n csrf: undefined,\n trustedIpHeader: undefined,\n trustedProxies: [],\n authCookieName: 'sb-access-token',\n }\n private _routes: NativeRouteDefinition<TRegistry>[] = []\n\n // --- Module Queuing Flags ---\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 private _isHttpCoreQueued = false\n private _isHttpServerQueued = false\n private _isRouteModuleQueued = false\n private _isContextModuleQueued = false\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Application Modules Configuration\n // ─────────────────────────────────────────────────────────────────────────────\n\n protected setApplicationFactory(\n factory: (container: IServiceContainer<TRegistry>) => TApp,\n ): this {\n this._appFactory = factory\n return this\n }\n\n /**\n * @description Add http server plugin to the application.\n * @param plugin - The http server plugin to be added.\n * @returns {this} The current instance of the class.\n */\n public addHttpServer(plugin: HttpServerPlugin<TRegistry>): this {\n if (this._isHttpServerQueued) return this\n plugin(this, this._configuration)\n this._isHttpServerQueued = true\n return this\n }\n\n /**\n * @description Add a new route to the application.\n * @param routes - The routes to be added.\n * @returns {this} The current instance of the class.\n */\n public addRoutes(routes: NativeRouteDefinition<TRegistry>[]): this {\n this._routes.push(...routes)\n\n if (this._isRouteModuleQueued) return this\n this._modules.push({\n priority: 5,\n name: 'RouteModule',\n action: async () => {\n const routeModule = new RouteModule<TRegistry>()\n await routeModule.configure(this._container, this._routes)\n },\n })\n this._isRouteModuleQueued = true\n return this\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 * @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 if (this._isMiddlewareModuleQueued) return this\n if (Guards.isDefined(setupAction)) setupAction(this._middlewareConfig, this._configuration)\n\n this._modules.push({\n priority: 4,\n name: 'MiddlewareModule',\n action: async () => {\n const middlewareModule = new MiddlewareModule<TRegistry>()\n await middlewareModule.configure(this._container, {\n ...this._middlewareConfig,\n routes: this._routes,\n })\n },\n })\n\n this._isMiddlewareModuleQueued = true\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 * @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(plugin?: ContextPlugin<TRegistry>): this {\n if (this._isContextModuleQueued) return this\n\n if (Guards.isDefined(plugin)) plugin(this, this._configuration)\n else\n this._modules.push({\n priority: 0,\n name: 'ContextModule',\n action: async () => {\n const contextModule = new ContextModule<TRegistry>()\n await contextModule.configure(this._container)\n },\n })\n\n this._isContextModuleQueued = true\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 custom logging services.\n * @param plugin A LoggerPlugin instance or an array of LoggerPlugin instances to configure the logger.\n * @returns The current instance of AppBuilder for method chaining.\n */\n public addLogger(plugin?: LoggerPlugin<TRegistry> | LoggerPlugin<TRegistry>[]): this\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 custom logging services.\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 * @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(setupAction?: SetupAction<LoggerConfig<TRegistry>, IConfigurationService>): this\n\n public addLogger(\n pluginOrSetup?:\n | LoggerPlugin<TRegistry>\n | LoggerPlugin<TRegistry>[]\n | SetupAction<LoggerConfig<TRegistry>, IConfigurationService>,\n ): this {\n if (this._isLoggerModuleQueued) return this\n\n if (!Guards.isDefined(pluginOrSetup)) {\n this._modules.push({\n priority: 1,\n name: 'LoggerModule',\n action: async () => {\n const module = new LoggerModule<TRegistry>()\n await module.configure(this._container, {\n level: LOG_LEVEL.DEBUG,\n console: true,\n builder: this,\n config: this._configuration,\n })\n },\n })\n } else if (Guards.isArray(pluginOrSetup)) {\n this._modules.push({\n priority: 1,\n name: 'LoggerModule',\n action: async () => {\n const module = new LoggerModule<TRegistry>()\n await module.configure(this._container, {\n console: false,\n builder: this,\n config: this._configuration,\n plugins: pluginOrSetup,\n })\n },\n })\n } else if ((pluginOrSetup as LoggerPlugin<TRegistry>).__kind === 'logger') {\n this._modules.push({\n priority: 1,\n name: 'LoggerModule',\n action: async () => {\n const module = new LoggerModule<TRegistry>()\n await module.configure(this._container, {\n console: false,\n builder: this,\n config: this._configuration,\n plugins: [pluginOrSetup as LoggerPlugin<TRegistry>],\n })\n },\n })\n } else {\n const loggerConfig = {\n console: true,\n level: LOG_LEVEL.DEBUG,\n customLoggers: [],\n }\n const setupAction = pluginOrSetup as SetupAction<\n LoggerConfig<TRegistry>,\n IConfigurationService\n >\n setupAction(loggerConfig, this._configuration)\n this._modules.push({\n priority: 1,\n name: 'LoggerModule',\n action: async () => {\n const module = new LoggerModule<TRegistry>()\n await module.configure(this._container, {\n ...loggerConfig,\n builder: this,\n config: this._configuration,\n })\n },\n })\n }\n\n this._isLoggerModuleQueued = true\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 plugin Optional plugin function to configure the caching module.\n * @defaults The default caching module is the in-memory caching module.\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 addCache(plugin?: CachePlugin<TRegistry>): this\n public addCache(setupAction?: SetupAction<CacheConfig, IConfigurationService>): this\n public addCache(\n pluginOrSetup?: CachePlugin<TRegistry> | SetupAction<CacheConfig, IConfigurationService>,\n ): this {\n if (this._isCacheModuleQueued) return this\n\n if (!Guards.isDefined(pluginOrSetup))\n this._modules.push({\n priority: 2,\n name: 'CacheModule',\n action: async () => {\n await new CacheModule<TRegistry>().configure(this._container, { inMemory: true })\n },\n })\n else if ((pluginOrSetup as CachePlugin<TRegistry>).__kind === 'cache')\n (pluginOrSetup as CachePlugin<TRegistry>)(this, this._configuration)\n else {\n const cacheConfig: CacheConfig = {\n inMemory: true,\n }\n const setupAction = pluginOrSetup as SetupAction<CacheConfig, IConfigurationService>\n\n setupAction(cacheConfig, this._configuration)\n\n this._modules.push({\n priority: 2,\n name: 'CacheModule',\n action: async () => {\n await new CacheModule<TRegistry>().configure(this._container, cacheConfig)\n },\n })\n }\n\n this._isCacheModuleQueued = true\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 plugin A plugin function that configures the authentication client.\n * @returns The current instance of AppBuilder for method chaining.\n */\n public addAuth(plugin: AuthPlugin<TRegistry>): this\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 function that configures the authentication client.\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 addAuth(\n setupAction: SetupAction<AuthModuleOptions<TRegistry>, IConfigurationService>,\n ): this\n\n public addAuth(\n pluginOrSetup:\n AuthPlugin<TRegistry> | SetupAction<AuthModuleOptions<TRegistry>, IConfigurationService>,\n ): this {\n if (this._isAuthModuleQueued) return this\n if ((pluginOrSetup as AuthPlugin<TRegistry>).__kind === 'auth')\n (pluginOrSetup as AuthPlugin<TRegistry>)(this, this._configuration)\n else {\n withAuth<TRegistry>(\n pluginOrSetup as SetupAction<AuthModuleOptions<TRegistry>, IConfigurationService>,\n )(this, this._configuration)\n }\n this._isAuthModuleQueued = true\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 plugin 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 * @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(plugin: DbPlugin<TRegistry>): this {\n if (this._isDbContextModuleQueued) return this\n plugin(this, this._configuration)\n this._isDbContextModuleQueued = true\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(\n TOKENS.CONCURRENCY_SERVICE,\n () => new PLimitConcurrencyService(),\n )\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 pluginOrPlugins?: PipelinePlugin<TRegistry> | PipelinePlugin<TRegistry>[],\n ): this {\n if (this._isPipelineModuleQueued) return this\n\n if (Guards.isDefined(pluginOrPlugins))\n this._pipelinePlugins = Guards.isArray(pluginOrPlugins) ? pluginOrPlugins : [pluginOrPlugins]\n\n this._modules.push({\n priority: 5,\n name: 'CqrsModule',\n action: async () => {\n await new CqrsModule<TRegistry>().configure(this._container, {\n plugins: this._pipelinePlugins,\n builder: this,\n })\n },\n })\n\n this._isPipelineModuleQueued = true\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 and HTTP client configuration.\n * @param plugin A HttpPlugin object that contains the HTTP core configuration.\n * @returns The current instance of AppBuilder for method chaining.\n */\n public addHttpClient(plugin: HttpPlugin<TRegistry>): this\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 SetupAction<HttpConfig, IConfigurationService> object to configure the HTTP core settings.\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 addHttpClient(setupAction: SetupAction<HttpConfig, IConfigurationService>): this\n\n public addHttpClient(\n pluginOrSetup: HttpPlugin<TRegistry> | SetupAction<HttpConfig, IConfigurationService>,\n ): this {\n if (this._isHttpCoreQueued) return this\n if ((pluginOrSetup as HttpPlugin<TRegistry>).__kind === 'http')\n (pluginOrSetup as HttpPlugin<TRegistry>)(this, this._configuration)\n else {\n const httpConfig: HttpConfig = {\n clients: [],\n }\n const setupAction = pluginOrSetup as SetupAction<HttpConfig, IConfigurationService>\n setupAction(httpConfig, this._configuration)\n withCustomHttp<TRegistry>(httpConfig)(this, this._configuration)\n }\n\n this._isHttpCoreQueued = true\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 priority = 99,\n ): this {\n this._modules.push({\n priority,\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>(\n name: string,\n factory: () => Promise<IModule<TRegistry, T>>,\n opts?: T,\n priority = 50,\n ): this {\n this._modules.push({\n priority,\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 * @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 * @author Xeno\n * @version 1.0.0\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-js\n */\n public build(): Promise<TApp> {\n if (Guards.isDefined(this._buildPromise)) {\n return this._buildPromise\n }\n\n const attempt = this._executeBuild()\n this._buildPromise = attempt\n\n void attempt.then(\n () => {\n /* noop */\n },\n async () => {\n if (this._buildPromise === attempt) {\n this._buildPromise = null\n await this._resetContainer()\n }\n },\n )\n\n return attempt\n }\n\n protected async _resetContainer(): Promise<void> {\n await this._container.dispose()\n this._container = new ServiceContainer<TRegistry>()\n this._container.addSingleton(TOKENS.CONFIGURATION_SERVICE, () => this._configuration)\n }\n\n /**\n * @description Executes the build process by initializing all registered modules in the container.\n */\n private async _executeBuild(): Promise<TApp> {\n console.info('⚙️ Bootstrapping application modules...')\n if (!this._isContextModuleQueued) {\n if (this._configuration instanceof ViteConfigurationService)\n throw new Error(\n 'Cannot add node context module to the application builder when using ViteConfigurationService. \\nPlease use addContext passing a context plugin such as withPiniaContext() from @xeno-js/vue',\n )\n else this.addContext()\n }\n\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 if (Guards.isDefined(this._appFactory)) return this._appFactory(this._container)\n\n return new XenoApplication<TRegistry>(this._container) as TApp\n }\n}\n","import type { IConfigurationService } from '@xeno-js/shared'\nimport type { Dictionary, Optional } from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\n/**\n * @description\n * This class implements the IConfigurationService interface and provides methods to retrieve configuration values from environment variables.\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 EnvironmentConfigurationService implements IConfigurationService {\n /**\n * @description Internal dictionary to hold environment variables.\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 readonly _env: Dictionary<Optional<string>>\n\n /**\n * @description Constructs an instance of EnvironmentConfigurationService and initializes the internal environment variable dictionary.\n * @author Xeno\n * @version 1.0.0\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-js\n */\n constructor() {\n this._env = process.env\n }\n\n public get(key: string, defaultValue?: string): Optional<string> {\n const value = this._env[key]\n if (Guards.isNullOrEmpty(value)) {\n return defaultValue\n }\n return value\n }\n\n public getEnvironment(): string {\n return this._env.NODE_ENV ?? 'development'\n }\n\n public getNumber(key: string, defaultValue?: number): Optional<number> {\n const value = this.get(key)\n if (Guards.isNullOrEmpty(value)) {\n return defaultValue\n }\n const parsed = Number(value)\n if (isNaN(parsed)) {\n throw new Error(\n `[Configuration Error]: Key \"${key}\" with value \"${value}\" is not a valid number.`,\n )\n }\n return parsed\n }\n\n public getBoolean(key: string, defaultValue?: boolean): Optional<boolean> {\n const value = this.get(key)\n if (Guards.isNullOrEmpty(value)) {\n return defaultValue\n }\n const normalized = value.toLowerCase().trim()\n if (normalized === 'true' || normalized === '1') return true\n if (normalized === 'false' || normalized === '0') return false\n\n throw new Error(\n `[Configuration Error]: Key \"${key}\" with value \"${value}\" is not a valid boolean.`,\n )\n }\n\n public getOrThrow(key: string): string {\n const value = this.get(key)\n if (!Guards.isDefined(value)) {\n throw new Error(\n `[Configuration Error]: Required configuration key \"${key}\" is missing in the environment.`,\n )\n }\n return value\n }\n}\n","import type { Dictionary, IConfigurationService, Optional } from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\ndeclare global {\n interface ImportMeta {\n env: Dictionary\n }\n}\n\nconst VITE_PREFIX = 'VITE_'\n\n/**\n * @description Implementation of IConfigurationService for Vite/Browser environments.\n * Encapsulates environment variable reading with type-safety and default fallbacks.\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 ViteConfigurationService implements IConfigurationService {\n constructor(private readonly _env: Dictionary = import.meta.env ?? {}) {}\n\n public get(key: string, defaultValue?: string): Optional<string> {\n const fullKey = key.startsWith(VITE_PREFIX) ? key : `VITE_${key}`\n const value = String(this._env[fullKey])\n\n if (!Guards.isNullOrEmpty(value)) return value\n\n return defaultValue\n }\n\n public getNumber(key: string, defaultValue?: number): Optional<number> {\n const rawValue = this.get(key)\n if (Guards.isDefined(rawValue)) {\n const parsed = Number(rawValue)\n if (!Number.isNaN(parsed)) return parsed\n }\n return defaultValue\n }\n\n public getBoolean(key: string, defaultValue?: boolean): Optional<boolean> {\n const rawValue = this.get(key)\n if (Guards.isDefined(rawValue)) {\n const str = String(rawValue).toLowerCase().trim()\n if (str.toLowerCase() === 'true' || str === '1') return true\n if (str.toLowerCase() === 'false' || str === '0') return false\n }\n return defaultValue\n }\n\n public getOrThrow(key: string): string {\n const val = this.get(key)\n if (!Guards.isDefined(val)) {\n throw new Error(`[Configuration Error]: Missing required environment variable \"${key}\".`)\n }\n return val\n }\n\n public getEnvironment(): string {\n return (this._env.MODE as string) ?? 'development'\n }\n}\n","// import { AsyncLocalStorage } from 'node:async_hooks'\n\nimport type {\n Factory,\n IDisposable,\n IServiceContainer,\n IServiceScope,\n Lifetime,\n Optional,\n XenoRegistry,\n} from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * @description Represents a registration entry in the service container, encapsulating the token, lifetime, and factory function for creating instances of the service.\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 RegistrationEntry<T, Registry extends XenoRegistry = XenoRegistry> {\n /**\n * The unique injection token that identifies the service registration.\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 token: keyof Registry\n /**\n * The lifetime of the service registration, indicating how instances are managed and reused.\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 lifetime: Lifetime\n /**\n * The factory function responsible for creating instances of the service.\n * It receives the current service scope as an argument, allowing for dependency resolution within that scope.\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 factory: Factory<T, [IServiceScope<Registry>]>\n}\n\n/**\n * @description Represents the context of service resolution, including the stack of tokens being resolved and the active lifetime of the current resolution.\n * @author Xeno\n * @version 1.0.0\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-js\n */\ninterface ResolutionContext<Registry> {\n /**\n * A set of tokens currently being resolved, used to detect circular dependencies.\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 stack: Set<keyof Registry>\n /**\n * The active lifetime of the current resolution, indicating whether we are constructing a singleton, scoped, or transient service.\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 activeLifetime?: Lifetime\n}\n\n/**\n * @description Concrete implementation of {@link IServiceScope}, representing a logical scope for resolving scoped services within the service container.\n * @author Xeno\n * @version 1.0.0\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-js\n */\nclass ContainerScope<\n Registry extends XenoRegistry = XenoRegistry,\n> implements IServiceScope<Registry> {\n private readonly scopedInstances = new Map<keyof Registry, unknown>()\n private readonly trackedDisposables: unknown[] = []\n private isDisposed = false\n\n constructor(\n private readonly container: ServiceContainer<Registry>,\n private readonly parentScope?: ContainerScope<Registry>,\n ) {}\n\n public resolve<K extends keyof Registry>(token: K): Registry[K] {\n if (this.isDisposed) {\n throw new Error(\n `[DI Container Error]: Unable to resolve '${token as string}'. The scope has been closed.`,\n )\n }\n return this.container.internalExecuteInContext(() =>\n this.container.internalResolveInternal(token, this),\n )\n }\n\n public getScopedInstance<K extends keyof Registry>(token: K): Registry[K] | undefined {\n return this.scopedInstances.get(token) as Registry[K] | undefined\n }\n\n public setScopedInstance<K extends keyof Registry>(token: K, instance: Registry[K]): void {\n this.scopedInstances.set(token, instance)\n if (isDisposable.check(instance)) {\n this.trackedDisposables.push(instance)\n }\n }\n\n public trackInstance(instance: unknown): void {\n if (isDisposable.check(instance) && !this.trackedDisposables.includes(instance)) {\n this.trackedDisposables.push(instance)\n }\n }\n\n public async dispose(): Promise<void> {\n if (this.isDisposed) return\n this.isDisposed = true\n\n for (let i = this.trackedDisposables.length - 1; i >= 0; i--) {\n const disposable = this.trackedDisposables[i]\n if (isDisposable.check(disposable)) {\n try {\n await disposable.dispose()\n } catch (err) {\n console.error(`[DI Container Dispose Error]: Failed to dispose resource`, err)\n }\n }\n }\n\n this.scopedInstances.clear()\n this.trackedDisposables.length = 0\n }\n}\n\n/**\n * @description Concrete implementation of {@link IServiceContainer}.\n *\n * Supports three registration lifetimes:\n * - **singleton** — one shared instance per container.\n * - **transient** — a new instance on every {@link resolve} call.\n * - **scoped** — one instance per {@link IServiceScope}; must be resolved\n * through a scope obtained via {@link createScope}.\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 ServiceContainer<\n Registry extends XenoRegistry = XenoRegistry,\n> implements IServiceContainer<Registry> {\n private readonly registrations = new Map<keyof Registry, RegistrationEntry<unknown, Registry>>()\n private readonly singletonInstances = new Map<keyof Registry, unknown>()\n private readonly rootScope: ContainerScope<Registry>\n private resolutionStack: Optional<ResolutionContext<Registry>> = undefined\n\n constructor() {\n this.rootScope = new ContainerScope<Registry>(this)\n }\n\n public addSingleton<K extends keyof Registry>(\n token: K,\n factory: Factory<Registry[K], [IServiceScope<Registry>]>,\n ): this {\n this.register(token, 'singleton', factory)\n return this\n }\n\n public addScoped<K extends keyof Registry>(\n token: K,\n factory: Factory<Registry[K], [IServiceScope<Registry>]>,\n ): this {\n this.register(token, 'scoped', factory)\n return this\n }\n\n public addTransient<K extends keyof Registry>(\n token: K,\n factory: Factory<Registry[K], [IServiceScope<Registry>]>,\n ): this {\n this.register(token, 'transient', factory)\n return this\n }\n\n private register<K extends keyof Registry>(\n token: K,\n lifetime: Lifetime,\n factory: Factory<Registry[K], [IServiceScope<Registry>]>,\n ): void {\n if (this.registrations.has(token)) {\n const tokenName = token.toString()\n throw new Error(\n `[DI Container Error]: The token '${tokenName}' is already registered in the container.`,\n )\n }\n this.registrations.set(token, { token, lifetime, factory })\n }\n\n public resolve<K extends keyof Registry>(token: K): Registry[K] {\n const registration = this.registrations.get(token)\n\n if (registration?.lifetime === 'scoped') {\n throw new Error(\n `[DI Container Error]: Scoped service '${String(token)}' requires an active scope.`,\n )\n }\n\n return this.internalExecuteInContext(() => this.rootScope.resolve(token))\n }\n\n public isRegistered<K extends keyof Registry>(token: K): boolean {\n return this.registrations.has(token)\n }\n\n public createScope(): IServiceScope<Registry> {\n return new ContainerScope<Registry>(this, this.rootScope)\n }\n\n /**\n * Executes a callback function within the context of the service container's resolution stack.\n * This method ensures that the resolution stack is properly managed, allowing for circular dependency detection and lifetime tracking during service resolution.\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 internalExecuteInContext<T>(callback: () => T): T {\n if (Guards.isDefined(this.resolutionStack)) return callback()\n\n this.resolutionStack = {\n stack: new Set<keyof Registry>(),\n }\n\n try {\n return callback()\n } finally {\n this.resolutionStack = undefined\n }\n }\n\n /**\n * Resolve the service for the given token within the provided scope.\n * @param token The injection token to resolve.\n * @param currentScope The current service scope for resolving scoped services.\n * @returns The resolved service instance of type `T`.\n * @throws An error if no registration is found for the given token.\n * @throws An error if a circular dependency is detected.\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 internalResolveInternal<K extends keyof Registry>(\n token: K,\n currentScope: ContainerScope<Registry>,\n ): Registry[K] {\n const registration = this.registrations.get(token)\n if (!Guards.isDefined(registration)) {\n const tokenName = token.toString()\n throw new Error(\n `[DI Container Error]: Registration not found for token '${tokenName}'. Ensure the service is registered before resolving.`,\n )\n }\n\n const currentStack = this.resolutionStack\n if (!Guards.isDefined(currentStack)) {\n throw new Error(`[DI Container Error]: Execution outside the IoC container context.`)\n }\n\n if (currentStack.stack.has(token)) {\n const cyclePath = [...currentStack.stack, token].map((t) => t.toString()).join(' -> ')\n const tokenName = token.toString()\n throw new Error(\n `[DI Circular Dependency Error]: Detected circular dependency while resolving '${tokenName}'. Resolution path: ${cyclePath}`,\n )\n }\n\n if (currentStack.activeLifetime === 'singleton' && registration.lifetime === 'scoped') {\n const captivePath = [...currentStack.stack, token].map((t) => t.toString()).join(' -> ')\n throw new Error(\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}`,\n )\n }\n\n const executeWithStackIsolation = (\n targetLifetime: Lifetime,\n factoryFn: () => Registry[K],\n ): Registry[K] => {\n const previousLifetime = currentStack.activeLifetime\n currentStack.stack.add(token)\n\n currentStack.activeLifetime =\n registration.lifetime === 'singleton' ? 'singleton' : previousLifetime\n try {\n return factoryFn()\n } finally {\n currentStack.stack.delete(token)\n currentStack.activeLifetime = previousLifetime\n }\n }\n\n if (registration.lifetime === 'singleton') {\n if (this.singletonInstances.has(token)) {\n return this.singletonInstances.get(token) as Registry[K]\n }\n\n return executeWithStackIsolation('singleton', () => {\n const instance = registration.factory(this.rootScope) as Registry[K]\n this.singletonInstances.set(token, instance)\n this.rootScope.trackInstance(instance)\n return instance\n })\n }\n\n if (registration.lifetime === 'scoped') {\n const existingInstance = currentScope.getScopedInstance(token)\n if (Guards.isDefined(existingInstance)) {\n return existingInstance\n }\n\n return executeWithStackIsolation('scoped', () => {\n const instance = registration.factory(currentScope) as Registry[K]\n currentScope.setScopedInstance(token, instance)\n return instance\n })\n }\n\n return executeWithStackIsolation('transient', () => {\n const instance = registration.factory(currentScope) as Registry[K]\n if (isDisposable.check(instance)) {\n currentScope.trackInstance(instance)\n }\n return instance\n })\n }\n\n public async dispose(): Promise<void> {\n await this.rootScope.dispose()\n this.singletonInstances.clear()\n this.registrations.clear()\n }\n}\n\nconst isDisposable = Object.freeze({\n check: (obj: unknown): obj is IDisposable => {\n return (\n Guards.isDefined(obj) &&\n Guards.isObject(obj) &&\n 'dispose' in obj &&\n Guards.hasMethod(obj, 'dispose')\n )\n },\n} as const)\n","import type { AuthModuleOptions, IModule, IServiceContainer, XenoRegistry } from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\nimport { TOKENS } from '@xeno-js/shared'\n\nimport { BearerTokenExtractor, CookieHandler } from '../services'\n\n/**\n * @description AuthModule is responsible for registering authentication services and\n * the token extractor in the IoC container. If no custom tokenExtractor is provided,\n * it falls back to the default BearerTokenExtractor.\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 AuthModule<TRegistry extends XenoRegistry = XenoRegistry> implements IModule<\n TRegistry,\n AuthModuleOptions<TRegistry>\n> {\n public async configure(\n container: IServiceContainer<TRegistry>,\n opts: AuthModuleOptions<TRegistry>,\n ): Promise<void> {\n if (!Guards.isDefined(opts.authService))\n throw new Error(\n '[AuthModule Error]: An authService instance is required to configure AuthModule.',\n )\n\n if (Guards.isDefined(opts.cookieHandlerOptions)) {\n if (Guards.isDefined(opts.cookieHandlerOptions.cookieHandlerCustom)) {\n container.addScoped(TOKENS.COOKIE_HANDLER, (c) =>\n opts.cookieHandlerOptions!.cookieHandlerCustom!(c),\n )\n } else if (\n Guards.isDefined(opts.cookieHandlerOptions.enableDefault) &&\n opts.cookieHandlerOptions.enableDefault.enable\n ) {\n container.addScoped(\n TOKENS.COOKIE_HANDLER,\n (c) =>\n new CookieHandler(\n c.resolve(TOKENS.NETWORK_CONTEXT_ACCESSOR),\n c.resolve(TOKENS.CONFIGURATION_SERVICE),\n opts.cookieHandlerOptions!.enableDefault?.options,\n ),\n )\n }\n }\n\n this.getExtractor(opts, container)\n\n container.addScoped(TOKENS.AUTH_SERVICE, (c) => opts.authService(c))\n container.addScoped(TOKENS.BASE_AUTH_SERVICE, (c) => c.resolve(TOKENS.AUTH_SERVICE))\n }\n\n private getExtractor(\n opts: AuthModuleOptions<TRegistry>,\n container: IServiceContainer<TRegistry>,\n ): void {\n if (Guards.isDefined(opts.tokenExtractor)) {\n container.addSingleton(TOKENS.TOKEN_SERVICE_EXTRACTOR, (c) => opts.tokenExtractor!(c))\n } else {\n container.addSingleton(\n TOKENS.TOKEN_SERVICE_EXTRACTOR,\n () => new BearerTokenExtractor(opts.defaultCookieName ?? 'sb-access-token'),\n )\n }\n }\n}\n","import type { IAllowMethod } from '@xeno-js/shared'\nimport { Guards, type HttpMethod, type Optional, RoutePatternHelper } from '@xeno-js/shared'\n\ninterface DynamicRoute {\n pattern: RegExp\n methods: HttpMethod[]\n}\n\nexport class AllowMethodRegistry implements IAllowMethod {\n private readonly _staticRoutes = new Map<string, HttpMethod[]>()\n private readonly _dynamicRoutes: DynamicRoute[] = []\n\n public add(path: string, methods: HttpMethod[]): void {\n const normalizedPath = RoutePatternHelper.normalizePath(path)\n if (RoutePatternHelper.isDynamicPath(normalizedPath)) {\n const pattern = RoutePatternHelper.createRoutePattern(normalizedPath)\n this._dynamicRoutes.push({ pattern, methods })\n } else {\n this._staticRoutes.set(normalizedPath, methods)\n }\n }\n\n public check(path: string, method: HttpMethod): boolean {\n const cleanPath = RoutePatternHelper.normalizePath(path.split('?')[0].split('#')[0])\n const staticMethods = this._staticRoutes.get(cleanPath)\n if (Guards.isDefined(staticMethods)) return staticMethods.includes(method)\n for (const route of this._dynamicRoutes) {\n if (route.pattern.test(cleanPath)) return route.methods.includes(method)\n }\n return false\n }\n\n public getMethods(path: string): string {\n const cleanPath = RoutePatternHelper.normalizePath(path.split('?')[0].split('#')[0])\n const methods = this.findMethods(cleanPath)\n return Guards.isDefined(methods) ? methods.join(', ').toUpperCase() : ''\n }\n\n private findMethods(cleanPath: string): Optional<HttpMethod[]> {\n const staticMethods = this._staticRoutes.get(cleanPath)\n if (Guards.isDefined(staticMethods)) return staticMethods\n for (const route of this._dynamicRoutes) {\n if (route.pattern.test(cleanPath)) return route.methods\n }\n return undefined\n }\n}\n","import type { Optional } from '@xeno-js/shared'\nimport type { IAllowOrigin } from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\n/**\n * @description A class that implements the IAllowOrigin interface.\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 AllowOrigin implements IAllowOrigin {\n constructor(private readonly _list: string[]) {}\n\n public isAllowed(origin: Optional<string>): boolean {\n if (Guards.isNullOrEmpty(origin)) return true\n\n const cleanOrigin = origin.trim().toLowerCase()\n\n for (const pattern of this._list) {\n const cleanPattern = pattern.trim().toLowerCase()\n\n if (cleanPattern === '*') return true\n\n if (cleanPattern === cleanOrigin) return true\n\n if (cleanPattern.startsWith('*.')) {\n const domainSuffix = cleanPattern.substring(1)\n if (cleanOrigin.endsWith(domainSuffix)) {\n const prefix = cleanOrigin.slice(0, cleanOrigin.length - domainSuffix.length)\n if (!Guards.isNullOrEmpty(prefix) && !prefix.includes('.')) return true\n }\n }\n }\n\n return false\n }\n}\n","export * from './allow_methods/index'\nexport * from './allow_origins/index'\nexport * from './concurrency/index'\nexport * from './cookies/index'\nexport * from './crypto/index'\nexport * from './csrf/index'\nexport * from './extractors/index'\nexport * from './resolver/index'\n","import type { IConfigurationService, INetworkContextAccessor } from '@xeno-js/shared'\nimport type { ISsrCookie, ISsrCookieHandler, ISsrCookieToSet } from '@xeno-js/shared'\nimport { Guards, HttpHelper } from '@xeno-js/shared'\n\n/**\n *\n */\nexport class CookieHandler implements ISsrCookieHandler {\n private readonly _pendingCookies: ISsrCookieToSet[] = []\n\n constructor(\n private readonly _contextAccessor: INetworkContextAccessor,\n private readonly _config: IConfigurationService,\n private readonly _defaultOpts?: Partial<ISsrCookieToSet>,\n ) {}\n\n public getAll(): ISsrCookie[] {\n const network = this._contextAccessor.getNetworkContext()\n const cookie = network?.cookies\n\n if (Guards.isNullOrEmpty(cookie)) return []\n\n const parsedCookies = HttpHelper.parseCookies(network?.cookies)\n\n return Object.entries(parsedCookies).map(([name, value]) => ({\n name,\n value,\n }))\n }\n\n public setAll(cookies: ISsrCookieToSet[]): void {\n this._pendingCookies.push(...cookies)\n }\n\n public getPendingCookies(): string[] {\n return this._pendingCookies.map((c) => this.serialize(c))\n }\n\n private serialize(cookie: ISsrCookieToSet): string {\n const safeName = encodeURIComponent(cookie.name)\n const safeValue = encodeURIComponent(cookie.value ?? '')\n let str = `${safeName}=${safeValue}`\n\n const isProd = this._config.get('NODE_ENV') === 'production'\n const merged: ISsrCookieToSet = {\n path: '/',\n httpOnly: true,\n secure: isProd,\n sameSite: 'lax',\n ...this._defaultOpts,\n ...cookie,\n }\n\n if (!Guards.isNullOrEmpty(merged.path)) str += `; Path=${merged.path}`\n\n if (!Guards.isNullOrEmpty(merged.maxAge)) str += `; Max-Age=${merged.maxAge}`\n\n if (!Guards.isNullOrEmpty(merged.expires)) str += `; Expires=${merged.expires.toUTCString()}`\n\n if (!Guards.isNullOrEmpty(merged.domain)) str += `; Domain=${merged.domain}`\n\n if (!Guards.isNullOrEmpty(merged.secure) && merged.secure) str += '; Secure'\n\n if (!Guards.isNullOrEmpty(merged.httpOnly) && merged.httpOnly) str += '; HttpOnly'\n\n if (!Guards.isNullOrEmpty(merged.sameSite)) {\n if (Guards.isBoolean(merged.sameSite)) {\n str += merged.sameSite ? '; SameSite=Strict' : ''\n } else {\n const val = merged.sameSite.toLowerCase()\n const formatted = val.charAt(0).toUpperCase() + val.slice(1)\n str += `; SameSite=${formatted}`\n }\n }\n\n if (Guards.isDefined(merged.partitioned)) str += '; Partitioned'\n\n if (Guards.isDefined(merged.priority)) {\n const p = merged.priority.toLowerCase()\n const formattedPriority = p.charAt(0).toUpperCase() + p.slice(1)\n str += `; Priority=${formattedPriority}`\n }\n\n return str\n }\n}\n","import type { ICryptoService } from '@xeno-js/shared'\n\n/**\n * @description The EdgeCryptoService class implements the ICryptoService interface, providing a concrete implementation for cryptographic operations using the Web Cryptography API.\n *\n */\nexport class EdgeCryptoService implements ICryptoService {\n public randomBytes(size: number): Uint8Array {\n const buffer = new Uint8Array(size)\n crypto.getRandomValues(buffer)\n return buffer\n }\n\n public async hmacSha256(secret: string, data: string): Promise<string> {\n const encoder = new TextEncoder()\n const keyData = encoder.encode(secret)\n const messageData = encoder.encode(data)\n\n const cryptoKey = await crypto.subtle.importKey(\n 'raw',\n keyData,\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign'],\n )\n\n const signature = await crypto.subtle.sign('HMAC', cryptoKey, messageData)\n\n // Converte l'ArrayBuffer risultante in una stringa base64url compatibile\n return btoa(String.fromCharCode(...new Uint8Array(signature)))\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=/g, '')\n }\n\n public timingSafeEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) {\n return false\n }\n let mismatch = 0\n for (let i = 0; i < a.length; i++) {\n mismatch |= a[i] ^ b[i]\n }\n return mismatch === 0\n }\n}\n","import type { ICryptoService, ICsrfTokenService } from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\n/**\n * @description Service for generating and validating CSRF tokens\n */\nexport class CsrfTokenService implements ICsrfTokenService {\n constructor(\n private readonly _secret: string,\n private readonly _cryptoService: ICryptoService,\n ) {}\n\n public async generate(subject: string): Promise<string> {\n const randomBuffer = this._cryptoService.randomBytes(32)\n const nonce = btoa(String.fromCharCode(...randomBuffer))\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=/g, '')\n\n const signature = await this._cryptoService.hmacSha256(this._secret, `${subject}.${nonce}`)\n\n return `${nonce}.${signature}`\n }\n\n public async validate(token: string, subject: string): Promise<boolean> {\n const separatorIndex = token.indexOf('.')\n\n if (separatorIndex <= 0) return false\n\n const nonce = token.slice(0, separatorIndex)\n const signature = token.slice(separatorIndex + 1)\n\n if (Guards.isNullOrEmpty(nonce) || Guards.isNullOrEmpty(signature)) return false\n\n const expected = await this._cryptoService.hmacSha256(this._secret, `${subject}.${nonce}`)\n\n const encoder = new TextEncoder()\n const actualBuffer = encoder.encode(signature)\n const expectedBuffer = encoder.encode(expected)\n\n if (actualBuffer.length !== expectedBuffer.length) return false\n\n return this._cryptoService.timingSafeEqual(actualBuffer, expectedBuffer)\n }\n}\n","import type { IServiceExtractor, Optional } from '@xeno-js/shared'\nimport { Guards, HttpHelper } from '@xeno-js/shared'\n\n/**\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.\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 BearerTokenExtractor implements IServiceExtractor<\n Request['headers'],\n Optional<string>\n> {\n constructor(private readonly _cookiePrefix: string) {}\n extract(headers: Request['headers']): Optional<string> {\n const authHeader = headers.get('Authorization')\n\n if (Guards.isDefined(authHeader) && authHeader.toLowerCase().startsWith('bearer ')) {\n return authHeader.substring(7)\n }\n\n const cookieHeader = headers.get('cookie')\n if (Guards.isDefined(cookieHeader)) {\n const cookies = HttpHelper.parseCookies(cookieHeader)\n const token = cookies[this._cookiePrefix]\n\n if (Guards.isDefined(token)) {\n return token\n }\n }\n\n return undefined\n }\n}\n","import { Guards, HttpHelper, type IServiceExtractor, type Optional } from '@xeno-js/shared'\n\n/**\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.\n */\nexport class HttpCookieExtractor implements IServiceExtractor<\n {\n header: Optional<string>\n name: string\n },\n Optional<string>\n> {\n extract(cookie: { header: Optional<string>; name: string }): Optional<string> {\n if (!Guards.isDefined(cookie.header)) return undefined\n\n const cookies = HttpHelper.parseCookies(cookie.header)\n return cookies[cookie.name]\n }\n}\n","import type { IServiceExtractor } from '@xeno-js/shared'\nimport type { Metadata } from '@xeno-js/shared'\nimport { Guards, GuidHelper, HttpHelper, MathHelper, type Optional } from '@xeno-js/shared'\n\n/**\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.\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 HttpHeaderExtractor implements IServiceExtractor<Request['headers'], Metadata> {\n /**\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.\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 constructor(\n private readonly _cookieExtractor: IServiceExtractor<\n {\n header: Optional<string>\n name: string\n },\n Optional<string>\n >,\n private readonly _trustedIp: Optional<string>,\n private readonly _cookieName: string,\n private readonly _csrfCookieHeader = 'x-csrf-token',\n ) {}\n\n extract(headers: Request['headers']): Metadata {\n const correlationId = GuidHelper.parse(headers.get('x-correlation-id') ?? undefined)\n const requestId = GuidHelper.parse(headers.get('x-request-id') ?? undefined)\n const clientIp =\n headers.get(this._trustedIp?.toLowerCase() ?? 'x-forwarded-for') ??\n headers.get('x-real-ip') ??\n undefined\n const spanId = GuidHelper.parse(headers.get('x-span-id') ?? undefined)\n const parentSpanId = headers.get('x-parent-span-id') ?? undefined\n const acceptHeader = headers.get('accept') ?? undefined\n const contentTypeHeader = headers.get('content-type') ?? undefined\n const userAgent = headers.get('user-agent') ?? undefined\n const returnAddress = headers.get('x-return-address') ?? undefined\n const sequenceId = headers.get('x-sequence-id') ?? undefined\n const position = headers.get('x-sequence-position')\n const size = headers.get('x-sequence-size')\n const expiration = headers.get('x-expiration')\n\n const csrf = headers.get(this._csrfCookieHeader) ?? undefined\n const cookieHeader = headers.get('cookie') ?? undefined\n const csrfCookie = this._cookieExtractor.extract({\n header: cookieHeader,\n name: this._cookieName,\n })\n const origin = headers.get('origin') ?? undefined\n const cleanOrigin = HttpHelper.sanitizeOriginUrl(origin)\n const referer = headers.get('referer') ?? undefined\n const cleanReferer = HttpHelper.sanitizeOriginUrl(referer)\n\n const formatIndicator = HttpHelper.resolveFormatIndicator(acceptHeader, contentTypeHeader)\n\n const metadata: Metadata = {\n correlationId,\n requestId,\n clientIp,\n spanId,\n parentSpanId,\n formatIndicator,\n userAgent,\n returnAddress,\n csrf,\n csrfCookie,\n cookies: cookieHeader,\n origin: cleanOrigin,\n referer: cleanReferer,\n sequence: {\n sequenceId,\n position: Guards.isDefined(position) ? MathHelper.toNumber(position) : undefined,\n size: Guards.isDefined(size) ? MathHelper.toNumber(size) : undefined,\n },\n expiration: Guards.isDefined(expiration) ? MathHelper.toNumber(expiration) : undefined,\n }\n\n return metadata\n }\n}\n","import type { Optional, XenoRequest } from '@xeno-js/shared'\nimport type { IIPResolver } from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\n/**\n * @description ClientIpResolver is a resolver that extracts the client IP address from the network context or the socket IP address.\n */\nexport class ClientIpResolver implements IIPResolver {\n constructor(private readonly _trustedProxies: string[] = []) {}\n\n public resolve(req: XenoRequest, clientIp: Optional<string>): Optional<string> {\n const socketIp = req.socket?.remoteAddress\n\n if (!Guards.isDefined(socketIp))\n return !Guards.isNullOrEmpty(clientIp) ? clientIp.split(',')[0].trim() : undefined\n\n const isTrustedProxy = this._trustedProxies.includes(socketIp)\n\n if (!isTrustedProxy) return socketIp\n if (Guards.isDefined(clientIp)) return clientIp.split(',')[0].trim()\n\n return socketIp\n }\n}\n","import type { CacheConfig, IModule, IServiceContainer, XenoRegistry } from '@xeno-js/shared'\nimport { Guards, TOKENS } from '@xeno-js/shared'\n\nimport { CacheKeyBuilder } from '../cache'\nimport { CacheUtils } from './utils'\n\n/**\n * @description CacheModule is responsible for registering cache services in the IoC container. Default implementation is in-memory\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 CacheModule<TRegistry extends XenoRegistry = XenoRegistry> implements IModule<\n TRegistry,\n CacheConfig\n> {\n public async configure(\n container: IServiceContainer<TRegistry>,\n opts: CacheConfig = { inMemory: true },\n ): Promise<void> {\n container.addSingleton(\n TOKENS.CACHE_KEY_BUILDER,\n (c) => new CacheKeyBuilder(c.resolve(TOKENS.IDENTITY_ACCESSOR)),\n )\n\n if (opts.inMemory && Guards.isDefined(opts.provider))\n throw new Error('Cannot use both in memory and provider cache')\n else if (opts.inMemory) {\n await CacheUtils.addCache(container)\n } else if (Guards.isDefined(opts.provider)) {\n container.addSingleton(TOKENS.CACHE, (c) => opts.provider!(c))\n } else throw new Error('No cache provider specified')\n }\n}\n","import type { ICache, IDisposable, Optional } from '@xeno-js/shared'\nimport type { IAtomicCache } from '@xeno-js/shared'\nimport { Guards, StringHelper } from '@xeno-js/shared'\n\ninterface NodeTimeout {\n unref: () => void\n}\n\n/**\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.\n */\nexport class InMemoryCache implements ICache, IAtomicCache, IDisposable {\n private _cleanupInterval: ReturnType<typeof setInterval>\n\n /**\n * @description Constructs a new instance of the InMemoryCache class, which initializes an internal Map to store cached values. The Map is used to associate cache keys with their corresponding values and expiration times, allowing for efficient retrieval and management of cached data. The constructor does not take any parameters, as the in-memory cache is self-contained and does not require external dependencies or configuration.\n * @param _cache An optional Map instance to use as the underlying storage for the cache. If not provided, a new Map will be created to store cached values.\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 constructor(\n private _cache: Map<string, { value: string; expiresAt: Optional<number> }> = new Map(),\n ) {\n this._cleanupInterval = setInterval(() => this.evictExpired(), 300_000)\n if (this._isNodeTimeout(this._cleanupInterval)) {\n this._cleanupInterval.unref()\n }\n }\n\n private _isNodeTimeout(timer: unknown): timer is NodeTimeout {\n return Guards.isDefined(timer) && Guards.isObject(timer) && Guards.hasMethod(timer, 'unref')\n }\n\n public async get<T>(key: string): Promise<Optional<T>> {\n const entry = this._cache.get(key)\n if (!Guards.isDefined(entry)) {\n return undefined\n }\n if (Guards.isDefined(entry.expiresAt) && entry.expiresAt < Date.now()) {\n this._cache.delete(key)\n return undefined\n }\n return JSON.parse(entry.value) as T\n }\n\n public async set<T>(key: string, value: T, ttl: Optional<number>): Promise<void> {\n const expiresAt = Guards.isDefined(ttl) ? Date.now() + ttl * 1000 : undefined\n this._cache.set(key, { value: StringHelper.safeStringify(value), expiresAt })\n }\n\n public async setIfAbsent<T>(key: string, value: T, ttl: Optional<number>): Promise<boolean> {\n if (this._cache.has(key)) {\n return false\n }\n await this.set(key, value, ttl)\n return true\n }\n\n public async remove(key: string): Promise<void> {\n this._cache.delete(key)\n }\n\n public async has(key: string): Promise<boolean> {\n const entry = this._cache.get(key)\n if (!Guards.isDefined(entry)) {\n return false\n }\n if (Guards.isDefined(entry.expiresAt) && entry.expiresAt < Date.now()) {\n this._cache.delete(key)\n return false\n }\n return true\n }\n\n public async clear(): Promise<void> {\n this._cache.clear()\n }\n\n public async increment(key: string, ttlSeconds: Optional<string | number>): Promise<number> {\n const entry = this._cache.get(key)\n const now = Date.now()\n\n if (Guards.isDefined(entry) && (!Guards.isDefined(entry.expiresAt) || entry.expiresAt > now)) {\n const nextValue = Number(StringHelper.safeParse(entry.value)) + 1\n this._cache.set(key, {\n value: StringHelper.safeStringify(nextValue),\n expiresAt: entry.expiresAt,\n })\n return nextValue\n }\n\n const ttl = !Guards.isNullOrEmpty(ttlSeconds) ? Number(ttlSeconds) : 60\n const expiresAt = now + ttl * 1000\n this._cache.set(key, { value: StringHelper.safeStringify(1), expiresAt })\n\n return 1\n }\n\n private evictExpired(): void {\n const now = Date.now()\n for (const [key, entry] of this._cache.entries()) {\n if (!Guards.isDefined(entry.expiresAt) || entry.expiresAt > now) {\n this._cache.delete(key)\n }\n }\n }\n\n public async dispose(): Promise<void> {\n clearInterval(this._cleanupInterval)\n this._cache.clear()\n }\n\n public async removePattern(pattern: string): Promise<void> {\n const escaped = pattern.replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&')\n const regexString = `^${escaped.replace(/\\*/g, '.*')}$`\n const regex = new RegExp(regexString)\n for (const key of this._cache.keys()) {\n if (regex.test(key)) {\n this._cache.delete(key)\n }\n }\n }\n}\n","import type { ICacheKeyBuilder, IIdentityAccessor } from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\n/**\n * @description The CacheKeyBuilder class implements the ICacheKeyBuilder interface, providing a method to build contextual cache 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 cache keys in multi-tenant applications. If a tenant ID is present in the identity, the cache key is prefixed with the tenant ID; otherwise, it defaults to a public cache key. This approach ensures that cached data is appropriately scoped to the user's context, preventing data leakage between tenants.\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 CacheKeyBuilder implements ICacheKeyBuilder {\n /**\n * @description Constructs a new instance of the CacheKeyBuilder class, which requires an IIdentityAccessor to access the current user's identity. The constructor initializes the dependency needed for building contextual cache keys based on the user's identity, enabling tenant-specific caching behavior in multi-tenant applications.\n * @param _identityAccessor An instance of IIdentityAccessor used to retrieve the current user's identity, allowing for the construction of tenant-specific cache keys.\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 constructor(private readonly _identityAccessor: IIdentityAccessor) {}\n\n public buildContextualKey(key: string): string {\n const identity = this._identityAccessor.getIdentity()\n\n if (Guards.isDefined(identity) && !Guards.isNullOrEmpty(identity.tenantId)) {\n return `tenant:${identity.tenantId}:${key}`\n }\n\n return `${key}:public`\n }\n\n public buildUserScopedKey(key: string): string {\n const identity = this._identityAccessor.getIdentity()\n\n if (Guards.isDefined(identity) && !Guards.isNullOrEmpty(identity.userId)) {\n return this.buildContextualKey(`user:${identity.userId}:${key}`)\n }\n\n return this.buildContextualKey(key)\n }\n}\n","import type { Optional, RequestContext } from '@xeno-js/shared'\nimport type { IRateLimitKeyBuilder, IRequestContext, XenoRegistry } from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\n/**\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.\n *\n * @author Xeno\n * @version 1.0.0\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-vue\n * @copyright Xeno\n * @license MIT\n */\nexport class RateLimitKeyBuilder implements IRateLimitKeyBuilder {\n constructor(\n private readonly _contextAccessor: IRequestContext<RequestContext, XenoRegistry<unknown>>,\n ) {}\n\n public buildRateLimitKey(resource: string): Optional<string> {\n const ctx = this._contextAccessor.getContext()\n\n const tenantId = ctx?.identity?.tenantId\n const userId = ctx?.identity?.userId\n const clientIp = ctx?.network?.clientIp\n\n if (!Guards.isNullOrEmpty(tenantId) && !Guards.isNullOrEmpty(userId))\n return `ratelimit:tenant:${tenantId}:user:${userId}:${resource}`\n\n if (!Guards.isNullOrEmpty(tenantId) && !Guards.isNullOrEmpty(clientIp))\n return `ratelimit:tenant:${tenantId}:ip:${clientIp}:${resource}`\n\n if (!Guards.isNullOrEmpty(userId)) return `ratelimit:user:${userId}:${resource}`\n\n if (!Guards.isNullOrEmpty(clientIp)) return `ratelimit:ip:${clientIp}:${resource}`\n\n return undefined\n }\n}\n","import { Guards, type IPipelineBehavior, type IRequest, type IStrategy } from '@xeno-js/shared'\nimport {\n type AuthorizationOptions,\n type IServiceContainer,\n TOKENS,\n type XenoRegistry,\n} from '@xeno-js/shared'\n\nimport {\n AuthorizationPipeline,\n PermissionAuthorizationStrategy,\n PolicyRegistry,\n RoleAuthorizationStrategy,\n TenantAuthorizationStrategy,\n UserAuthorizationStrategy,\n} from '@/application'\n\n/**\n * @description Utility functions for configuring authentication and authorization in the service container.\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 const AuthUtils = Object.freeze({\n /**\n * @description Checks if the provided authorization configuration requires any authorization strategies.\n * @param authorizationConfig The authorization configuration to check.\n * @returns True if any authorization strategies are required, false otherwise.\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 async addAuthZ<TRegistry extends XenoRegistry = XenoRegistry>(\n container: IServiceContainer<TRegistry>,\n opts: AuthorizationOptions<TRegistry>,\n ): Promise<IPipelineBehavior<IRequest<unknown>, unknown>> {\n const strategies: IStrategy<IRequest>[] = []\n\n if (Guards.isDefined(opts.policies)) {\n const policyRegistry = opts.policies\n const registryInstance = new PolicyRegistry()\n const ctxAccessor = container.resolve(TOKENS.CONTEXT_ACCESSOR)\n const Policies = new Set<string>()\n\n if (Guards.isDefined(opts.superadmin)) {\n const superadminRoles = Guards.isArray(opts.superadmin)\n ? opts.superadmin\n : [opts.superadmin]\n registryInstance.setSuperadminRoles(superadminRoles)\n }\n\n for (const [intent, policy] of Object.entries(policyRegistry)) {\n const intentLower = intent.toLowerCase()\n registryInstance.addPolicy(intentLower, policy)\n\n if (!Guards.isNullOrEmpty(policy.roles)) {\n Policies.add('roles')\n }\n\n if (!Guards.isNullOrEmpty(policy.permissions)) {\n Policies.add('permissions')\n }\n\n if (!Guards.isNullOrEmpty(policy.userId)) {\n Policies.add('userId')\n }\n\n if (!Guards.isNullOrEmpty(policy.tenantId)) {\n Policies.add('tenantId')\n }\n }\n\n if (Policies.has('roles')) {\n strategies.push(new RoleAuthorizationStrategy(registryInstance, ctxAccessor))\n }\n\n if (Policies.has('permissions')) {\n strategies.push(new PermissionAuthorizationStrategy(registryInstance, ctxAccessor))\n }\n\n if (Policies.has('userId')) {\n strategies.push(new UserAuthorizationStrategy(registryInstance, ctxAccessor))\n }\n\n if (Policies.has('tenantId')) {\n strategies.push(new TenantAuthorizationStrategy(registryInstance, ctxAccessor))\n }\n }\n\n if (!Guards.isNullOrEmpty(opts.customAuthorizationStrategy)) {\n const customStrategies = opts.customAuthorizationStrategy\n customStrategies.forEach((strategyToken) => {\n if (Guards.isDefined(strategyToken)) {\n strategies.push(strategyToken(container))\n }\n })\n }\n\n return new AuthorizationPipeline(strategies)\n },\n} as const)\n","import type { IServiceContainer, XenoRegistry } from '@xeno-js/shared'\nimport { TOKENS } from '@xeno-js/shared'\n\nimport { InMemoryCache } from '@/infrastructure/cache'\n\n/**\n * @description Utility functions for configuring caching in the service container.\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 const CacheUtils = Object.freeze({\n /**\n * @description Checks if the provided cache configuration requires any cache strategies.\n * @param container The service container to which the cache strategies will be added.\n * @param opts The cache configuration options.\n * @returns True if any cache strategies are required, false otherwise.\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 async addCache<TRegistry extends XenoRegistry = XenoRegistry>(\n container: IServiceContainer<TRegistry>,\n ): Promise<void> {\n container.addSingleton(TOKENS.CACHE, () => new InMemoryCache())\n },\n} as const)\n","import type { ILoggerClient } from '@xeno-js/shared'\nimport type { IServiceContainer, LoggerConfig, XenoRegistry } from '@xeno-js/shared'\nimport { Guards, LOG_LEVEL } from '@xeno-js/shared'\nimport { TOKENS } from '@xeno-js/shared'\n\nimport { BaseLogger } from '@/application'\nimport { ConsoleLogger } from '@/infrastructure/loggers'\n\n/**\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.\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 const LoggerUtils = Object.freeze({\n /**\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.\n *\n * @param container - The service container to register logging services with.\n * @param opts - The LoggerConfig options to determine which loggers to enable and their configurations.\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 async addLogger<TRegistry extends XenoRegistry = XenoRegistry>(\n container: IServiceContainer<TRegistry>,\n opts: LoggerConfig<TRegistry>,\n ): Promise<void> {\n const loggerDependencies: ILoggerClient[] = []\n\n if (opts.console) loggerDependencies.push(new ConsoleLogger(opts?.level))\n\n if (!Guards.isNullOrEmpty(opts.customLoggers)) {\n const customLoggers = opts.customLoggers\n for (const logger of customLoggers) {\n loggerDependencies.push(logger(container))\n }\n }\n\n container.addSingleton(TOKENS.LOGGER, (c) => {\n const context = c.resolve(TOKENS.CONTEXT_ACCESSOR)\n return new BaseLogger(context, opts?.level ?? LOG_LEVEL.DEBUG, loggerDependencies)\n })\n },\n} as const)\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 {\n IModule,\n IRequestContext,\n IServiceContainer,\n Optional,\n RequestContext,\n XenoRegistry,\n} from '@xeno-js/shared'\nimport { Guards, TOKENS } from '@xeno-js/shared'\n\nimport { EventDispatcher } from '../events'\nimport { ServiceScopeFactory, UserContextFactory } from '../factories'\nimport { HttpAdapter } from '../http'\nimport { UrlBuilder } from '../http/url-builder.http'\nimport { CreateServicesProxy } from '../services/service_proxy/services.proxy'\n\n/**\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.\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 ContextModule<TRegistry extends XenoRegistry = XenoRegistry> implements IModule<\n TRegistry,\n Optional<IRequestContext<RequestContext, TRegistry>>\n> {\n async configure(\n container: IServiceContainer<TRegistry>,\n opts?: IRequestContext<RequestContext, TRegistry>,\n ): Promise<void> {\n if (container.isRegistered(TOKENS.REQUEST_CONTEXT)) return\n\n const requestContext = await this._getRequestContext(container, opts)\n\n container.addSingleton(TOKENS.REQUEST_CONTEXT, () => requestContext)\n container.addSingleton(TOKENS.CONTEXT_ACCESSOR, () => requestContext)\n container.addSingleton(TOKENS.IDENTITY_ACCESSOR, () => requestContext)\n container.addSingleton(TOKENS.SERVICE_SCOPE_ACCESSOR, () => requestContext)\n container.addSingleton(TOKENS.NETWORK_CONTEXT_ACCESSOR, () => requestContext)\n container.addSingleton(TOKENS.TRACING_CONTEXT_ACCESSOR, () => requestContext)\n\n container.addSingleton(TOKENS.USER_CONTEXT_FACTORY, () => {\n return new UserContextFactory(requestContext)\n })\n\n const serviceProxy = new CreateServicesProxy()\n container.addSingleton(TOKENS.SERVICE_PROXY, () => serviceProxy)\n\n container.addSingleton(TOKENS.HTTP_ADAPTER, () => new HttpAdapter(new UrlBuilder()))\n\n container.addSingleton(TOKENS.EVENT_DISPATCHER, () => new EventDispatcher())\n }\n\n private async _getRequestContext(\n container: IServiceContainer<TRegistry>,\n opts?: IRequestContext<RequestContext, TRegistry>,\n ) {\n if (Guards.isDefined(opts)) return opts\n\n const { NodeRequestContextFactory } = await import('../factories/request-context.factory')\n return new NodeRequestContextFactory<TRegistry>(\n new ServiceScopeFactory<TRegistry>(container),\n ).create()\n }\n}\n","import type { IEventDispatcher, IEventHandler, Optional, ResultType } from '@xeno-js/shared'\nimport { AppError, Guards, Result } from '@xeno-js/shared'\n\nexport class EventDispatcher implements IEventDispatcher {\n private readonly _handlers = new Map<string, IEventHandler<unknown>[]>()\n\n public subscribe<TEvent>(eventType: string, handler: IEventHandler<TEvent>): void {\n const handlers = this._handlers.get(eventType) ?? []\n handlers.push(handler)\n this._handlers.set(eventType, handlers)\n }\n\n public async publish<TEvent extends { eventType: string }>(\n event: TEvent,\n signal?: Optional<AbortSignal>,\n ): Promise<ResultType<void>> {\n AppError.throwIfAborted(signal, 'EventDispatcher.publish')\n\n const handlers = this._handlers.get(event.eventType)\n if (Guards.isNullOrEmpty(handlers)) return Result.ok()\n\n try {\n for (const handler of handlers) {\n const result = await handler.handle(event, signal)\n if (!result.isOk()) {\n return Result.fail(result.getErrorOrThrow())\n }\n }\n return Result.ok()\n } catch (error) {\n return Result.fail(AppError.internalServerError('EventDispatcher', error))\n }\n }\n}\n","import type { HttpMethod } from '@xeno-js/shared'\nimport type { IAllowMethod, NativeRouteDefinition, XenoRegistry } from '@xeno-js/shared'\n\nimport { AllowMethodRegistry } from '../services'\n\n/**\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.\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 AllowMethodFactory {\n public create<TRegistry extends XenoRegistry = XenoRegistry>(\n opts: NativeRouteDefinition<TRegistry>[],\n ): IAllowMethod {\n const allowMethodService = new AllowMethodRegistry()\n\n const routes = opts ?? []\n const routesMap = new Map<string, HttpMethod[]>()\n for (const r of routes) {\n const methods = routesMap.get(r.path) ?? []\n if (!methods.includes(r.method)) {\n methods.push(r.method)\n }\n routesMap.set(r.path, methods)\n }\n\n for (const [path, methods] of routesMap) {\n allowMethodService.add(path, methods)\n }\n\n return allowMethodService\n }\n}\n","export * from './allow-method.factory'\nexport * from './request-context.factory'\nexport * from './service-scope.factory'\nexport * from './user-context.factory'\n","import type { IFactory } from '@xeno-js/shared'\nimport type { IServiceContainer, IServiceScope, XenoRegistry } from '@xeno-js/shared'\n\n/**\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.\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 ServiceScopeFactory<T extends XenoRegistry = XenoRegistry> implements IFactory<\n void,\n IServiceScope<T>\n> {\n constructor(private readonly _container: IServiceContainer<T>) {}\n\n public create(): IServiceScope<T> {\n return this._container.createScope()\n }\n}\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, IHttpAdapter, XenoIncomingRequest, XenoRequest } from '@xeno-js/shared'\nimport { Guards, HttpHelper, HttpRouteParamHelper } from '@xeno-js/shared'\n\n/**\n * @description Base HTTP adapter.\n * @author Xeno\n * @version 1.2.1\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-js\n */\nexport class HttpAdapter implements IHttpAdapter {\n constructor(private readonly _urlFactory: IFactory<Headers, string>) {}\n /**\n * @description Creates the XenoRequest.\n * @param req The XenoIncomingRequest\n * @returns The XenoRequest.\n */\n public adapt(req: XenoIncomingRequest): XenoRequest {\n const baseUrl = this._urlFactory.create(req.headers)\n const safeUrl = HttpHelper.parseSafeUrl(req.url, baseUrl)\n const method = req.method.toUpperCase()\n\n const init: RequestInit & { duplex?: 'half' } = {\n method,\n headers: req.headers,\n }\n\n const parsedBody = HttpHelper.parseBody(method, req.body)\n if (Guards.isDefined(parsedBody)) {\n init.body = parsedBody\n init.duplex = 'half'\n }\n\n const xenoRequest = new Request(safeUrl.toString(), init) as XenoRequest\n\n xenoRequest.path = safeUrl.pathname\n xenoRequest.socket = req.socket\n xenoRequest.query = req.query ?? HttpRouteParamHelper.extractQueryParams(req.url)\n\n return xenoRequest\n }\n}\n","import { Guards, type IFactory } from '@xeno-js/shared'\n\nexport class UrlBuilder implements IFactory<Headers, string> {\n create(headers: Headers): string {\n const forwardedProto = headers.get('x-forwarded-proto')\n const protocol = Guards.isDefined(forwardedProto) ? forwardedProto.split(',')[0].trim() : 'http'\n const forwardedHost = headers.get('x-forwarded-host')\n const hostHeader = headers.get('host')\n const host = Guards.isDefined(forwardedHost)\n ? forwardedHost.split(',')[0].trim()\n : (hostHeader ?? 'localhost')\n\n return `${protocol}://${host}`\n }\n}\n","import type { IServiceProxy, IServiceScope, ServicesProxy, XenoRegistry } from '@xeno-js/shared'\n\n/**\n * @description CreateServicesProxy is a service proxy factory that creates a proxy object for accessing services within a given scope.\n * The proxy object allows for convenient access to services by their names, providing a simplified way to retrieve and use services within the scope.\n */\nexport class CreateServicesProxy implements IServiceProxy {\n /**\n * @description CreateServicesProxy constructor.\n * @param scope - The scope within which services are accessed.\n * @returns A proxy object for accessing services within the specified scope.\n */\n public getServiceProxy<TRegistry extends XenoRegistry = XenoRegistry>(\n scope: IServiceScope<TRegistry>,\n ): ServicesProxy<TRegistry> {\n return new Proxy({} as ServicesProxy<TRegistry>, {\n get(_target, prop: string | symbol) {\n return scope.resolve(prop as keyof TRegistry)\n },\n })\n }\n}\n","import type { ICommand, IQuery } from '@xeno-js/shared'\nimport type {\n IAppBuilder,\n IModule,\n IServiceContainer,\n IServiceScopeAccessor,\n IXenoApplication,\n PipelinePlugin,\n XenoRegistry,\n} from '@xeno-js/shared'\nimport { Guards, LOG_LEVEL } from '@xeno-js/shared'\nimport { TOKENS } from '@xeno-js/shared'\n\nimport {\n CompositePipeline,\n ExceptionPipeline,\n IdempotencyPipeline,\n LoggingPipeline,\n Mediator,\n QueryCachingPipeline,\n} from '@/application'\nimport { CommandCacheInvalidationBehavior } from '@/application/cqrs/pipelines/cache-invalidation.pipeline'\n\nimport { IdempotencyStore } from '../idempotency'\nimport { PipelineSetupContext } from '../pipeline_setup'\nimport { CacheModule } from './cache.module'\nimport { AuthUtils, LoggerUtils } from './utils'\n\n/**\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.\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 CqrsModule<TRegistry extends XenoRegistry = XenoRegistry> implements IModule<\n TRegistry,\n {\n plugins: PipelinePlugin<TRegistry>[]\n builder: IAppBuilder<TRegistry, IXenoApplication<TRegistry>>\n }\n> {\n public async configure(\n container: IServiceContainer<TRegistry>,\n opts: {\n plugins: PipelinePlugin<TRegistry>[]\n builder: IAppBuilder<TRegistry, IXenoApplication<TRegistry>>\n },\n ): Promise<void> {\n if (!container.isRegistered(TOKENS.LOGGER))\n await LoggerUtils.addLogger(container, { level: LOG_LEVEL.INFO, console: true })\n\n const logger = container.resolve(TOKENS.LOGGER)\n\n if (!container.isRegistered(TOKENS.MEDIATOR)) {\n container.addSingleton(TOKENS.MEDIATOR, (c) => {\n const serviceScopeAccessor = c.resolve(TOKENS.SERVICE_SCOPE_ACCESSOR)\n return new Mediator<TRegistry>(serviceScopeAccessor as IServiceScopeAccessor<TRegistry>)\n })\n }\n\n const context = new PipelineSetupContext()\n\n context.addCommon(new ExceptionPipeline(), 0)\n context.addCommon(new LoggingPipeline(logger), 10)\n\n for (const plugin of opts.plugins)\n await plugin(opts.builder, container.resolve(TOKENS.CONFIGURATION_SERVICE), context)\n\n if (Guards.isDefined(context.authzOpts)) {\n const authzPipeline = await AuthUtils.addAuthZ(container, context.authzOpts)\n context.addCommon(authzPipeline, 40)\n }\n\n if (\n (Guards.isDefined(context.idempotencyOpts) || context.isQueryCaching) &&\n !container.isRegistered(TOKENS.CACHE)\n ) {\n await new CacheModule().configure(container)\n }\n\n if (Guards.isDefined(context.idempotencyOpts)) {\n const store = new IdempotencyStore(\n container.resolve(TOKENS.CACHE),\n container.resolve(TOKENS.CACHE_KEY_BUILDER),\n )\n const networkCtxAccessor = container.resolve(TOKENS.NETWORK_CONTEXT_ACCESSOR)\n context.addCommand(\n new IdempotencyPipeline(networkCtxAccessor, store, context.idempotencyOpts),\n 30,\n )\n }\n\n const sortedCommandBehaviors = context.getSortedCommandBehaviors()\n const sortedQueryBehaviors = context.getSortedQueryBehaviors()\n\n if (context.isQueryCaching) {\n sortedCommandBehaviors.push(\n new CommandCacheInvalidationBehavior(\n container.resolve(TOKENS.CACHE),\n container.resolve(TOKENS.LOGGER),\n ),\n )\n\n sortedQueryBehaviors.push(\n new QueryCachingPipeline(\n container.resolve(TOKENS.CACHE),\n container.resolve(TOKENS.CACHE_KEY_BUILDER),\n container.resolve(TOKENS.LOGGER),\n ),\n )\n }\n\n container.addSingleton(\n TOKENS.COMMAND_PIPELINES_BEHAVIOR,\n () => new CompositePipeline<ICommand<unknown>, unknown>(sortedCommandBehaviors),\n )\n\n container.addSingleton(\n TOKENS.QUERY_PIPELINES_BEHAVIOR,\n () => new CompositePipeline<IQuery<unknown>, unknown>(sortedQueryBehaviors),\n )\n }\n}\n","import type {\n Delegate,\n ICache,\n ICommand,\n ILogger,\n IPipelineBehavior,\n ResultType,\n} from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\nexport class CommandCacheInvalidationBehavior<\n TInput extends ICommand<TResult>,\n TResult,\n> implements IPipelineBehavior<TInput, TResult> {\n constructor(\n private readonly _cacheService: ICache,\n private readonly _logger: ILogger,\n ) {}\n\n public async handle(request: TInput, next: Delegate<TResult>): Promise<ResultType<TResult>> {\n const result = await next()\n\n if (result.isOk() && Guards.isDefined(request.cacheInvalidation)) {\n try {\n const { keys, patterns } = request.cacheInvalidation\n\n if (Guards.isArray(keys)) {\n for (const key of keys) {\n await this._cacheService.remove(key)\n this._logger.debug(`[Cache Invalidation] Removed key: ${key}`)\n }\n }\n\n if (Guards.isArray(patterns) && Guards.hasMethod(this._cacheService, 'removePattern')) {\n for (const pattern of patterns) {\n await this._cacheService.removePattern(pattern)\n this._logger.debug(`[Cache Invalidation] Removed pattern: ${pattern}`)\n }\n }\n } catch (error) {\n this._logger.warn(\n `[Cache Invalidation ERROR] Failed to clear cache: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n }\n\n return result\n }\n}\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 {\n AuthorizationOptions,\n IdempotencyOptions,\n IPipelineSetup,\n XenoRegistry,\n} from '@xeno-js/shared'\nimport {\n Guards,\n type ICommand,\n type IPipelineBehavior,\n type IQuery,\n type IRequest,\n type Optional,\n} from '@xeno-js/shared'\n\ninterface QueuedBehavior<T> {\n readonly order: number\n readonly behavior: T\n}\n\nexport class PipelineSetupContext<\n TRegistry extends XenoRegistry = XenoRegistry,\n> implements IPipelineSetup<TRegistry> {\n public isQueryCaching = false\n private readonly _commandBehaviors: QueuedBehavior<\n IPipelineBehavior<ICommand<unknown>, unknown>\n >[] = []\n private readonly _queryBehaviors: QueuedBehavior<IPipelineBehavior<IQuery<unknown>, unknown>>[] =\n []\n private _authzOpts: Optional<AuthorizationOptions<TRegistry>> = undefined\n private _idempotencyOpts: Optional<IdempotencyOptions> = undefined\n\n public set idempotencyOpts(opts: IdempotencyOptions) {\n this._idempotencyOpts = opts\n }\n\n public get idempotencyOpts(): Optional<IdempotencyOptions> {\n if (Guards.isDefined(this._idempotencyOpts)) return Object.freeze(this._idempotencyOpts)\n return this._idempotencyOpts\n }\n\n public set authzOpts(opts: AuthorizationOptions<TRegistry>) {\n this._authzOpts = opts\n }\n\n public get authzOpts(): Optional<AuthorizationOptions<TRegistry>> {\n if (Guards.isDefined(this._authzOpts)) return Object.freeze(this._authzOpts)\n return this._authzOpts\n }\n\n public addCommon(behavior: IPipelineBehavior<IRequest<unknown>, unknown>, order = 50): this {\n this._commandBehaviors.push({ order, behavior })\n this._queryBehaviors.push({ order, behavior })\n return this\n }\n\n public addCommand(behavior: IPipelineBehavior<ICommand<unknown>, unknown>, order = 50): this {\n this._commandBehaviors.push({ order, behavior })\n return this\n }\n\n public addQuery(): this {\n this.isQueryCaching = true\n return this\n }\n\n public getSortedCommandBehaviors(): IPipelineBehavior<ICommand<unknown>, unknown>[] {\n return [...this._commandBehaviors]\n .sort((a, b) => a.order - b.order)\n .map((entry) => entry.behavior)\n }\n\n public getSortedQueryBehaviors(): IPipelineBehavior<IQuery<unknown>, unknown>[] {\n return [...this._queryBehaviors]\n .sort((a, b) => a.order - b.order)\n .map((entry) => entry.behavior)\n }\n}\n","import type {\n DbModuleOptions,\n IDisposable,\n IModule,\n IServiceContainer,\n IServiceScope,\n ITransactionalDb,\n IUnitOfWork,\n XenoRegistry,\n} from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\nimport { TOKENS } from '@xeno-js/shared'\n\nimport { UnitOfWork } from '../transaction'\nimport { TransactionState } from '../transaction/transaction-state'\n\ninterface OptionalUnitOfWork<TTx = unknown> extends IUnitOfWork<TTx>, IDisposable {}\n\n/**\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.\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 DbModule<\n TRegistry extends XenoRegistry<DbContext, DbTransaction>,\n DbContext extends ITransactionalDb<DbTransaction>,\n DbTransaction = unknown,\n> implements IModule<\n TRegistry,\n DbModuleOptions<DbContext, DbTransaction> & {\n uow?: (c: IServiceScope<TRegistry>) => OptionalUnitOfWork<DbContext>\n }\n> {\n async configure(\n container: IServiceContainer<TRegistry>,\n opts: DbModuleOptions<DbContext, DbTransaction> & {\n uow?: (c: IServiceScope<TRegistry>) => OptionalUnitOfWork<DbContext>\n },\n ): Promise<void> {\n const db = opts.client\n\n container.addScoped(TOKENS.TRANSACTION_STATE, () => {\n return new TransactionState<DbTransaction>()\n })\n\n if (Guards.isDefined(opts.uow)) {\n container.addScoped(TOKENS.UNIT_OF_WORK, (c) => {\n return opts.uow!(c)\n })\n } else {\n container.addScoped(TOKENS.UNIT_OF_WORK, (c) => {\n const ttx = c.resolve(TOKENS.TRANSACTION_STATE)\n return new UnitOfWork(db, ttx) as unknown as TRegistry['unitOfWork']\n })\n }\n\n container.addScoped(TOKENS.DB_CONTEXT, (c) => {\n const ttx = c.resolve(TOKENS.TRANSACTION_STATE)\n return new Proxy(db, {\n get(_target, prop, receiver) {\n const activeState = ttx.state\n if (Guards.isDefined(activeState)) {\n const value: unknown = Reflect.get(activeState as object, prop, receiver)\n if (Guards.isFunction(value)) {\n return value.bind(activeState)\n }\n return value\n }\n return Reflect.get(db, prop, receiver) as DbContext\n },\n })\n })\n }\n}\n","import type { AggregateRoot, IDisposable, ITransactionState, IUnitOfWork } from '@xeno-js/shared'\nimport type { ITransactionalDb } from '@xeno-js/shared'\nimport { AppError } from '@xeno-js/shared'\nimport { Guards, type Optional } from '@xeno-js/shared'\n\n/**\n * @file unit-of-work.ts\n * @description This file contains the implementation of the Unit of Work pattern.\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 UnitOfWork<TTransaction = unknown> implements IUnitOfWork<TTransaction>, IDisposable {\n /**\n * Creates an instance of UnitOfWork.\n * @param _dbContext - The database context used for managing transactions.\n * @param _ttx - The transaction state, which can be either a specific transaction type or null.\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 constructor(\n private readonly _dbContext: ITransactionalDb<TTransaction>,\n private readonly _ttx: ITransactionState<TTransaction>,\n ) {}\n\n async runInTransaction<T, TProps, TEvent = unknown, TId extends string = string>(\n callback: (tx: TTransaction) => Promise<T>,\n aggregates?: AggregateRoot<TProps, TEvent, TId> | AggregateRoot<TProps, TEvent, TId>[],\n signal?: Optional<AbortSignal>,\n ): Promise<T> {\n AppError.throwIfAborted(signal, 'UnitOfWork.runInTransaction')\n\n return this._dbContext.transaction(async (tx) => {\n this._ttx.state = tx\n try {\n const result = await callback(this._ttx.state)\n return result\n } finally {\n this._ttx.state = null\n }\n })\n }\n\n async dispose(): Promise<void> {\n if (Guards.isDefined(this._ttx.state)) {\n try {\n if (Guards.hasMethod(this._ttx.state, 'rollback')) {\n await (this._ttx.state as { rollback: () => Promise<void> }).rollback()\n }\n } finally {\n this._ttx.state = null\n }\n }\n }\n}\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 { IModule, IServiceContainer, XenoRegistry } from '@xeno-js/shared'\nimport { TOKENS } from '@xeno-js/shared'\n\nimport { RouteMatcherFactory } from '../factories/route-matcher.factory'\nimport { ServerOptionsFactory } from '../factories/server-options.factory'\n\nexport class HttpServerModule<\n TRegistry extends XenoRegistry = XenoRegistry,\n> implements IModule<TRegistry> {\n async configure(container: IServiceContainer<TRegistry>): Promise<void> {\n container.addSingleton(\n TOKENS.SERVER_OPTIONS_FACTORY,\n (c) => new ServerOptionsFactory(c.resolve(TOKENS.CONFIGURATION_SERVICE)),\n )\n\n if (!container.isRegistered(TOKENS.ROUTE_MATCHER)) {\n container.addSingleton(TOKENS.ROUTE_MATCHER, () => new RouteMatcherFactory().create([]))\n }\n }\n}\n","import type { IRoute, IRouteFactory, NativeRouteDefinition, XenoRegistry } from '@xeno-js/shared'\nimport { RoutePatternHelper } from '@xeno-js/shared'\n\nimport { RouteMatcher } from '../http/route-matcher.http'\n\nexport class RouteMatcherFactory implements IRouteFactory {\n create<TRegistry extends XenoRegistry = XenoRegistry>(\n opts: NativeRouteDefinition<TRegistry>[],\n ): IRoute<TRegistry> {\n const routes = opts.map((r) => {\n const normalizedPath = RoutePatternHelper.normalizePath(r.path)\n const { pattern } = RoutePatternHelper.parse(normalizedPath)\n return {\n definition: r,\n pattern,\n upperMethod: r.method.toUpperCase(),\n }\n })\n return new RouteMatcher<TRegistry>(routes)\n }\n}\n","import type {\n IRoute,\n NativeRouteDefinition,\n RouteHandlerContext,\n RoutePolicy,\n XenoRegistry,\n} from '@xeno-js/shared'\nimport {\n Guards,\n HttpHelper,\n type Optional,\n RoutePatternHelper,\n STATUS_CODES,\n} from '@xeno-js/shared'\n\ninterface CompiledRoute<TRegistry extends XenoRegistry> {\n readonly definition: NativeRouteDefinition<TRegistry>\n readonly pattern: RegExp\n readonly upperMethod: string\n}\n\nexport class RouteMatcher<\n TRegistry extends XenoRegistry = XenoRegistry,\n> implements IRoute<TRegistry> {\n constructor(private readonly _compiledRoutes: CompiledRoute<TRegistry>[]) {}\n\n public match(rawUrl: string, method: string): Optional<NativeRouteDefinition<TRegistry>> {\n const url = !Guards.isNullOrEmpty(rawUrl) ? rawUrl : '/'\n const safeUrl = HttpHelper.parseSafeUrl(url)\n const parsedPath = RoutePatternHelper.normalizePath(safeUrl.pathname)\n const upperMethod = method.toUpperCase()\n\n const matched = this._compiledRoutes.find(\n (r) => r.upperMethod === upperMethod && r.pattern.test(parsedPath),\n )\n\n if (Guards.isDefined(matched)) return matched.definition\n\n if (upperMethod === 'OPTIONS') {\n const pathExists = this._compiledRoutes.some((r) => r.pattern.test(parsedPath))\n\n if (pathExists) {\n return {\n path: parsedPath,\n method: 'OPTIONS',\n handler: async <TOutput>(ctx: RouteHandlerContext<TRegistry>) => {\n try {\n return await ctx.handle('__PREFLIGHT__' as keyof TRegistry)\n } catch {\n return {\n status: STATUS_CODES.NO_CONTENT,\n ok: true,\n headers: {},\n data: undefined as TOutput,\n }\n }\n },\n } as unknown as NativeRouteDefinition<TRegistry>\n }\n }\n\n return undefined\n }\n\n public checkRoutePolicy(path: string, method: string): RoutePolicy {\n const route = this.match(path, method)\n\n return {\n withCredentials: route?.security?.withCredentials,\n allowOrigins: route?.security?.allowOrigins,\n withCsrf: route?.security?.withCsrf,\n withCors: route?.security?.withCors,\n }\n }\n}\n","import type { IConfigurationService } from '@xeno-js/shared'\nimport type { IServerOptionsFactory, NativeListenOptions } from '@xeno-js/shared'\n\nexport class ServerOptionsFactory implements IServerOptionsFactory {\n constructor(private readonly _config: IConfigurationService) {}\n\n public create(options?: NativeListenOptions): NativeListenOptions {\n const defaultPort = this._config.getNumber('PORT', 3000) ?? 3000\n const defaultHost = this._config.get('HOST', '0.0.0.0') ?? '0.0.0.0'\n\n return {\n port: options?.port ?? defaultPort,\n host: options?.host ?? defaultHost,\n onListening: options?.onListening,\n }\n }\n}\n","import type { IConfigurationService } from '@xeno-js/shared'\nimport type {\n IAppBuilder,\n IModule,\n IServiceContainer,\n IXenoApplication,\n LoggerConfig,\n LoggerPlugin,\n XenoRegistry,\n} from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\nimport { LoggerSetupContext } from '../loggers/setup.logger'\nimport { LoggerUtils } from './utils'\n\n/**\n * @description CacheModule is responsible for registering cache services in the IoC container. Default implementation is in-memory\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 LoggerModule<TRegistry extends XenoRegistry = XenoRegistry> implements IModule<\n TRegistry,\n LoggerConfig<TRegistry> & { plugins?: LoggerPlugin<TRegistry>[] }\n> {\n public async configure(\n container: IServiceContainer<TRegistry>,\n opts: LoggerConfig<TRegistry> & {\n builder: IAppBuilder<TRegistry, IXenoApplication<TRegistry>>\n config: IConfigurationService\n plugins?: LoggerPlugin<TRegistry>[]\n },\n ): Promise<void> {\n const loggerSetup = new LoggerSetupContext<TRegistry>()\n loggerSetup.addConsole(opts.console, opts.level)\n if (!Guards.isNullOrEmpty(opts.plugins))\n opts.plugins.forEach((plugin) => plugin(opts.builder, opts.config, loggerSetup))\n\n if (!Guards.isNullOrEmpty(opts.customLoggers)) {\n for (const logger of opts.customLoggers) {\n loggerSetup.addCustomLogger((c) => logger(c))\n }\n }\n\n const options = {\n level: loggerSetup.level,\n console: loggerSetup.console,\n customLoggers: loggerSetup.getCustomLoggers(),\n }\n\n await LoggerUtils.addLogger(container, options)\n }\n}\n","import type { ILoggerClient, LogLevel } from '@xeno-js/shared'\nimport type { ILoggerSetup, IServiceScope, XenoRegistry } from '@xeno-js/shared'\nimport { Guards, LOG_LEVEL } from '@xeno-js/shared'\n\nexport class LoggerSetupContext<\n TRegistry extends XenoRegistry = XenoRegistry,\n> implements ILoggerSetup<TRegistry> {\n public console = false\n public level: LogLevel = LOG_LEVEL.DEBUG\n private readonly _customLoggers: ((container: IServiceScope<TRegistry>) => ILoggerClient)[] = []\n\n public addConsole(enabled = true, level?: LogLevel): void {\n this.console = enabled\n if (Guards.isDefined(level)) {\n this.level = level\n }\n }\n\n public addCustomLogger(factory: (container: IServiceScope<TRegistry>) => ILoggerClient): void {\n this._customLoggers.push(factory)\n }\n\n public getCustomLoggers(): ((container: IServiceScope<TRegistry>) => ILoggerClient)[] {\n return [...this._customLoggers]\n }\n}\n","import type { ILogger, IMiddleware, IRoute, Optional, RequestContext } from '@xeno-js/shared'\nimport type {\n IAllowMethod,\n IModule,\n IRequestContext,\n IServiceContainer,\n MiddlewareConfig,\n NativeRouteDefinition,\n XenoRegistry,\n} from '@xeno-js/shared'\nimport { Guards, LOG_LEVEL } from '@xeno-js/shared'\nimport { TOKENS } from '@xeno-js/shared'\n\nimport { ClaimsIdentityMapper, GateKeeper, NoAuthGateKeeper } from '@/application'\nimport {\n AllowOriginMiddleware,\n AuthenticationMiddleware,\n CompositeMiddleware,\n CookieResponseMiddleware,\n CORSMiddleware,\n CsrfCookieMiddleware,\n CsrfMiddleware,\n MethodCheckMiddleware,\n OptionsMiddleware,\n RateLimitMiddleware,\n RequestContextMiddleware,\n} from '@/presentation'\n\nimport { RateLimitKeyBuilder } from '../cache'\nimport { AllowMethodFactory } from '../factories'\nimport { HttpDispatcher } from '../http/dispatcher.http'\nimport {\n AllowOrigin,\n BearerTokenExtractor,\n ClientIpResolver,\n CsrfTokenService,\n EdgeCryptoService,\n HttpCookieExtractor,\n HttpHeaderExtractor,\n} from '../services'\nimport { CacheModule } from './cache.module'\nimport { LoggerUtils } from './utils'\n\nexport class MiddlewareModule<TRegistry extends XenoRegistry = XenoRegistry> implements IModule<\n TRegistry,\n MiddlewareConfig\n> {\n public async configure(\n container: IServiceContainer<TRegistry>,\n opts: MiddlewareConfig & { routes: NativeRouteDefinition<TRegistry>[] },\n ): Promise<void> {\n if (!container.isRegistered(TOKENS.LOGGER))\n await LoggerUtils.addLogger(container, { level: LOG_LEVEL.INFO, console: true })\n\n const logger = container.resolve(TOKENS.LOGGER)\n const requestContext = container.resolve(TOKENS.REQUEST_CONTEXT) as IRequestContext<\n RequestContext,\n TRegistry\n >\n const configuration = container.resolve(TOKENS.CONFIGURATION_SERVICE)\n\n const allowMethod = new AllowMethodFactory().create<TRegistry>(opts.routes)\n\n container.addSingleton(\n TOKENS.SERVICE_EXTRACTOR,\n () =>\n new HttpHeaderExtractor(\n new HttpCookieExtractor(),\n opts.trustedIpHeader,\n opts.csrf?.cookieName ?? '__Host-xeno-csrf',\n opts.csrf?.headerName ?? 'x-csrf-token',\n ),\n )\n\n const getRouteMatcher = () => container.resolve(TOKENS.ROUTE_MATCHER)\n\n const withCredentials =\n Guards.isDefined(opts.cors?.withCredentials) && opts.cors?.withCredentials ? 'true' : 'false'\n\n const [optionsMw, cookieRespMw, corsMw, authMw, csrfMws] = [\n this._buildOptionsMiddleware(\n opts,\n requestContext,\n () => allowMethod,\n withCredentials,\n getRouteMatcher,\n ),\n this._buildCookieResponseMiddleware(opts, requestContext),\n this._buildCorsMiddleware(opts, requestContext, withCredentials, getRouteMatcher),\n this._createAuthMiddleware(container, requestContext, logger, opts),\n this._buildCsrfMiddlewares(opts, container, requestContext, getRouteMatcher),\n ]\n\n const rateLimitMw = await this._buildRateLimitMiddleware(\n opts,\n container,\n requestContext,\n logger,\n )\n\n const requestCtxMw = new RequestContextMiddleware(\n requestContext,\n container.resolve(TOKENS.SERVICE_EXTRACTOR),\n new ClientIpResolver(opts.trustedProxies),\n logger,\n )\n\n const defaultOrigin =\n configuration.get('APP_URL') ?? `http://localhost:${configuration.getNumber('PORT', 3000)}`\n const origins = !Guards.isNullOrEmpty(opts.cors?.allowOrigins)\n ? opts.cors.allowOrigins\n : [defaultOrigin]\n\n const allowOriginMw = new AllowOriginMiddleware(\n new AllowOrigin(origins),\n requestContext,\n logger,\n getRouteMatcher,\n )\n const methodCheckMw = new MethodCheckMiddleware(requestContext, allowMethod)\n\n const pipeline: IMiddleware[] = [\n requestCtxMw,\n ...(Guards.isDefined(cookieRespMw) ? [cookieRespMw] : []),\n allowOriginMw,\n ...(Guards.isDefined(optionsMw) && !Guards.isNullOrEmpty(opts.routes) ? [optionsMw] : []),\n ...(!Guards.isNullOrEmpty(opts.routes) ? [methodCheckMw] : []),\n ...(Guards.isDefined(corsMw) ? [corsMw] : []),\n ...(Guards.isDefined(rateLimitMw) ? [rateLimitMw] : []),\n authMw,\n ...(!Guards.isNullOrEmpty(csrfMws) ? csrfMws : []),\n ]\n\n container.addSingleton(TOKENS.MIDDLEWARE, () => new CompositeMiddleware(pipeline))\n\n container.addSingleton(\n TOKENS.HTTP_DISPATCHER,\n (c) =>\n new HttpDispatcher<TRegistry>(\n c.resolve(TOKENS.REQUEST_CONTEXT) as IRequestContext<RequestContext, TRegistry>,\n c.resolve(TOKENS.MIDDLEWARE),\n c.resolve(TOKENS.SERVICE_PROXY),\n ),\n )\n }\n\n private _buildCookieResponseMiddleware(\n opts: MiddlewareConfig,\n requestContext: IRequestContext<RequestContext, TRegistry>,\n ): Optional<IMiddleware> {\n if (!Guards.isDefined(opts.isSSR) || !opts.isSSR) return undefined\n\n return new CookieResponseMiddleware<TRegistry>(requestContext)\n }\n\n private _buildCsrfMiddlewares(\n opts: MiddlewareConfig,\n container: IServiceContainer<TRegistry>,\n requestContext: IRequestContext<RequestContext, TRegistry>,\n routePolicyCheck: () => IRoute<TRegistry>,\n ) {\n if (!Guards.isDefined(opts.csrf)) return []\n const csrf = opts.csrf\n\n container.addSingleton(TOKENS.CRYPTO_SERVICE, () => new EdgeCryptoService())\n container.addSingleton(TOKENS.CSRF_TOKEN_SERVICE, (c) => {\n return new CsrfTokenService(csrf.secret, c.resolve(TOKENS.CRYPTO_SERVICE))\n })\n\n return [\n new CsrfCookieMiddleware(requestContext, container.resolve(TOKENS.CSRF_TOKEN_SERVICE), csrf),\n new CsrfMiddleware(\n requestContext,\n container.resolve(TOKENS.CSRF_TOKEN_SERVICE),\n routePolicyCheck,\n ),\n ]\n }\n\n private async _buildRateLimitMiddleware(\n opts: MiddlewareConfig,\n container: IServiceContainer<TRegistry>,\n requestContext: IRequestContext<RequestContext, TRegistry>,\n logger: ILogger,\n ) {\n if (Guards.isDefined(opts.rateLimit?.enabled) && opts.rateLimit?.enabled) {\n const maxRequests = opts.rateLimit?.maxRequests ?? 100\n const windowSeconds = opts.rateLimit?.windowSeconds ?? 60\n\n if (!container.isRegistered(TOKENS.CACHE)) {\n await new CacheModule().configure(container)\n }\n\n return new RateLimitMiddleware(\n requestContext,\n container.resolve(TOKENS.CACHE),\n new RateLimitKeyBuilder(requestContext),\n logger,\n { maxRequests, windowSeconds },\n )\n }\n }\n\n private _buildCorsMiddleware(\n opts: MiddlewareConfig,\n requestContext: IRequestContext<RequestContext, TRegistry>,\n withCredentials: Optional<'true' | 'false'>,\n routePolicyCheck: () => IRoute<TRegistry>,\n ) {\n if (Guards.isDefined(opts.cors?.enabled) && opts.cors.enabled) {\n return new CORSMiddleware(requestContext, routePolicyCheck, withCredentials)\n }\n }\n\n private _buildOptionsMiddleware(\n opts: MiddlewareConfig,\n requestContext: IRequestContext<RequestContext, TRegistry>,\n allowMethod: () => IAllowMethod,\n withCredentials: Optional<'true' | 'false'>,\n routePolicyCheck: () => IRoute<TRegistry>,\n ) {\n if (Guards.isDefined(opts.cors?.enablePreflight) && opts.cors?.enablePreflight) {\n const allowHeaders = Array.from(\n new Set([\n 'x-csrf-token',\n 'Authorization',\n 'Content-Type',\n 'X-Requested-With',\n 'Accept',\n 'Origin',\n 'referer',\n 'x-correlation-id',\n 'x-request-id',\n 'x-span-id',\n 'x-parent-span-id',\n 'x-return-address',\n 'x-sequence-id',\n 'x-sequence-position',\n 'x-sequence-size',\n 'x-expiration',\n ...(opts.cors.allowHeaders ?? []),\n ]),\n )\n return new OptionsMiddleware(\n requestContext,\n allowMethod(),\n routePolicyCheck,\n allowHeaders,\n withCredentials,\n )\n }\n }\n\n private _createAuthMiddleware(\n container: IServiceContainer<TRegistry>,\n requestContext: IRequestContext<RequestContext, TRegistry>,\n logger: ILogger,\n opts: MiddlewareConfig,\n ): IMiddleware {\n if (!container.isRegistered(TOKENS.TOKEN_SERVICE_EXTRACTOR)) {\n container.addSingleton(\n TOKENS.TOKEN_SERVICE_EXTRACTOR,\n () => new BearerTokenExtractor(opts.authCookieName ?? 'sb-access-token'),\n )\n }\n const tokenExtractor = container.resolve(TOKENS.TOKEN_SERVICE_EXTRACTOR)\n\n if (!container.isRegistered(TOKENS.BASE_AUTH_SERVICE)) {\n return new AuthenticationMiddleware(\n requestContext,\n tokenExtractor,\n new NoAuthGateKeeper(),\n logger,\n )\n }\n\n return new AuthenticationMiddleware(\n requestContext,\n tokenExtractor,\n new GateKeeper(() => {\n const scope = requestContext.getScope()\n if (!Guards.isDefined(scope)) {\n throw new Error('[GateKeeper Error]: No active scope found.')\n }\n return scope.resolve(TOKENS.BASE_AUTH_SERVICE)\n }, new ClaimsIdentityMapper()),\n logger,\n )\n }\n}\n","import type {\n AppError,\n ICommand,\n IContextAccessor,\n IController,\n IMediator,\n IQuery,\n RequestContext,\n ResultType,\n} from '@xeno-js/shared'\nimport type { Dictionary, Optional, ResponseDto } from '@xeno-js/shared'\nimport { GuidHelper, HttpHelper } from '@xeno-js/shared'\n\n/**\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.\n * @template TRequest - The type of the request object that the controller will handle.\n * @template TResponse - The type of the response object that the controller will return.\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 abstract class BaseController<TRequest, TResponse> implements IController<\n TRequest,\n TResponse\n> {\n /**\n * Constructs a new instance of the BaseController class.\n * @param _requestContext - An instance of IContextAccessor used to manage the execution context for requests.\n * @param _mediator - An instance of IMediator used to facilitate communication between different parts of the application.\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 constructor(\n private readonly _requestContext: IContextAccessor<RequestContext>,\n private readonly _mediator: IMediator,\n ) {}\n\n abstract handle(request: TRequest, signal: Optional<AbortSignal>): Promise<ResponseDto<TResponse>>\n\n /**\n * Helper to return a successful 200/201 response.\n * @param data - The data to include in the response.\n * @param status - The HTTP status code (default is 200).\n * @param meta - Optional metadata to include in the response.\n * @param headers - Optional headers to include in the response.\n * @returns A ResponseDto containing the data and status.\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 protected ok<T>(\n data: T,\n status = 200,\n meta: Optional<Dictionary> = {},\n headers: Optional<Dictionary<string[]>> = {},\n ): ResponseDto<T> {\n return HttpHelper.success(data, status, meta, headers)\n }\n\n /**\n * Helper to automatically map a failed Result (from the CQRS pipeline)\n * into a standardized ErrorResponseDto.\n * @param error - The AppError instance representing the error.\n * @param details - Optional additional details about the error.\n * @param headers - Optional headers to include in the error response.\n * @returns A ResponseDto representing the error response.\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 protected fail(\n error: AppError,\n details: Optional<string> = undefined,\n headers: Optional<Dictionary<string[]>> = {},\n ): ResponseDto<TResponse> {\n const context = this._requestContext.getContext()\n\n const customHeaders = error['header'] as Optional<Dictionary<string[]>>\n\n return HttpHelper.error<TResponse>(\n {\n success: false,\n error: {\n code: error.code,\n message: error.message,\n path: context?.network.path,\n details: details ?? error.message,\n },\n correlationId: context?.tracing.correlationId ?? GuidHelper.generate(),\n requestId: context?.network.requestId ?? GuidHelper.generate(),\n spanId: context?.tracing.spanId ?? GuidHelper.generate(),\n timestamp: new Date().toISOString(),\n },\n error.status,\n {\n 'Content-Type': [context?.network.formatIndicator ?? 'application/json'],\n ...customHeaders,\n ...headers,\n },\n )\n }\n\n /**\n * Helper to send a query through the mediator and return the result.\n * @param request - The IQuery instance to be sent.\n * @param signal - The AbortSignal\n * @returns A promise resolving to the result of the query.\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 protected _query(\n request: IQuery<TResponse>,\n signal: Optional<AbortSignal>,\n ): Promise<ResultType<TResponse>> {\n return this._mediator.query(request, signal)\n }\n\n /**\n * Helper to send a command through the mediator and return the result.\n * @param request - The ICommand instance to be sent.\n * @param signal - The AbortSignal\n * @returns A promise resolving to the result of the command.\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 protected _send(\n request: ICommand<TResponse>,\n signal: Optional<AbortSignal>,\n ): Promise<ResultType<TResponse>> {\n return this._mediator.send(request, signal)\n }\n\n protected getContext(): Optional<RequestContext> {\n return this._requestContext.getContext()\n }\n}\n","import type {\n HttpMethod,\n IMiddleware,\n RequestContext,\n ResponseDto,\n XenoRequest,\n} from '@xeno-js/shared'\nimport type { IAllowMethod, IRequestContext, XenoRegistry } from '@xeno-js/shared'\nimport {\n ERROR_CODE_MESSAGES,\n ERROR_CODES,\n GuidHelper,\n HttpHelper,\n STATUS_CODES,\n} from '@xeno-js/shared'\n\n/**\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\n * status code with an error message.\n * @author Xeno\n * @version 1.0.0\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-js\n * @param {IAllowMethod} _allowMethod - The allow method service to check if the method is allowed.\n * @param {IRequestContext<RequestContext, XenoRegistry>} _requestContext - The request context to get the request context.\n * @returns {IMiddleware} - The middleware function that checks if the method is allowed.\n * @throws {Error} - If the method is not allowed, it throws an error with a 405 status code and an error message.\n * @see {@link IAllowMethod} - The allow method service.\n * @see {@link IRequestContext} - The request context.\n * @see {@link IMiddleware} - The middleware interface.\n * @see {@link IResponseDto} - The response DTO.\n */\nexport class MethodCheckMiddleware implements IMiddleware {\n constructor(\n private readonly _requestContext: IRequestContext<RequestContext, XenoRegistry>,\n private readonly _allowMethod: IAllowMethod,\n ) {}\n\n public async execute<T>(\n req: XenoRequest,\n next: () => Promise<ResponseDto<T>>,\n ): Promise<ResponseDto<T>> {\n const isAllowed = this._allowMethod.check(req.path, req.method as HttpMethod)\n\n if (!isAllowed) {\n const { network, tracing } = this._requestContext.getContext() ?? {}\n\n return HttpHelper.error(\n {\n success: false,\n error: {\n code: ERROR_CODES.NOT_ALLOWED,\n message: ERROR_CODE_MESSAGES[ERROR_CODES.NOT_ALLOWED],\n details: `Operation blocked by allow method middleware`,\n path: req.path,\n },\n correlationId: tracing?.correlationId ?? GuidHelper.generate(),\n requestId: network?.requestId ?? GuidHelper.generate(),\n spanId: tracing?.spanId ?? GuidHelper.generate(),\n timestamp: new Date().toISOString(),\n },\n STATUS_CODES.NOT_ALLOWED,\n {\n Allow: this._allowMethod.getMethods(req.path),\n },\n )\n }\n\n return await next()\n }\n}\n","import type {\n IContextAccessor,\n ILogger,\n IMiddleware,\n IRoutePolicyCheck,\n Optional,\n RequestContext,\n ResponseDto,\n RoutePolicy,\n XenoRequest,\n} from '@xeno-js/shared'\nimport type { IAllowOrigin } from '@xeno-js/shared'\nimport {\n ERROR_CODE_MESSAGES,\n ERROR_CODES,\n Guards,\n GuidHelper,\n HttpHelper,\n STATUS_CODES,\n} from '@xeno-js/shared'\n\n/**\n * @description A middleware that checks if the origin of the request is allowed.\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 AllowOriginMiddleware implements IMiddleware {\n constructor(\n private readonly _allowOrigin: IAllowOrigin,\n private readonly _requestContext: IContextAccessor<RequestContext>,\n private readonly _logger: ILogger,\n private readonly _getRouteMatcher: () => IRoutePolicyCheck,\n ) {}\n\n public async execute<T>(\n req: XenoRequest,\n next: () => Promise<ResponseDto<T>>,\n ): Promise<ResponseDto<T>> {\n const { network, tracing } = this._requestContext.getContext() ?? {}\n const origin = network?.origin\n\n const policy = this._getRouteMatcher().checkRoutePolicy(req.path, req.method)\n\n const isAllowed = this.checkOrigin(policy, origin)\n\n if (!isAllowed) {\n this._logger.warn(`Access denied by AllowOrigin policy for origin: ${origin ?? 'unknown'}`)\n\n return HttpHelper.error(\n {\n success: false,\n error: {\n code: ERROR_CODES.FORBIDDEN,\n message: ERROR_CODE_MESSAGES[ERROR_CODES.FORBIDDEN],\n details: `The origin '${origin ?? 'unknown'}' is not allowed to access this resource.`,\n path: req.path,\n },\n correlationId: tracing?.correlationId ?? GuidHelper.generate(),\n requestId: network?.requestId ?? GuidHelper.generate(),\n spanId: tracing?.spanId ?? GuidHelper.generate(),\n timestamp: new Date().toISOString(),\n },\n STATUS_CODES.FORBIDDEN,\n )\n }\n\n return next()\n }\n\n private checkOrigin(policy: RoutePolicy, origin: Optional<string>): boolean {\n if (Guards.isDefined(policy.allowOrigins)) {\n return policy.allowOrigins.includes('*') || policy.allowOrigins.includes(origin ?? '')\n } else {\n return this._allowOrigin.isAllowed(origin)\n }\n }\n}\n","import type {\n IGateKeeper,\n ILogger,\n IMiddleware,\n IServiceExtractor,\n Optional,\n RequestContext,\n ResponseDto,\n XenoRequest,\n} from '@xeno-js/shared'\nimport type { IRequestContext, XenoRegistry } from '@xeno-js/shared'\nimport { GuidHelper, HttpHelper, STATUS_CODES } from '@xeno-js/shared'\n\n/**\n * @description Middleware that checks if the request is authenticated. If the request is not authenticated, it returns a 401\n * status code with an error message.\n * @author Xeno\n * @version 1.0.0\n * @since 2025-09-30\n * @param {IRequestContext<RequestContext, XenoRegistry>} _requestContext - The request context to use for resolving services.\n * @param {IGateKeeper} _gateKeeper - The gate keeper to use for authentication.\n * @param {ILogger} _logger - The logger to use for logging.\n * @param {IServiceExtractor<HttpHeaders, Optional<string>>} _tokenExtractor - The token extractor to use for extracting the token from the request.\n * @returns {IMiddleware} - The middleware function.\n * @link https://github.com/xeno-js/xeno-js\n *\n * @see {@link IRequestContext} - The request context interface.\n * @see {@link IGateKeeper} - The gate keeper interface.\n * @see {@link ILogger} - The logger interface.\n * @see {@link IServiceExtractor} - The service extractor interface.\n */\nexport class AuthenticationMiddleware implements IMiddleware {\n constructor(\n private readonly _requestContext: IRequestContext<RequestContext, XenoRegistry>,\n private readonly _tokenExtractor: IServiceExtractor<Request['headers'], Optional<string>>,\n private readonly _gateKeeper: IGateKeeper,\n private readonly _logger: ILogger,\n ) {}\n\n public async execute<T>(\n req: XenoRequest,\n next: () => Promise<ResponseDto<T>>,\n ): Promise<ResponseDto<T>> {\n const token = this._tokenExtractor.extract(req.headers)\n const authResult = await this._gateKeeper.authenticate(token)\n\n if (!authResult.isOk()) {\n const error = authResult.getErrorOrThrow()\n this._logger.warn(\n `Authentication failed for request on path: ${req.path}. Code: ${error.code}. Error: ${error}`,\n )\n\n const { network, tracing } = this._requestContext.getContext() ?? {}\n\n return HttpHelper.error(\n {\n success: false,\n error: {\n code: error.code,\n message: error.message,\n details: `[Authentication Error] Failed to authenticate request on path: ${req.path}`,\n path: req.path,\n },\n correlationId: tracing?.correlationId ?? GuidHelper.generate(),\n requestId: network?.requestId ?? GuidHelper.generate(),\n spanId: tracing?.spanId ?? GuidHelper.generate(),\n timestamp: new Date().toISOString(),\n },\n error.status ?? STATUS_CODES.UNAUTHORIZED,\n { 'Content-Type': [network?.formatIndicator ?? 'application/json'] },\n )\n }\n\n this._requestContext.updateIdentity(authResult.getValueOrThrow()!)\n\n return next()\n }\n}\n","import type { IMiddleware, ResponseDto, XenoRequest } from '@xeno-js/shared'\n\n/**\n * @description A middleware that executes a list of middlewares in a chain.\n *\n * @author Xeno\n * @version 1.0.1\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-js\n */\nexport class CompositeMiddleware implements IMiddleware {\n constructor(private readonly _middlewares: IMiddleware[]) {}\n\n public async execute<T>(\n req: XenoRequest,\n next: () => Promise<ResponseDto<T>>,\n ): Promise<ResponseDto<T>> {\n let currentNext = next\n\n for (let i = this._middlewares.length - 1; i >= 0; i--) {\n const currentBehavior = this._middlewares[i]\n const previousNext = currentNext\n currentNext = () => currentBehavior.execute(req, previousNext)\n }\n\n return currentNext()\n }\n}\n","import type { IMiddleware, ResponseDto, XenoRequest } from '@xeno-js/shared'\nimport type { IRequestContext, XenoRegistry } from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\nimport { TOKENS } from '@xeno-js/shared'\n\nexport class CookieResponseMiddleware<\n TRegistry extends XenoRegistry = XenoRegistry,\n> implements IMiddleware {\n constructor(private readonly _requestContext: IRequestContext<unknown, TRegistry>) {}\n\n public async execute<T>(\n req: XenoRequest,\n next: () => Promise<ResponseDto<T>>,\n ): Promise<ResponseDto<T>> {\n const response = await next()\n\n const scope = this._requestContext.getScope()\n if (!Guards.isDefined(scope)) {\n return response\n }\n\n try {\n const cookieHandler = scope.resolve(TOKENS.COOKIE_HANDLER)\n const pending = cookieHandler.getPendingCookies()\n\n if (!Guards.isNullOrEmpty(pending)) {\n const existingSetCookie = response.headers?.['Set-Cookie']\n const mergedCookies = Guards.isArray(existingSetCookie)\n ? [...existingSetCookie, ...pending]\n : Guards.isDefined(existingSetCookie)\n ? [String(existingSetCookie), ...pending]\n : [...pending]\n\n response.headers = {\n ...(response?.headers ?? {}),\n 'Set-Cookie': mergedCookies,\n }\n }\n } catch {\n /* noop */\n }\n\n return response\n }\n}\n","import type {\n IContextAccessor,\n IMiddleware,\n IRoutePolicyCheck,\n RequestContext,\n ResponseDto,\n XenoRequest,\n} from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\n/**\n * @description A cors middleware that checks if the origin of the request is allowed.\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 CORSMiddleware implements IMiddleware {\n constructor(\n private readonly _requestContext: IContextAccessor<RequestContext>,\n private readonly _getRouteMatcher: () => IRoutePolicyCheck,\n private readonly _withCredentials: 'true' | 'false' = 'false',\n ) {}\n\n public async execute<T>(\n req: XenoRequest,\n next: () => Promise<ResponseDto<T>>,\n ): Promise<ResponseDto<T>> {\n const { network } = this._requestContext.getContext() ?? {}\n const origin = network?.origin\n\n const response = await next()\n\n const policy = this._getRouteMatcher().checkRoutePolicy(req.path, req.method)\n const withCredentials = Guards.isDefined(policy.withCredentials)\n ? policy.withCredentials\n ? 'true'\n : 'false'\n : this._withCredentials\n\n const allowOrigins = policy.allowOrigins\n\n if (\n Guards.isDefined(origin) ||\n (Guards.isDefined(allowOrigins) && allowOrigins.includes('*'))\n ) {\n response.headers = {\n ...(response?.headers ?? {}),\n 'Access-Control-Allow-Origin':\n Guards.isDefined(allowOrigins) &&\n allowOrigins.includes('*') &&\n withCredentials === 'false'\n ? '*'\n : origin!,\n 'Access-Control-Allow-Credentials': withCredentials,\n 'Vary': 'Origin',\n }\n }\n return response\n }\n}\n","import type {\n IMiddleware,\n IRoutePolicyCheck,\n RequestContext,\n ResponseDto,\n XenoRequest,\n} from '@xeno-js/shared'\nimport type { ICsrfTokenService, IRequestContext, XenoRegistry } from '@xeno-js/shared'\nimport {\n ERROR_CODE_MESSAGES,\n ERROR_CODES,\n Guards,\n GuidHelper,\n HttpHelper,\n STATUS_CODES,\n} from '@xeno-js/shared'\n\n/**\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.\n */\nexport class CsrfMiddleware implements IMiddleware {\n constructor(\n private readonly _requestContext: IRequestContext<RequestContext, XenoRegistry>,\n private readonly _csrfTokenService: ICsrfTokenService,\n private readonly _getRouteMatcher: () => IRoutePolicyCheck,\n ) {}\n\n public async execute<T>(\n req: XenoRequest,\n next: () => Promise<ResponseDto<T>>,\n ): Promise<ResponseDto<T>> {\n const method = req.method.toUpperCase()\n const isStateChanging = ['POST', 'PUT', 'DELETE', 'PATCH'].includes(method)\n\n if (isStateChanging) {\n const policy = this._getRouteMatcher().checkRoutePolicy(req.path, method)\n\n if (Guards.isDefined(policy.withCsrf) && !policy.withCsrf) return await next()\n\n const { network, tracing, identity } = this._requestContext.getContext() ?? {}\n const headerToken = network?.csrf\n const cookieToken = network?.csrfCookie\n\n if (!Guards.isDefined(headerToken) || !Guards.isDefined(cookieToken)) {\n return HttpHelper.error(\n {\n success: false,\n error: {\n code: ERROR_CODES.FORBIDDEN,\n message: ERROR_CODE_MESSAGES[ERROR_CODES.FORBIDDEN],\n details: 'CSRF token missing',\n path: req.path,\n },\n correlationId: tracing?.correlationId ?? GuidHelper.generate(),\n requestId: network?.requestId ?? GuidHelper.generate(),\n spanId: tracing?.spanId ?? GuidHelper.generate(),\n timestamp: new Date().toISOString(),\n },\n STATUS_CODES.FORBIDDEN,\n {\n 'Content-Type': [network?.formatIndicator ?? 'application/json'],\n },\n )\n }\n\n if (headerToken !== cookieToken) {\n return HttpHelper.error(\n {\n success: false,\n error: {\n code: ERROR_CODES.FORBIDDEN,\n message: ERROR_CODE_MESSAGES[ERROR_CODES.FORBIDDEN],\n details: 'CSRF token mismatch',\n path: req.path,\n },\n correlationId: tracing?.correlationId ?? GuidHelper.generate(),\n requestId: network?.requestId ?? GuidHelper.generate(),\n spanId: tracing?.spanId ?? GuidHelper.generate(),\n timestamp: new Date().toISOString(),\n },\n STATUS_CODES.FORBIDDEN,\n {\n 'Content-Type': [network?.formatIndicator ?? 'application/json'],\n },\n )\n }\n\n if (\n !Guards.isDefined(identity?.userId) ||\n !(await this._csrfTokenService.validate(headerToken, identity?.userId))\n ) {\n return HttpHelper.error(\n {\n success: false,\n error: {\n code: ERROR_CODES.FORBIDDEN,\n message: ERROR_CODE_MESSAGES[ERROR_CODES.FORBIDDEN],\n details: 'CSRF token invalid',\n path: req.path,\n },\n correlationId: tracing?.correlationId ?? GuidHelper.generate(),\n requestId: network?.requestId ?? GuidHelper.generate(),\n spanId: tracing?.spanId ?? GuidHelper.generate(),\n timestamp: new Date().toISOString(),\n },\n STATUS_CODES.FORBIDDEN,\n {\n 'Content-Type': [network?.formatIndicator ?? 'application/json'],\n },\n )\n }\n }\n\n return await next()\n }\n}\n","import type {\n IContextAccessor,\n IMiddleware,\n RequestContext,\n ResponseDto,\n XenoRequest,\n} from '@xeno-js/shared'\nimport type { ICsrfTokenService, MiddlewareConfig } from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\n/**\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.\n *\n * @author Xeno\n * @version 1.0.0\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-js\n * @license MIT\n */\nexport class CsrfCookieMiddleware implements IMiddleware {\n constructor(\n private readonly _requestContext: IContextAccessor<RequestContext>,\n private readonly _csrfTokenService: ICsrfTokenService,\n private readonly _csrf: NonNullable<MiddlewareConfig['csrf']>,\n ) {}\n\n public async execute<T>(\n req: XenoRequest,\n next: () => Promise<ResponseDto<T>>,\n ): Promise<ResponseDto<T>> {\n const response = await next()\n\n const context = this._requestContext.getContext()\n const identity = context?.identity\n const network = context?.network\n\n if (!Guards.isDefined(identity?.userId)) return response\n\n if (Guards.isDefined(network?.csrfCookie)) return response\n\n const token = await this._csrfTokenService.generate(identity.userId)\n\n const cookieName = this._csrf.cookieName ?? '__Host-xeno-csrf'\n const maxAge = this._csrf.cookieMaxAgeSeconds ?? 3600\n const sameSite = this._csrf.sameSite ?? 'lax'\n\n const cookie =\n `${cookieName}=${encodeURIComponent(token)}; ` +\n `Path=/; ` +\n `Secure; ` +\n `SameSite=${sameSite}; ` +\n `Max-Age=${maxAge}`\n\n const existingCookies = response.headers?.['Set-Cookie']\n\n response.headers = {\n ...(response?.headers ?? {}),\n 'Set-Cookie': [...(existingCookies ?? []), cookie],\n }\n\n return response\n }\n}\n","import type {\n HttpHeaders,\n IMiddleware,\n INetworkContextAccessor,\n IRoutePolicyCheck,\n ResponseDto,\n XenoRequest,\n} from '@xeno-js/shared'\nimport type { IAllowMethod } from '@xeno-js/shared'\nimport { Guards, HttpHelper, STATUS_CODES } from '@xeno-js/shared'\n\n/**\n * @description A middleware that handles OPTIONS requests.\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 OptionsMiddleware implements IMiddleware {\n constructor(\n private readonly _requestContext: INetworkContextAccessor,\n private readonly _allowMethod: IAllowMethod,\n private readonly _getRouteMatcher: () => IRoutePolicyCheck,\n private readonly _allowHeaders: string[] = [],\n private readonly _withCredentials: 'true' | 'false' = 'false',\n ) {}\n\n public async execute<T>(\n req: XenoRequest,\n next: () => Promise<ResponseDto<T>>,\n ): Promise<ResponseDto<T>> {\n if (req.method.toUpperCase() === 'OPTIONS') {\n const network = this._requestContext.getNetworkContext()\n const origin = network?.origin\n const targetMethod = req.headers.get('access-control-request-method') ?? 'GET'\n\n const policy = this._getRouteMatcher().checkRoutePolicy(req.path, targetMethod)\n\n const withCredentials = Guards.isDefined(policy.withCredentials)\n ? policy.withCredentials\n ? 'true'\n : 'false'\n : this._withCredentials\n\n const headers: HttpHeaders = {}\n if (\n Guards.isDefined(origin) ||\n (Guards.isDefined(policy.allowOrigins) && policy.allowOrigins.includes('*'))\n ) {\n headers['Access-Control-Allow-Origin'] =\n Guards.isDefined(policy.allowOrigins) &&\n policy.allowOrigins.includes('*') &&\n withCredentials === 'false'\n ? '*'\n : origin!\n headers['Access-Control-Allow-Credentials'] = withCredentials\n headers['Vary'] = 'Origin'\n }\n\n headers['Access-Control-Allow-Methods'] = this._allowMethod.getMethods(req.path)\n headers['Access-Control-Allow-Headers'] = this._allowHeaders.join(', ')\n\n return HttpHelper.success(null as T, STATUS_CODES.NO_CONTENT, {}, headers)\n }\n return await next()\n }\n}\n","import type {\n IContextAccessor,\n ILogger,\n IMiddleware,\n RequestContext,\n ResponseDto,\n XenoRequest,\n} from '@xeno-js/shared'\nimport type { IAtomicCache, IRateLimitKeyBuilder } from '@xeno-js/shared'\nimport {\n ERROR_CODE_MESSAGES,\n ERROR_CODES,\n Guards,\n GuidHelper,\n HttpHelper,\n STATUS_CODES,\n} from '@xeno-js/shared'\n\n/**\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.\n *\n * @author Xeno\n * @version 1.0.0\n * @since 1.0.0\n * @param {IContextAccessor<RequestContext>} _ctxAccessor - The context accessor for the request.\n * @param {IAtomicCache} _cache - The cache used to store the request counts.\n * @param {ILogger} _logger - The logger used to log messages.\n * @param {number} _opts.maxRequests - The maximum number of requests allowed within the time window.\n * @param {number} _opts.windowSeconds - The time window in seconds within which the maximum number of requests is allowed.\n * @link https://github.com/xenowits/xeno-js\n */\nexport class RateLimitMiddleware implements IMiddleware {\n constructor(\n private readonly _ctxAccessor: IContextAccessor<RequestContext>,\n private readonly _cache: IAtomicCache,\n private readonly _keyBuilder: IRateLimitKeyBuilder,\n private readonly _logger: ILogger,\n private readonly _opts: {\n maxRequests: number\n windowSeconds: number\n },\n ) {}\n\n public async execute<T>(\n req: XenoRequest,\n next: () => Promise<ResponseDto<T>>,\n ): Promise<ResponseDto<T>> {\n const cacheKey = this._keyBuilder.buildRateLimitKey(req.path)\n const { network, tracing } = this._ctxAccessor.getContext() ?? {}\n\n if (!Guards.isDefined(cacheKey))\n return HttpHelper.error(\n {\n success: false,\n error: {\n code: ERROR_CODES.SYSTEM_ERROR,\n message: ERROR_CODE_MESSAGES[ERROR_CODES.SYSTEM_ERROR],\n details: `Bad Request: Unable to identify client context for rate limiting.`,\n path: req.path,\n },\n correlationId: tracing?.correlationId ?? GuidHelper.generate(),\n requestId: network?.requestId ?? GuidHelper.generate(),\n spanId: tracing?.spanId ?? GuidHelper.generate(),\n timestamp: new Date().toISOString(),\n },\n STATUS_CODES.SERVICE_UNAVAILABLE,\n {\n 'Content-Type': [network?.formatIndicator ?? 'application/json'],\n 'Retry-After': [String(this._opts.windowSeconds)],\n },\n )\n\n const currentHits = await this._cache.increment(cacheKey, this._opts.windowSeconds)\n\n if (currentHits > this._opts.maxRequests) {\n this._logger.warn(`[RateLimit] key ${cacheKey} has been blocked on ${req.path}`)\n\n return HttpHelper.error(\n {\n success: false,\n error: {\n code: ERROR_CODES.TOO_MANY_REQUESTS,\n message: ERROR_CODE_MESSAGES[ERROR_CODES.TOO_MANY_REQUESTS],\n details: `Rate limit exceeded.`,\n path: req.path,\n },\n correlationId: tracing?.correlationId ?? GuidHelper.generate(),\n requestId: network?.requestId ?? GuidHelper.generate(),\n spanId: tracing?.spanId ?? GuidHelper.generate(),\n timestamp: new Date().toISOString(),\n },\n STATUS_CODES.TOO_MANY_REQUESTS,\n {\n 'Content-Type': [network?.formatIndicator ?? 'application/json'],\n 'Retry-After': [String(this._opts.windowSeconds)],\n },\n )\n }\n\n return next()\n }\n}\n","import type {\n Identity,\n ILogger,\n IMiddleware,\n IServiceExtractor,\n RequestContext,\n XenoRequest,\n} from '@xeno-js/shared'\nimport type { Guid, Metadata, ResponseDto } from '@xeno-js/shared'\nimport type { IIPResolver, IRequestContext, XenoRegistry } from '@xeno-js/shared'\nimport {\n ERROR_CODE_MESSAGES,\n ERROR_CODES,\n GUEST,\n GuidHelper,\n HttpHelper,\n STATUS_CODES,\n} from '@xeno-js/shared'\n\nimport { ContextMapper } from '../mappers/context.mapper'\n\n/**\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.\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 RequestContextMiddleware implements IMiddleware {\n /**\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.\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.\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.\n * @param _logger\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 constructor(\n private readonly _requestContext: IRequestContext<RequestContext, XenoRegistry>,\n private readonly _extractor: IServiceExtractor<Request['headers'], Metadata>,\n private readonly _resolver: IIPResolver,\n private readonly _logger: ILogger,\n ) {}\n\n public async execute<T>(\n req: XenoRequest,\n next: () => Promise<ResponseDto<T>>,\n ): Promise<ResponseDto<T>> {\n const correlationId = GuidHelper.generate()\n const requestId = GuidHelper.generate()\n const spanId: Guid = GuidHelper.generate()\n let formatIndicator = 'application/json'\n\n try {\n const meta = this._extractor.extract(req.headers)\n\n const clientIp = this._resolver.resolve(req, meta.clientIp)\n\n formatIndicator = meta.formatIndicator\n const metadata: Metadata = {\n ...meta,\n clientIp,\n correlationId: meta.correlationId ?? correlationId,\n requestId: meta.requestId ?? requestId,\n spanId: meta.spanId ?? spanId,\n formatIndicator,\n }\n\n const tmpContext = ContextMapper.map({\n metadata,\n identity: GUEST as unknown as Identity,\n path: req.path,\n })\n\n const result = await this._requestContext.runAsync(tmpContext, async () => {\n return next()\n })\n if (!result.ok && !result.data.success)\n this._logger.error(result.data.error.message, result.data)\n\n return result\n } catch (error) {\n this._logger.error('RequestContextMiddleware encountered an error', error)\n return HttpHelper.error(\n {\n success: false,\n error: {\n code: ERROR_CODES.SYSTEM_ERROR,\n message: ERROR_CODE_MESSAGES[ERROR_CODES.SYSTEM_ERROR],\n details: `[Fatal System Error] Exception caught during request handling on path: ${req.path}`,\n path: req.path,\n },\n correlationId,\n requestId,\n spanId,\n timestamp: new Date().toISOString(),\n },\n STATUS_CODES.INTERNAL_SERVER_ERROR,\n { 'Content-Type': [formatIndicator] },\n )\n }\n }\n}\n","import type {\n IBaseMapper,\n Identity,\n MessagingContext,\n NetworkContext,\n RequestContext,\n TracingContext,\n} from '@xeno-js/shared'\nimport { Guards, type Metadata, type Optional } from '@xeno-js/shared'\n\ninterface ContextMapperSource {\n readonly metadata: Metadata\n readonly identity: Identity\n readonly path: string\n}\n\nexport const ContextMapper: IBaseMapper<ContextMapperSource, RequestContext> = Object.freeze({\n /**\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.\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 map: (source: ContextMapperSource): RequestContext => {\n const { metadata, identity, path } = source\n\n const network: NetworkContext = {\n requestId: metadata.requestId!,\n clientIp: metadata.clientIp,\n userAgent: metadata.userAgent,\n formatIndicator: metadata.formatIndicator,\n path,\n csrf: metadata.csrf,\n csrfCookie: metadata.csrfCookie,\n cookies: metadata.cookies,\n origin: metadata.origin,\n }\n const tracing: TracingContext = {\n correlationId: metadata.correlationId!,\n startTime: Date.now(),\n spanId: metadata.spanId,\n parentSpanId: metadata.parentSpanId,\n referer: metadata.referer,\n }\n const messaging = _buildMessagingContext(metadata)\n\n const requestContext: RequestContext = {\n identity,\n network,\n tracing,\n messaging,\n }\n\n return requestContext\n },\n} as const)\n\n/**\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.\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.\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.\n *\n * @author Xeno\n * @version 1.0.0\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-js\n */\nfunction _buildMessagingContext(meta: Metadata): Optional<MessagingContext> {\n const hasSequenceData =\n Guards.isDefined(meta.sequence?.sequenceId) ||\n Guards.isDefined(meta.sequence?.position) ||\n Guards.isDefined(meta.sequence?.size)\n\n const hasMessagingData =\n hasSequenceData || Guards.isDefined(meta.expiration) || Guards.isDefined(meta.returnAddress)\n\n if (!hasMessagingData) return undefined\n\n return {\n returnAddress: meta.returnAddress,\n expiration: meta.expiration,\n sequence:\n hasSequenceData && Guards.isDefined(meta.sequence)\n ? {\n sequenceId: meta.sequence.sequenceId,\n position: meta.sequence.position,\n size: meta.sequence.size,\n }\n : undefined,\n }\n}\n","import type {\n IController,\n IMiddleware,\n Optional,\n RequestContext,\n ResponseDto,\n XenoRequest,\n} from '@xeno-js/shared'\nimport type { IHttpDispatcher, IRequestContext, IServiceProxy, XenoRegistry } from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\nexport class HttpDispatcher<\n TRegistry extends XenoRegistry = XenoRegistry,\n> implements IHttpDispatcher<TRegistry> {\n constructor(\n private readonly _requestContext: IRequestContext<RequestContext, TRegistry>,\n private readonly _middleware: IMiddleware,\n private readonly _serviceProxy: IServiceProxy,\n ) {}\n\n public async handle<TInput, TOutput, K extends keyof TRegistry>(\n req: XenoRequest,\n token: K,\n input?: Optional<TInput>,\n ): Promise<ResponseDto<TOutput>> {\n return await this._middleware.execute(req, async () => {\n const scope = this._requestContext.getScope()\n\n if (!Guards.isDefined(scope)) {\n throw new Error(\n '[HttpDispatcher Error]: Active scope not found. Execution outside RequestContext.',\n )\n }\n\n const services = this._serviceProxy.getServiceProxy<TRegistry>(scope)\n const controller = services[token] as Optional<IController<Optional<TInput>, TOutput>>\n\n if (!Guards.isDefined(controller) || !Guards.hasMethod(controller, 'handle')) {\n throw new Error(\n `[HttpDispatcher Error]: The provided '${String(token)}' does not implement the 'handle' method.`,\n )\n }\n\n return await controller.handle(input, req.signal)\n })\n }\n}\n","import type { Identity, RequestContext, ResponseDto, XenoRequest } from '@xeno-js/shared'\nimport type {\n IModule,\n IRequestContext,\n IServiceContainer,\n NativeRouteDefinition,\n XenoRegistry,\n} from '@xeno-js/shared'\nimport { GUEST, GuidHelper } from '@xeno-js/shared'\nimport { TOKENS } from '@xeno-js/shared'\n\nimport { RouteMatcherFactory } from '../factories/route-matcher.factory'\nimport { HttpDispatcher } from '../http/dispatcher.http'\n\n/**\n * @description RouteModule is responsible for registering routes services in the IoC container.\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 RouteModule<TRegistry extends XenoRegistry = XenoRegistry> implements IModule<\n TRegistry,\n NativeRouteDefinition<TRegistry>[]\n> {\n public async configure(\n container: IServiceContainer<TRegistry>,\n opts: NativeRouteDefinition<TRegistry>[],\n ): Promise<void> {\n container.addSingleton(TOKENS.ROUTE_MATCHER, () =>\n new RouteMatcherFactory().create<TRegistry>(opts),\n )\n\n if (!container.isRegistered(TOKENS.MIDDLEWARE)) {\n const requestContext = container.resolve(TOKENS.REQUEST_CONTEXT)\n container.addSingleton(TOKENS.MIDDLEWARE, () => ({\n execute: async <T>(\n req: XenoRequest,\n next: () => Promise<ResponseDto<T>>,\n ): Promise<ResponseDto<T>> => {\n const syntheticContext: RequestContext = {\n identity: GUEST as unknown as Identity,\n network: {\n requestId: GuidHelper.generate(),\n clientIp: '127.0.0.1',\n path: req.path,\n formatIndicator: 'application/json',\n },\n tracing: {\n correlationId: GuidHelper.generate(),\n startTime: Date.now(),\n spanId: GuidHelper.generate(),\n },\n }\n return await requestContext.runAsync(syntheticContext, next)\n },\n }))\n }\n\n if (!container.isRegistered(TOKENS.HTTP_DISPATCHER)) {\n container.addSingleton(\n TOKENS.HTTP_DISPATCHER,\n (c) =>\n new HttpDispatcher<TRegistry>(\n c.resolve(TOKENS.REQUEST_CONTEXT) as IRequestContext<RequestContext, TRegistry>,\n c.resolve(TOKENS.MIDDLEWARE),\n c.resolve(TOKENS.SERVICE_PROXY),\n ),\n )\n }\n }\n}\n","import type { IConfigurationService } from '@xeno-js/shared'\nimport type { IAppBuilder, IXenoApplication, XenoPlugin, XenoRegistry } from '@xeno-js/shared'\n\nexport const definePlugin = <\n TKind extends string,\n TRegistry extends XenoRegistry = XenoRegistry,\n TCtx = unknown,\n>(\n kind: TKind,\n fn: (\n builder: IAppBuilder<TRegistry, IXenoApplication<TRegistry>>,\n config: IConfigurationService,\n ctx?: TCtx,\n ) => unknown,\n): XenoPlugin<TKind, TRegistry, TCtx> => {\n Object.defineProperty(fn, '__kind', { value: kind, writable: false })\n return fn as XenoPlugin<TKind, TRegistry, TCtx>\n}\n","import type { IConfigurationService, SetupAction } from '@xeno-js/shared'\nimport type {\n AuthModuleOptions,\n AuthPlugin,\n IAppBuilder,\n IXenoApplication,\n XenoRegistry,\n} from '@xeno-js/shared'\n\nimport { AuthModule } from '../modules/auth.module'\nimport { definePlugin } from './define.plugin'\n\n/**\n * @description Generic plugin to register any custom authentication implementation into Xeno.JS.\n * It delegates the registration to the Core AuthModule.\n *\n * @param configurator Either the AuthModuleOptions object or a factory receiving the configuration service.\n * @returns A XenoPlugin ready to be passed to builder.addAuth(...)\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 const withAuth = <TRegistry extends XenoRegistry = XenoRegistry>(\n setup: SetupAction<AuthModuleOptions<TRegistry>, IConfigurationService>,\n): AuthPlugin<TRegistry> => {\n return definePlugin(\n 'auth',\n (\n builder: IAppBuilder<TRegistry, IXenoApplication<TRegistry>>,\n config: IConfigurationService,\n ) => {\n const options = {} as AuthModuleOptions<TRegistry>\n setup(options, config)\n builder.addModule('AuthModule', async () => new AuthModule<TRegistry>(), options, 2)\n },\n )\n}\n","// ==========================================\n// 3. AUTHORIZATION (AuthZ)\n// ==========================================\n\nimport type { IConfigurationService, Optional, SetupAction } from '@xeno-js/shared'\nimport type {\n AuthorizationOptions,\n IAppBuilder,\n IPipelineSetup,\n IXenoApplication,\n PipelinePlugin,\n XenoRegistry,\n} from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\nimport { definePlugin } from './define.plugin'\n\nexport const withAuthZ = <TRegistry extends XenoRegistry = XenoRegistry>(\n setup: SetupAction<AuthorizationOptions<TRegistry>, IConfigurationService>,\n): PipelinePlugin<TRegistry> => {\n return definePlugin(\n 'pipeline',\n (\n _builder: IAppBuilder<TRegistry, IXenoApplication<TRegistry>>,\n config: IConfigurationService,\n context: Optional<IPipelineSetup<TRegistry>>,\n ) => {\n if (!Guards.isDefined(context)) throw new Error('Pipeline setup is not available.')\n\n const options: AuthorizationOptions<TRegistry> = {\n policies: undefined,\n }\n setup(options, config)\n\n context.authzOpts = options\n },\n )\n}\n","// ==========================================\n// 5. CONCURRENCY RETRY (PER-INTENT)\n// ==========================================\nimport type {\n ConcurrencyOptions,\n IAppBuilder,\n IPipelineSetup,\n IXenoApplication,\n PipelinePlugin,\n XenoRegistry,\n} from '@xeno-js/shared'\nimport {\n Guards,\n type IConfigurationService,\n type Optional,\n type SetupAction,\n} from '@xeno-js/shared'\n\nimport { ConcurrencyRetryPipeline } from '@/application'\n\nimport { definePlugin } from './define.plugin'\n\nexport const withConcurrency = <TRegistry extends XenoRegistry = XenoRegistry>(\n setup?: SetupAction<ConcurrencyOptions, IConfigurationService>,\n): PipelinePlugin<TRegistry> => {\n return definePlugin(\n 'pipeline',\n (\n _builder: IAppBuilder<TRegistry, IXenoApplication<TRegistry>>,\n config: IConfigurationService,\n context: Optional<IPipelineSetup<TRegistry>>,\n ) => {\n if (!Guards.isDefined(context)) throw new Error('Pipeline setup is not available.')\n const options: ConcurrencyOptions = {}\n if (Guards.isDefined(setup)) setup(options, config)\n context.addCommand(new ConcurrencyRetryPipeline(options), 70)\n },\n )\n}\n","import type {\n HttpConfig,\n HttpPlugin,\n IAppBuilder,\n IXenoApplication,\n XenoRegistry,\n} from '@xeno-js/shared'\nimport { Guards, type IConfigurationService } from '@xeno-js/shared'\n\nimport { HttpCoreModule } from '../modules/http-core.module'\nimport { definePlugin } from './define.plugin'\n\n/**\n * @description Generic plugin to register any custom authentication implementation into Xeno.JS.\n * It delegates the registration to the Core AuthModule.\n *\n * @param configurator Either the AuthModuleOptions object or a factory receiving the configuration service.\n * @returns A XenoPlugin ready to be passed to builder.addAuth(...)\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 const withCustomHttp = <TRegistry extends XenoRegistry = XenoRegistry>(\n config: HttpConfig<TRegistry>,\n): HttpPlugin<TRegistry> => {\n return definePlugin(\n 'http',\n (\n builder: IAppBuilder<TRegistry, IXenoApplication<TRegistry>>,\n _config: IConfigurationService,\n ) => {\n const clientEntries = Guards.isArray(config.clients) ? config.clients : [config.clients]\n\n const entries = clientEntries.map((item) => {\n if (!Guards.isDefined(item.client)) {\n throw new Error(\n `[withCustomHttp Error]: 'client' instance is required for registration '${item.name ?? 'default'}'.`,\n )\n }\n\n return {\n name: item.name ?? 'default',\n client: item.client,\n resilience: item.resilience,\n }\n })\n\n builder.addModule('HttpCoreModule', async () => new HttpCoreModule<TRegistry>(), {\n clients: entries,\n })\n },\n )\n}\n","import type {\n HttpCoreConfig,\n IModule,\n IServiceContainer,\n IServiceScope,\n XenoRegistry,\n} from '@xeno-js/shared'\nimport { Guards, type IServiceResilience, type Optional } from '@xeno-js/shared'\nimport { TOKENS } from '@xeno-js/shared'\n\nimport { RemoteDataSource } from '../datasources'\nimport { HttpClientFactory } from '../factories/http.factory'\nimport { NoOpResilienceService } from '../services/resiliences'\n\n/**\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.\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 HttpCoreModule<TRegistry extends XenoRegistry = XenoRegistry> implements IModule<\n TRegistry,\n HttpCoreConfig<TRegistry>\n> {\n public async configure(\n container: IServiceContainer<TRegistry>,\n opts: HttpCoreConfig<TRegistry>,\n ): Promise<void> {\n const factory = new HttpClientFactory()\n\n for (const entry of opts.clients) {\n const clientName = entry.name ?? 'default'\n const resilience = this.getResilienceService(container, entry.resilience)\n const dataSource = new RemoteDataSource(entry.client(container), resilience)\n factory.add(clientName, dataSource)\n }\n\n container.addSingleton(TOKENS.HTTP_CLIENT_FACTORY, () => factory)\n }\n\n private getResilienceService(\n container: IServiceContainer<TRegistry>,\n resilience?: Optional<(scope: IServiceScope<TRegistry>) => IServiceResilience>,\n ) {\n if (!Guards.isDefined(resilience)) {\n return new NoOpResilienceService()\n } else {\n return resilience(container)\n }\n }\n}\n","import type {\n HttpBaseRequest,\n HttpMethod,\n HttpRequest,\n IHttpClient,\n IRemoteDataSource,\n IServiceResilience,\n Optional,\n ResultType,\n} from '@xeno-js/shared'\nimport { AppError, Result } from '@xeno-js/shared'\n\n/**\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.\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 RemoteDataSource implements IRemoteDataSource {\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.\n * These dependencies are injected into the class, allowing for greater flexibility and testability.\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.\n * @param _httpClient An instance of an agnostic HTTP client that implements the IHttpClient interface, used for sending HTTP requests to remote endpoints.\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.\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 constructor(\n private readonly _httpClient: IHttpClient,\n private readonly _resilienceService: IServiceResilience,\n ) {}\n\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.\n * @param endpoint The URL or endpoint to which the HTTP request is sent.\n * @param options The HttpRequest options that specify the HTTP method, headers, query parameters, body, and other request configurations.\n * @returns A Promise that resolves to a ResultType containing either the successful response data or an error if the request fails.\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 async send<TResponse, TBody = unknown>(\n endpoint: string,\n options: HttpRequest<TBody>,\n ): Promise<ResultType<TResponse>> {\n const response = await this._resilienceService.execute(async () => {\n switch (options.method) {\n case 'GET':\n return await this._httpClient.get<TResponse>(endpoint, options)\n case 'POST':\n return await this._httpClient.post<TResponse, TBody>(endpoint, options.body, options)\n case 'PUT':\n return await this._httpClient.put<TResponse, TBody>(endpoint, options.body, options)\n case 'PATCH':\n return await this._httpClient.patch<TResponse, TBody>(endpoint, options.body, options)\n case 'DELETE':\n return await this._httpClient.delete<TResponse>(endpoint, options)\n default:\n throw AppError.notSupported(\n this.constructor.name,\n `Unsupported HTTP method: ${options.method}`,\n )\n }\n }, options.signal)\n\n return Result.ok(response.data)\n }\n\n protected setOptions<T>(\n request: Optional<HttpBaseRequest>,\n method: HttpMethod,\n body: Optional<T> = undefined,\n ): HttpRequest<T> {\n return {\n query: request?.query,\n signal: request?.signal,\n timeoutMs: request?.timeoutMs,\n headers: request?.headers,\n responseType: request?.responseType,\n method,\n body,\n }\n }\n\n public async get<TResponse>(\n endpoint: string,\n request?: HttpBaseRequest,\n ): Promise<ResultType<TResponse>> {\n const options = this.setOptions(request, 'GET')\n\n return await this.send<TResponse>(endpoint, options)\n }\n\n public async post<TResponse, TBody = unknown>(\n endpoint: string,\n body: TBody,\n request?: HttpBaseRequest,\n ): Promise<ResultType<TResponse>> {\n const options = this.setOptions(request, 'POST', body)\n\n return await this.send<TResponse, TBody>(endpoint, options)\n }\n\n public async put<TResponse, TBody = unknown>(\n endpoint: string,\n body: TBody,\n request?: HttpBaseRequest,\n ): Promise<ResultType<TResponse>> {\n const options = this.setOptions(request, 'PUT', body)\n\n return await this.send<TResponse, TBody>(endpoint, options)\n }\n\n public async patch<TResponse, TBody = unknown>(\n endpoint: string,\n body: TBody,\n request?: HttpBaseRequest,\n ): Promise<ResultType<TResponse>> {\n const options = this.setOptions(request, 'PATCH', body)\n\n return await this.send<TResponse, TBody>(endpoint, options)\n }\n\n public async delete<TResponse>(\n endpoint: string,\n request?: HttpBaseRequest,\n ): Promise<ResultType<TResponse>> {\n const options = this.setOptions(request, 'DELETE')\n\n return await this.send<TResponse>(endpoint, options)\n }\n}\n","import type { IHttpClientFactory } from '@xeno-js/shared'\nimport { AppError, Guards, type IRemoteDataSource } from '@xeno-js/shared'\n\nexport class HttpClientFactory implements IHttpClientFactory {\n private readonly _clients = new Map<string, IRemoteDataSource>()\n\n public add(name: string, client: IRemoteDataSource): void {\n if (this._clients.has(name)) {\n throw new Error(`[HttpClientFactory Error]: Client '${name}' already registered.`)\n }\n this._clients.set(name, client)\n }\n\n public get(name = 'default'): IRemoteDataSource {\n const client = this._clients.get(name)\n if (!Guards.isDefined(client)) {\n const available = Array.from(this._clients.keys()).join(', ') ?? 'none'\n throw AppError.notFound(\n 'HttpClientFactory',\n `[HttpClientFactory Error]: Client '${name}' not found. Available clients: [${available}].`,\n )\n }\n return client\n }\n}\n","import type { IServiceResilience, Optional } from '@xeno-js/shared'\nimport { AppError } from '@xeno-js/shared'\n\n/**\n * @description No-Op (Pass-Through) of IServiceResilience.\n * Using when resilience pattern is not required\n */\nexport class NoOpResilienceService implements IServiceResilience {\n public async execute<T>(operation: () => Promise<T>, signal?: Optional<AbortSignal>): Promise<T> {\n AppError.throwIfAborted(signal, 'NoOpResilienceService.execute')\n return await operation()\n }\n}\n","import type {\n IAppBuilder,\n IdempotencyOptions,\n IPipelineSetup,\n IXenoApplication,\n PipelinePlugin,\n XenoRegistry,\n} from '@xeno-js/shared'\nimport {\n Guards,\n type IConfigurationService,\n type Optional,\n type SetupAction,\n} from '@xeno-js/shared'\n\nimport { definePlugin } from './define.plugin'\n\n// ==========================================\n// 4. IDEMPOTENCY (PER-INTENT)\n// ==========================================\nexport const withIdempotency = <TRegistry extends XenoRegistry = XenoRegistry>(\n setup?: SetupAction<IdempotencyOptions, IConfigurationService>,\n): PipelinePlugin<TRegistry> => {\n return definePlugin(\n 'pipeline',\n (\n _builder: IAppBuilder<TRegistry, IXenoApplication<TRegistry>>,\n config: IConfigurationService,\n context: Optional<IPipelineSetup<TRegistry>>,\n ) => {\n if (!Guards.isDefined(context)) throw new Error('Pipeline setup is not available.')\n\n const options: IdempotencyOptions = {}\n if (Guards.isDefined(setup)) setup(options, config)\n\n context.idempotencyOpts = options\n },\n )\n}\n","import type { IConfigurationService, LogLevel, SetupAction } from '@xeno-js/shared'\nimport type {\n IAppBuilder,\n ILoggerSetup,\n IXenoApplication,\n LoggerPlugin,\n XenoRegistry,\n} from '@xeno-js/shared'\nimport { Guards, LOG_LEVEL } from '@xeno-js/shared'\n\nimport { definePlugin } from './define.plugin'\n\ninterface ConsoleOptions {\n isEnabled?: boolean\n level?: LogLevel\n}\n\n/**\n * @description Plugin for configuring the logger in the application.\n *\n * @param builder - The application builder instance.\n * @param config - The configuration service instance.\n * @returns void\n *\n * @author Xeno\n */\nexport const withConsoleLogger = <TRegistry extends XenoRegistry = XenoRegistry>(\n setup: SetupAction<ConsoleOptions, IConfigurationService>,\n): LoggerPlugin<TRegistry> => {\n return definePlugin(\n 'logger',\n (\n _builder: IAppBuilder<TRegistry, IXenoApplication<TRegistry>>,\n config: IConfigurationService,\n ctx?: ILoggerSetup<TRegistry>,\n ) => {\n if (!Guards.isDefined(ctx)) throw new Error('LoggerSetup is not defined.')\n const options: ConsoleOptions = {\n isEnabled: true,\n level: LOG_LEVEL.DEBUG,\n }\n setup(options, config)\n\n ctx.addConsole(options.isEnabled ?? true, options.level)\n },\n )\n}\n","import type {\n IAppBuilder,\n IPipelineSetup,\n IXenoApplication,\n PerformanceOptions,\n PipelinePlugin,\n XenoRegistry,\n} from '@xeno-js/shared'\nimport {\n Guards,\n type IConfigurationService,\n type Optional,\n type SetupAction,\n} from '@xeno-js/shared'\nimport { TOKENS } from '@xeno-js/shared'\n\nimport { PerformancePipeline } from '@/application'\n\nimport { definePlugin } from './define.plugin'\n\n// ==========================================\n// 6. PERFORMANCE (PER-INTENT)\n// ==========================================\nexport const withPerformance = <TRegistry extends XenoRegistry = XenoRegistry>(\n setup?: SetupAction<PerformanceOptions, IConfigurationService>,\n): PipelinePlugin<TRegistry> => {\n return definePlugin(\n 'pipeline',\n (\n builder: IAppBuilder<TRegistry, IXenoApplication<TRegistry>>,\n config: IConfigurationService,\n context: Optional<IPipelineSetup<TRegistry>>,\n ) => {\n if (!Guards.isDefined(context)) throw new Error('Pipeline setup is not available.')\n\n const options: PerformanceOptions = {}\n if (Guards.isDefined(setup)) setup(options, config)\n\n const logger = builder.resolve(TOKENS.LOGGER)\n context.addCommon(\n new PerformancePipeline(logger, options?.intentThresholdMs, options?.thresholdMs ?? 500),\n 20,\n )\n },\n )\n}\n","// ==========================================\n// 7. QUERY CACHING\nimport type { IConfigurationService, Optional } from '@xeno-js/shared'\nimport type {\n IAppBuilder,\n IPipelineSetup,\n IXenoApplication,\n PipelinePlugin,\n XenoRegistry,\n} from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\nimport { definePlugin } from './define.plugin'\n\n// ==========================================\nexport const withQueryCaching = <\n TRegistry extends XenoRegistry = XenoRegistry,\n>(): PipelinePlugin<TRegistry> => {\n return definePlugin(\n 'pipeline',\n (\n _builder: IAppBuilder<TRegistry, IXenoApplication<TRegistry>>,\n _config: IConfigurationService,\n context: Optional<IPipelineSetup<TRegistry>>,\n ) => {\n if (!Guards.isDefined(context)) throw new Error('Pipeline setup is not available.')\n\n context.addQuery()\n },\n )\n}\n","import type {\n IAppBuilder,\n IPipelineSetup,\n IXenoApplication,\n PipelinePlugin,\n XenoRegistry,\n} from '@xeno-js/shared'\nimport {\n Guards,\n type IConfigurationService,\n type IRequest,\n type IStrategy,\n type Optional,\n type SetupAction,\n} from '@xeno-js/shared'\n\nimport { ValidationPipeline } from '@/application'\n\nimport { definePlugin } from './define.plugin'\n\n// ==========================================\n// 2. CUSTOM VALIDATION\n// ==========================================\nexport const withValidation = <TRegistry extends XenoRegistry = XenoRegistry>(\n setup: SetupAction<IStrategy<IRequest, boolean>[], IConfigurationService>,\n): PipelinePlugin<TRegistry> => {\n return definePlugin(\n 'pipeline',\n (\n _builder: IAppBuilder<TRegistry, IXenoApplication<TRegistry>>,\n config: IConfigurationService,\n context: Optional<IPipelineSetup<TRegistry>>,\n ) => {\n if (!Guards.isDefined(context)) throw new Error('Pipeline setup is not available.')\n\n const strategies: IStrategy<IRequest, boolean>[] = []\n setup(strategies, config)\n\n if (Guards.isNullOrEmpty(strategies)) return\n const validationPipeline = new ValidationPipeline(strategies)\n context.addCommon(validationPipeline, 50)\n },\n )\n}\n","import type {\n Identity,\n Optional,\n RequestContext,\n ResponseDto,\n XenoIncomingRequest,\n} from '@xeno-js/shared'\nimport type {\n IHttpDispatcher,\n IRequestContext,\n IServiceContainer,\n IXenoApplication,\n NativeListenOptions,\n ServicesProxy,\n XenoRegistry,\n} from '@xeno-js/shared'\nimport { AppError, Guards, GUEST, GuidHelper } from '@xeno-js/shared'\nimport { TOKENS } from '@xeno-js/shared'\n\nexport class XenoApplication<\n TRegistry extends XenoRegistry = XenoRegistry,\n> implements IXenoApplication<TRegistry> {\n constructor(protected readonly _container: IServiceContainer<TRegistry>) {}\n\n /**\n * @description Resolve the services proxy\n * @returns The services proxy\n */\n public getServices(): ServicesProxy<TRegistry> {\n const container = this._container\n return new Proxy({} as ServicesProxy<TRegistry>, {\n get(_target, prop: string | symbol) {\n return container.resolve(prop as keyof TRegistry)\n },\n })\n }\n\n /**\n * @description Resolve the services proxy for the current request scope.\n * @returns {ServicesProxy<TRegistry>} The services proxy.\n */\n public getScopedServices(): ServicesProxy<TRegistry> {\n const serviceProxy = this._container.resolve(TOKENS.SERVICE_PROXY)\n const requestContext = this._container.resolve(TOKENS.REQUEST_CONTEXT) as IRequestContext<\n RequestContext,\n TRegistry\n >\n const scope = requestContext.getScope()\n if (!Guards.isDefined(scope)) {\n throw AppError.notFound(\n '[XenoApplication Error]',\n 'Active scope not found.\\n' +\n 'Please use the \"runInScope\" or \"handle\" method for tasks outside the HTTP transport.',\n )\n }\n return serviceProxy.getServiceProxy<TRegistry>(scope)\n }\n\n /**\n * @description Run the given operation in a new scope.\n * @param {Function} operation The operation to run.\n * @param {Partial<RequestContext>} [ctx] The request context.\n * @returns {Promise<T>} The result of the operation.\n */\n public async runInScope<T>(\n operation: (services: ServicesProxy<TRegistry>) => Promise<T>,\n ctx: Optional<Partial<RequestContext>> = undefined,\n ): Promise<T> {\n const requestContext = this._container.resolve(TOKENS.REQUEST_CONTEXT) as IRequestContext<\n RequestContext,\n TRegistry\n >\n\n const syntheticContext: RequestContext = {\n identity: ctx?.identity ?? (GUEST as unknown as Identity),\n network: ctx?.network ?? {\n requestId: GuidHelper.generate(),\n clientIp: '127.0.0.1',\n path: 'internal://scope-runner',\n formatIndicator: 'application/json',\n },\n tracing: ctx?.tracing ?? {\n correlationId: GuidHelper.generate(),\n startTime: Date.now(),\n spanId: GuidHelper.generate(),\n },\n messaging: ctx?.messaging,\n }\n\n return await requestContext.runAsync(syntheticContext, async () => {\n const scope = requestContext.getScope()!\n const serviceProxy = this._container.resolve(TOKENS.SERVICE_PROXY)\n const services = serviceProxy.getServiceProxy<TRegistry>(scope)\n return await operation(services)\n })\n }\n\n /**\n * @description Runs a controller operation in the context of a request.\n * Use it only if middlewares are registered in the container.\n * @param req The XenoIncomingRequest request object.\n * @param token The token of the controller operation to run.\n * @param input The input to the controller operation.\n * @returns A promise that resolves to the output of the controller operation.\n */\n public async handle<TInput, TOutput, K extends keyof TRegistry>(\n req: XenoIncomingRequest,\n token: K,\n input?: Optional<TInput>,\n ): Promise<ResponseDto<TOutput>> {\n const dispatcher = this._container.resolve(TOKENS.HTTP_DISPATCHER) as IHttpDispatcher<TRegistry>\n const adapter = this._container.resolve(TOKENS.HTTP_ADAPTER)\n const extendedRequest = adapter.adapt(req)\n return await dispatcher.handle(extendedRequest, token, input)\n }\n\n /**\n * @description Resolves the HTTP server and starts listening on the specified port.\n * @param options The options for the HTTP server.\n * @returns A promise that resolves to the result of the HTTP server listen method.\n */\n public async listen(options?: NativeListenOptions): Promise<unknown> {\n const server = this._container.resolve(TOKENS.HTTP_SERVER)\n const opts = this._container.resolve(TOKENS.SERVER_OPTIONS_FACTORY).create(options)\n return await server.listen(opts)\n }\n}\n","import type { IMapper, IReadDao, IReadDataSource, ResultType } from '@xeno-js/shared'\nimport type { Optional, UserContext } from '@xeno-js/shared'\nimport { AppError, Result } from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\n/**\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.\n * @template T - The type of the entity that the DAO will manage.\n * @template TDto - The type of the Data Transfer Object (DTO) used for data access.\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 abstract class ReadDao<T, TDto> implements IReadDao<T> {\n /**\n * Constructs a new ReadDao instance.\n * @param _dataSource An instance of IReadDataSource used to execute SQL queries and commands for data access.\n * @param _mapper An instance of IMapper used to convert between entities and DTOs.\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 constructor(\n protected readonly _dataSource: IReadDataSource<TDto>,\n protected readonly _mapper: IMapper<T, TDto>,\n ) {}\n\n public async findById(\n id: string | number,\n ctx: UserContext,\n signal: Optional<AbortSignal>,\n ): Promise<ResultType<Optional<T>>> {\n AppError.throwIfAborted(signal, 'ReadDao.findById')\n const result = await this._dataSource.findById(id, ctx, signal)\n if (Guards.isNullOrEmpty(result)) return Result.ok()\n\n const entity = this._mapper.toEntity(result)\n return Result.ok(entity)\n }\n\n public async findAll(ctx: UserContext, signal: Optional<AbortSignal>): Promise<ResultType<T[]>> {\n AppError.throwIfAborted(signal, 'ReadDao.findAll')\n const results = await this._dataSource.findAll(ctx, signal)\n const entities = results.map((result) => this._mapper.toEntity(result))\n return Result.ok(entities)\n }\n}\n","import type { IMapper, IRepository, IWriteDataSource, ResultType } from '@xeno-js/shared'\nimport type { Optional, UserContext } from '@xeno-js/shared'\nimport { AppError, Result } from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\n/**\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.\n * @template T - The type of the entity that the repository will manage.\n * @template TDto - The type of the Data Transfer Object (DTO) used for data access.\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 abstract class Repository<T, TDto> implements IRepository<T> {\n /**\n * Constructs a new Repository instance.\n * @param _dataSource An instance of IWriteDataSource used to execute SQL queries and commands for data access.\n * @param _mapper An instance of IMapper used to convert between entities and DTOs.\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 constructor(\n protected readonly _dataSource: IWriteDataSource<TDto>,\n protected readonly _mapper: IMapper<T, TDto>,\n ) {}\n\n public async findById(\n id: string | number,\n ctx: UserContext,\n signal: Optional<AbortSignal>,\n ): Promise<ResultType<Optional<T>>> {\n AppError.throwIfAborted(signal, 'Repository.findById')\n\n const result = await this._dataSource.findById(id, ctx, signal)\n if (Guards.isNullOrEmpty(result)) return Result.ok()\n\n const entity = this._mapper.toEntity(result)\n return Result.ok(entity)\n }\n\n public async findAll(ctx: UserContext, signal: Optional<AbortSignal>): Promise<ResultType<T[]>> {\n AppError.throwIfAborted(signal, 'Repository.findAll')\n\n const results = await this._dataSource.findAll(ctx, signal)\n const entities = results.map((result) => this._mapper.toEntity(result))\n return Result.ok(entities)\n }\n\n public async save(entity: T, signal: Optional<AbortSignal>): Promise<ResultType<void>> {\n const dto = this._mapper.toDto(entity)\n\n AppError.throwIfAborted(signal, 'Repository.save')\n\n await this._dataSource.insert(dto, signal)\n return Result.ok()\n }\n\n public async delete(\n entity: T,\n ctx: UserContext,\n signal: Optional<AbortSignal>,\n ): Promise<ResultType<void>> {\n const dto = this._mapper.toDto(entity)\n\n AppError.throwIfAborted(signal, 'Repository.delete')\n\n await this._dataSource.delete(dto, ctx, signal)\n return Result.ok()\n }\n\n public async update(\n id: string | number,\n entity: Partial<T>,\n ctx: UserContext,\n signal: Optional<AbortSignal>,\n ): Promise<ResultType<void>> {\n const dto = this._mapper.toPartialDto(entity)\n\n AppError.throwIfAborted(signal, 'Repository.update')\n\n await this._dataSource.update(id, dto, ctx, signal)\n return Result.ok()\n }\n}\n","import type { NativeRouteDefinition, XenoRegistry } from '@xeno-js/shared'\n\n/**\n * @description Add CORS headers to a route definition.\n * Remember to add CORS middleware to your application during bootstrap.\n *\n * @param route The route to add CORS headers to.\n * @param allowOrigins Array of allowed origins (eg. ['https://example.com'] or ['*']).\n * @param withCredentials Whether to allow credentials. Default: true.\n * @returns The route definition with CORS headers added.\n */\nexport function withCors<TRegistry extends XenoRegistry = XenoRegistry>(\n route: NativeRouteDefinition<TRegistry>,\n allowOrigins: string[],\n withCredentials = true,\n): NativeRouteDefinition<TRegistry> {\n return {\n ...route,\n security: {\n ...route.security,\n allowOrigins,\n withCredentials,\n },\n }\n}\n\n/**\n * @description Disable CSRF protection for a route definition.\n * Use this if you need to allow cross-origin requests without CSRF protection. (eg. for Server to Server or a Webhook)\n *\n * @param route The route to disable CSRF protection for.\n * @returns The route definition with CSRF protection disabled.\n */\nexport function withoutCsrf<TRegistry extends XenoRegistry = XenoRegistry>(\n route: NativeRouteDefinition<TRegistry>,\n): NativeRouteDefinition<TRegistry> {\n return {\n ...route,\n security: {\n ...route.security,\n withCsrf: false,\n },\n }\n}\n\n/**\n * @description Allow CSRF protection for a route definition.\n * Remember to add CSRF middleware to your application during bootstrap.\n *\n * (Methods POST/PUT/PATCH/DELETE have a default CSRF protection if you added it during bootstrap, use this function if you want to force it for another method).\n *\n * @param route The route to disable CSRF protection for.\n * @returns The route definition with CSRF protection disabled.\n */\nexport function withCsrf<TRegistry extends XenoRegistry = XenoRegistry>(\n route: NativeRouteDefinition<TRegistry>,\n): NativeRouteDefinition<TRegistry> {\n return {\n ...route,\n security: {\n ...route.security,\n withCsrf: true,\n },\n }\n}\n","export {\n BaseAuthorizationStrategy,\n BaseHandler,\n Command,\n Query,\n SchemaValidationStrategy,\n Specification,\n ValidationPipeline,\n} from './application'\nexport {\n AuthModule,\n CacheModule,\n ContextModule,\n DbModule,\n HttpServerModule,\n LoggerModule,\n ReadDao,\n Repository,\n XenoAppBuilder,\n} from './infrastructure'\nexport * from './infrastructure/http/native-route.helper'\nexport * from './infrastructure/plugin'\nexport { BaseController } from './presentation'\nexport * from '@xeno-js/shared'\n"],"mappings":";;;;;;;;;;;;;;;;AAAA,IAYa;AAZb;AAAA;AAAA;AAYO,IAAM,2BAAN,MAA8D;AAAA,MACnE,MAAa,kBACX,OACA,kBACc;AACd,cAAM,EAAE,SAAS,OAAO,IAAI,MAAM,OAAO,SAAS;AAElD,cAAM,QAAQ,OAAO,gBAAgB;AAErC,cAAM,WAAW,MAAM,IAAI,CAAC,SAAS,MAAM,IAAI,CAAC;AAEhD,eAAO,QAAQ,IAAI,QAAQ;AAAA,MAC7B;AAAA,IACF;AAAA;AAAA;;;ACzBA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACgBA,SAAS,UAAAA,gBAAc;AAhBvB,IA4Ba;AA5Bb;AAAA;AAAA;AA4BO,IAAM,qBAAN,MAEiD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAWtD,YACmB,UACA,eACjB;AAFiB;AACA;AAAA,MAChB;AAAA,MAFgB;AAAA,MACA;AAAA,MAGnB,MAAa,SAAY,SAAyB,IAAkC;AAClF,cAAM,QAAQ,KAAK,cAAc,OAAO;AACxC,YAAI;AACF,iBAAO,MAAM,KAAK,SAAS,IAAI,EAAE,SAAS,MAAM,GAAG,EAAE;AAAA,QACvD,UAAE;AACA,gBAAM,MAAM,QAAQ;AAAA,QACtB;AAAA,MACF;AAAA,MAEO,eAAe,UAA0B;AAC9C,cAAM,QAAQ,KAAK,SAAS,SAAS;AACrC,YAAIA,SAAO,UAAU,KAAK,KAAKA,SAAO,UAAU,MAAM,OAAO,GAAG;AAC9D,gBAAM,UAAU,OAAO,OAAO;AAAA,YAC5B,GAAG,MAAM;AAAA,YACT,UAAU,OAAO,OAAO,QAAQ;AAAA,UAClC,CAAC;AAAA,QACH;AAAA,MACF;AAAA,MAEO,aAAuC;AAC5C,cAAM,QAAQ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O,KAAK,MAAM;AACzC,WAAOC,SAAO,GAAG;AAAA,EACnB;AAAA,EAEA,MAAa,OACX,QACA,KACA,QAC2B;AAC3B,UAAM,MAAM,KAAK,QAAQ,MAAM,MAAM;AAErC,IAAAD,WAAS,eAAe,QAAQ,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;;;AC/EO,SAAS,SACd,OACA,cACA,kBAAkB,MACgB;AAClC,SAAO;AAAA,IACL,GAAG;AAAA,IACH,UAAU;AAAA,MACR,GAAG,MAAM;AAAA,MACT;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;AASO,SAAS,YACd,OACkC;AAClC,SAAO;AAAA,IACL,GAAG;AAAA,IACH,UAAU;AAAA,MACR,GAAG,MAAM;AAAA,MACT,UAAU;AAAA,IACZ;AAAA,EACF;AACF;AAWO,SAAS,SACd,OACkC;AAClC,SAAO;AAAA,IACL,GAAG;AAAA,IACH,UAAU;AAAA,MACR,GAAG,MAAM;AAAA,MACT,UAAU;AAAA,IACZ;AAAA,EACF;AACF;;;ACzCA,cAAc;","names":["Guards","AppError","Result","AppError","ERROR_CODES","Result","STATUS_CODES","AppError","Result","ERROR_CODE_MESSAGES","ERROR_CODES","STATUS_CODES","AppError","Result","Guards","Guards","AppError","Result","Guards","AppError","Result","Guards","Guards","Result","AppError","AppError","Result","Guards","Guards","Result","AppError","AppError","Result","Guards","Guards","Result","AppError","AppError","Result","Guards","GuidHelper","Guards","GuidHelper","Result","AppError","AppError","Result","Result","Guards","Result","REQUEST_TYPE","Result","Guards","Result","GUEST","Guards","GuidHelper","Guards","LOG_LEVEL","TOKENS","Guards","Guards","Guards","Guards","TOKENS","Guards","Guards","Guards","HttpHelper","Guards","Guards","HttpHelper","Guards","HttpHelper","Guards","GuidHelper","HttpHelper","Guards","Guards","TOKENS","Guards","TOKENS","Guards","StringHelper","Guards","Guards","Guards","TOKENS","Guards","TOKENS","TOKENS","TOKENS","Guards","LOG_LEVEL","TOKENS","Guards","LOG_LEVEL","LoggerUtils","Guards","TOKENS","LOG_LEVEL","TOKENS","Guards","Guards","TOKENS","AppError","Guards","Result","Guards","Guards","HttpHelper","Guards","TOKENS","Guards","NodeRequestContextFactory","Guards","LOG_LEVEL","TOKENS","Guards","IDEMPOTENCY_CONSTANTS","Guards","TOKENS","LoggerUtils","LOG_LEVEL","Guards","Guards","TOKENS","AppError","Guards","TOKENS","Guards","TOKENS","RoutePatternHelper","Guards","HttpHelper","RoutePatternHelper","STATUS_CODES","RoutePatternHelper","TOKENS","Guards","Guards","LOG_LEVEL","Guards","LoggerUtils","Guards","LOG_LEVEL","TOKENS","GuidHelper","HttpHelper","ERROR_CODE_MESSAGES","ERROR_CODES","GuidHelper","HttpHelper","STATUS_CODES","ERROR_CODE_MESSAGES","ERROR_CODES","Guards","GuidHelper","HttpHelper","STATUS_CODES","GuidHelper","HttpHelper","STATUS_CODES","Guards","TOKENS","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","ERROR_CODE_MESSAGES","ERROR_CODES","GUEST","GuidHelper","HttpHelper","STATUS_CODES","Guards","GuidHelper","GUEST","HttpHelper","ERROR_CODES","ERROR_CODE_MESSAGES","STATUS_CODES","Guards","TOKENS","LoggerUtils","LOG_LEVEL","Guards","GUEST","GuidHelper","TOKENS","TOKENS","GUEST","GuidHelper","Guards","Guards","Guards","Guards","Guards","Guards","TOKENS","AppError","Result","AppError","Guards","AppError","TOKENS","Guards","Guards","Guards","Guards","Guards","LOG_LEVEL","Guards","LOG_LEVEL","Guards","TOKENS","Guards","TOKENS","Guards","Guards","Guards","Guards","AppError","Guards","GUEST","GuidHelper","TOKENS","TOKENS","Guards","LOG_LEVEL","PLimitConcurrencyService","AppError","Result","Guards","AppError","Result","Guards"]}
|
|
1
|
+
{"version":3,"sources":["../src/infrastructure/services/concurrency/p-limit.service.ts","../src/infrastructure/services/concurrency/index.ts","../src/infrastructure/context/request-context.ts","../src/infrastructure/factories/request-context.factory.ts","../src/application/cqrs/base-handler.ts","../src/application/cqrs/command/command.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/identity-enrichment.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/enrichment/noop-identity-enrichment.strategy.ts","../src/application/cqrs/pipelines/pipeline_strategies/validation/schema-validation.strategy.ts","../src/application/cqrs/pipelines/query-caching.pipeline.ts","../src/application/cqrs/pipelines/validation.pipeline.ts","../src/application/cqrs/query/query.ts","../src/application/gate_keepers/gate-keeper.ts","../src/application/gate_keepers/noauth.gate-keeper.ts","../src/application/loggers/base.logger.ts","../src/application/loggers/utils/logger-context.utils.ts","../src/application/mappers/claims-identity.mapper.ts","../src/application/policies/policy-registry.ts","../src/application/specifications/specification.ts","../src/infrastructure/builder/app.builder.ts","../src/infrastructure/configuration/node.configuration.ts","../src/infrastructure/configuration/vite.configuration.ts","../src/infrastructure/container/service-container.ts","../src/infrastructure/modules/auth.module.ts","../src/infrastructure/services/allow_methods/allow-method.service.ts","../src/infrastructure/services/allow_origins/allow-origin.http.ts","../src/infrastructure/services/index.ts","../src/infrastructure/services/cookies/cookies.service.ts","../src/infrastructure/services/crypto/crypto.service.ts","../src/infrastructure/services/csrf/csrf-token.service.ts","../src/infrastructure/services/extractors/extract-bearer.extractor.ts","../src/infrastructure/services/extractors/http-cookie.extractor.ts","../src/infrastructure/services/extractors/http-header.extractor.ts","../src/infrastructure/services/resolver/client-ip.resolver.ts","../src/infrastructure/modules/cache.module.ts","../src/infrastructure/cache/inmemory.cache.ts","../src/infrastructure/cache/key-builder.cache.ts","../src/infrastructure/cache/rate-limit-key-builder.cache.ts","../src/infrastructure/modules/utils/auth.utils.ts","../src/infrastructure/modules/utils/cache.utils.ts","../src/infrastructure/modules/utils/logger.utils.ts","../src/infrastructure/loggers/console.logger.ts","../src/infrastructure/modules/context.module.ts","../src/infrastructure/events/event.dispatcher.ts","../src/infrastructure/factories/allow-method.factory.ts","../src/infrastructure/factories/index.ts","../src/infrastructure/factories/service-scope.factory.ts","../src/infrastructure/factories/user-context.factory.ts","../src/infrastructure/http/adapter.http.ts","../src/infrastructure/http/url-builder.http.ts","../src/infrastructure/services/service_proxy/services.proxy.ts","../src/infrastructure/modules/cqrs.module.ts","../src/application/cqrs/pipelines/cache-invalidation.pipeline.ts","../src/infrastructure/idempotency/idempotency-store.ts","../src/infrastructure/pipeline_setup/setup.pipeline.ts","../src/infrastructure/modules/db.module.ts","../src/infrastructure/transaction/unit-of-work.ts","../src/infrastructure/transaction/transaction-state.ts","../src/infrastructure/modules/http-server.module.ts","../src/infrastructure/factories/route-matcher.factory.ts","../src/infrastructure/http/route-matcher.http.ts","../src/infrastructure/factories/server-options.factory.ts","../src/infrastructure/modules/logger.module.ts","../src/infrastructure/loggers/setup.logger.ts","../src/infrastructure/modules/middleware.module.ts","../src/presentation/controllers/base.controller.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/cookie-response.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/middlewares/request.middleware.ts","../src/presentation/mappers/context.mapper.ts","../src/infrastructure/http/dispatcher.http.ts","../src/infrastructure/modules/route.module.ts","../src/infrastructure/plugin/define.plugin.ts","../src/infrastructure/plugin/auth.plugin.ts","../src/infrastructure/plugin/authz.plugin.ts","../src/infrastructure/plugin/concurrency.plugin.ts","../src/infrastructure/plugin/http.plugin.ts","../src/infrastructure/modules/http-core.module.ts","../src/infrastructure/datasources/remote.datasource.ts","../src/infrastructure/factories/http.factory.ts","../src/infrastructure/services/resiliences/resilience.service.ts","../src/infrastructure/plugin/idempotency.plugin.ts","../src/infrastructure/plugin/identity-enrichment.plugin.ts","../src/infrastructure/plugin/logger.plugin.ts","../src/infrastructure/plugin/performance.plugin.ts","../src/infrastructure/plugin/query.plugin.ts","../src/infrastructure/plugin/validation.plugin.ts","../src/infrastructure/xeno_application/xeno.application.ts","../src/infrastructure/repositories/read-dao.ts","../src/infrastructure/repositories/repository.ts","../src/infrastructure/http/native-route.helper.ts","../src/index.ts"],"sourcesContent":["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 { AsyncLocalStorage } from 'node:async_hooks'\n\nimport type {\n Identity,\n IFactory,\n NetworkContext,\n Optional,\n RequestContext,\n TracingContext,\n} from '@xeno-js/shared'\nimport type {\n ExecutionContext,\n IRequestContext,\n IServiceScope,\n XenoRegistry,\n} from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\n/**\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.\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.\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 NodeRequestContext<\n TRegistry extends XenoRegistry = XenoRegistry,\n> implements IRequestContext<RequestContext, TRegistry> {\n /**\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.\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.\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.\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 constructor(\n private readonly _storage: AsyncLocalStorage<ExecutionContext<TRegistry>>,\n private readonly _factoryScope: IFactory<void, IServiceScope<TRegistry>>,\n ) {}\n\n public async runAsync<T>(context: RequestContext, fn: () => Promise<T>): Promise<T> {\n const scope = this._factoryScope.create()\n try {\n return await this._storage.run({ context, scope }, fn)\n } finally {\n await scope.dispose()\n }\n }\n\n public updateIdentity(identity: Identity): void {\n const store = this._storage.getStore()\n if (Guards.isDefined(store) && Guards.isDefined(store.context)) {\n store.context = Object.freeze({\n ...store.context,\n identity: Object.freeze(identity),\n })\n }\n }\n\n public getContext(): Optional<RequestContext> {\n const store = this._storage.getStore()\n if (!Guards.isDefined(store)) return undefined\n const context = store.context\n return Object.freeze(context)\n }\n\n public getIdentity(): Optional<Identity> {\n const store = this._storage.getStore()\n if (!Guards.isDefined(store)) return undefined\n return Object.freeze(store.context?.identity)\n }\n\n public getScope(): Optional<IServiceScope<TRegistry>> {\n const store = this._storage.getStore()\n if (!Guards.isDefined(store)) return undefined\n return store.scope\n }\n\n public getNetworkContext(): Optional<NetworkContext> {\n const store = this._storage.getStore()\n if (!Guards.isDefined(store)) return undefined\n return Object.freeze(store.context?.network)\n }\n\n public getTracingContext(): Optional<TracingContext> {\n const store = this._storage.getStore()\n if (!Guards.isDefined(store)) return undefined\n return Object.freeze(store.context?.tracing)\n }\n}\n","import { AsyncLocalStorage } from 'node:async_hooks'\n\nimport type { IFactory, RequestContext } from '@xeno-js/shared'\nimport type {\n ExecutionContext,\n IRequestContext,\n IServiceScope,\n XenoRegistry,\n} from '@xeno-js/shared'\n\nimport { NodeRequestContext } from '../context/request-context'\n\n/**\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.\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 NodeRequestContextFactory<\n TRegistry extends XenoRegistry = XenoRegistry,\n> implements IFactory<void, IRequestContext<RequestContext, TRegistry>> {\n private _store: AsyncLocalStorage<ExecutionContext<TRegistry>> = new AsyncLocalStorage<\n ExecutionContext<TRegistry>\n >()\n\n constructor(private readonly _factoryScope: IFactory<void, IServiceScope<TRegistry>>) {}\n\n public create(): IRequestContext<RequestContext, TRegistry> {\n return new NodeRequestContext<TRegistry>(this._store, this._factoryScope)\n }\n}\n","import type {\n IFactory,\n IHandler,\n IRequest,\n Optional,\n ResultType,\n UserContext,\n} from '@xeno-js/shared'\nimport { AppError } from '@xeno-js/shared'\n\n/**\n * BaseHandler is an abstract class that implements the IHandler interface.\n * It provides a base implementation for handling requests and executing strategies.\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 abstract class BaseHandler<\n TRequest extends IRequest<TResponse>,\n TResponse,\n> implements IHandler<TRequest, TResponse> {\n constructor(private readonly _identityFactory: IFactory<void, UserContext>) {}\n\n public async handle(\n request: TRequest,\n signal: Optional<AbortSignal>,\n ): Promise<ResultType<TResponse>> {\n AppError.throwIfAborted(signal, this.constructor.name)\n\n return await this.executeAsync(request, signal)\n }\n\n /**\n * Executes the strategy for the given request.\n * @param request - The request to be handled.\n * @param signal - (Optional) The abort signal for the request.\n * @throws {AppError} If the strategy execution fails.\n * @protected - This method should be overridden by subclasses.\n * @abstract - This method must be implemented by subclasses.\n * @async - This method is asynchronous.\n * @template TRequest - The type of the request.\n * @template TResponse - The type of the response.\n * @returns {Promise<ResultType<TResponse>>} A promise that resolves to the result of the strategy execution.\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 protected abstract executeAsync(\n request: TRequest,\n signal?: Optional<AbortSignal>,\n ): Promise<ResultType<TResponse>>\n\n /**\n * Gets the current context.\n * @returns {UserContext} The current context.\n * {@link UserContext}\n */\n protected _getCurrentContext(): UserContext {\n return this._identityFactory.create()\n }\n}\n","import type { ICommand, Optional, RequestType } from '@xeno-js/shared'\nimport { REQUEST_TYPE } from '@xeno-js/shared'\n\n/**\n * @description Base class for all commands.\n * @author Xeno\n * @version 1.0.0\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-js\n */\nexport abstract class Command<TResponse = unknown> implements ICommand<TResponse> {\n public readonly type: RequestType = REQUEST_TYPE.COMMAND\n public readonly cacheInvalidation: Optional<{\n keys?: string[]\n patterns?: string[]\n }> = undefined\n\n constructor(\n readonly intent: string,\n cacheInvalidation?: {\n keys?: string[]\n patterns?: string[]\n },\n ) {\n this.cacheInvalidation = cacheInvalidation\n }\n}\n","import type {\n Delegate,\n ICommand,\n IHandler,\n IMediator,\n IPipelineBehavior,\n IQuery,\n IRequest,\n Optional,\n ResultType,\n} from '@xeno-js/shared'\nimport type { IServiceScopeAccessor, XenoRegistry } from '@xeno-js/shared'\nimport { AppError, Result } from '@xeno-js/shared'\nimport { ERROR_CODE_MESSAGES, ERROR_CODES, Guards, STATUS_CODES } from '@xeno-js/shared'\nimport { TOKENS } from '@xeno-js/shared'\n\n/**\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).\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 Mediator<TRegistry extends XenoRegistry = XenoRegistry> implements IMediator {\n /**\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.\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 constructor(private readonly _factoryScope: IServiceScopeAccessor<TRegistry>) {}\n\n /**\n * @inheritdoc\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 async send<TResponse>(\n request: ICommand<TResponse>,\n signal: Optional<AbortSignal>,\n ): Promise<ResultType<TResponse>> {\n return this.process<TResponse>(request, TOKENS.COMMAND_PIPELINES_BEHAVIOR, signal)\n }\n\n /**\n * @inheritdoc\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 async query<TResponse>(\n request: IQuery<TResponse>,\n signal: Optional<AbortSignal>,\n ): Promise<ResultType<TResponse>> {\n return this.process<TResponse>(request, TOKENS.QUERY_PIPELINES_BEHAVIOR, signal)\n }\n\n /**\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.\n * @param request The command or query to be processed.\n * @param pipelineToken The token used to resolve the pipeline behaviors for the request.\n * @param signal An optional AbortSignal to allow cancellation of the request.\n * @returns A promise that resolves to the result of processing the request.\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 async process<TResponse>(\n request: IRequest<TResponse>,\n pipelineToken: keyof XenoRegistry,\n signal: Optional<AbortSignal>,\n ): Promise<ResultType<TResponse>> {\n if (Guards.isDefined(signal) && signal.aborted)\n return Result.fail(AppError.aborted(request.intent))\n\n const scope = this._factoryScope.getScope()\n\n if (!Guards.isDefined(scope))\n return Result.fail(\n AppError.create({\n code: ERROR_CODES.SCOPE_NOT_AVAILABLE,\n status: STATUS_CODES.INTERNAL_SERVER_ERROR,\n name: request.intent,\n message: ERROR_CODE_MESSAGES[ERROR_CODES.SCOPE_NOT_AVAILABLE],\n cause: new Error('Service scope is required to process the request.'),\n }),\n )\n\n const pipelines = scope.resolve(pipelineToken) as unknown as IPipelineBehavior<\n IRequest<TResponse>,\n TResponse\n >\n\n if (!Guards.isDefined(pipelines) || !Guards.hasMethod(pipelines, 'handle')) {\n return Result.fail(\n AppError.create({\n code: ERROR_CODES.PIPELINE_NOT_AVAILABLE,\n status: STATUS_CODES.INTERNAL_SERVER_ERROR,\n name: request.intent,\n message: ERROR_CODE_MESSAGES[ERROR_CODES.PIPELINE_NOT_AVAILABLE],\n cause: new Error('Pipeline behavior is required to process the request.'),\n }),\n )\n }\n\n const next: Delegate<TResponse> = () => {\n const handler = scope.resolve(request.intent as keyof TRegistry) as IHandler<\n IRequest<TResponse>,\n TResponse\n >\n\n if (!Guards.isDefined(handler) || !Guards.hasMethod(handler, 'handle')) {\n AppError.throw({\n code: ERROR_CODES.HANDLER_NOT_FOUND,\n status: STATUS_CODES.INTERNAL_SERVER_ERROR,\n name: request.intent,\n message: ERROR_CODE_MESSAGES[ERROR_CODES.HANDLER_NOT_FOUND],\n cause: new Error('Handler is required to process the request.'),\n })\n }\n return handler.handle(request, signal)\n }\n\n return pipelines.handle(request, next)\n }\n}\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","/* eslint-disable @typescript-eslint/naming-convention */\nimport type { Delegate, ICommand, IPipelineBehavior, Optional, ResultType } from '@xeno-js/shared'\nimport type { ConcurrencyOptions } from '@xeno-js/shared'\nimport {\n AppError,\n DEFAULT_CONCURRENCY,\n ERROR_CODES,\n PromiseHelper,\n Result,\n STATUS_CODES,\n} from '@xeno-js/shared'\n\n/**\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.\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 ConcurrencyRetryPipeline<\n TInput extends ICommand<TResult>,\n TResult,\n> implements IPipelineBehavior<TInput, TResult> {\n private static readonly DEFAULT_MAX_RETRIES = DEFAULT_CONCURRENCY.MAX_RETRIES\n private static readonly DEFAULT_BASE_DELAY_MS = DEFAULT_CONCURRENCY.BASE_DELAY\n private static readonly DEFAULT_MAX_JITTER_MS = DEFAULT_CONCURRENCY.MAX_JITTER\n\n /**\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.\n * @param _options Optional configuration options for the behavior, including the maximum number of retry attempts and the delay configuration for the exponential backoff strategy.\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 constructor(private readonly _options: Optional<ConcurrencyOptions> = undefined) {}\n\n /**\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.\n * @param request The input request to be handled, which must extend ICommand.\n * @param next The delegate function that represents the next behavior or handler in the pipeline.\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.\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 handle(request: TInput, next: Delegate<TResult>): Promise<ResultType<TResult>> {\n const intentConfig = this._options?.intentRegistry?.[request.intent]\n\n const maxRetries =\n intentConfig?.maxRetries ??\n this._options?.maxRetries ??\n ConcurrencyRetryPipeline.DEFAULT_MAX_RETRIES\n\n const baseDelay =\n intentConfig?.delayConfig?.baseDelayMs ??\n this._options?.delayConfig?.baseDelayMs ??\n ConcurrencyRetryPipeline.DEFAULT_BASE_DELAY_MS\n\n const jitter =\n intentConfig?.delayConfig?.maxJitterMs ??\n this._options?.delayConfig?.maxJitterMs ??\n ConcurrencyRetryPipeline.DEFAULT_MAX_JITTER_MS\n\n let attempts = 0\n\n while (true) {\n attempts++\n\n const result = await next()\n\n if (result.isOk() || !this.isConcurrencyError(result.getErrorOrThrow())) return result\n\n if (attempts >= maxRetries)\n return Result.fail(\n AppError.conflict(\n request.intent,\n `Maximum retry attempts (${maxRetries}) exceeded due to concurrency conflicts.`,\n ),\n )\n\n await PromiseHelper.delayWithJitter(baseDelay, jitter)\n }\n }\n\n /**\n * @description Checks if the given error is a concurrency conflict error.\n * @param error The error to be checked.\n * @returns A boolean indicating whether the error is a concurrency conflict error.\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 isConcurrencyError(error: AppError): boolean {\n return error.code === ERROR_CODES.CONFLICT && error.status === STATUS_CODES.CONFLICT\n }\n}\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","/* eslint-disable @typescript-eslint/naming-convention */\nimport type {\n Delegate,\n ICommand,\n IIdempotencyStore,\n INetworkContextAccessor,\n IPipelineBehavior,\n Optional,\n ResultType,\n} from '@xeno-js/shared'\nimport type { IdempotencyOptions } from '@xeno-js/shared'\nimport { AppError, Result } from '@xeno-js/shared'\nimport { Guards, IDEMPOTENCY_CONSTANTS } from '@xeno-js/shared'\n\n/**\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.\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 IdempotencyPipeline<\n TInput extends ICommand<TResult>,\n TResult,\n> implements IPipelineBehavior<TInput, TResult> {\n private static readonly DEFAULT_LOCK_TTL =\n IDEMPOTENCY_CONSTANTS.DEFAULT_IDEMPOTENCY_LOCK_TTL_SECONDS\n private static readonly DEFAULT_PROCESSED_TTL = IDEMPOTENCY_CONSTANTS.DEFAULT_TTL_SECONDS\n\n /**\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.\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.\n * @param _options Optional configuration options for the idempotency pipeline, including the TTL values for locks and processed results. These options allow for customization of the idempotency behavior based on the specific needs of the application. The constructor validates the input options 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.\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 constructor(\n private readonly _requestContextFactory: INetworkContextAccessor,\n private readonly _idempotencyStore: IIdempotencyStore,\n private readonly _options: Optional<IdempotencyOptions> = undefined,\n ) {}\n\n public async handle(request: TInput, next: Delegate<TResult>): Promise<ResultType<TResult>> {\n const network = this._requestContextFactory.getNetworkContext()\n if (!Guards.isDefined(network))\n return Result.fail(\n AppError.conflict(\n request.intent,\n `network context is not defined for request ${request.intent}`,\n ),\n )\n\n const intentConfig = this._options?.intentRegistry?.[request.intent]\n const lockTtl =\n intentConfig?.lockTtlSeconds ??\n this._options?.lockTtlSeconds ??\n IdempotencyPipeline.DEFAULT_LOCK_TTL\n\n const processedTtl =\n intentConfig?.processedTtlSeconds ??\n this._options?.processedTtlSeconds ??\n IdempotencyPipeline.DEFAULT_PROCESSED_TTL\n\n try {\n const alreadyProcessed = await this._idempotencyStore.hasBeenProcessed(network.requestId)\n if (alreadyProcessed) {\n const payload = await this._idempotencyStore.getPayload<TResult>(network.requestId)\n if (Guards.isDefined(payload)) {\n return Result.ok(payload)\n } else {\n return Result.fail(\n AppError.conflict(\n request.intent,\n `Idempotency store indicates request has been processed but no payload found for request ID ${network.requestId}`,\n ),\n )\n }\n }\n\n const lockAcquired = await this._idempotencyStore.acquireLock(network.requestId, lockTtl)\n\n if (!lockAcquired) {\n return Result.fail(\n AppError.conflict(\n request.intent,\n `Failed to acquire lock for request ID ${network.requestId}`,\n ),\n )\n }\n\n const result = await next()\n\n if (result.isOk()) {\n await this._idempotencyStore.markAsProcessed(\n network.requestId,\n result.getValueOrThrow() ?? { success: true },\n processedTtl,\n )\n } else {\n await this._idempotencyStore.releaseLock(network.requestId)\n }\n\n return result\n } catch (error: unknown) {\n await this._idempotencyStore.releaseLock(network.requestId)\n\n throw error\n }\n }\n}\n","import type {\n Delegate,\n Identity,\n IPipelineBehavior,\n IRequest,\n IRequestContext,\n IStrategy,\n RequestContext,\n ResultType,\n} from '@xeno-js/shared'\n\n/**\n * @description Pipeline behavior that runs the identity enrichment strategy selected for the request intent (or the global one, or a noop) before the next behavior is invoked.\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 IdentityEnrichmentPipeline implements IPipelineBehavior<IRequest<unknown>, unknown> {\n constructor(\n private readonly _requestContext: IRequestContext<RequestContext>,\n private readonly _strategy: IStrategy<Identity>,\n ) {}\n\n public async handle(\n request: IRequest<unknown>,\n next: Delegate<unknown>,\n ): Promise<ResultType<unknown>> {\n const identity: Identity = this._requestContext.getIdentity() ?? {}\n await this._strategy.execute(identity)\n return next()\n }\n}\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 {\n Delegate,\n Dictionary,\n ILogger,\n IPipelineBehavior,\n IRequest,\n ResultType,\n} from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\n/**\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.\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 */\nconst defaultThresholdMs = 500\n\n/**\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.\n *\n * @template TInput - The type of the input request, which must extend the IRequest interface.\n * @template TResult - The type of the result returned by the request handler.\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 PerformancePipeline<\n TInput extends IRequest<TResult>,\n TResult,\n> implements IPipelineBehavior<TInput, TResult> {\n /**\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.\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 readonly _thresholdMs: number\n\n private readonly _intentThresholdMS: Dictionary<{ thresholdMs: number }>\n\n /**\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.\n * @param _logger An instance of ILogger used for logging performance warnings related to the handling of requests.\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.\n * @throws Will throw an error if the provided thresholdMs value is not a positive integer.\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 constructor(\n private readonly _logger: ILogger,\n intentThresholdMS: Dictionary<{ thresholdMs: number }> = {},\n thresholdMs: number = defaultThresholdMs,\n ) {\n const message = `Invalid thresholdMs value: ${thresholdMs}. It must be a positive integer.`\n Guards.throwIfNegative(thresholdMs, message)\n if (thresholdMs === 0) {\n throw new Error(message)\n }\n this._thresholdMs = thresholdMs\n\n for (const [intent, val] of Object.entries(intentThresholdMS)) {\n const intentMessage = `Invalid thresholdMs value for intent '${intent}': ${val.thresholdMs}. It must be a positive integer.`\n Guards.throwIfNegative(val.thresholdMs, intentMessage)\n Guards.throwIfNotInteger(val.thresholdMs, intentMessage)\n if (val.thresholdMs === 0) {\n throw new Error(intentMessage)\n }\n }\n this._intentThresholdMS = intentThresholdMS\n }\n\n public async handle(request: TInput, next: Delegate<TResult>): Promise<ResultType<TResult>> {\n const startTime = performance.now()\n try {\n return await next()\n } finally {\n const endTime = performance.now()\n const duration = endTime - startTime\n\n const thresholdMs =\n this._intentThresholdMS?.[request.intent]?.thresholdMs ?? this._thresholdMs\n if (duration > thresholdMs) {\n this._logger.warn(`Performance warning: ${request.intent} took ${duration.toFixed(2)}ms`)\n }\n }\n }\n}\n","import type {\n IContextAccessor,\n Identity,\n IPolicyRegistry,\n IRequest,\n IStrategy,\n RequestContext,\n ResultType,\n} from '@xeno-js/shared'\nimport { AppError, Result } from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\n/**\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.\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 abstract class BaseAuthorizationStrategy<\n TInput extends IRequest,\n> implements IStrategy<TInput> {\n /**\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.\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.\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 constructor(\n protected readonly _policy: IPolicyRegistry,\n private readonly _requestContext: IContextAccessor<RequestContext>,\n ) {}\n\n public async execute(request: IRequest): Promise<ResultType<void>> {\n const context = this._requestContext.getContext()\n\n if (!Guards.isDefined(context)) {\n return Result.fail(AppError.unauthorized(request.intent, 'User is not authenticated.'))\n }\n\n const superadmin = this._policy.getPolicy('superadmin')\n if (!Guards.isNullOrEmpty(superadmin?.roles)) {\n const auth = context?.identity\n const roles = auth?.roles ?? []\n const hasRequiredRole = superadmin.roles?.some((role) => roles.includes(role))\n if (hasRequiredRole) return Result.ok()\n }\n\n return await this.performAuthorizationCheck(request, context.identity)\n }\n\n /**\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.\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.\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.\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.\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 protected abstract performAuthorizationCheck(\n request: IRequest,\n auth: Identity,\n ): Promise<ResultType<void>>\n}\n","import type {\n IContextAccessor,\n Identity,\n IPolicyRegistry,\n IRequest,\n RequestContext,\n} from '@xeno-js/shared'\nimport { AppError, Result } from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\nimport { BaseAuthorizationStrategy } from './base-authorization.strategy'\n\n/**\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.\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 PermissionAuthorizationStrategy extends BaseAuthorizationStrategy<IRequest> {\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.\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.\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.\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 constructor(policy: IPolicyRegistry, requestContext: IContextAccessor<RequestContext>) {\n super(policy, requestContext)\n }\n\n protected async performAuthorizationCheck(\n command: IRequest,\n auth: Identity,\n ): Promise<Result<void, AppError>> {\n const policy = this._policy.getPolicy(command.intent)\n\n if (!Guards.isNullOrEmpty(policy?.permissions)) {\n const permissions = auth.permissions ?? []\n const hasRequiredPermission = policy.permissions?.some((permission) =>\n permissions.includes(permission),\n )\n if (!hasRequiredPermission)\n return Result.fail(\n AppError.forbidden(command.intent, 'User does not have the required permissions.'),\n )\n }\n\n return Result.ok()\n }\n}\n","import type {\n IContextAccessor,\n Identity,\n IPolicyRegistry,\n IRequest,\n RequestContext,\n} from '@xeno-js/shared'\nimport { AppError, Result } from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\nimport { BaseAuthorizationStrategy } from './base-authorization.strategy'\n\n/**\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.\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 RoleAuthorizationStrategy extends BaseAuthorizationStrategy<IRequest> {\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.\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.\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 constructor(policy: IPolicyRegistry, requestContext: IContextAccessor<RequestContext>) {\n super(policy, requestContext)\n }\n\n protected async performAuthorizationCheck(\n command: IRequest,\n auth: Identity,\n ): Promise<Result<void, AppError>> {\n const policy = this._policy.getPolicy(command.intent)\n\n if (!Guards.isNullOrEmpty(policy?.roles)) {\n const roles = auth.roles ?? []\n const hasRequiredRole = policy.roles?.some((role) => roles.includes(role))\n if (!hasRequiredRole)\n return Result.fail(\n AppError.forbidden(command.intent, 'User does not have the required roles.'),\n )\n }\n\n return Result.ok()\n }\n}\n","import type {\n IContextAccessor,\n Identity,\n IPolicyRegistry,\n IRequest,\n RequestContext,\n} from '@xeno-js/shared'\nimport { AppError, Result } from '@xeno-js/shared'\nimport { Guards, GuidHelper } from '@xeno-js/shared'\n\nimport { BaseAuthorizationStrategy } from './base-authorization.strategy'\n\n/**\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.\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 TenantAuthorizationStrategy extends BaseAuthorizationStrategy<IRequest> {\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.\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.\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 constructor(policy: IPolicyRegistry, requestContext: IContextAccessor<RequestContext>) {\n super(policy, requestContext)\n }\n\n protected async performAuthorizationCheck(\n command: IRequest,\n auth: Identity,\n ): Promise<Result<void, AppError>> {\n const policy = this._policy.getPolicy(command.intent)\n\n if (Guards.isDefined(policy?.tenantId)) {\n if (Guards.isNullOrEmpty(auth.tenantId) || !GuidHelper.isValidGuid(auth.tenantId))\n return Result.fail(AppError.unauthorized(command.intent, 'Tenant is not authenticated.'))\n }\n\n return Result.ok()\n }\n}\n","import type {\n IContextAccessor,\n Identity,\n IPolicyRegistry,\n IRequest,\n RequestContext,\n} from '@xeno-js/shared'\nimport { AppError, Result } from '@xeno-js/shared'\nimport { Guards, GuidHelper } from '@xeno-js/shared'\n\nimport { BaseAuthorizationStrategy } from './base-authorization.strategy'\n\n/**\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.\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 UserAuthorizationStrategy extends BaseAuthorizationStrategy<IRequest> {\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.\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.\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 constructor(policy: IPolicyRegistry, requestContext: IContextAccessor<RequestContext>) {\n super(policy, requestContext)\n }\n\n protected async performAuthorizationCheck(\n command: IRequest,\n auth: Identity,\n ): Promise<Result<void, AppError>> {\n const policy = this._policy.getPolicy(command.intent)\n\n if (Guards.isDefined(policy?.userId)) {\n if (Guards.isNullOrEmpty(auth.userId) || !GuidHelper.isValidGuid(auth.userId))\n return Result.fail(AppError.unauthorized(command.intent, 'User is not authenticated.'))\n }\n\n return Result.ok()\n }\n}\n","import type { Identity, IStrategy, ResultType } from '@xeno-js/shared'\nimport { Result } from '@xeno-js/shared'\n\n/**\n * @description Default identity enrichment strategy. Leaves the identity unchanged.\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 NoopIdentityEnrichmentStrategy implements IStrategy<Identity> {\n public async execute(_identity: Identity): Promise<ResultType<void>> {\n return Result.ok()\n }\n}\n","import type { IRequest, IStrategy, IValidatorService, ResultType } from '@xeno-js/shared'\nimport { AppError, Result } from '@xeno-js/shared'\n\n/**\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.\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 SchemaValidationStrategy implements IStrategy<IRequest, boolean> {\n /**\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.\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.\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 constructor(private readonly _validator: IValidatorService) {}\n\n public async execute(request: IRequest): Promise<ResultType<boolean>> {\n const key = request.intent\n const parseResult = await this._validator.validate(key, request)\n\n if (!parseResult.isOk()) {\n const validatorError = parseResult.getErrorOrThrow()\n const details =\n validatorError.cause instanceof Error\n ? validatorError.cause.message\n : validatorError.message\n\n return Result.fail(\n Object.assign(AppError.validationError(request.intent, `Validation failed: ${details}`), {\n validatorError,\n }),\n )\n }\n\n return Result.ok(true)\n }\n}\n","import type {\n Delegate,\n ICache,\n ICacheKeyBuilder,\n ILogger,\n IPipelineBehavior,\n IQuery,\n ResultType,\n} from '@xeno-js/shared'\nimport { Result } from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\n/**\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.\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 QueryCachingPipeline<\n TInput extends IQuery<TResult>,\n TResult,\n> implements IPipelineBehavior<TInput, TResult> {\n /**\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.\n * @param _cacheService An instance of ICache used for interacting with the cache, including retrieving and storing cached responses based on cache keys.\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.\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 constructor(\n private readonly _cacheService: ICache,\n private readonly _cacheKeyBuilder: ICacheKeyBuilder,\n private readonly _logger: ILogger,\n ) {}\n\n public async handle(request: TInput, next: Delegate<TResult>): Promise<ResultType<TResult>> {\n if (\n Guards.isNullOrEmpty(request.cacheOptions) ||\n Guards.isNullOrEmpty(request.cacheOptions.cacheKey)\n )\n return next()\n\n const bypass =\n request.cacheOptions.bypassCache === true || request.cacheOptions.consistentRead === true\n\n const key = request.cacheOptions.isUserScoped\n ? this._cacheKeyBuilder.buildUserScopedKey(request.cacheOptions.cacheKey)\n : this._cacheKeyBuilder.buildContextualKey(request.cacheOptions.cacheKey)\n\n if (!bypass) {\n try {\n const cachedResponse = await this._cacheService.get<TResult>(key)\n if (Guards.isDefined(cachedResponse)) {\n this._logger.debug(\n `[Cache HIT] Returning data from cache for: ${request.cacheOptions.cacheKey}`,\n )\n return Result.ok(cachedResponse)\n }\n } catch (error) {\n this._logger.warn(\n `[Cache ERROR] Unable to read cache for: ${request.cacheOptions.cacheKey}. Proceeding to DB. Error: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n }\n\n const result = await next()\n\n if (result.isOk()) {\n try {\n await this._cacheService.set(key, result.getValueOrThrow(), request.cacheOptions.ttl)\n this._logger.debug(`[Cache SET] Data saved in cache for: ${key}`)\n } catch (error) {\n this._logger.warn(\n `[Cache ERROR] Unable to save cache for: ${key}. Error: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n }\n\n return result\n }\n}\n","import type { Delegate, IPipelineBehavior, IRequest, IStrategy, ResultType } from '@xeno-js/shared'\nimport { Result } from '@xeno-js/shared'\n/**\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.\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 ValidationPipeline<\n TInput extends IRequest<TResult>,\n TResult,\n> implements IPipelineBehavior<TInput, TResult> {\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.\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.\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 constructor(private readonly _validators: readonly IStrategy<TInput, boolean>[]) {}\n\n public async handle(request: TInput, next: Delegate<TResult>): Promise<ResultType<TResult>> {\n for (const validator of this._validators) {\n const validationResult = await validator.execute(request)\n if (!validationResult.isOk()) {\n return Result.fail(validationResult.getErrorOrThrow())\n }\n }\n return next()\n }\n}\n","import type { ICacheableOptions, IQuery, RequestType } from '@xeno-js/shared'\nimport { REQUEST_TYPE } from '@xeno-js/shared'\n\n/**\n * @description Base class for all queries.\n * @author Xeno\n * @version 1.0.0\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-js\n */\nexport abstract class Query<TResponse = unknown> implements IQuery<TResponse> {\n public readonly type: RequestType = REQUEST_TYPE.QUERY\n\n constructor(\n readonly intent: string,\n readonly cacheOptions: ICacheableOptions,\n ) {}\n}\n","import type {\n IBaseAuthService,\n IBaseMapper,\n Identity,\n IGateKeeper,\n ResultType,\n} from '@xeno-js/shared'\nimport type { AuthClaims, Optional } from '@xeno-js/shared'\nimport { Result } from '@xeno-js/shared'\nimport { Guards, GUEST } from '@xeno-js/shared'\n\n/**\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.\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 GateKeeper implements IGateKeeper {\n constructor(\n private readonly _authServiceResolver: () => IBaseAuthService,\n private readonly _mapper: IBaseMapper<AuthClaims, Identity>,\n ) {}\n\n public async authenticate(token: Optional<string>): Promise<ResultType<Identity>> {\n const guest = GUEST as unknown as Identity\n const authService = this._authServiceResolver()\n if (!Guards.isNullOrEmpty(token)) {\n const authResult = await authService.authenticate(token)\n\n if (!authResult.isOk()) return Result.fail(authResult.getErrorOrThrow())\n\n const claims = authResult.getValueOrThrow()\n if (!Guards.isNullOrEmpty(claims)) return Result.ok(this._mapper.map(claims))\n\n return Result.ok(guest)\n }\n\n const userResult = await authService.getUser()\n\n if (userResult.isOk()) {\n const user = userResult.getValueOrThrow()\n if (Guards.isDefined(user)) {\n return Result.ok(this._mapper.map(user))\n }\n }\n\n return Result.ok(guest)\n }\n}\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","import type { IContextAccessor, ILogger, ILoggerClient, RequestContext } from '@xeno-js/shared'\nimport type { LogLevel, Optional } from '@xeno-js/shared'\nimport { LOG_LEVEL, LOG_LEVEL_NAMES } from '@xeno-js/shared'\n\nimport { LoggerUtils } from './utils'\n\n/**\n * @description Concrete implementation of the ILogger interface that serves as a central logging service within the application. This class is designed to broadcast log messages to multiple logging clients (implementations of ILoggerClient) that are injected via the constructor. The BaseLogger class provides methods for logging messages at different levels (info, warn, debug, error) and ensures that only messages that meet or exceed the specified minimum log level are forwarded to the registered logging clients. This design allows for flexibility in logging, enabling the use of various logging providers (e.g., Sentry, Pino) without coupling the application code to specific logging frameworks.\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 BaseLogger implements ILogger {\n // ─── Private Fields ─────────────────────────────────────────────────────────\n private readonly _minLevel: LogLevel\n private readonly _loggers: ILoggerClient[]\n\n /**\n * @description Constructs a new instance of the BaseLogger class, which takes an array of ILoggerClient instances and an optional minimum log level. The ILoggerClient instances represent the various logging providers that will receive log messages from this logger. The minimum log level determines the threshold for logging messages, where messages with a log level below the specified minimum will not be forwarded to the logging clients. This allows for efficient logging by filtering out less critical log messages based on the configured log level.\n * @param _requestContext The request context that provides contextual information for log messages, such as request-specific data or metadata.\n * @param config The minimum log level for this logger instance. Only messages with a log level equal to or higher than this level will be processed and forwarded to the logging clients.\n * @param loggers An array of ILoggerClient instances that will receive log messages from this logger. Each ILoggerClient represents a different logging provider or destination (e.g., console, file, external service).\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 constructor(\n private readonly _requestContext: IContextAccessor<RequestContext>,\n config: LogLevel,\n loggers: ILoggerClient[],\n ) {\n this._minLevel = config\n this._loggers = loggers\n }\n\n public info(message: string): void {\n this.broadcast(LOG_LEVEL.INFO, message)\n }\n\n public warn(message: string): void {\n this.broadcast(LOG_LEVEL.WARN, message)\n }\n\n public debug(message: string): void {\n this.broadcast(LOG_LEVEL.DEBUG, message)\n }\n\n public error(message: string, error: unknown): void {\n this.broadcast(LOG_LEVEL.ERROR, message, error)\n }\n\n /**\n * @description Private method to broadcast log messages to all registered ILoggerClient instances. This method checks if the log level of the message meets or exceeds the configured minimum log level before forwarding the message to the logging clients. It iterates through the array of ILoggerClient instances and calls their track method with the appropriate parameters (log level, message, context, and error if applicable). This design allows for efficient logging by ensuring that only relevant log messages are processed and forwarded to the logging clients based on the configured log level.\n * @param level The log level of the message.\n * @param message The log message.\n * @param context Optional context information to include with the log message.\n * @param error Optional error object to include with the log message.\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 broadcast(level: LogLevel, message: string, error: Optional<unknown> = undefined): void {\n if (level < this._minLevel) return\n\n const logMessage = `[${LOG_LEVEL_NAMES[level]}] ${message}`\n const context = this._requestContext.getContext()\n const safeContext = LoggerUtils.toSafeContext(context)\n const safeError = LoggerUtils.toNormalizeError(error)\n for (const logger of this._loggers) {\n logger.track(level, logMessage, safeContext, safeError)\n }\n }\n}\n","import type { Dictionary, Optional, RequestContext } from '@xeno-js/shared'\nimport { Guards, HttpHelper, StringHelper } from '@xeno-js/shared'\n\n/**\n * @description LoggerUtils provides utility functions for working with LoggerContext objects.\n */\nexport const LoggerUtils = Object.freeze({\n /**\n * @description toSafeContext converts a RequestContext object to a LoggerContext object, ensuring that only the necessary fields are included.\n * @param ctx The RequestContext object to convert.\n * @returns The converted LoggerContext object.\n */\n toSafeContext(ctx: Optional<RequestContext>): Dictionary {\n const context = {\n identity: {\n userId: ctx?.identity?.userId,\n tenantId: ctx?.identity?.tenantId,\n },\n network: {\n requestId: ctx?.network?.requestId,\n path: ctx?.network?.path,\n origin: ctx?.network?.origin,\n clientIp: HttpHelper.maskIp(ctx?.network?.clientIp),\n },\n tracing: {\n correlationId: ctx?.tracing?.correlationId,\n spanId: ctx?.tracing?.spanId,\n startTime: ctx?.tracing?.startTime,\n parentSpanId: ctx?.tracing?.parentSpanId,\n },\n messaging: ctx?.messaging,\n }\n return StringHelper.safeStringifyObject(context)\n },\n\n toNormalizeError(error: unknown): Dictionary {\n if (error instanceof Error) {\n return {\n ...error,\n name: error.name,\n message: error.message,\n stack: error.stack,\n cause: Guards.isDefined(error.cause)\n ? LoggerUtils.toNormalizeError(error.cause)\n : error.cause,\n }\n }\n if (Guards.isObject(error)) {\n return { ...error }\n }\n return { message: Guards.isString(error) ? error : StringHelper.safeStringify(error) }\n },\n} as const)\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","import type { IPolicyRegistry } from '@xeno-js/shared'\nimport type { AuthPolicy, Optional } from '@xeno-js/shared'\n\n/**\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.\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 PolicyRegistry implements IPolicyRegistry {\n /**\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.\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.\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 constructor(private readonly _cache: Map<string, AuthPolicy> = new Map()) {}\n\n public addPolicy(intent: string, policy: AuthPolicy): this {\n const key = this.getKey(intent)\n this._cache.set(key, policy)\n return this\n }\n\n public setSuperadminRoles(roles: string[]): this {\n const key = this.getKey('superadmin')\n this._cache.set(key, { roles })\n return this\n }\n\n public getPolicy(intent: string): Optional<AuthPolicy> {\n const key = this.getKey(intent)\n return this._cache.get(key)\n }\n\n private getKey(intent: string): string {\n return `policy:${intent.toLowerCase()}`\n }\n}\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","import type {\n AuthModuleOptions,\n AuthPlugin,\n CacheConfig,\n CachePlugin,\n ContextPlugin,\n DbPlugin,\n HttpConfig,\n HttpPlugin,\n HttpServerPlugin,\n IAppBuilder,\n IConfigurationService,\n IModule,\n IServiceContainer,\n LoggerConfig,\n LoggerPlugin,\n MiddlewareConfig,\n NativeRouteDefinition,\n Nullable,\n PipelinePlugin,\n SetupAction,\n XenoRegistry,\n} from '@xeno-js/shared'\nimport { Guards, LOG_LEVEL, TOKENS } from '@xeno-js/shared'\n\nimport { EnvironmentConfigurationService } from '../configuration'\nimport { ViteConfigurationService } from '../configuration/vite.configuration'\nimport { ServiceContainer } from '../container/service-container'\nimport {\n CacheModule,\n ContextModule,\n CqrsModule,\n LoggerModule,\n MiddlewareModule,\n RouteModule,\n} from '../modules'\nimport { withAuth, withCustomHttp } from '../plugin'\nimport { XenoApplication } from '../xeno_application/xeno.application'\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 * @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 * @author Xeno\n * @version 1.0.0\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-js\n */\nexport class XenoAppBuilder<\n TRegistry extends XenoRegistry = XenoRegistry,\n TApp extends XenoApplication<TRegistry> = XenoApplication<TRegistry>,\n> implements IAppBuilder<TRegistry, TApp> {\n protected _container: IServiceContainer<TRegistry> = new ServiceContainer<TRegistry>()\n protected readonly _configuration: IConfigurationService\n protected _buildPromise: Nullable<Promise<TApp>> = null\n private _pipelinePlugins: PipelinePlugin<TRegistry>[] = []\n private _appFactory: Nullable<(container: IServiceContainer<TRegistry>) => TApp> = null\n\n constructor(\n container?: IServiceContainer<TRegistry>,\n configurationService?: 'vite' | 'node' | IConfigurationService,\n ) {\n this._container = container ?? new ServiceContainer<TRegistry>()\n\n this._configuration = this._getConfigurationService(configurationService)\n this._container.addSingleton(TOKENS.CONFIGURATION_SERVICE, () => this._configuration)\n }\n\n private _getConfigurationService(service?: 'vite' | 'node' | IConfigurationService) {\n if (!Guards.isDefined(service) || service === 'node')\n return new EnvironmentConfigurationService()\n\n if (service === 'vite') return new ViteConfigurationService()\n\n return service\n }\n\n // --- Module Configurations ---\n protected readonly _modules: QueuedModule[] = []\n\n // --- Specific Configurations ---\n private _middlewareConfig: MiddlewareConfig = {\n isSSR: false,\n cors: {\n enabled: true,\n enablePreflight: true,\n withCredentials: true,\n allowOrigins: [],\n allowHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'Accept', 'Origin'],\n },\n rateLimit: {\n enabled: true,\n maxRequests: 100,\n windowSeconds: 60,\n },\n csrf: undefined,\n trustedIpHeader: undefined,\n trustedProxies: [],\n authCookieName: 'sb-access-token',\n }\n private _routes: NativeRouteDefinition<TRegistry>[] = []\n\n // --- Module Queuing Flags ---\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 private _isHttpCoreQueued = false\n private _isHttpServerQueued = false\n private _isRouteModuleQueued = false\n private _isContextModuleQueued = false\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Application Modules Configuration\n // ─────────────────────────────────────────────────────────────────────────────\n\n protected setApplicationFactory(\n factory: (container: IServiceContainer<TRegistry>) => TApp,\n ): this {\n this._appFactory = factory\n return this\n }\n\n /**\n * @description Add http server plugin to the application.\n * @param plugin - The http server plugin to be added.\n * @returns {this} The current instance of the class.\n */\n public addHttpServer(plugin: HttpServerPlugin<TRegistry>): this {\n if (this._isHttpServerQueued) return this\n plugin(this, this._configuration)\n this._isHttpServerQueued = true\n return this\n }\n\n /**\n * @description Add a new route to the application.\n * @param routes - The routes to be added.\n * @returns {this} The current instance of the class.\n */\n public addRoutes(routes: NativeRouteDefinition<TRegistry>[]): this {\n this._routes.push(...routes)\n\n if (this._isRouteModuleQueued) return this\n this._modules.push({\n priority: 5,\n name: 'RouteModule',\n action: async () => {\n const routeModule = new RouteModule<TRegistry>()\n await routeModule.configure(this._container, this._routes)\n },\n })\n this._isRouteModuleQueued = true\n return this\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 * @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 if (this._isMiddlewareModuleQueued) return this\n if (Guards.isDefined(setupAction)) setupAction(this._middlewareConfig, this._configuration)\n\n this._modules.push({\n priority: 4,\n name: 'MiddlewareModule',\n action: async () => {\n const middlewareModule = new MiddlewareModule<TRegistry>()\n await middlewareModule.configure(this._container, {\n ...this._middlewareConfig,\n routes: this._routes,\n })\n },\n })\n\n this._isMiddlewareModuleQueued = true\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 * @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(plugin?: ContextPlugin<TRegistry>): this {\n if (this._isContextModuleQueued) return this\n\n if (Guards.isDefined(plugin)) plugin(this, this._configuration)\n else\n this._modules.push({\n priority: 0,\n name: 'ContextModule',\n action: async () => {\n const contextModule = new ContextModule<TRegistry>()\n await contextModule.configure(this._container)\n },\n })\n\n this._isContextModuleQueued = true\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 custom logging services.\n * @param plugin A LoggerPlugin instance or an array of LoggerPlugin instances to configure the logger.\n * @returns The current instance of AppBuilder for method chaining.\n */\n public addLogger(plugin?: LoggerPlugin<TRegistry> | LoggerPlugin<TRegistry>[]): this\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 custom logging services.\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 * @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(setupAction?: SetupAction<LoggerConfig<TRegistry>, IConfigurationService>): this\n\n public addLogger(\n pluginOrSetup?:\n | LoggerPlugin<TRegistry>\n | LoggerPlugin<TRegistry>[]\n | SetupAction<LoggerConfig<TRegistry>, IConfigurationService>,\n ): this {\n if (this._isLoggerModuleQueued) return this\n\n if (!Guards.isDefined(pluginOrSetup)) {\n this._modules.push({\n priority: 1,\n name: 'LoggerModule',\n action: async () => {\n const module = new LoggerModule<TRegistry>()\n await module.configure(this._container, {\n level: LOG_LEVEL.DEBUG,\n console: true,\n builder: this,\n config: this._configuration,\n })\n },\n })\n } else if (Guards.isArray(pluginOrSetup)) {\n this._modules.push({\n priority: 1,\n name: 'LoggerModule',\n action: async () => {\n const module = new LoggerModule<TRegistry>()\n await module.configure(this._container, {\n console: false,\n builder: this,\n config: this._configuration,\n plugins: pluginOrSetup,\n })\n },\n })\n } else if ((pluginOrSetup as LoggerPlugin<TRegistry>).__kind === 'logger') {\n this._modules.push({\n priority: 1,\n name: 'LoggerModule',\n action: async () => {\n const module = new LoggerModule<TRegistry>()\n await module.configure(this._container, {\n console: false,\n builder: this,\n config: this._configuration,\n plugins: [pluginOrSetup as LoggerPlugin<TRegistry>],\n })\n },\n })\n } else {\n const loggerConfig = {\n console: true,\n level: LOG_LEVEL.DEBUG,\n customLoggers: [],\n }\n const setupAction = pluginOrSetup as SetupAction<\n LoggerConfig<TRegistry>,\n IConfigurationService\n >\n setupAction(loggerConfig, this._configuration)\n this._modules.push({\n priority: 1,\n name: 'LoggerModule',\n action: async () => {\n const module = new LoggerModule<TRegistry>()\n await module.configure(this._container, {\n ...loggerConfig,\n builder: this,\n config: this._configuration,\n })\n },\n })\n }\n\n this._isLoggerModuleQueued = true\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 plugin Optional plugin function to configure the caching module.\n * @defaults The default caching module is the in-memory caching module.\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 addCache(plugin?: CachePlugin<TRegistry>): this\n public addCache(setupAction?: SetupAction<CacheConfig, IConfigurationService>): this\n public addCache(\n pluginOrSetup?: CachePlugin<TRegistry> | SetupAction<CacheConfig, IConfigurationService>,\n ): this {\n if (this._isCacheModuleQueued) return this\n\n if (!Guards.isDefined(pluginOrSetup))\n this._modules.push({\n priority: 2,\n name: 'CacheModule',\n action: async () => {\n await new CacheModule<TRegistry>().configure(this._container, { inMemory: true })\n },\n })\n else if ((pluginOrSetup as CachePlugin<TRegistry>).__kind === 'cache')\n (pluginOrSetup as CachePlugin<TRegistry>)(this, this._configuration)\n else {\n const cacheConfig: CacheConfig = {\n inMemory: true,\n }\n const setupAction = pluginOrSetup as SetupAction<CacheConfig, IConfigurationService>\n\n setupAction(cacheConfig, this._configuration)\n\n this._modules.push({\n priority: 2,\n name: 'CacheModule',\n action: async () => {\n await new CacheModule<TRegistry>().configure(this._container, cacheConfig)\n },\n })\n }\n\n this._isCacheModuleQueued = true\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 plugin A plugin function that configures the authentication client.\n * @returns The current instance of AppBuilder for method chaining.\n */\n public addAuth(plugin: AuthPlugin<TRegistry>): this\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 function that configures the authentication client.\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 addAuth(\n setupAction: SetupAction<AuthModuleOptions<TRegistry>, IConfigurationService>,\n ): this\n\n public addAuth(\n pluginOrSetup:\n AuthPlugin<TRegistry> | SetupAction<AuthModuleOptions<TRegistry>, IConfigurationService>,\n ): this {\n if (this._isAuthModuleQueued) return this\n if ((pluginOrSetup as AuthPlugin<TRegistry>).__kind === 'auth')\n (pluginOrSetup as AuthPlugin<TRegistry>)(this, this._configuration)\n else {\n withAuth<TRegistry>(\n pluginOrSetup as SetupAction<AuthModuleOptions<TRegistry>, IConfigurationService>,\n )(this, this._configuration)\n }\n this._isAuthModuleQueued = true\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 plugin 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 * @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(plugin: DbPlugin<TRegistry>): this {\n if (this._isDbContextModuleQueued) return this\n plugin(this, this._configuration)\n this._isDbContextModuleQueued = true\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(\n TOKENS.CONCURRENCY_SERVICE,\n () => new PLimitConcurrencyService(),\n )\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 pluginOrPlugins?: PipelinePlugin<TRegistry> | PipelinePlugin<TRegistry>[],\n ): this {\n if (this._isPipelineModuleQueued) return this\n\n if (Guards.isDefined(pluginOrPlugins))\n this._pipelinePlugins = Guards.isArray(pluginOrPlugins) ? pluginOrPlugins : [pluginOrPlugins]\n\n this._modules.push({\n priority: 5,\n name: 'CqrsModule',\n action: async () => {\n await new CqrsModule<TRegistry>().configure(this._container, {\n plugins: this._pipelinePlugins,\n builder: this,\n })\n },\n })\n\n this._isPipelineModuleQueued = true\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 and HTTP client configuration.\n * @param plugin A HttpPlugin object that contains the HTTP core configuration.\n * @returns The current instance of AppBuilder for method chaining.\n */\n public addHttpClient(plugin: HttpPlugin<TRegistry>): this\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 SetupAction<HttpConfig, IConfigurationService> object to configure the HTTP core settings.\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 addHttpClient(setupAction: SetupAction<HttpConfig, IConfigurationService>): this\n\n public addHttpClient(\n pluginOrSetup: HttpPlugin<TRegistry> | SetupAction<HttpConfig, IConfigurationService>,\n ): this {\n if (this._isHttpCoreQueued) return this\n if ((pluginOrSetup as HttpPlugin<TRegistry>).__kind === 'http')\n (pluginOrSetup as HttpPlugin<TRegistry>)(this, this._configuration)\n else {\n const httpConfig: HttpConfig = {\n clients: [],\n }\n const setupAction = pluginOrSetup as SetupAction<HttpConfig, IConfigurationService>\n setupAction(httpConfig, this._configuration)\n withCustomHttp<TRegistry>(httpConfig)(this, this._configuration)\n }\n\n this._isHttpCoreQueued = true\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 priority = 99,\n ): this {\n this._modules.push({\n priority,\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>(\n name: string,\n factory: () => Promise<IModule<TRegistry, T>>,\n opts?: T,\n priority = 50,\n ): this {\n this._modules.push({\n priority,\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 * @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 * @author Xeno\n * @version 1.0.0\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-js\n */\n public build(): Promise<TApp> {\n if (Guards.isDefined(this._buildPromise)) {\n return this._buildPromise\n }\n\n const attempt = this._executeBuild()\n this._buildPromise = attempt\n\n void attempt.then(\n () => {\n /* noop */\n },\n async () => {\n if (this._buildPromise === attempt) {\n this._buildPromise = null\n await this._resetContainer()\n }\n },\n )\n\n return attempt\n }\n\n protected async _resetContainer(): Promise<void> {\n await this._container.dispose()\n this._container = new ServiceContainer<TRegistry>()\n this._container.addSingleton(TOKENS.CONFIGURATION_SERVICE, () => this._configuration)\n }\n\n /**\n * @description Executes the build process by initializing all registered modules in the container.\n */\n private async _executeBuild(): Promise<TApp> {\n console.info('⚙️ Bootstrapping application modules...')\n if (!this._isContextModuleQueued) {\n if (this._configuration instanceof ViteConfigurationService)\n throw new Error(\n 'Cannot add node context module to the application builder when using ViteConfigurationService. \\nPlease use addContext passing a context plugin such as withPiniaContext() from @xeno-js/vue',\n )\n else this.addContext()\n }\n\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 if (Guards.isDefined(this._appFactory)) return this._appFactory(this._container)\n\n return new XenoApplication<TRegistry>(this._container) as TApp\n }\n}\n","import type { IConfigurationService } from '@xeno-js/shared'\nimport type { Dictionary, Optional } from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\n/**\n * @description\n * This class implements the IConfigurationService interface and provides methods to retrieve configuration values from environment variables.\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 EnvironmentConfigurationService implements IConfigurationService {\n /**\n * @description Internal dictionary to hold environment variables.\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 readonly _env: Dictionary<Optional<string>>\n\n /**\n * @description Constructs an instance of EnvironmentConfigurationService and initializes the internal environment variable dictionary.\n * @author Xeno\n * @version 1.0.0\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-js\n */\n constructor() {\n this._env = process.env\n }\n\n public get(key: string, defaultValue?: string): Optional<string> {\n const value = this._env[key]\n if (Guards.isNullOrEmpty(value)) {\n return defaultValue\n }\n return value\n }\n\n public getEnvironment(): string {\n return this._env.NODE_ENV ?? 'development'\n }\n\n public getNumber(key: string, defaultValue?: number): Optional<number> {\n const value = this.get(key)\n if (Guards.isNullOrEmpty(value)) {\n return defaultValue\n }\n const parsed = Number(value)\n if (isNaN(parsed)) {\n throw new Error(\n `[Configuration Error]: Key \"${key}\" with value \"${value}\" is not a valid number.`,\n )\n }\n return parsed\n }\n\n public getBoolean(key: string, defaultValue?: boolean): Optional<boolean> {\n const value = this.get(key)\n if (Guards.isNullOrEmpty(value)) {\n return defaultValue\n }\n const normalized = value.toLowerCase().trim()\n if (normalized === 'true' || normalized === '1') return true\n if (normalized === 'false' || normalized === '0') return false\n\n throw new Error(\n `[Configuration Error]: Key \"${key}\" with value \"${value}\" is not a valid boolean.`,\n )\n }\n\n public getOrThrow(key: string): string {\n const value = this.get(key)\n if (!Guards.isDefined(value)) {\n throw new Error(\n `[Configuration Error]: Required configuration key \"${key}\" is missing in the environment.`,\n )\n }\n return value\n }\n}\n","import type { Dictionary, IConfigurationService, Optional } from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\ndeclare global {\n interface ImportMeta {\n env: Dictionary\n }\n}\n\nconst VITE_PREFIX = 'VITE_'\n\n/**\n * @description Implementation of IConfigurationService for Vite/Browser environments.\n * Encapsulates environment variable reading with type-safety and default fallbacks.\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 ViteConfigurationService implements IConfigurationService {\n constructor(private readonly _env: Dictionary = import.meta.env ?? {}) {}\n\n public get(key: string, defaultValue?: string): Optional<string> {\n const fullKey = key.startsWith(VITE_PREFIX) ? key : `VITE_${key}`\n const value = String(this._env[fullKey])\n\n if (!Guards.isNullOrEmpty(value)) return value\n\n return defaultValue\n }\n\n public getNumber(key: string, defaultValue?: number): Optional<number> {\n const rawValue = this.get(key)\n if (Guards.isDefined(rawValue)) {\n const parsed = Number(rawValue)\n if (!Number.isNaN(parsed)) return parsed\n }\n return defaultValue\n }\n\n public getBoolean(key: string, defaultValue?: boolean): Optional<boolean> {\n const rawValue = this.get(key)\n if (Guards.isDefined(rawValue)) {\n const str = String(rawValue).toLowerCase().trim()\n if (str.toLowerCase() === 'true' || str === '1') return true\n if (str.toLowerCase() === 'false' || str === '0') return false\n }\n return defaultValue\n }\n\n public getOrThrow(key: string): string {\n const val = this.get(key)\n if (!Guards.isDefined(val)) {\n throw new Error(`[Configuration Error]: Missing required environment variable \"${key}\".`)\n }\n return val\n }\n\n public getEnvironment(): string {\n return (this._env.MODE as string) ?? 'development'\n }\n}\n","// import { AsyncLocalStorage } from 'node:async_hooks'\n\nimport type {\n Factory,\n IDisposable,\n IServiceContainer,\n IServiceScope,\n Lifetime,\n Optional,\n XenoRegistry,\n} from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * @description Represents a registration entry in the service container, encapsulating the token, lifetime, and factory function for creating instances of the service.\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 RegistrationEntry<T, Registry extends XenoRegistry = XenoRegistry> {\n /**\n * The unique injection token that identifies the service registration.\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 token: keyof Registry\n /**\n * The lifetime of the service registration, indicating how instances are managed and reused.\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 lifetime: Lifetime\n /**\n * The factory function responsible for creating instances of the service.\n * It receives the current service scope as an argument, allowing for dependency resolution within that scope.\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 factory: Factory<T, [IServiceScope<Registry>]>\n}\n\n/**\n * @description Represents the context of service resolution, including the stack of tokens being resolved and the active lifetime of the current resolution.\n * @author Xeno\n * @version 1.0.0\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-js\n */\ninterface ResolutionContext<Registry> {\n /**\n * A set of tokens currently being resolved, used to detect circular dependencies.\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 stack: Set<keyof Registry>\n /**\n * The active lifetime of the current resolution, indicating whether we are constructing a singleton, scoped, or transient service.\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 activeLifetime?: Lifetime\n}\n\n/**\n * @description Concrete implementation of {@link IServiceScope}, representing a logical scope for resolving scoped services within the service container.\n * @author Xeno\n * @version 1.0.0\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-js\n */\nclass ContainerScope<\n Registry extends XenoRegistry = XenoRegistry,\n> implements IServiceScope<Registry> {\n private readonly scopedInstances = new Map<keyof Registry, unknown>()\n private readonly trackedDisposables: unknown[] = []\n private isDisposed = false\n\n constructor(\n private readonly container: ServiceContainer<Registry>,\n private readonly parentScope?: ContainerScope<Registry>,\n ) {}\n\n public resolve<K extends keyof Registry>(token: K): Registry[K] {\n if (this.isDisposed) {\n throw new Error(\n `[DI Container Error]: Unable to resolve '${token as string}'. The scope has been closed.`,\n )\n }\n return this.container.internalExecuteInContext(() =>\n this.container.internalResolveInternal(token, this),\n )\n }\n\n public getScopedInstance<K extends keyof Registry>(token: K): Registry[K] | undefined {\n return this.scopedInstances.get(token) as Registry[K] | undefined\n }\n\n public setScopedInstance<K extends keyof Registry>(token: K, instance: Registry[K]): void {\n this.scopedInstances.set(token, instance)\n if (isDisposable.check(instance)) {\n this.trackedDisposables.push(instance)\n }\n }\n\n public trackInstance(instance: unknown): void {\n if (isDisposable.check(instance) && !this.trackedDisposables.includes(instance)) {\n this.trackedDisposables.push(instance)\n }\n }\n\n public async dispose(): Promise<void> {\n if (this.isDisposed) return\n this.isDisposed = true\n\n for (let i = this.trackedDisposables.length - 1; i >= 0; i--) {\n const disposable = this.trackedDisposables[i]\n if (isDisposable.check(disposable)) {\n try {\n await disposable.dispose()\n } catch (err) {\n console.error(`[DI Container Dispose Error]: Failed to dispose resource`, err)\n }\n }\n }\n\n this.scopedInstances.clear()\n this.trackedDisposables.length = 0\n }\n}\n\n/**\n * @description Concrete implementation of {@link IServiceContainer}.\n *\n * Supports three registration lifetimes:\n * - **singleton** — one shared instance per container.\n * - **transient** — a new instance on every {@link resolve} call.\n * - **scoped** — one instance per {@link IServiceScope}; must be resolved\n * through a scope obtained via {@link createScope}.\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 ServiceContainer<\n Registry extends XenoRegistry = XenoRegistry,\n> implements IServiceContainer<Registry> {\n private readonly registrations = new Map<keyof Registry, RegistrationEntry<unknown, Registry>>()\n private readonly singletonInstances = new Map<keyof Registry, unknown>()\n private readonly rootScope: ContainerScope<Registry>\n private resolutionStack: Optional<ResolutionContext<Registry>> = undefined\n\n constructor() {\n this.rootScope = new ContainerScope<Registry>(this)\n }\n\n public addSingleton<K extends keyof Registry>(\n token: K,\n factory: Factory<Registry[K], [IServiceScope<Registry>]>,\n ): this {\n this.register(token, 'singleton', factory)\n return this\n }\n\n public addScoped<K extends keyof Registry>(\n token: K,\n factory: Factory<Registry[K], [IServiceScope<Registry>]>,\n ): this {\n this.register(token, 'scoped', factory)\n return this\n }\n\n public addTransient<K extends keyof Registry>(\n token: K,\n factory: Factory<Registry[K], [IServiceScope<Registry>]>,\n ): this {\n this.register(token, 'transient', factory)\n return this\n }\n\n private register<K extends keyof Registry>(\n token: K,\n lifetime: Lifetime,\n factory: Factory<Registry[K], [IServiceScope<Registry>]>,\n ): void {\n if (this.registrations.has(token)) {\n const tokenName = token.toString()\n throw new Error(\n `[DI Container Error]: The token '${tokenName}' is already registered in the container.`,\n )\n }\n this.registrations.set(token, { token, lifetime, factory })\n }\n\n public resolve<K extends keyof Registry>(token: K): Registry[K] {\n const registration = this.registrations.get(token)\n\n if (registration?.lifetime === 'scoped') {\n throw new Error(\n `[DI Container Error]: Scoped service '${String(token)}' requires an active scope.`,\n )\n }\n\n return this.internalExecuteInContext(() => this.rootScope.resolve(token))\n }\n\n public isRegistered<K extends keyof Registry>(token: K): boolean {\n return this.registrations.has(token)\n }\n\n public createScope(): IServiceScope<Registry> {\n return new ContainerScope<Registry>(this, this.rootScope)\n }\n\n /**\n * Executes a callback function within the context of the service container's resolution stack.\n * This method ensures that the resolution stack is properly managed, allowing for circular dependency detection and lifetime tracking during service resolution.\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 internalExecuteInContext<T>(callback: () => T): T {\n if (Guards.isDefined(this.resolutionStack)) return callback()\n\n this.resolutionStack = {\n stack: new Set<keyof Registry>(),\n }\n\n try {\n return callback()\n } finally {\n this.resolutionStack = undefined\n }\n }\n\n /**\n * Resolve the service for the given token within the provided scope.\n * @param token The injection token to resolve.\n * @param currentScope The current service scope for resolving scoped services.\n * @returns The resolved service instance of type `T`.\n * @throws An error if no registration is found for the given token.\n * @throws An error if a circular dependency is detected.\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 internalResolveInternal<K extends keyof Registry>(\n token: K,\n currentScope: ContainerScope<Registry>,\n ): Registry[K] {\n const registration = this.registrations.get(token)\n if (!Guards.isDefined(registration)) {\n const tokenName = token.toString()\n throw new Error(\n `[DI Container Error]: Registration not found for token '${tokenName}'. Ensure the service is registered before resolving.`,\n )\n }\n\n const currentStack = this.resolutionStack\n if (!Guards.isDefined(currentStack)) {\n throw new Error(`[DI Container Error]: Execution outside the IoC container context.`)\n }\n\n if (currentStack.stack.has(token)) {\n const cyclePath = [...currentStack.stack, token].map((t) => t.toString()).join(' -> ')\n const tokenName = token.toString()\n throw new Error(\n `[DI Circular Dependency Error]: Detected circular dependency while resolving '${tokenName}'. Resolution path: ${cyclePath}`,\n )\n }\n\n if (currentStack.activeLifetime === 'singleton' && registration.lifetime === 'scoped') {\n const captivePath = [...currentStack.stack, token].map((t) => t.toString()).join(' -> ')\n throw new Error(\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}`,\n )\n }\n\n const executeWithStackIsolation = (\n targetLifetime: Lifetime,\n factoryFn: () => Registry[K],\n ): Registry[K] => {\n const previousLifetime = currentStack.activeLifetime\n currentStack.stack.add(token)\n\n currentStack.activeLifetime =\n registration.lifetime === 'singleton' ? 'singleton' : previousLifetime\n try {\n return factoryFn()\n } finally {\n currentStack.stack.delete(token)\n currentStack.activeLifetime = previousLifetime\n }\n }\n\n if (registration.lifetime === 'singleton') {\n if (this.singletonInstances.has(token)) {\n return this.singletonInstances.get(token) as Registry[K]\n }\n\n return executeWithStackIsolation('singleton', () => {\n const instance = registration.factory(this.rootScope) as Registry[K]\n this.singletonInstances.set(token, instance)\n this.rootScope.trackInstance(instance)\n return instance\n })\n }\n\n if (registration.lifetime === 'scoped') {\n const existingInstance = currentScope.getScopedInstance(token)\n if (Guards.isDefined(existingInstance)) {\n return existingInstance\n }\n\n return executeWithStackIsolation('scoped', () => {\n const instance = registration.factory(currentScope) as Registry[K]\n currentScope.setScopedInstance(token, instance)\n return instance\n })\n }\n\n return executeWithStackIsolation('transient', () => {\n const instance = registration.factory(currentScope) as Registry[K]\n if (isDisposable.check(instance)) {\n currentScope.trackInstance(instance)\n }\n return instance\n })\n }\n\n public async dispose(): Promise<void> {\n await this.rootScope.dispose()\n this.singletonInstances.clear()\n this.registrations.clear()\n }\n}\n\nconst isDisposable = Object.freeze({\n check: (obj: unknown): obj is IDisposable => {\n return (\n Guards.isDefined(obj) &&\n Guards.isObject(obj) &&\n 'dispose' in obj &&\n Guards.hasMethod(obj, 'dispose')\n )\n },\n} as const)\n","import type { AuthModuleOptions, IModule, IServiceContainer, XenoRegistry } from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\nimport { TOKENS } from '@xeno-js/shared'\n\nimport { BearerTokenExtractor, CookieHandler } from '../services'\n\n/**\n * @description AuthModule is responsible for registering authentication services and\n * the token extractor in the IoC container. If no custom tokenExtractor is provided,\n * it falls back to the default BearerTokenExtractor.\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 AuthModule<TRegistry extends XenoRegistry = XenoRegistry> implements IModule<\n TRegistry,\n AuthModuleOptions<TRegistry>\n> {\n public async configure(\n container: IServiceContainer<TRegistry>,\n opts: AuthModuleOptions<TRegistry>,\n ): Promise<void> {\n if (!Guards.isDefined(opts.authService))\n throw new Error(\n '[AuthModule Error]: An authService instance is required to configure AuthModule.',\n )\n\n if (Guards.isDefined(opts.cookieHandlerOptions)) {\n if (Guards.isDefined(opts.cookieHandlerOptions.cookieHandlerCustom)) {\n container.addScoped(TOKENS.COOKIE_HANDLER, (c) =>\n opts.cookieHandlerOptions!.cookieHandlerCustom!(c),\n )\n } else if (\n Guards.isDefined(opts.cookieHandlerOptions.enableDefault) &&\n opts.cookieHandlerOptions.enableDefault.enable\n ) {\n container.addScoped(\n TOKENS.COOKIE_HANDLER,\n (c) =>\n new CookieHandler(\n c.resolve(TOKENS.NETWORK_CONTEXT_ACCESSOR),\n c.resolve(TOKENS.CONFIGURATION_SERVICE),\n opts.cookieHandlerOptions!.enableDefault?.options,\n ),\n )\n }\n }\n\n this.getExtractor(opts, container)\n\n container.addScoped(TOKENS.AUTH_SERVICE, (c) => opts.authService(c))\n container.addScoped(TOKENS.BASE_AUTH_SERVICE, (c) => c.resolve(TOKENS.AUTH_SERVICE))\n }\n\n private getExtractor(\n opts: AuthModuleOptions<TRegistry>,\n container: IServiceContainer<TRegistry>,\n ): void {\n if (Guards.isDefined(opts.tokenExtractor)) {\n container.addSingleton(TOKENS.TOKEN_SERVICE_EXTRACTOR, (c) => opts.tokenExtractor!(c))\n } else {\n container.addSingleton(\n TOKENS.TOKEN_SERVICE_EXTRACTOR,\n () => new BearerTokenExtractor(opts.defaultCookieName ?? 'sb-access-token'),\n )\n }\n }\n}\n","import type { IAllowMethod } from '@xeno-js/shared'\nimport { Guards, type HttpMethod, type Optional, RoutePatternHelper } from '@xeno-js/shared'\n\ninterface DynamicRoute {\n pattern: RegExp\n methods: HttpMethod[]\n}\n\nexport class AllowMethodRegistry implements IAllowMethod {\n private readonly _staticRoutes = new Map<string, HttpMethod[]>()\n private readonly _dynamicRoutes: DynamicRoute[] = []\n\n public add(path: string, methods: HttpMethod[]): void {\n const normalizedPath = RoutePatternHelper.normalizePath(path)\n if (RoutePatternHelper.isDynamicPath(normalizedPath)) {\n const pattern = RoutePatternHelper.createRoutePattern(normalizedPath)\n this._dynamicRoutes.push({ pattern, methods })\n } else {\n this._staticRoutes.set(normalizedPath, methods)\n }\n }\n\n public check(path: string, method: HttpMethod): boolean {\n const cleanPath = RoutePatternHelper.normalizePath(path.split('?')[0].split('#')[0])\n const staticMethods = this._staticRoutes.get(cleanPath)\n if (Guards.isDefined(staticMethods)) return staticMethods.includes(method)\n for (const route of this._dynamicRoutes) {\n if (route.pattern.test(cleanPath)) return route.methods.includes(method)\n }\n return false\n }\n\n public getMethods(path: string): string {\n const cleanPath = RoutePatternHelper.normalizePath(path.split('?')[0].split('#')[0])\n const methods = this.findMethods(cleanPath)\n return Guards.isDefined(methods) ? methods.join(', ').toUpperCase() : ''\n }\n\n private findMethods(cleanPath: string): Optional<HttpMethod[]> {\n const staticMethods = this._staticRoutes.get(cleanPath)\n if (Guards.isDefined(staticMethods)) return staticMethods\n for (const route of this._dynamicRoutes) {\n if (route.pattern.test(cleanPath)) return route.methods\n }\n return undefined\n }\n}\n","import type { Optional } from '@xeno-js/shared'\nimport type { IAllowOrigin } from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\n/**\n * @description A class that implements the IAllowOrigin interface.\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 AllowOrigin implements IAllowOrigin {\n constructor(private readonly _list: string[]) {}\n\n public isAllowed(origin: Optional<string>): boolean {\n if (Guards.isNullOrEmpty(origin)) return true\n\n const cleanOrigin = origin.trim().toLowerCase()\n\n for (const pattern of this._list) {\n const cleanPattern = pattern.trim().toLowerCase()\n\n if (cleanPattern === '*') return true\n\n if (cleanPattern === cleanOrigin) return true\n\n if (cleanPattern.startsWith('*.')) {\n const domainSuffix = cleanPattern.substring(1)\n if (cleanOrigin.endsWith(domainSuffix)) {\n const prefix = cleanOrigin.slice(0, cleanOrigin.length - domainSuffix.length)\n if (!Guards.isNullOrEmpty(prefix) && !prefix.includes('.')) return true\n }\n }\n }\n\n return false\n }\n}\n","export * from './allow_methods/index'\nexport * from './allow_origins/index'\nexport * from './concurrency/index'\nexport * from './cookies/index'\nexport * from './crypto/index'\nexport * from './csrf/index'\nexport * from './extractors/index'\nexport * from './resolver/index'\n","import type { IConfigurationService, INetworkContextAccessor } from '@xeno-js/shared'\nimport type { ISsrCookie, ISsrCookieHandler, ISsrCookieToSet } from '@xeno-js/shared'\nimport { Guards, HttpHelper } from '@xeno-js/shared'\n\n/**\n *\n */\nexport class CookieHandler implements ISsrCookieHandler {\n private readonly _pendingCookies: ISsrCookieToSet[] = []\n\n constructor(\n private readonly _contextAccessor: INetworkContextAccessor,\n private readonly _config: IConfigurationService,\n private readonly _defaultOpts?: Partial<ISsrCookieToSet>,\n ) {}\n\n public getAll(): ISsrCookie[] {\n const network = this._contextAccessor.getNetworkContext()\n const cookie = network?.cookies\n\n if (Guards.isNullOrEmpty(cookie)) return []\n\n const parsedCookies = HttpHelper.parseCookies(network?.cookies)\n\n return Object.entries(parsedCookies).map(([name, value]) => ({\n name,\n value,\n }))\n }\n\n public setAll(cookies: ISsrCookieToSet[]): void {\n this._pendingCookies.push(...cookies)\n }\n\n public getPendingCookies(): string[] {\n return this._pendingCookies.map((c) => this.serialize(c))\n }\n\n private serialize(cookie: ISsrCookieToSet): string {\n const safeName = encodeURIComponent(cookie.name)\n const safeValue = encodeURIComponent(cookie.value ?? '')\n let str = `${safeName}=${safeValue}`\n\n const isProd = this._config.get('NODE_ENV') === 'production'\n const merged: ISsrCookieToSet = {\n path: '/',\n httpOnly: true,\n secure: isProd,\n sameSite: 'lax',\n ...this._defaultOpts,\n ...cookie,\n }\n\n if (!Guards.isNullOrEmpty(merged.path)) str += `; Path=${merged.path}`\n\n if (!Guards.isNullOrEmpty(merged.maxAge)) str += `; Max-Age=${merged.maxAge}`\n\n if (!Guards.isNullOrEmpty(merged.expires)) str += `; Expires=${merged.expires.toUTCString()}`\n\n if (!Guards.isNullOrEmpty(merged.domain)) str += `; Domain=${merged.domain}`\n\n if (!Guards.isNullOrEmpty(merged.secure) && merged.secure) str += '; Secure'\n\n if (!Guards.isNullOrEmpty(merged.httpOnly) && merged.httpOnly) str += '; HttpOnly'\n\n if (!Guards.isNullOrEmpty(merged.sameSite)) {\n if (Guards.isBoolean(merged.sameSite)) {\n str += merged.sameSite ? '; SameSite=Strict' : ''\n } else {\n const val = merged.sameSite.toLowerCase()\n const formatted = val.charAt(0).toUpperCase() + val.slice(1)\n str += `; SameSite=${formatted}`\n }\n }\n\n if (Guards.isDefined(merged.partitioned)) str += '; Partitioned'\n\n if (Guards.isDefined(merged.priority)) {\n const p = merged.priority.toLowerCase()\n const formattedPriority = p.charAt(0).toUpperCase() + p.slice(1)\n str += `; Priority=${formattedPriority}`\n }\n\n return str\n }\n}\n","import type { ICryptoService } from '@xeno-js/shared'\n\n/**\n * @description The EdgeCryptoService class implements the ICryptoService interface, providing a concrete implementation for cryptographic operations using the Web Cryptography API.\n *\n */\nexport class EdgeCryptoService implements ICryptoService {\n public randomBytes(size: number): Uint8Array {\n const buffer = new Uint8Array(size)\n crypto.getRandomValues(buffer)\n return buffer\n }\n\n public async hmacSha256(secret: string, data: string): Promise<string> {\n const encoder = new TextEncoder()\n const keyData = encoder.encode(secret)\n const messageData = encoder.encode(data)\n\n const cryptoKey = await crypto.subtle.importKey(\n 'raw',\n keyData,\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign'],\n )\n\n const signature = await crypto.subtle.sign('HMAC', cryptoKey, messageData)\n\n // Converte l'ArrayBuffer risultante in una stringa base64url compatibile\n return btoa(String.fromCharCode(...new Uint8Array(signature)))\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=/g, '')\n }\n\n public timingSafeEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) {\n return false\n }\n let mismatch = 0\n for (let i = 0; i < a.length; i++) {\n mismatch |= a[i] ^ b[i]\n }\n return mismatch === 0\n }\n}\n","import type { ICryptoService, ICsrfTokenService } from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\n/**\n * @description Service for generating and validating CSRF tokens\n */\nexport class CsrfTokenService implements ICsrfTokenService {\n constructor(\n private readonly _secret: string,\n private readonly _cryptoService: ICryptoService,\n ) {}\n\n public async generate(subject: string): Promise<string> {\n const randomBuffer = this._cryptoService.randomBytes(32)\n const nonce = btoa(String.fromCharCode(...randomBuffer))\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=/g, '')\n\n const signature = await this._cryptoService.hmacSha256(this._secret, `${subject}.${nonce}`)\n\n return `${nonce}.${signature}`\n }\n\n public async validate(token: string, subject: string): Promise<boolean> {\n const separatorIndex = token.indexOf('.')\n\n if (separatorIndex <= 0) return false\n\n const nonce = token.slice(0, separatorIndex)\n const signature = token.slice(separatorIndex + 1)\n\n if (Guards.isNullOrEmpty(nonce) || Guards.isNullOrEmpty(signature)) return false\n\n const expected = await this._cryptoService.hmacSha256(this._secret, `${subject}.${nonce}`)\n\n const encoder = new TextEncoder()\n const actualBuffer = encoder.encode(signature)\n const expectedBuffer = encoder.encode(expected)\n\n if (actualBuffer.length !== expectedBuffer.length) return false\n\n return this._cryptoService.timingSafeEqual(actualBuffer, expectedBuffer)\n }\n}\n","import type { IServiceExtractor, Optional } from '@xeno-js/shared'\nimport { Guards, HttpHelper } from '@xeno-js/shared'\n\n/**\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.\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 BearerTokenExtractor implements IServiceExtractor<\n Request['headers'],\n Optional<string>\n> {\n constructor(private readonly _cookiePrefix: string) {}\n extract(headers: Request['headers']): Optional<string> {\n const authHeader = headers.get('Authorization')\n\n if (Guards.isDefined(authHeader) && authHeader.toLowerCase().startsWith('bearer ')) {\n return authHeader.substring(7)\n }\n\n const cookieHeader = headers.get('cookie')\n if (Guards.isDefined(cookieHeader)) {\n const cookies = HttpHelper.parseCookies(cookieHeader)\n const token = cookies[this._cookiePrefix]\n\n if (Guards.isDefined(token)) {\n return token\n }\n }\n\n return undefined\n }\n}\n","import { Guards, HttpHelper, type IServiceExtractor, type Optional } from '@xeno-js/shared'\n\n/**\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.\n */\nexport class HttpCookieExtractor implements IServiceExtractor<\n {\n header: Optional<string>\n name: string\n },\n Optional<string>\n> {\n extract(cookie: { header: Optional<string>; name: string }): Optional<string> {\n if (!Guards.isDefined(cookie.header)) return undefined\n\n const cookies = HttpHelper.parseCookies(cookie.header)\n return cookies[cookie.name]\n }\n}\n","import type { IServiceExtractor } from '@xeno-js/shared'\nimport type { Metadata } from '@xeno-js/shared'\nimport { Guards, GuidHelper, HttpHelper, MathHelper, type Optional } from '@xeno-js/shared'\n\n/**\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.\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 HttpHeaderExtractor implements IServiceExtractor<Request['headers'], Metadata> {\n /**\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.\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 constructor(\n private readonly _cookieExtractor: IServiceExtractor<\n {\n header: Optional<string>\n name: string\n },\n Optional<string>\n >,\n private readonly _trustedIp: Optional<string>,\n private readonly _cookieName: string,\n private readonly _csrfCookieHeader = 'x-csrf-token',\n ) {}\n\n extract(headers: Request['headers']): Metadata {\n const correlationId = GuidHelper.parse(headers.get('x-correlation-id') ?? undefined)\n const requestId = GuidHelper.parse(headers.get('x-request-id') ?? undefined)\n const clientIp =\n headers.get(this._trustedIp?.toLowerCase() ?? 'x-forwarded-for') ??\n headers.get('x-real-ip') ??\n undefined\n const spanId = GuidHelper.parse(headers.get('x-span-id') ?? undefined)\n const parentSpanId = headers.get('x-parent-span-id') ?? undefined\n const acceptHeader = headers.get('accept') ?? undefined\n const contentTypeHeader = headers.get('content-type') ?? undefined\n const userAgent = headers.get('user-agent') ?? undefined\n const returnAddress = headers.get('x-return-address') ?? undefined\n const sequenceId = headers.get('x-sequence-id') ?? undefined\n const position = headers.get('x-sequence-position')\n const size = headers.get('x-sequence-size')\n const expiration = headers.get('x-expiration')\n\n const csrf = headers.get(this._csrfCookieHeader) ?? undefined\n const cookieHeader = headers.get('cookie') ?? undefined\n const csrfCookie = this._cookieExtractor.extract({\n header: cookieHeader,\n name: this._cookieName,\n })\n const origin = headers.get('origin') ?? undefined\n const cleanOrigin = HttpHelper.sanitizeOriginUrl(origin)\n const referer = headers.get('referer') ?? undefined\n const cleanReferer = HttpHelper.sanitizeOriginUrl(referer)\n\n const formatIndicator = HttpHelper.resolveFormatIndicator(acceptHeader, contentTypeHeader)\n\n const metadata: Metadata = {\n correlationId,\n requestId,\n clientIp,\n spanId,\n parentSpanId,\n formatIndicator,\n userAgent,\n returnAddress,\n csrf,\n csrfCookie,\n cookies: cookieHeader,\n origin: cleanOrigin,\n referer: cleanReferer,\n sequence: {\n sequenceId,\n position: Guards.isDefined(position) ? MathHelper.toNumber(position) : undefined,\n size: Guards.isDefined(size) ? MathHelper.toNumber(size) : undefined,\n },\n expiration: Guards.isDefined(expiration) ? MathHelper.toNumber(expiration) : undefined,\n }\n\n return metadata\n }\n}\n","import type { Optional, XenoRequest } from '@xeno-js/shared'\nimport type { IIPResolver } from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\n/**\n * @description ClientIpResolver is a resolver that extracts the client IP address from the network context or the socket IP address.\n */\nexport class ClientIpResolver implements IIPResolver {\n constructor(private readonly _trustedProxies: string[] = []) {}\n\n public resolve(req: XenoRequest, clientIp: Optional<string>): Optional<string> {\n const socketIp = req.socket?.remoteAddress\n\n if (!Guards.isDefined(socketIp))\n return !Guards.isNullOrEmpty(clientIp) ? clientIp.split(',')[0].trim() : undefined\n\n const isTrustedProxy = this._trustedProxies.includes(socketIp)\n\n if (!isTrustedProxy) return socketIp\n if (Guards.isDefined(clientIp)) return clientIp.split(',')[0].trim()\n\n return socketIp\n }\n}\n","import type { CacheConfig, IModule, IServiceContainer, XenoRegistry } from '@xeno-js/shared'\nimport { Guards, TOKENS } from '@xeno-js/shared'\n\nimport { CacheKeyBuilder } from '../cache'\nimport { CacheUtils } from './utils'\n\n/**\n * @description CacheModule is responsible for registering cache services in the IoC container. Default implementation is in-memory\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 CacheModule<TRegistry extends XenoRegistry = XenoRegistry> implements IModule<\n TRegistry,\n CacheConfig\n> {\n public async configure(\n container: IServiceContainer<TRegistry>,\n opts: CacheConfig = { inMemory: true },\n ): Promise<void> {\n container.addSingleton(\n TOKENS.CACHE_KEY_BUILDER,\n (c) => new CacheKeyBuilder(c.resolve(TOKENS.IDENTITY_ACCESSOR)),\n )\n\n if (opts.inMemory && Guards.isDefined(opts.provider))\n throw new Error('Cannot use both in memory and provider cache')\n else if (opts.inMemory) {\n await CacheUtils.addCache(container)\n } else if (Guards.isDefined(opts.provider)) {\n container.addSingleton(TOKENS.CACHE, (c) => opts.provider!(c))\n } else throw new Error('No cache provider specified')\n }\n}\n","import type { ICache, IDisposable, Optional } from '@xeno-js/shared'\nimport type { IAtomicCache } from '@xeno-js/shared'\nimport { Guards, StringHelper } from '@xeno-js/shared'\n\ninterface NodeTimeout {\n unref: () => void\n}\n\n/**\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.\n */\nexport class InMemoryCache implements ICache, IAtomicCache, IDisposable {\n private _cleanupInterval: ReturnType<typeof setInterval>\n\n /**\n * @description Constructs a new instance of the InMemoryCache class, which initializes an internal Map to store cached values. The Map is used to associate cache keys with their corresponding values and expiration times, allowing for efficient retrieval and management of cached data. The constructor does not take any parameters, as the in-memory cache is self-contained and does not require external dependencies or configuration.\n * @param _cache An optional Map instance to use as the underlying storage for the cache. If not provided, a new Map will be created to store cached values.\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 constructor(\n private _cache: Map<string, { value: string; expiresAt: Optional<number> }> = new Map(),\n ) {\n this._cleanupInterval = setInterval(() => this.evictExpired(), 300_000)\n if (this._isNodeTimeout(this._cleanupInterval)) {\n this._cleanupInterval.unref()\n }\n }\n\n private _isNodeTimeout(timer: unknown): timer is NodeTimeout {\n return Guards.isDefined(timer) && Guards.isObject(timer) && Guards.hasMethod(timer, 'unref')\n }\n\n public async get<T>(key: string): Promise<Optional<T>> {\n const entry = this._cache.get(key)\n if (!Guards.isDefined(entry)) {\n return undefined\n }\n if (Guards.isDefined(entry.expiresAt) && entry.expiresAt < Date.now()) {\n this._cache.delete(key)\n return undefined\n }\n return JSON.parse(entry.value) as T\n }\n\n public async set<T>(key: string, value: T, ttl: Optional<number>): Promise<void> {\n const expiresAt = Guards.isDefined(ttl) ? Date.now() + ttl * 1000 : undefined\n this._cache.set(key, { value: StringHelper.safeStringify(value), expiresAt })\n }\n\n public async setIfAbsent<T>(key: string, value: T, ttl: Optional<number>): Promise<boolean> {\n if (this._cache.has(key)) {\n return false\n }\n await this.set(key, value, ttl)\n return true\n }\n\n public async remove(key: string): Promise<void> {\n this._cache.delete(key)\n }\n\n public async has(key: string): Promise<boolean> {\n const entry = this._cache.get(key)\n if (!Guards.isDefined(entry)) {\n return false\n }\n if (Guards.isDefined(entry.expiresAt) && entry.expiresAt < Date.now()) {\n this._cache.delete(key)\n return false\n }\n return true\n }\n\n public async clear(): Promise<void> {\n this._cache.clear()\n }\n\n public async increment(key: string, ttlSeconds: Optional<string | number>): Promise<number> {\n const entry = this._cache.get(key)\n const now = Date.now()\n\n if (Guards.isDefined(entry) && (!Guards.isDefined(entry.expiresAt) || entry.expiresAt > now)) {\n const nextValue = Number(StringHelper.safeParse(entry.value)) + 1\n this._cache.set(key, {\n value: StringHelper.safeStringify(nextValue),\n expiresAt: entry.expiresAt,\n })\n return nextValue\n }\n\n const ttl = !Guards.isNullOrEmpty(ttlSeconds) ? Number(ttlSeconds) : 60\n const expiresAt = now + ttl * 1000\n this._cache.set(key, { value: StringHelper.safeStringify(1), expiresAt })\n\n return 1\n }\n\n private evictExpired(): void {\n const now = Date.now()\n for (const [key, entry] of this._cache.entries()) {\n if (!Guards.isDefined(entry.expiresAt) || entry.expiresAt > now) {\n this._cache.delete(key)\n }\n }\n }\n\n public async dispose(): Promise<void> {\n clearInterval(this._cleanupInterval)\n this._cache.clear()\n }\n\n public async removePattern(pattern: string): Promise<void> {\n const escaped = pattern.replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&')\n const regexString = `^${escaped.replace(/\\*/g, '.*')}$`\n const regex = new RegExp(regexString)\n for (const key of this._cache.keys()) {\n if (regex.test(key)) {\n this._cache.delete(key)\n }\n }\n }\n}\n","import type { ICacheKeyBuilder, IIdentityAccessor } from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\n/**\n * @description The CacheKeyBuilder class implements the ICacheKeyBuilder interface, providing a method to build contextual cache 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 cache keys in multi-tenant applications. If a tenant ID is present in the identity, the cache key is prefixed with the tenant ID; otherwise, it defaults to a public cache key. This approach ensures that cached data is appropriately scoped to the user's context, preventing data leakage between tenants.\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 CacheKeyBuilder implements ICacheKeyBuilder {\n /**\n * @description Constructs a new instance of the CacheKeyBuilder class, which requires an IIdentityAccessor to access the current user's identity. The constructor initializes the dependency needed for building contextual cache keys based on the user's identity, enabling tenant-specific caching behavior in multi-tenant applications.\n * @param _identityAccessor An instance of IIdentityAccessor used to retrieve the current user's identity, allowing for the construction of tenant-specific cache keys.\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 constructor(private readonly _identityAccessor: IIdentityAccessor) {}\n\n public buildContextualKey(key: string): string {\n const identity = this._identityAccessor.getIdentity()\n\n if (Guards.isDefined(identity) && !Guards.isNullOrEmpty(identity.tenantId)) {\n return `tenant:${identity.tenantId}:${key}`\n }\n\n return `${key}:public`\n }\n\n public buildUserScopedKey(key: string): string {\n const identity = this._identityAccessor.getIdentity()\n\n if (Guards.isDefined(identity) && !Guards.isNullOrEmpty(identity.userId)) {\n return this.buildContextualKey(`user:${identity.userId}:${key}`)\n }\n\n return this.buildContextualKey(key)\n }\n}\n","import type { Optional, RequestContext } from '@xeno-js/shared'\nimport type { IRateLimitKeyBuilder, IRequestContext, XenoRegistry } from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\n/**\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.\n *\n * @author Xeno\n * @version 1.0.0\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-vue\n * @copyright Xeno\n * @license MIT\n */\nexport class RateLimitKeyBuilder implements IRateLimitKeyBuilder {\n constructor(\n private readonly _contextAccessor: IRequestContext<RequestContext, XenoRegistry<unknown>>,\n ) {}\n\n public buildRateLimitKey(resource: string): Optional<string> {\n const ctx = this._contextAccessor.getContext()\n\n const tenantId = ctx?.identity?.tenantId\n const userId = ctx?.identity?.userId\n const clientIp = ctx?.network?.clientIp\n\n if (!Guards.isNullOrEmpty(tenantId) && !Guards.isNullOrEmpty(userId))\n return `ratelimit:tenant:${tenantId}:user:${userId}:${resource}`\n\n if (!Guards.isNullOrEmpty(tenantId) && !Guards.isNullOrEmpty(clientIp))\n return `ratelimit:tenant:${tenantId}:ip:${clientIp}:${resource}`\n\n if (!Guards.isNullOrEmpty(userId)) return `ratelimit:user:${userId}:${resource}`\n\n if (!Guards.isNullOrEmpty(clientIp)) return `ratelimit:ip:${clientIp}:${resource}`\n\n return undefined\n }\n}\n","import { Guards, type IPipelineBehavior, type IRequest, type IStrategy } from '@xeno-js/shared'\nimport {\n type AuthorizationOptions,\n type IServiceContainer,\n TOKENS,\n type XenoRegistry,\n} from '@xeno-js/shared'\n\nimport {\n AuthorizationPipeline,\n PermissionAuthorizationStrategy,\n PolicyRegistry,\n RoleAuthorizationStrategy,\n TenantAuthorizationStrategy,\n UserAuthorizationStrategy,\n} from '@/application'\n\n/**\n * @description Utility functions for configuring authentication and authorization in the service container.\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 const AuthUtils = Object.freeze({\n /**\n * @description Checks if the provided authorization configuration requires any authorization strategies.\n * @param authorizationConfig The authorization configuration to check.\n * @returns True if any authorization strategies are required, false otherwise.\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 async addAuthZ<TRegistry extends XenoRegistry = XenoRegistry>(\n container: IServiceContainer<TRegistry>,\n opts: AuthorizationOptions<TRegistry>,\n ): Promise<IPipelineBehavior<IRequest<unknown>, unknown>> {\n const strategies: IStrategy<IRequest>[] = []\n\n if (Guards.isDefined(opts.policies)) {\n const policyRegistry = opts.policies\n const registryInstance = new PolicyRegistry()\n const ctxAccessor = container.resolve(TOKENS.CONTEXT_ACCESSOR)\n const Policies = new Set<string>()\n\n if (Guards.isDefined(opts.superadmin)) {\n const superadminRoles = Guards.isArray(opts.superadmin)\n ? opts.superadmin\n : [opts.superadmin]\n registryInstance.setSuperadminRoles(superadminRoles)\n }\n\n for (const [intent, policy] of Object.entries(policyRegistry)) {\n const intentLower = intent.toLowerCase()\n registryInstance.addPolicy(intentLower, policy)\n\n if (!Guards.isNullOrEmpty(policy.roles)) {\n Policies.add('roles')\n }\n\n if (!Guards.isNullOrEmpty(policy.permissions)) {\n Policies.add('permissions')\n }\n\n if (!Guards.isNullOrEmpty(policy.userId)) {\n Policies.add('userId')\n }\n\n if (!Guards.isNullOrEmpty(policy.tenantId)) {\n Policies.add('tenantId')\n }\n }\n\n if (Policies.has('roles')) {\n strategies.push(new RoleAuthorizationStrategy(registryInstance, ctxAccessor))\n }\n\n if (Policies.has('permissions')) {\n strategies.push(new PermissionAuthorizationStrategy(registryInstance, ctxAccessor))\n }\n\n if (Policies.has('userId')) {\n strategies.push(new UserAuthorizationStrategy(registryInstance, ctxAccessor))\n }\n\n if (Policies.has('tenantId')) {\n strategies.push(new TenantAuthorizationStrategy(registryInstance, ctxAccessor))\n }\n }\n\n if (!Guards.isNullOrEmpty(opts.customAuthorizationStrategy)) {\n const customStrategies = opts.customAuthorizationStrategy\n customStrategies.forEach((strategyToken) => {\n if (Guards.isDefined(strategyToken)) {\n strategies.push(strategyToken(container))\n }\n })\n }\n\n return new AuthorizationPipeline(strategies)\n },\n} as const)\n","import type { IServiceContainer, XenoRegistry } from '@xeno-js/shared'\nimport { TOKENS } from '@xeno-js/shared'\n\nimport { InMemoryCache } from '@/infrastructure/cache'\n\n/**\n * @description Utility functions for configuring caching in the service container.\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 const CacheUtils = Object.freeze({\n /**\n * @description Checks if the provided cache configuration requires any cache strategies.\n * @param container The service container to which the cache strategies will be added.\n * @param opts The cache configuration options.\n * @returns True if any cache strategies are required, false otherwise.\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 async addCache<TRegistry extends XenoRegistry = XenoRegistry>(\n container: IServiceContainer<TRegistry>,\n ): Promise<void> {\n container.addSingleton(TOKENS.CACHE, () => new InMemoryCache())\n },\n} as const)\n","import type { ILoggerClient } from '@xeno-js/shared'\nimport type { IServiceContainer, LoggerConfig, XenoRegistry } from '@xeno-js/shared'\nimport { Guards, LOG_LEVEL } from '@xeno-js/shared'\nimport { TOKENS } from '@xeno-js/shared'\n\nimport { BaseLogger } from '@/application'\nimport { ConsoleLogger } from '@/infrastructure/loggers'\n\n/**\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.\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 const LoggerUtils = Object.freeze({\n /**\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.\n *\n * @param container - The service container to register logging services with.\n * @param opts - The LoggerConfig options to determine which loggers to enable and their configurations.\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 async addLogger<TRegistry extends XenoRegistry = XenoRegistry>(\n container: IServiceContainer<TRegistry>,\n opts: LoggerConfig<TRegistry>,\n ): Promise<void> {\n const loggerDependencies: ILoggerClient[] = []\n\n if (opts.console) loggerDependencies.push(new ConsoleLogger(opts?.level))\n\n if (!Guards.isNullOrEmpty(opts.customLoggers)) {\n const customLoggers = opts.customLoggers\n for (const logger of customLoggers) {\n loggerDependencies.push(logger(container))\n }\n }\n\n container.addSingleton(TOKENS.LOGGER, (c) => {\n const context = c.resolve(TOKENS.CONTEXT_ACCESSOR)\n return new BaseLogger(context, opts?.level ?? LOG_LEVEL.DEBUG, loggerDependencies)\n })\n },\n} as const)\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 {\n IModule,\n IRequestContext,\n IServiceContainer,\n Optional,\n RequestContext,\n XenoRegistry,\n} from '@xeno-js/shared'\nimport { Guards, TOKENS } from '@xeno-js/shared'\n\nimport { EventDispatcher } from '../events'\nimport { ServiceScopeFactory, UserContextFactory } from '../factories'\nimport { HttpAdapter } from '../http'\nimport { UrlBuilder } from '../http/url-builder.http'\nimport { CreateServicesProxy } from '../services/service_proxy/services.proxy'\n\n/**\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.\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 ContextModule<TRegistry extends XenoRegistry = XenoRegistry> implements IModule<\n TRegistry,\n Optional<IRequestContext<RequestContext, TRegistry>>\n> {\n async configure(\n container: IServiceContainer<TRegistry>,\n opts?: IRequestContext<RequestContext, TRegistry>,\n ): Promise<void> {\n if (container.isRegistered(TOKENS.REQUEST_CONTEXT)) return\n\n const requestContext = await this._getRequestContext(container, opts)\n\n container.addSingleton(TOKENS.REQUEST_CONTEXT, () => requestContext)\n container.addSingleton(TOKENS.CONTEXT_ACCESSOR, () => requestContext)\n container.addSingleton(TOKENS.IDENTITY_ACCESSOR, () => requestContext)\n container.addSingleton(TOKENS.SERVICE_SCOPE_ACCESSOR, () => requestContext)\n container.addSingleton(TOKENS.NETWORK_CONTEXT_ACCESSOR, () => requestContext)\n container.addSingleton(TOKENS.TRACING_CONTEXT_ACCESSOR, () => requestContext)\n\n container.addSingleton(TOKENS.USER_CONTEXT_FACTORY, () => {\n return new UserContextFactory(requestContext)\n })\n\n const serviceProxy = new CreateServicesProxy()\n container.addSingleton(TOKENS.SERVICE_PROXY, () => serviceProxy)\n\n container.addSingleton(TOKENS.HTTP_ADAPTER, () => new HttpAdapter(new UrlBuilder()))\n\n container.addSingleton(TOKENS.EVENT_DISPATCHER, () => new EventDispatcher())\n }\n\n private async _getRequestContext(\n container: IServiceContainer<TRegistry>,\n opts?: IRequestContext<RequestContext, TRegistry>,\n ) {\n if (Guards.isDefined(opts)) return opts\n\n const { NodeRequestContextFactory } = await import('../factories/request-context.factory')\n return new NodeRequestContextFactory<TRegistry>(\n new ServiceScopeFactory<TRegistry>(container),\n ).create()\n }\n}\n","import type { IEventDispatcher, IEventHandler, Optional, ResultType } from '@xeno-js/shared'\nimport { AppError, Guards, Result } from '@xeno-js/shared'\n\nexport class EventDispatcher implements IEventDispatcher {\n private readonly _handlers = new Map<string, IEventHandler<unknown>[]>()\n\n public subscribe<TEvent>(eventType: string, handler: IEventHandler<TEvent>): void {\n const handlers = this._handlers.get(eventType) ?? []\n handlers.push(handler)\n this._handlers.set(eventType, handlers)\n }\n\n public async publish<TEvent extends { eventType: string }>(\n event: TEvent,\n signal?: Optional<AbortSignal>,\n ): Promise<ResultType<void>> {\n AppError.throwIfAborted(signal, 'EventDispatcher.publish')\n\n const handlers = this._handlers.get(event.eventType)\n if (Guards.isNullOrEmpty(handlers)) return Result.ok()\n\n try {\n for (const handler of handlers) {\n const result = await handler.handle(event, signal)\n if (!result.isOk()) {\n return Result.fail(result.getErrorOrThrow())\n }\n }\n return Result.ok()\n } catch (error) {\n return Result.fail(AppError.internalServerError('EventDispatcher', error))\n }\n }\n}\n","import type { HttpMethod } from '@xeno-js/shared'\nimport type { IAllowMethod, NativeRouteDefinition, XenoRegistry } from '@xeno-js/shared'\n\nimport { AllowMethodRegistry } from '../services'\n\n/**\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.\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 AllowMethodFactory {\n public create<TRegistry extends XenoRegistry = XenoRegistry>(\n opts: NativeRouteDefinition<TRegistry>[],\n ): IAllowMethod {\n const allowMethodService = new AllowMethodRegistry()\n\n const routes = opts ?? []\n const routesMap = new Map<string, HttpMethod[]>()\n for (const r of routes) {\n const methods = routesMap.get(r.path) ?? []\n if (!methods.includes(r.method)) {\n methods.push(r.method)\n }\n routesMap.set(r.path, methods)\n }\n\n for (const [path, methods] of routesMap) {\n allowMethodService.add(path, methods)\n }\n\n return allowMethodService\n }\n}\n","export * from './allow-method.factory'\nexport * from './request-context.factory'\nexport * from './service-scope.factory'\nexport * from './user-context.factory'\n","import type { IFactory } from '@xeno-js/shared'\nimport type { IServiceContainer, IServiceScope, XenoRegistry } from '@xeno-js/shared'\n\n/**\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.\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 ServiceScopeFactory<T extends XenoRegistry = XenoRegistry> implements IFactory<\n void,\n IServiceScope<T>\n> {\n constructor(private readonly _container: IServiceContainer<T>) {}\n\n public create(): IServiceScope<T> {\n return this._container.createScope()\n }\n}\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, IHttpAdapter, XenoIncomingRequest, XenoRequest } from '@xeno-js/shared'\nimport { Guards, HttpHelper, HttpRouteParamHelper } from '@xeno-js/shared'\n\n/**\n * @description Base HTTP adapter.\n * @author Xeno\n * @version 1.2.1\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-js\n */\nexport class HttpAdapter implements IHttpAdapter {\n constructor(private readonly _urlFactory: IFactory<Headers, string>) {}\n /**\n * @description Creates the XenoRequest.\n * @param req The XenoIncomingRequest\n * @returns The XenoRequest.\n */\n public adapt(req: XenoIncomingRequest): XenoRequest {\n const baseUrl = this._urlFactory.create(req.headers)\n const safeUrl = HttpHelper.parseSafeUrl(req.url, baseUrl)\n const method = req.method.toUpperCase()\n\n const init: RequestInit & { duplex?: 'half' } = {\n method,\n headers: req.headers,\n }\n\n const parsedBody = HttpHelper.parseBody(method, req.body)\n if (Guards.isDefined(parsedBody)) {\n init.body = parsedBody\n init.duplex = 'half'\n }\n\n const xenoRequest = new Request(safeUrl.toString(), init) as XenoRequest\n\n xenoRequest.path = safeUrl.pathname\n xenoRequest.socket = req.socket\n xenoRequest.query = req.query ?? HttpRouteParamHelper.extractQueryParams(req.url)\n\n return xenoRequest\n }\n}\n","import { Guards, type IFactory } from '@xeno-js/shared'\n\nexport class UrlBuilder implements IFactory<Headers, string> {\n create(headers: Headers): string {\n const forwardedProto = headers.get('x-forwarded-proto')\n const protocol = Guards.isDefined(forwardedProto) ? forwardedProto.split(',')[0].trim() : 'http'\n const forwardedHost = headers.get('x-forwarded-host')\n const hostHeader = headers.get('host')\n const host = Guards.isDefined(forwardedHost)\n ? forwardedHost.split(',')[0].trim()\n : (hostHeader ?? 'localhost')\n\n return `${protocol}://${host}`\n }\n}\n","import type { IServiceProxy, IServiceScope, ServicesProxy, XenoRegistry } from '@xeno-js/shared'\n\n/**\n * @description CreateServicesProxy is a service proxy factory that creates a proxy object for accessing services within a given scope.\n * The proxy object allows for convenient access to services by their names, providing a simplified way to retrieve and use services within the scope.\n */\nexport class CreateServicesProxy implements IServiceProxy {\n /**\n * @description CreateServicesProxy constructor.\n * @param scope - The scope within which services are accessed.\n * @returns A proxy object for accessing services within the specified scope.\n */\n public getServiceProxy<TRegistry extends XenoRegistry = XenoRegistry>(\n scope: IServiceScope<TRegistry>,\n ): ServicesProxy<TRegistry> {\n return new Proxy({} as ServicesProxy<TRegistry>, {\n get(_target, prop: string | symbol) {\n return scope.resolve(prop as keyof TRegistry)\n },\n })\n }\n}\n","import type { ICommand, IQuery } from '@xeno-js/shared'\nimport type {\n IAppBuilder,\n IModule,\n IRequestContext,\n IServiceContainer,\n IServiceScopeAccessor,\n IXenoApplication,\n PipelinePlugin,\n RequestContext,\n XenoRegistry,\n} from '@xeno-js/shared'\nimport { Guards, LOG_LEVEL } from '@xeno-js/shared'\nimport { TOKENS } from '@xeno-js/shared'\n\nimport {\n CompositePipeline,\n ExceptionPipeline,\n IdempotencyPipeline,\n IdentityEnrichmentPipeline,\n LoggingPipeline,\n Mediator,\n NoopIdentityEnrichmentStrategy,\n QueryCachingPipeline,\n} from '@/application'\nimport { CommandCacheInvalidationBehavior } from '@/application/cqrs/pipelines/cache-invalidation.pipeline'\n\nimport { IdempotencyStore } from '../idempotency'\nimport { PipelineSetupContext } from '../pipeline_setup'\nimport { CacheModule } from './cache.module'\nimport { AuthUtils, LoggerUtils } from './utils'\n\n/**\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.\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 CqrsModule<TRegistry extends XenoRegistry = XenoRegistry> implements IModule<\n TRegistry,\n {\n plugins: PipelinePlugin<TRegistry>[]\n builder: IAppBuilder<TRegistry, IXenoApplication<TRegistry>>\n }\n> {\n public async configure(\n container: IServiceContainer<TRegistry>,\n opts: {\n plugins: PipelinePlugin<TRegistry>[]\n builder: IAppBuilder<TRegistry, IXenoApplication<TRegistry>>\n },\n ): Promise<void> {\n if (!container.isRegistered(TOKENS.LOGGER))\n await LoggerUtils.addLogger(container, { level: LOG_LEVEL.INFO, console: true })\n\n const logger = container.resolve(TOKENS.LOGGER)\n\n if (!container.isRegistered(TOKENS.MEDIATOR)) {\n container.addSingleton(TOKENS.MEDIATOR, (c) => {\n const serviceScopeAccessor = c.resolve(TOKENS.SERVICE_SCOPE_ACCESSOR)\n return new Mediator<TRegistry>(serviceScopeAccessor as IServiceScopeAccessor<TRegistry>)\n })\n }\n\n const context = new PipelineSetupContext()\n\n context.addCommon(new ExceptionPipeline(), 0)\n context.addCommon(new LoggingPipeline(logger), 10)\n\n for (const plugin of opts.plugins)\n await plugin(opts.builder, container.resolve(TOKENS.CONFIGURATION_SERVICE), context)\n\n if (Guards.isDefined(context.authzOpts)) {\n const authzPipeline = await AuthUtils.addAuthZ(container, context.authzOpts)\n context.addCommon(authzPipeline, 40)\n }\n\n if (Guards.isDefined(context.identityEnrichmentOpts)) {\n const requestContext = container.resolve(TOKENS.REQUEST_CONTEXT) as IRequestContext<\n RequestContext,\n TRegistry\n >\n const strategy =\n context.identityEnrichmentOpts.strategy ?? new NoopIdentityEnrichmentStrategy()\n context.addCommon(new IdentityEnrichmentPipeline(requestContext, strategy), 20)\n }\n\n if (\n (Guards.isDefined(context.idempotencyOpts) || context.isQueryCaching) &&\n !container.isRegistered(TOKENS.CACHE)\n ) {\n await new CacheModule().configure(container)\n }\n\n if (Guards.isDefined(context.idempotencyOpts)) {\n const store = new IdempotencyStore(\n container.resolve(TOKENS.CACHE),\n container.resolve(TOKENS.CACHE_KEY_BUILDER),\n )\n const networkCtxAccessor = container.resolve(TOKENS.NETWORK_CONTEXT_ACCESSOR)\n context.addCommand(\n new IdempotencyPipeline(networkCtxAccessor, store, context.idempotencyOpts),\n 30,\n )\n }\n\n const sortedCommandBehaviors = context.getSortedCommandBehaviors()\n const sortedQueryBehaviors = context.getSortedQueryBehaviors()\n\n if (context.isQueryCaching) {\n sortedCommandBehaviors.push(\n new CommandCacheInvalidationBehavior(\n container.resolve(TOKENS.CACHE),\n container.resolve(TOKENS.LOGGER),\n ),\n )\n\n sortedQueryBehaviors.push(\n new QueryCachingPipeline(\n container.resolve(TOKENS.CACHE),\n container.resolve(TOKENS.CACHE_KEY_BUILDER),\n container.resolve(TOKENS.LOGGER),\n ),\n )\n }\n\n container.addSingleton(\n TOKENS.COMMAND_PIPELINES_BEHAVIOR,\n () => new CompositePipeline<ICommand<unknown>, unknown>(sortedCommandBehaviors),\n )\n\n container.addSingleton(\n TOKENS.QUERY_PIPELINES_BEHAVIOR,\n () => new CompositePipeline<IQuery<unknown>, unknown>(sortedQueryBehaviors),\n )\n }\n}\n","import type {\n Delegate,\n ICache,\n ICommand,\n ILogger,\n IPipelineBehavior,\n ResultType,\n} from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\nexport class CommandCacheInvalidationBehavior<\n TInput extends ICommand<TResult>,\n TResult,\n> implements IPipelineBehavior<TInput, TResult> {\n constructor(\n private readonly _cacheService: ICache,\n private readonly _logger: ILogger,\n ) {}\n\n public async handle(request: TInput, next: Delegate<TResult>): Promise<ResultType<TResult>> {\n const result = await next()\n\n if (result.isOk() && Guards.isDefined(request.cacheInvalidation)) {\n try {\n const { keys, patterns } = request.cacheInvalidation\n\n if (Guards.isArray(keys)) {\n for (const key of keys) {\n await this._cacheService.remove(key)\n this._logger.debug(`[Cache Invalidation] Removed key: ${key}`)\n }\n }\n\n if (Guards.isArray(patterns) && Guards.hasMethod(this._cacheService, 'removePattern')) {\n for (const pattern of patterns) {\n await this._cacheService.removePattern(pattern)\n this._logger.debug(`[Cache Invalidation] Removed pattern: ${pattern}`)\n }\n }\n } catch (error) {\n this._logger.warn(\n `[Cache Invalidation ERROR] Failed to clear cache: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n }\n\n return result\n }\n}\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 {\n AuthorizationOptions,\n IdempotencyOptions,\n IdentityEnrichmentOptions,\n IPipelineSetup,\n XenoRegistry,\n} from '@xeno-js/shared'\nimport {\n Guards,\n type ICommand,\n type IPipelineBehavior,\n type IQuery,\n type IRequest,\n type Optional,\n} from '@xeno-js/shared'\n\ninterface QueuedBehavior<T> {\n readonly order: number\n readonly behavior: T\n}\n\nexport class PipelineSetupContext<\n TRegistry extends XenoRegistry = XenoRegistry,\n> implements IPipelineSetup<TRegistry> {\n public isQueryCaching = false\n private readonly _commandBehaviors: QueuedBehavior<\n IPipelineBehavior<ICommand<unknown>, unknown>\n >[] = []\n private readonly _queryBehaviors: QueuedBehavior<IPipelineBehavior<IQuery<unknown>, unknown>>[] =\n []\n private _authzOpts: Optional<AuthorizationOptions<TRegistry>> = undefined\n private _idempotencyOpts: Optional<IdempotencyOptions> = undefined\n private _identityEnrichmentOpts: Optional<IdentityEnrichmentOptions> = undefined\n\n public set idempotencyOpts(opts: IdempotencyOptions) {\n this._idempotencyOpts = opts\n }\n\n public get idempotencyOpts(): Optional<IdempotencyOptions> {\n if (Guards.isDefined(this._idempotencyOpts)) return Object.freeze(this._idempotencyOpts)\n return this._idempotencyOpts\n }\n\n public set identityEnrichmentOpts(opts: IdentityEnrichmentOptions) {\n this._identityEnrichmentOpts = opts\n }\n\n public get identityEnrichmentOpts(): Optional<IdentityEnrichmentOptions> {\n if (Guards.isDefined(this._identityEnrichmentOpts))\n return Object.freeze(this._identityEnrichmentOpts)\n return this._identityEnrichmentOpts\n }\n\n public set authzOpts(opts: AuthorizationOptions<TRegistry>) {\n this._authzOpts = opts\n }\n\n public get authzOpts(): Optional<AuthorizationOptions<TRegistry>> {\n if (Guards.isDefined(this._authzOpts)) return Object.freeze(this._authzOpts)\n return this._authzOpts\n }\n\n public addCommon(behavior: IPipelineBehavior<IRequest<unknown>, unknown>, order = 50): this {\n this._commandBehaviors.push({ order, behavior })\n this._queryBehaviors.push({ order, behavior })\n return this\n }\n\n public addCommand(behavior: IPipelineBehavior<ICommand<unknown>, unknown>, order = 50): this {\n this._commandBehaviors.push({ order, behavior })\n return this\n }\n\n public addQuery(): this {\n this.isQueryCaching = true\n return this\n }\n\n public getSortedCommandBehaviors(): IPipelineBehavior<ICommand<unknown>, unknown>[] {\n return [...this._commandBehaviors]\n .sort((a, b) => a.order - b.order)\n .map((entry) => entry.behavior)\n }\n\n public getSortedQueryBehaviors(): IPipelineBehavior<IQuery<unknown>, unknown>[] {\n return [...this._queryBehaviors]\n .sort((a, b) => a.order - b.order)\n .map((entry) => entry.behavior)\n }\n}\n","import type {\n DbModuleOptions,\n IDisposable,\n IModule,\n IServiceContainer,\n IServiceScope,\n ITransactionalDb,\n IUnitOfWork,\n XenoRegistry,\n} from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\nimport { TOKENS } from '@xeno-js/shared'\n\nimport { UnitOfWork } from '../transaction'\nimport { TransactionState } from '../transaction/transaction-state'\n\ninterface OptionalUnitOfWork<TTx = unknown> extends IUnitOfWork<TTx>, IDisposable {}\n\n/**\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.\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 DbModule<\n TRegistry extends XenoRegistry<DbContext, DbTransaction>,\n DbContext extends ITransactionalDb<DbTransaction>,\n DbTransaction = unknown,\n> implements IModule<\n TRegistry,\n DbModuleOptions<DbContext, DbTransaction> & {\n uow?: (c: IServiceScope<TRegistry>) => OptionalUnitOfWork<DbContext>\n }\n> {\n async configure(\n container: IServiceContainer<TRegistry>,\n opts: DbModuleOptions<DbContext, DbTransaction> & {\n uow?: (c: IServiceScope<TRegistry>) => OptionalUnitOfWork<DbContext>\n },\n ): Promise<void> {\n const db = opts.client\n\n container.addScoped(TOKENS.TRANSACTION_STATE, () => {\n return new TransactionState<DbTransaction>()\n })\n\n if (Guards.isDefined(opts.uow)) {\n container.addScoped(TOKENS.UNIT_OF_WORK, (c) => {\n return opts.uow!(c)\n })\n } else {\n container.addScoped(TOKENS.UNIT_OF_WORK, (c) => {\n const ttx = c.resolve(TOKENS.TRANSACTION_STATE)\n return new UnitOfWork(db, ttx) as unknown as TRegistry['unitOfWork']\n })\n }\n\n container.addScoped(TOKENS.DB_CONTEXT, (c) => {\n const ttx = c.resolve(TOKENS.TRANSACTION_STATE)\n return new Proxy(db, {\n get(_target, prop, receiver) {\n const activeState = ttx.state\n if (Guards.isDefined(activeState)) {\n const value: unknown = Reflect.get(activeState as object, prop, receiver)\n if (Guards.isFunction(value)) {\n return value.bind(activeState)\n }\n return value\n }\n return Reflect.get(db, prop, receiver) as DbContext\n },\n })\n })\n }\n}\n","import type { AggregateRoot, IDisposable, ITransactionState, IUnitOfWork } from '@xeno-js/shared'\nimport type { ITransactionalDb } from '@xeno-js/shared'\nimport { AppError } from '@xeno-js/shared'\nimport { Guards, type Optional } from '@xeno-js/shared'\n\n/**\n * @file unit-of-work.ts\n * @description This file contains the implementation of the Unit of Work pattern.\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 UnitOfWork<TTransaction = unknown> implements IUnitOfWork<TTransaction>, IDisposable {\n /**\n * Creates an instance of UnitOfWork.\n * @param _dbContext - The database context used for managing transactions.\n * @param _ttx - The transaction state, which can be either a specific transaction type or null.\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 constructor(\n private readonly _dbContext: ITransactionalDb<TTransaction>,\n private readonly _ttx: ITransactionState<TTransaction>,\n ) {}\n\n async runInTransaction<T, TProps, TEvent = unknown, TId extends string = string>(\n callback: (tx: TTransaction) => Promise<T>,\n aggregates?: AggregateRoot<TProps, TEvent, TId> | AggregateRoot<TProps, TEvent, TId>[],\n signal?: Optional<AbortSignal>,\n ): Promise<T> {\n AppError.throwIfAborted(signal, 'UnitOfWork.runInTransaction')\n\n return this._dbContext.transaction(async (tx) => {\n this._ttx.state = tx\n try {\n const result = await callback(this._ttx.state)\n return result\n } finally {\n this._ttx.state = null\n }\n })\n }\n\n async dispose(): Promise<void> {\n if (Guards.isDefined(this._ttx.state)) {\n try {\n if (Guards.hasMethod(this._ttx.state, 'rollback')) {\n await (this._ttx.state as { rollback: () => Promise<void> }).rollback()\n }\n } finally {\n this._ttx.state = null\n }\n }\n }\n}\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 { IModule, IServiceContainer, XenoRegistry } from '@xeno-js/shared'\nimport { TOKENS } from '@xeno-js/shared'\n\nimport { RouteMatcherFactory } from '../factories/route-matcher.factory'\nimport { ServerOptionsFactory } from '../factories/server-options.factory'\n\nexport class HttpServerModule<\n TRegistry extends XenoRegistry = XenoRegistry,\n> implements IModule<TRegistry> {\n async configure(container: IServiceContainer<TRegistry>): Promise<void> {\n container.addSingleton(\n TOKENS.SERVER_OPTIONS_FACTORY,\n (c) => new ServerOptionsFactory(c.resolve(TOKENS.CONFIGURATION_SERVICE)),\n )\n\n if (!container.isRegistered(TOKENS.ROUTE_MATCHER)) {\n container.addSingleton(TOKENS.ROUTE_MATCHER, () => new RouteMatcherFactory().create([]))\n }\n }\n}\n","import type { IRoute, IRouteFactory, NativeRouteDefinition, XenoRegistry } from '@xeno-js/shared'\nimport { RoutePatternHelper } from '@xeno-js/shared'\n\nimport { RouteMatcher } from '../http/route-matcher.http'\n\nexport class RouteMatcherFactory implements IRouteFactory {\n create<TRegistry extends XenoRegistry = XenoRegistry>(\n opts: NativeRouteDefinition<TRegistry>[],\n ): IRoute<TRegistry> {\n const routes = opts.map((r) => {\n const normalizedPath = RoutePatternHelper.normalizePath(r.path)\n const { pattern } = RoutePatternHelper.parse(normalizedPath)\n return {\n definition: r,\n pattern,\n upperMethod: r.method.toUpperCase(),\n }\n })\n return new RouteMatcher<TRegistry>(routes)\n }\n}\n","import type {\n IRoute,\n NativeRouteDefinition,\n RouteHandlerContext,\n RoutePolicy,\n XenoRegistry,\n} from '@xeno-js/shared'\nimport {\n Guards,\n HttpHelper,\n type Optional,\n RoutePatternHelper,\n STATUS_CODES,\n} from '@xeno-js/shared'\n\ninterface CompiledRoute<TRegistry extends XenoRegistry> {\n readonly definition: NativeRouteDefinition<TRegistry>\n readonly pattern: RegExp\n readonly upperMethod: string\n}\n\nexport class RouteMatcher<\n TRegistry extends XenoRegistry = XenoRegistry,\n> implements IRoute<TRegistry> {\n constructor(private readonly _compiledRoutes: CompiledRoute<TRegistry>[]) {}\n\n public match(rawUrl: string, method: string): Optional<NativeRouteDefinition<TRegistry>> {\n const url = !Guards.isNullOrEmpty(rawUrl) ? rawUrl : '/'\n const safeUrl = HttpHelper.parseSafeUrl(url)\n const parsedPath = RoutePatternHelper.normalizePath(safeUrl.pathname)\n const upperMethod = method.toUpperCase()\n\n const matched = this._compiledRoutes.find(\n (r) => r.upperMethod === upperMethod && r.pattern.test(parsedPath),\n )\n\n if (Guards.isDefined(matched)) return matched.definition\n\n if (upperMethod === 'OPTIONS') {\n const pathExists = this._compiledRoutes.some((r) => r.pattern.test(parsedPath))\n\n if (pathExists) {\n return {\n path: parsedPath,\n method: 'OPTIONS',\n handler: async <TOutput>(ctx: RouteHandlerContext<TRegistry>) => {\n try {\n return await ctx.handle('__PREFLIGHT__' as keyof TRegistry)\n } catch {\n return {\n status: STATUS_CODES.NO_CONTENT,\n ok: true,\n headers: {},\n data: undefined as TOutput,\n }\n }\n },\n } as unknown as NativeRouteDefinition<TRegistry>\n }\n }\n\n return undefined\n }\n\n public checkRoutePolicy(path: string, method: string): RoutePolicy {\n const route = this.match(path, method)\n\n return {\n withCredentials: route?.security?.withCredentials,\n allowOrigins: route?.security?.allowOrigins,\n withCsrf: route?.security?.withCsrf,\n withCors: route?.security?.withCors,\n }\n }\n}\n","import type { IConfigurationService } from '@xeno-js/shared'\nimport type { IServerOptionsFactory, NativeListenOptions } from '@xeno-js/shared'\n\nexport class ServerOptionsFactory implements IServerOptionsFactory {\n constructor(private readonly _config: IConfigurationService) {}\n\n public create(options?: NativeListenOptions): NativeListenOptions {\n const defaultPort = this._config.getNumber('PORT', 3000) ?? 3000\n const defaultHost = this._config.get('HOST', '0.0.0.0') ?? '0.0.0.0'\n\n return {\n port: options?.port ?? defaultPort,\n host: options?.host ?? defaultHost,\n onListening: options?.onListening,\n }\n }\n}\n","import type { IConfigurationService } from '@xeno-js/shared'\nimport type {\n IAppBuilder,\n IModule,\n IServiceContainer,\n IXenoApplication,\n LoggerConfig,\n LoggerPlugin,\n XenoRegistry,\n} from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\nimport { LoggerSetupContext } from '../loggers/setup.logger'\nimport { LoggerUtils } from './utils'\n\n/**\n * @description CacheModule is responsible for registering cache services in the IoC container. Default implementation is in-memory\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 LoggerModule<TRegistry extends XenoRegistry = XenoRegistry> implements IModule<\n TRegistry,\n LoggerConfig<TRegistry> & { plugins?: LoggerPlugin<TRegistry>[] }\n> {\n public async configure(\n container: IServiceContainer<TRegistry>,\n opts: LoggerConfig<TRegistry> & {\n builder: IAppBuilder<TRegistry, IXenoApplication<TRegistry>>\n config: IConfigurationService\n plugins?: LoggerPlugin<TRegistry>[]\n },\n ): Promise<void> {\n const loggerSetup = new LoggerSetupContext<TRegistry>()\n loggerSetup.addConsole(opts.console, opts.level)\n if (!Guards.isNullOrEmpty(opts.plugins))\n opts.plugins.forEach((plugin) => plugin(opts.builder, opts.config, loggerSetup))\n\n if (!Guards.isNullOrEmpty(opts.customLoggers)) {\n for (const logger of opts.customLoggers) {\n loggerSetup.addCustomLogger((c) => logger(c))\n }\n }\n\n const options = {\n level: loggerSetup.level,\n console: loggerSetup.console,\n customLoggers: loggerSetup.getCustomLoggers(),\n }\n\n await LoggerUtils.addLogger(container, options)\n }\n}\n","import type { ILoggerClient, LogLevel } from '@xeno-js/shared'\nimport type { ILoggerSetup, IServiceScope, XenoRegistry } from '@xeno-js/shared'\nimport { Guards, LOG_LEVEL } from '@xeno-js/shared'\n\nexport class LoggerSetupContext<\n TRegistry extends XenoRegistry = XenoRegistry,\n> implements ILoggerSetup<TRegistry> {\n public console = false\n public level: LogLevel = LOG_LEVEL.DEBUG\n private readonly _customLoggers: ((container: IServiceScope<TRegistry>) => ILoggerClient)[] = []\n\n public addConsole(enabled = true, level?: LogLevel): void {\n this.console = enabled\n if (Guards.isDefined(level)) {\n this.level = level\n }\n }\n\n public addCustomLogger(factory: (container: IServiceScope<TRegistry>) => ILoggerClient): void {\n this._customLoggers.push(factory)\n }\n\n public getCustomLoggers(): ((container: IServiceScope<TRegistry>) => ILoggerClient)[] {\n return [...this._customLoggers]\n }\n}\n","import type { ILogger, IMiddleware, IRoute, Optional, RequestContext } from '@xeno-js/shared'\nimport type {\n IAllowMethod,\n IModule,\n IRequestContext,\n IServiceContainer,\n MiddlewareConfig,\n NativeRouteDefinition,\n XenoRegistry,\n} from '@xeno-js/shared'\nimport { Guards, LOG_LEVEL } from '@xeno-js/shared'\nimport { TOKENS } from '@xeno-js/shared'\n\nimport { ClaimsIdentityMapper, GateKeeper, NoAuthGateKeeper } from '@/application'\nimport {\n AllowOriginMiddleware,\n AuthenticationMiddleware,\n CompositeMiddleware,\n CookieResponseMiddleware,\n CORSMiddleware,\n CsrfCookieMiddleware,\n CsrfMiddleware,\n MethodCheckMiddleware,\n OptionsMiddleware,\n RateLimitMiddleware,\n RequestContextMiddleware,\n} from '@/presentation'\n\nimport { RateLimitKeyBuilder } from '../cache'\nimport { AllowMethodFactory } from '../factories'\nimport { HttpDispatcher } from '../http/dispatcher.http'\nimport {\n AllowOrigin,\n BearerTokenExtractor,\n ClientIpResolver,\n CsrfTokenService,\n EdgeCryptoService,\n HttpCookieExtractor,\n HttpHeaderExtractor,\n} from '../services'\nimport { CacheModule } from './cache.module'\nimport { LoggerUtils } from './utils'\n\nexport class MiddlewareModule<TRegistry extends XenoRegistry = XenoRegistry> implements IModule<\n TRegistry,\n MiddlewareConfig\n> {\n public async configure(\n container: IServiceContainer<TRegistry>,\n opts: MiddlewareConfig & { routes: NativeRouteDefinition<TRegistry>[] },\n ): Promise<void> {\n if (!container.isRegistered(TOKENS.LOGGER))\n await LoggerUtils.addLogger(container, { level: LOG_LEVEL.INFO, console: true })\n\n const logger = container.resolve(TOKENS.LOGGER)\n const requestContext = container.resolve(TOKENS.REQUEST_CONTEXT) as IRequestContext<\n RequestContext,\n TRegistry\n >\n const configuration = container.resolve(TOKENS.CONFIGURATION_SERVICE)\n\n const allowMethod = new AllowMethodFactory().create<TRegistry>(opts.routes)\n\n container.addSingleton(\n TOKENS.SERVICE_EXTRACTOR,\n () =>\n new HttpHeaderExtractor(\n new HttpCookieExtractor(),\n opts.trustedIpHeader,\n opts.csrf?.cookieName ?? '__Host-xeno-csrf',\n opts.csrf?.headerName ?? 'x-csrf-token',\n ),\n )\n\n const getRouteMatcher = () => container.resolve(TOKENS.ROUTE_MATCHER)\n\n const withCredentials =\n Guards.isDefined(opts.cors?.withCredentials) && opts.cors?.withCredentials ? 'true' : 'false'\n\n const [optionsMw, cookieRespMw, corsMw, authMw, csrfMws] = [\n this._buildOptionsMiddleware(\n opts,\n requestContext,\n () => allowMethod,\n withCredentials,\n getRouteMatcher,\n ),\n this._buildCookieResponseMiddleware(opts, requestContext),\n this._buildCorsMiddleware(opts, requestContext, withCredentials, getRouteMatcher),\n this._createAuthMiddleware(container, requestContext, logger, opts),\n this._buildCsrfMiddlewares(opts, container, requestContext, getRouteMatcher),\n ]\n\n const rateLimitMw = await this._buildRateLimitMiddleware(\n opts,\n container,\n requestContext,\n logger,\n )\n\n const requestCtxMw = new RequestContextMiddleware(\n requestContext,\n container.resolve(TOKENS.SERVICE_EXTRACTOR),\n new ClientIpResolver(opts.trustedProxies),\n logger,\n )\n\n const defaultOrigin =\n configuration.get('APP_URL') ?? `http://localhost:${configuration.getNumber('PORT', 3000)}`\n const origins = !Guards.isNullOrEmpty(opts.cors?.allowOrigins)\n ? opts.cors.allowOrigins\n : [defaultOrigin]\n\n const allowOriginMw = new AllowOriginMiddleware(\n new AllowOrigin(origins),\n requestContext,\n logger,\n getRouteMatcher,\n )\n const methodCheckMw = new MethodCheckMiddleware(requestContext, allowMethod)\n\n const pipeline: IMiddleware[] = [\n requestCtxMw,\n ...(Guards.isDefined(cookieRespMw) ? [cookieRespMw] : []),\n allowOriginMw,\n ...(Guards.isDefined(optionsMw) && !Guards.isNullOrEmpty(opts.routes) ? [optionsMw] : []),\n ...(!Guards.isNullOrEmpty(opts.routes) ? [methodCheckMw] : []),\n ...(Guards.isDefined(corsMw) ? [corsMw] : []),\n ...(Guards.isDefined(rateLimitMw) ? [rateLimitMw] : []),\n authMw,\n ...(!Guards.isNullOrEmpty(csrfMws) ? csrfMws : []),\n ]\n\n container.addSingleton(TOKENS.MIDDLEWARE, () => new CompositeMiddleware(pipeline))\n\n container.addSingleton(\n TOKENS.HTTP_DISPATCHER,\n (c) =>\n new HttpDispatcher<TRegistry>(\n c.resolve(TOKENS.REQUEST_CONTEXT) as IRequestContext<RequestContext, TRegistry>,\n c.resolve(TOKENS.MIDDLEWARE),\n c.resolve(TOKENS.SERVICE_PROXY),\n ),\n )\n }\n\n private _buildCookieResponseMiddleware(\n opts: MiddlewareConfig,\n requestContext: IRequestContext<RequestContext, TRegistry>,\n ): Optional<IMiddleware> {\n if (!Guards.isDefined(opts.isSSR) || !opts.isSSR) return undefined\n\n return new CookieResponseMiddleware<TRegistry>(requestContext)\n }\n\n private _buildCsrfMiddlewares(\n opts: MiddlewareConfig,\n container: IServiceContainer<TRegistry>,\n requestContext: IRequestContext<RequestContext, TRegistry>,\n routePolicyCheck: () => IRoute<TRegistry>,\n ) {\n if (!Guards.isDefined(opts.csrf)) return []\n const csrf = opts.csrf\n\n container.addSingleton(TOKENS.CRYPTO_SERVICE, () => new EdgeCryptoService())\n container.addSingleton(TOKENS.CSRF_TOKEN_SERVICE, (c) => {\n return new CsrfTokenService(csrf.secret, c.resolve(TOKENS.CRYPTO_SERVICE))\n })\n\n return [\n new CsrfCookieMiddleware(requestContext, container.resolve(TOKENS.CSRF_TOKEN_SERVICE), csrf),\n new CsrfMiddleware(\n requestContext,\n container.resolve(TOKENS.CSRF_TOKEN_SERVICE),\n routePolicyCheck,\n ),\n ]\n }\n\n private async _buildRateLimitMiddleware(\n opts: MiddlewareConfig,\n container: IServiceContainer<TRegistry>,\n requestContext: IRequestContext<RequestContext, TRegistry>,\n logger: ILogger,\n ) {\n if (Guards.isDefined(opts.rateLimit?.enabled) && opts.rateLimit?.enabled) {\n const maxRequests = opts.rateLimit?.maxRequests ?? 100\n const windowSeconds = opts.rateLimit?.windowSeconds ?? 60\n\n if (!container.isRegistered(TOKENS.CACHE)) {\n await new CacheModule().configure(container)\n }\n\n return new RateLimitMiddleware(\n requestContext,\n container.resolve(TOKENS.CACHE),\n new RateLimitKeyBuilder(requestContext),\n logger,\n { maxRequests, windowSeconds },\n )\n }\n }\n\n private _buildCorsMiddleware(\n opts: MiddlewareConfig,\n requestContext: IRequestContext<RequestContext, TRegistry>,\n withCredentials: Optional<'true' | 'false'>,\n routePolicyCheck: () => IRoute<TRegistry>,\n ) {\n if (Guards.isDefined(opts.cors?.enabled) && opts.cors.enabled) {\n return new CORSMiddleware(requestContext, routePolicyCheck, withCredentials)\n }\n }\n\n private _buildOptionsMiddleware(\n opts: MiddlewareConfig,\n requestContext: IRequestContext<RequestContext, TRegistry>,\n allowMethod: () => IAllowMethod,\n withCredentials: Optional<'true' | 'false'>,\n routePolicyCheck: () => IRoute<TRegistry>,\n ) {\n if (Guards.isDefined(opts.cors?.enablePreflight) && opts.cors?.enablePreflight) {\n const allowHeaders = Array.from(\n new Set([\n 'x-csrf-token',\n 'Authorization',\n 'Content-Type',\n 'X-Requested-With',\n 'Accept',\n 'Origin',\n 'referer',\n 'x-correlation-id',\n 'x-request-id',\n 'x-span-id',\n 'x-parent-span-id',\n 'x-return-address',\n 'x-sequence-id',\n 'x-sequence-position',\n 'x-sequence-size',\n 'x-expiration',\n ...(opts.cors.allowHeaders ?? []),\n ]),\n )\n return new OptionsMiddleware(\n requestContext,\n allowMethod(),\n routePolicyCheck,\n allowHeaders,\n withCredentials,\n )\n }\n }\n\n private _createAuthMiddleware(\n container: IServiceContainer<TRegistry>,\n requestContext: IRequestContext<RequestContext, TRegistry>,\n logger: ILogger,\n opts: MiddlewareConfig,\n ): IMiddleware {\n if (!container.isRegistered(TOKENS.TOKEN_SERVICE_EXTRACTOR)) {\n container.addSingleton(\n TOKENS.TOKEN_SERVICE_EXTRACTOR,\n () => new BearerTokenExtractor(opts.authCookieName ?? 'sb-access-token'),\n )\n }\n const tokenExtractor = container.resolve(TOKENS.TOKEN_SERVICE_EXTRACTOR)\n\n if (!container.isRegistered(TOKENS.BASE_AUTH_SERVICE)) {\n return new AuthenticationMiddleware(\n requestContext,\n tokenExtractor,\n new NoAuthGateKeeper(),\n logger,\n )\n }\n\n return new AuthenticationMiddleware(\n requestContext,\n tokenExtractor,\n new GateKeeper(() => {\n const scope = requestContext.getScope()\n if (!Guards.isDefined(scope)) {\n throw new Error('[GateKeeper Error]: No active scope found.')\n }\n return scope.resolve(TOKENS.BASE_AUTH_SERVICE)\n }, new ClaimsIdentityMapper()),\n logger,\n )\n }\n}\n","import type {\n AppError,\n ICommand,\n IContextAccessor,\n IController,\n IMediator,\n IQuery,\n RequestContext,\n ResultType,\n} from '@xeno-js/shared'\nimport type { Dictionary, Optional, ResponseDto } from '@xeno-js/shared'\nimport { GuidHelper, HttpHelper } from '@xeno-js/shared'\n\n/**\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.\n * @template TRequest - The type of the request object that the controller will handle.\n * @template TResponse - The type of the response object that the controller will return.\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 abstract class BaseController<TRequest, TResponse> implements IController<\n TRequest,\n TResponse\n> {\n /**\n * Constructs a new instance of the BaseController class.\n * @param _requestContext - An instance of IContextAccessor used to manage the execution context for requests.\n * @param _mediator - An instance of IMediator used to facilitate communication between different parts of the application.\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 constructor(\n private readonly _requestContext: IContextAccessor<RequestContext>,\n private readonly _mediator: IMediator,\n ) {}\n\n abstract handle(request: TRequest, signal: Optional<AbortSignal>): Promise<ResponseDto<TResponse>>\n\n /**\n * Helper to return a successful 200/201 response.\n * @param data - The data to include in the response.\n * @param status - The HTTP status code (default is 200).\n * @param meta - Optional metadata to include in the response.\n * @param headers - Optional headers to include in the response.\n * @returns A ResponseDto containing the data and status.\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 protected ok<T>(\n data: T,\n status = 200,\n meta: Optional<Dictionary> = {},\n headers: Optional<Dictionary<string[]>> = {},\n ): ResponseDto<T> {\n return HttpHelper.success(data, status, meta, headers)\n }\n\n /**\n * Helper to automatically map a failed Result (from the CQRS pipeline)\n * into a standardized ErrorResponseDto.\n * @param error - The AppError instance representing the error.\n * @param details - Optional additional details about the error.\n * @param headers - Optional headers to include in the error response.\n * @returns A ResponseDto representing the error response.\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 protected fail(\n error: AppError,\n details: Optional<string> = undefined,\n headers: Optional<Dictionary<string[]>> = {},\n ): ResponseDto<TResponse> {\n const context = this._requestContext.getContext()\n\n const customHeaders = error['header'] as Optional<Dictionary<string[]>>\n\n return HttpHelper.error<TResponse>(\n {\n success: false,\n error: {\n code: error.code,\n message: error.message,\n path: context?.network.path,\n details: details ?? error.message,\n },\n correlationId: context?.tracing.correlationId ?? GuidHelper.generate(),\n requestId: context?.network.requestId ?? GuidHelper.generate(),\n spanId: context?.tracing.spanId ?? GuidHelper.generate(),\n timestamp: new Date().toISOString(),\n },\n error.status,\n {\n 'Content-Type': [context?.network.formatIndicator ?? 'application/json'],\n ...customHeaders,\n ...headers,\n },\n )\n }\n\n /**\n * Helper to send a query through the mediator and return the result.\n * @param request - The IQuery instance to be sent.\n * @param signal - The AbortSignal\n * @returns A promise resolving to the result of the query.\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 protected _query(\n request: IQuery<TResponse>,\n signal: Optional<AbortSignal>,\n ): Promise<ResultType<TResponse>> {\n return this._mediator.query(request, signal)\n }\n\n /**\n * Helper to send a command through the mediator and return the result.\n * @param request - The ICommand instance to be sent.\n * @param signal - The AbortSignal\n * @returns A promise resolving to the result of the command.\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 protected _send(\n request: ICommand<TResponse>,\n signal: Optional<AbortSignal>,\n ): Promise<ResultType<TResponse>> {\n return this._mediator.send(request, signal)\n }\n\n protected getContext(): Optional<RequestContext> {\n return this._requestContext.getContext()\n }\n}\n","import type {\n HttpMethod,\n IMiddleware,\n RequestContext,\n ResponseDto,\n XenoRequest,\n} from '@xeno-js/shared'\nimport type { IAllowMethod, IRequestContext, XenoRegistry } from '@xeno-js/shared'\nimport {\n ERROR_CODE_MESSAGES,\n ERROR_CODES,\n GuidHelper,\n HttpHelper,\n STATUS_CODES,\n} from '@xeno-js/shared'\n\n/**\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\n * status code with an error message.\n * @author Xeno\n * @version 1.0.0\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-js\n * @param {IAllowMethod} _allowMethod - The allow method service to check if the method is allowed.\n * @param {IRequestContext<RequestContext, XenoRegistry>} _requestContext - The request context to get the request context.\n * @returns {IMiddleware} - The middleware function that checks if the method is allowed.\n * @throws {Error} - If the method is not allowed, it throws an error with a 405 status code and an error message.\n * @see {@link IAllowMethod} - The allow method service.\n * @see {@link IRequestContext} - The request context.\n * @see {@link IMiddleware} - The middleware interface.\n * @see {@link IResponseDto} - The response DTO.\n */\nexport class MethodCheckMiddleware implements IMiddleware {\n constructor(\n private readonly _requestContext: IRequestContext<RequestContext, XenoRegistry>,\n private readonly _allowMethod: IAllowMethod,\n ) {}\n\n public async execute<T>(\n req: XenoRequest,\n next: () => Promise<ResponseDto<T>>,\n ): Promise<ResponseDto<T>> {\n const isAllowed = this._allowMethod.check(req.path, req.method as HttpMethod)\n\n if (!isAllowed) {\n const { network, tracing } = this._requestContext.getContext() ?? {}\n\n return HttpHelper.error(\n {\n success: false,\n error: {\n code: ERROR_CODES.NOT_ALLOWED,\n message: ERROR_CODE_MESSAGES[ERROR_CODES.NOT_ALLOWED],\n details: `Operation blocked by allow method middleware`,\n path: req.path,\n },\n correlationId: tracing?.correlationId ?? GuidHelper.generate(),\n requestId: network?.requestId ?? GuidHelper.generate(),\n spanId: tracing?.spanId ?? GuidHelper.generate(),\n timestamp: new Date().toISOString(),\n },\n STATUS_CODES.NOT_ALLOWED,\n {\n Allow: this._allowMethod.getMethods(req.path),\n },\n )\n }\n\n return await next()\n }\n}\n","import type {\n IContextAccessor,\n ILogger,\n IMiddleware,\n IRoutePolicyCheck,\n Optional,\n RequestContext,\n ResponseDto,\n RoutePolicy,\n XenoRequest,\n} from '@xeno-js/shared'\nimport type { IAllowOrigin } from '@xeno-js/shared'\nimport {\n ERROR_CODE_MESSAGES,\n ERROR_CODES,\n Guards,\n GuidHelper,\n HttpHelper,\n STATUS_CODES,\n} from '@xeno-js/shared'\n\n/**\n * @description A middleware that checks if the origin of the request is allowed.\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 AllowOriginMiddleware implements IMiddleware {\n constructor(\n private readonly _allowOrigin: IAllowOrigin,\n private readonly _requestContext: IContextAccessor<RequestContext>,\n private readonly _logger: ILogger,\n private readonly _getRouteMatcher: () => IRoutePolicyCheck,\n ) {}\n\n public async execute<T>(\n req: XenoRequest,\n next: () => Promise<ResponseDto<T>>,\n ): Promise<ResponseDto<T>> {\n const { network, tracing } = this._requestContext.getContext() ?? {}\n const origin = network?.origin\n\n const policy = this._getRouteMatcher().checkRoutePolicy(req.path, req.method)\n\n const isAllowed = this.checkOrigin(policy, origin)\n\n if (!isAllowed) {\n this._logger.warn(`Access denied by AllowOrigin policy for origin: ${origin ?? 'unknown'}`)\n\n return HttpHelper.error(\n {\n success: false,\n error: {\n code: ERROR_CODES.FORBIDDEN,\n message: ERROR_CODE_MESSAGES[ERROR_CODES.FORBIDDEN],\n details: `The origin '${origin ?? 'unknown'}' is not allowed to access this resource.`,\n path: req.path,\n },\n correlationId: tracing?.correlationId ?? GuidHelper.generate(),\n requestId: network?.requestId ?? GuidHelper.generate(),\n spanId: tracing?.spanId ?? GuidHelper.generate(),\n timestamp: new Date().toISOString(),\n },\n STATUS_CODES.FORBIDDEN,\n )\n }\n\n return next()\n }\n\n private checkOrigin(policy: RoutePolicy, origin: Optional<string>): boolean {\n if (Guards.isDefined(policy.allowOrigins)) {\n return policy.allowOrigins.includes('*') || policy.allowOrigins.includes(origin ?? '')\n } else {\n return this._allowOrigin.isAllowed(origin)\n }\n }\n}\n","import type {\n IGateKeeper,\n ILogger,\n IMiddleware,\n IServiceExtractor,\n Optional,\n RequestContext,\n ResponseDto,\n XenoRequest,\n} from '@xeno-js/shared'\nimport type { IRequestContext, XenoRegistry } from '@xeno-js/shared'\nimport { GuidHelper, HttpHelper, STATUS_CODES } from '@xeno-js/shared'\n\n/**\n * @description Middleware that checks if the request is authenticated. If the request is not authenticated, it returns a 401\n * status code with an error message.\n * @author Xeno\n * @version 1.0.0\n * @since 2025-09-30\n * @param {IRequestContext<RequestContext, XenoRegistry>} _requestContext - The request context to use for resolving services.\n * @param {IGateKeeper} _gateKeeper - The gate keeper to use for authentication.\n * @param {ILogger} _logger - The logger to use for logging.\n * @param {IServiceExtractor<HttpHeaders, Optional<string>>} _tokenExtractor - The token extractor to use for extracting the token from the request.\n * @returns {IMiddleware} - The middleware function.\n * @link https://github.com/xeno-js/xeno-js\n *\n * @see {@link IRequestContext} - The request context interface.\n * @see {@link IGateKeeper} - The gate keeper interface.\n * @see {@link ILogger} - The logger interface.\n * @see {@link IServiceExtractor} - The service extractor interface.\n */\nexport class AuthenticationMiddleware implements IMiddleware {\n constructor(\n private readonly _requestContext: IRequestContext<RequestContext, XenoRegistry>,\n private readonly _tokenExtractor: IServiceExtractor<Request['headers'], Optional<string>>,\n private readonly _gateKeeper: IGateKeeper,\n private readonly _logger: ILogger,\n ) {}\n\n public async execute<T>(\n req: XenoRequest,\n next: () => Promise<ResponseDto<T>>,\n ): Promise<ResponseDto<T>> {\n const token = this._tokenExtractor.extract(req.headers)\n const authResult = await this._gateKeeper.authenticate(token)\n\n if (!authResult.isOk()) {\n const error = authResult.getErrorOrThrow()\n this._logger.warn(\n `Authentication failed for request on path: ${req.path}. Code: ${error.code}. Error: ${error}`,\n )\n\n const { network, tracing } = this._requestContext.getContext() ?? {}\n\n return HttpHelper.error(\n {\n success: false,\n error: {\n code: error.code,\n message: error.message,\n details: `[Authentication Error] Failed to authenticate request on path: ${req.path}`,\n path: req.path,\n },\n correlationId: tracing?.correlationId ?? GuidHelper.generate(),\n requestId: network?.requestId ?? GuidHelper.generate(),\n spanId: tracing?.spanId ?? GuidHelper.generate(),\n timestamp: new Date().toISOString(),\n },\n error.status ?? STATUS_CODES.UNAUTHORIZED,\n { 'Content-Type': [network?.formatIndicator ?? 'application/json'] },\n )\n }\n\n this._requestContext.updateIdentity(authResult.getValueOrThrow()!)\n\n return next()\n }\n}\n","import type { IMiddleware, ResponseDto, XenoRequest } from '@xeno-js/shared'\n\n/**\n * @description A middleware that executes a list of middlewares in a chain.\n *\n * @author Xeno\n * @version 1.0.1\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-js\n */\nexport class CompositeMiddleware implements IMiddleware {\n constructor(private readonly _middlewares: IMiddleware[]) {}\n\n public async execute<T>(\n req: XenoRequest,\n next: () => Promise<ResponseDto<T>>,\n ): Promise<ResponseDto<T>> {\n let currentNext = next\n\n for (let i = this._middlewares.length - 1; i >= 0; i--) {\n const currentBehavior = this._middlewares[i]\n const previousNext = currentNext\n currentNext = () => currentBehavior.execute(req, previousNext)\n }\n\n return currentNext()\n }\n}\n","import type { IMiddleware, ResponseDto, XenoRequest } from '@xeno-js/shared'\nimport type { IRequestContext, XenoRegistry } from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\nimport { TOKENS } from '@xeno-js/shared'\n\nexport class CookieResponseMiddleware<\n TRegistry extends XenoRegistry = XenoRegistry,\n> implements IMiddleware {\n constructor(private readonly _requestContext: IRequestContext<unknown, TRegistry>) {}\n\n public async execute<T>(\n req: XenoRequest,\n next: () => Promise<ResponseDto<T>>,\n ): Promise<ResponseDto<T>> {\n const response = await next()\n\n const scope = this._requestContext.getScope()\n if (!Guards.isDefined(scope)) {\n return response\n }\n\n try {\n const cookieHandler = scope.resolve(TOKENS.COOKIE_HANDLER)\n const pending = cookieHandler.getPendingCookies()\n\n if (!Guards.isNullOrEmpty(pending)) {\n const existingSetCookie = response.headers?.['Set-Cookie']\n const mergedCookies = Guards.isArray(existingSetCookie)\n ? [...existingSetCookie, ...pending]\n : Guards.isDefined(existingSetCookie)\n ? [String(existingSetCookie), ...pending]\n : [...pending]\n\n response.headers = {\n ...(response?.headers ?? {}),\n 'Set-Cookie': mergedCookies,\n }\n }\n } catch {\n /* noop */\n }\n\n return response\n }\n}\n","import type {\n IContextAccessor,\n IMiddleware,\n IRoutePolicyCheck,\n RequestContext,\n ResponseDto,\n XenoRequest,\n} from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\n/**\n * @description A cors middleware that checks if the origin of the request is allowed.\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 CORSMiddleware implements IMiddleware {\n constructor(\n private readonly _requestContext: IContextAccessor<RequestContext>,\n private readonly _getRouteMatcher: () => IRoutePolicyCheck,\n private readonly _withCredentials: 'true' | 'false' = 'false',\n ) {}\n\n public async execute<T>(\n req: XenoRequest,\n next: () => Promise<ResponseDto<T>>,\n ): Promise<ResponseDto<T>> {\n const { network } = this._requestContext.getContext() ?? {}\n const origin = network?.origin\n\n const response = await next()\n\n const policy = this._getRouteMatcher().checkRoutePolicy(req.path, req.method)\n const withCredentials = Guards.isDefined(policy.withCredentials)\n ? policy.withCredentials\n ? 'true'\n : 'false'\n : this._withCredentials\n\n const allowOrigins = policy.allowOrigins\n\n if (\n Guards.isDefined(origin) ||\n (Guards.isDefined(allowOrigins) && allowOrigins.includes('*'))\n ) {\n response.headers = {\n ...(response?.headers ?? {}),\n 'Access-Control-Allow-Origin':\n Guards.isDefined(allowOrigins) &&\n allowOrigins.includes('*') &&\n withCredentials === 'false'\n ? '*'\n : origin!,\n 'Access-Control-Allow-Credentials': withCredentials,\n 'Vary': 'Origin',\n }\n }\n return response\n }\n}\n","import type {\n IMiddleware,\n IRoutePolicyCheck,\n RequestContext,\n ResponseDto,\n XenoRequest,\n} from '@xeno-js/shared'\nimport type { ICsrfTokenService, IRequestContext, XenoRegistry } from '@xeno-js/shared'\nimport {\n ERROR_CODE_MESSAGES,\n ERROR_CODES,\n Guards,\n GuidHelper,\n HttpHelper,\n STATUS_CODES,\n} from '@xeno-js/shared'\n\n/**\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.\n */\nexport class CsrfMiddleware implements IMiddleware {\n constructor(\n private readonly _requestContext: IRequestContext<RequestContext, XenoRegistry>,\n private readonly _csrfTokenService: ICsrfTokenService,\n private readonly _getRouteMatcher: () => IRoutePolicyCheck,\n ) {}\n\n public async execute<T>(\n req: XenoRequest,\n next: () => Promise<ResponseDto<T>>,\n ): Promise<ResponseDto<T>> {\n const method = req.method.toUpperCase()\n const isStateChanging = ['POST', 'PUT', 'DELETE', 'PATCH'].includes(method)\n\n if (isStateChanging) {\n const policy = this._getRouteMatcher().checkRoutePolicy(req.path, method)\n\n if (Guards.isDefined(policy.withCsrf) && !policy.withCsrf) return await next()\n\n const { network, tracing, identity } = this._requestContext.getContext() ?? {}\n const headerToken = network?.csrf\n const cookieToken = network?.csrfCookie\n\n if (!Guards.isDefined(headerToken) || !Guards.isDefined(cookieToken)) {\n return HttpHelper.error(\n {\n success: false,\n error: {\n code: ERROR_CODES.FORBIDDEN,\n message: ERROR_CODE_MESSAGES[ERROR_CODES.FORBIDDEN],\n details: 'CSRF token missing',\n path: req.path,\n },\n correlationId: tracing?.correlationId ?? GuidHelper.generate(),\n requestId: network?.requestId ?? GuidHelper.generate(),\n spanId: tracing?.spanId ?? GuidHelper.generate(),\n timestamp: new Date().toISOString(),\n },\n STATUS_CODES.FORBIDDEN,\n {\n 'Content-Type': [network?.formatIndicator ?? 'application/json'],\n },\n )\n }\n\n if (headerToken !== cookieToken) {\n return HttpHelper.error(\n {\n success: false,\n error: {\n code: ERROR_CODES.FORBIDDEN,\n message: ERROR_CODE_MESSAGES[ERROR_CODES.FORBIDDEN],\n details: 'CSRF token mismatch',\n path: req.path,\n },\n correlationId: tracing?.correlationId ?? GuidHelper.generate(),\n requestId: network?.requestId ?? GuidHelper.generate(),\n spanId: tracing?.spanId ?? GuidHelper.generate(),\n timestamp: new Date().toISOString(),\n },\n STATUS_CODES.FORBIDDEN,\n {\n 'Content-Type': [network?.formatIndicator ?? 'application/json'],\n },\n )\n }\n\n if (\n !Guards.isDefined(identity?.userId) ||\n !(await this._csrfTokenService.validate(headerToken, identity?.userId))\n ) {\n return HttpHelper.error(\n {\n success: false,\n error: {\n code: ERROR_CODES.FORBIDDEN,\n message: ERROR_CODE_MESSAGES[ERROR_CODES.FORBIDDEN],\n details: 'CSRF token invalid',\n path: req.path,\n },\n correlationId: tracing?.correlationId ?? GuidHelper.generate(),\n requestId: network?.requestId ?? GuidHelper.generate(),\n spanId: tracing?.spanId ?? GuidHelper.generate(),\n timestamp: new Date().toISOString(),\n },\n STATUS_CODES.FORBIDDEN,\n {\n 'Content-Type': [network?.formatIndicator ?? 'application/json'],\n },\n )\n }\n }\n\n return await next()\n }\n}\n","import type {\n IContextAccessor,\n IMiddleware,\n RequestContext,\n ResponseDto,\n XenoRequest,\n} from '@xeno-js/shared'\nimport type { ICsrfTokenService, MiddlewareConfig } from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\n/**\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.\n *\n * @author Xeno\n * @version 1.0.0\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-js\n * @license MIT\n */\nexport class CsrfCookieMiddleware implements IMiddleware {\n constructor(\n private readonly _requestContext: IContextAccessor<RequestContext>,\n private readonly _csrfTokenService: ICsrfTokenService,\n private readonly _csrf: NonNullable<MiddlewareConfig['csrf']>,\n ) {}\n\n public async execute<T>(\n req: XenoRequest,\n next: () => Promise<ResponseDto<T>>,\n ): Promise<ResponseDto<T>> {\n const response = await next()\n\n const context = this._requestContext.getContext()\n const identity = context?.identity\n const network = context?.network\n\n if (!Guards.isDefined(identity?.userId)) return response\n\n if (Guards.isDefined(network?.csrfCookie)) return response\n\n const token = await this._csrfTokenService.generate(identity.userId)\n\n const cookieName = this._csrf.cookieName ?? '__Host-xeno-csrf'\n const maxAge = this._csrf.cookieMaxAgeSeconds ?? 3600\n const sameSite = this._csrf.sameSite ?? 'lax'\n\n const cookie =\n `${cookieName}=${encodeURIComponent(token)}; ` +\n `Path=/; ` +\n `Secure; ` +\n `SameSite=${sameSite}; ` +\n `Max-Age=${maxAge}`\n\n const existingCookies = response.headers?.['Set-Cookie']\n\n response.headers = {\n ...(response?.headers ?? {}),\n 'Set-Cookie': [...(existingCookies ?? []), cookie],\n }\n\n return response\n }\n}\n","import type {\n HttpHeaders,\n IMiddleware,\n INetworkContextAccessor,\n IRoutePolicyCheck,\n ResponseDto,\n XenoRequest,\n} from '@xeno-js/shared'\nimport type { IAllowMethod } from '@xeno-js/shared'\nimport { Guards, HttpHelper, STATUS_CODES } from '@xeno-js/shared'\n\n/**\n * @description A middleware that handles OPTIONS requests.\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 OptionsMiddleware implements IMiddleware {\n constructor(\n private readonly _requestContext: INetworkContextAccessor,\n private readonly _allowMethod: IAllowMethod,\n private readonly _getRouteMatcher: () => IRoutePolicyCheck,\n private readonly _allowHeaders: string[] = [],\n private readonly _withCredentials: 'true' | 'false' = 'false',\n ) {}\n\n public async execute<T>(\n req: XenoRequest,\n next: () => Promise<ResponseDto<T>>,\n ): Promise<ResponseDto<T>> {\n if (req.method.toUpperCase() === 'OPTIONS') {\n const network = this._requestContext.getNetworkContext()\n const origin = network?.origin\n const targetMethod = req.headers.get('access-control-request-method') ?? 'GET'\n\n const policy = this._getRouteMatcher().checkRoutePolicy(req.path, targetMethod)\n\n const withCredentials = Guards.isDefined(policy.withCredentials)\n ? policy.withCredentials\n ? 'true'\n : 'false'\n : this._withCredentials\n\n const headers: HttpHeaders = {}\n if (\n Guards.isDefined(origin) ||\n (Guards.isDefined(policy.allowOrigins) && policy.allowOrigins.includes('*'))\n ) {\n headers['Access-Control-Allow-Origin'] =\n Guards.isDefined(policy.allowOrigins) &&\n policy.allowOrigins.includes('*') &&\n withCredentials === 'false'\n ? '*'\n : origin!\n headers['Access-Control-Allow-Credentials'] = withCredentials\n headers['Vary'] = 'Origin'\n }\n\n headers['Access-Control-Allow-Methods'] = this._allowMethod.getMethods(req.path)\n headers['Access-Control-Allow-Headers'] = this._allowHeaders.join(', ')\n\n return HttpHelper.success(null as T, STATUS_CODES.NO_CONTENT, {}, headers)\n }\n return await next()\n }\n}\n","import type {\n IContextAccessor,\n ILogger,\n IMiddleware,\n RequestContext,\n ResponseDto,\n XenoRequest,\n} from '@xeno-js/shared'\nimport type { IAtomicCache, IRateLimitKeyBuilder } from '@xeno-js/shared'\nimport {\n ERROR_CODE_MESSAGES,\n ERROR_CODES,\n Guards,\n GuidHelper,\n HttpHelper,\n STATUS_CODES,\n} from '@xeno-js/shared'\n\n/**\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.\n *\n * @author Xeno\n * @version 1.0.0\n * @since 1.0.0\n * @param {IContextAccessor<RequestContext>} _ctxAccessor - The context accessor for the request.\n * @param {IAtomicCache} _cache - The cache used to store the request counts.\n * @param {ILogger} _logger - The logger used to log messages.\n * @param {number} _opts.maxRequests - The maximum number of requests allowed within the time window.\n * @param {number} _opts.windowSeconds - The time window in seconds within which the maximum number of requests is allowed.\n * @link https://github.com/xenowits/xeno-js\n */\nexport class RateLimitMiddleware implements IMiddleware {\n constructor(\n private readonly _ctxAccessor: IContextAccessor<RequestContext>,\n private readonly _cache: IAtomicCache,\n private readonly _keyBuilder: IRateLimitKeyBuilder,\n private readonly _logger: ILogger,\n private readonly _opts: {\n maxRequests: number\n windowSeconds: number\n },\n ) {}\n\n public async execute<T>(\n req: XenoRequest,\n next: () => Promise<ResponseDto<T>>,\n ): Promise<ResponseDto<T>> {\n const cacheKey = this._keyBuilder.buildRateLimitKey(req.path)\n const { network, tracing } = this._ctxAccessor.getContext() ?? {}\n\n if (!Guards.isDefined(cacheKey))\n return HttpHelper.error(\n {\n success: false,\n error: {\n code: ERROR_CODES.SYSTEM_ERROR,\n message: ERROR_CODE_MESSAGES[ERROR_CODES.SYSTEM_ERROR],\n details: `Bad Request: Unable to identify client context for rate limiting.`,\n path: req.path,\n },\n correlationId: tracing?.correlationId ?? GuidHelper.generate(),\n requestId: network?.requestId ?? GuidHelper.generate(),\n spanId: tracing?.spanId ?? GuidHelper.generate(),\n timestamp: new Date().toISOString(),\n },\n STATUS_CODES.SERVICE_UNAVAILABLE,\n {\n 'Content-Type': [network?.formatIndicator ?? 'application/json'],\n 'Retry-After': [String(this._opts.windowSeconds)],\n },\n )\n\n const currentHits = await this._cache.increment(cacheKey, this._opts.windowSeconds)\n\n if (currentHits > this._opts.maxRequests) {\n this._logger.warn(`[RateLimit] key ${cacheKey} has been blocked on ${req.path}`)\n\n return HttpHelper.error(\n {\n success: false,\n error: {\n code: ERROR_CODES.TOO_MANY_REQUESTS,\n message: ERROR_CODE_MESSAGES[ERROR_CODES.TOO_MANY_REQUESTS],\n details: `Rate limit exceeded.`,\n path: req.path,\n },\n correlationId: tracing?.correlationId ?? GuidHelper.generate(),\n requestId: network?.requestId ?? GuidHelper.generate(),\n spanId: tracing?.spanId ?? GuidHelper.generate(),\n timestamp: new Date().toISOString(),\n },\n STATUS_CODES.TOO_MANY_REQUESTS,\n {\n 'Content-Type': [network?.formatIndicator ?? 'application/json'],\n 'Retry-After': [String(this._opts.windowSeconds)],\n },\n )\n }\n\n return next()\n }\n}\n","import type {\n Identity,\n ILogger,\n IMiddleware,\n IServiceExtractor,\n RequestContext,\n XenoRequest,\n} from '@xeno-js/shared'\nimport type { Guid, Metadata, ResponseDto } from '@xeno-js/shared'\nimport type { IIPResolver, IRequestContext, XenoRegistry } from '@xeno-js/shared'\nimport {\n ERROR_CODE_MESSAGES,\n ERROR_CODES,\n GUEST,\n GuidHelper,\n HttpHelper,\n STATUS_CODES,\n} from '@xeno-js/shared'\n\nimport { ContextMapper } from '../mappers/context.mapper'\n\n/**\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.\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 RequestContextMiddleware implements IMiddleware {\n /**\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.\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.\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.\n * @param _logger\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 constructor(\n private readonly _requestContext: IRequestContext<RequestContext, XenoRegistry>,\n private readonly _extractor: IServiceExtractor<Request['headers'], Metadata>,\n private readonly _resolver: IIPResolver,\n private readonly _logger: ILogger,\n ) {}\n\n public async execute<T>(\n req: XenoRequest,\n next: () => Promise<ResponseDto<T>>,\n ): Promise<ResponseDto<T>> {\n const correlationId = GuidHelper.generate()\n const requestId = GuidHelper.generate()\n const spanId: Guid = GuidHelper.generate()\n let formatIndicator = 'application/json'\n\n try {\n const meta = this._extractor.extract(req.headers)\n\n const clientIp = this._resolver.resolve(req, meta.clientIp)\n\n formatIndicator = meta.formatIndicator\n const metadata: Metadata = {\n ...meta,\n clientIp,\n correlationId: meta.correlationId ?? correlationId,\n requestId: meta.requestId ?? requestId,\n spanId: meta.spanId ?? spanId,\n formatIndicator,\n }\n\n const tmpContext = ContextMapper.map({\n metadata,\n identity: GUEST as unknown as Identity,\n path: req.path,\n })\n\n const result = await this._requestContext.runAsync(tmpContext, async () => {\n return next()\n })\n if (!result.ok && !result.data.success)\n this._logger.error(result.data.error.message, result.data)\n\n return result\n } catch (error) {\n this._logger.error('RequestContextMiddleware encountered an error', error)\n return HttpHelper.error(\n {\n success: false,\n error: {\n code: ERROR_CODES.SYSTEM_ERROR,\n message: ERROR_CODE_MESSAGES[ERROR_CODES.SYSTEM_ERROR],\n details: `[Fatal System Error] Exception caught during request handling on path: ${req.path}`,\n path: req.path,\n },\n correlationId,\n requestId,\n spanId,\n timestamp: new Date().toISOString(),\n },\n STATUS_CODES.INTERNAL_SERVER_ERROR,\n { 'Content-Type': [formatIndicator] },\n )\n }\n }\n}\n","import type {\n IBaseMapper,\n Identity,\n MessagingContext,\n NetworkContext,\n RequestContext,\n TracingContext,\n} from '@xeno-js/shared'\nimport { Guards, type Metadata, type Optional } from '@xeno-js/shared'\n\ninterface ContextMapperSource {\n readonly metadata: Metadata\n readonly identity: Identity\n readonly path: string\n}\n\nexport const ContextMapper: IBaseMapper<ContextMapperSource, RequestContext> = Object.freeze({\n /**\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.\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 map: (source: ContextMapperSource): RequestContext => {\n const { metadata, identity, path } = source\n\n const network: NetworkContext = {\n requestId: metadata.requestId!,\n clientIp: metadata.clientIp,\n userAgent: metadata.userAgent,\n formatIndicator: metadata.formatIndicator,\n path,\n csrf: metadata.csrf,\n csrfCookie: metadata.csrfCookie,\n cookies: metadata.cookies,\n origin: metadata.origin,\n }\n const tracing: TracingContext = {\n correlationId: metadata.correlationId!,\n startTime: Date.now(),\n spanId: metadata.spanId,\n parentSpanId: metadata.parentSpanId,\n referer: metadata.referer,\n }\n const messaging = _buildMessagingContext(metadata)\n\n const requestContext: RequestContext = {\n identity,\n network,\n tracing,\n messaging,\n }\n\n return requestContext\n },\n} as const)\n\n/**\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.\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.\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.\n *\n * @author Xeno\n * @version 1.0.0\n * @since 2025-09-30\n * @link https://github.com/xeno-js/xeno-js\n */\nfunction _buildMessagingContext(meta: Metadata): Optional<MessagingContext> {\n const hasSequenceData =\n Guards.isDefined(meta.sequence?.sequenceId) ||\n Guards.isDefined(meta.sequence?.position) ||\n Guards.isDefined(meta.sequence?.size)\n\n const hasMessagingData =\n hasSequenceData || Guards.isDefined(meta.expiration) || Guards.isDefined(meta.returnAddress)\n\n if (!hasMessagingData) return undefined\n\n return {\n returnAddress: meta.returnAddress,\n expiration: meta.expiration,\n sequence:\n hasSequenceData && Guards.isDefined(meta.sequence)\n ? {\n sequenceId: meta.sequence.sequenceId,\n position: meta.sequence.position,\n size: meta.sequence.size,\n }\n : undefined,\n }\n}\n","import type {\n IController,\n IMiddleware,\n Optional,\n RequestContext,\n ResponseDto,\n XenoRequest,\n} from '@xeno-js/shared'\nimport type { IHttpDispatcher, IRequestContext, IServiceProxy, XenoRegistry } from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\nexport class HttpDispatcher<\n TRegistry extends XenoRegistry = XenoRegistry,\n> implements IHttpDispatcher<TRegistry> {\n constructor(\n private readonly _requestContext: IRequestContext<RequestContext, TRegistry>,\n private readonly _middleware: IMiddleware,\n private readonly _serviceProxy: IServiceProxy,\n ) {}\n\n public async handle<TInput, TOutput, K extends keyof TRegistry>(\n req: XenoRequest,\n token: K,\n input?: Optional<TInput>,\n ): Promise<ResponseDto<TOutput>> {\n return await this._middleware.execute(req, async () => {\n const scope = this._requestContext.getScope()\n\n if (!Guards.isDefined(scope)) {\n throw new Error(\n '[HttpDispatcher Error]: Active scope not found. Execution outside RequestContext.',\n )\n }\n\n const services = this._serviceProxy.getServiceProxy<TRegistry>(scope)\n const controller = services[token] as Optional<IController<Optional<TInput>, TOutput>>\n\n if (!Guards.isDefined(controller) || !Guards.hasMethod(controller, 'handle')) {\n throw new Error(\n `[HttpDispatcher Error]: The provided '${String(token)}' does not implement the 'handle' method.`,\n )\n }\n\n return await controller.handle(input, req.signal)\n })\n }\n}\n","import type { Identity, RequestContext, ResponseDto, XenoRequest } from '@xeno-js/shared'\nimport type {\n IModule,\n IRequestContext,\n IServiceContainer,\n NativeRouteDefinition,\n XenoRegistry,\n} from '@xeno-js/shared'\nimport { GUEST, GuidHelper } from '@xeno-js/shared'\nimport { TOKENS } from '@xeno-js/shared'\n\nimport { RouteMatcherFactory } from '../factories/route-matcher.factory'\nimport { HttpDispatcher } from '../http/dispatcher.http'\n\n/**\n * @description RouteModule is responsible for registering routes services in the IoC container.\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 RouteModule<TRegistry extends XenoRegistry = XenoRegistry> implements IModule<\n TRegistry,\n NativeRouteDefinition<TRegistry>[]\n> {\n public async configure(\n container: IServiceContainer<TRegistry>,\n opts: NativeRouteDefinition<TRegistry>[],\n ): Promise<void> {\n container.addSingleton(TOKENS.ROUTE_MATCHER, () =>\n new RouteMatcherFactory().create<TRegistry>(opts),\n )\n\n if (!container.isRegistered(TOKENS.MIDDLEWARE)) {\n const requestContext = container.resolve(TOKENS.REQUEST_CONTEXT)\n container.addSingleton(TOKENS.MIDDLEWARE, () => ({\n execute: async <T>(\n req: XenoRequest,\n next: () => Promise<ResponseDto<T>>,\n ): Promise<ResponseDto<T>> => {\n const syntheticContext: RequestContext = {\n identity: GUEST as unknown as Identity,\n network: {\n requestId: GuidHelper.generate(),\n clientIp: '127.0.0.1',\n path: req.path,\n formatIndicator: 'application/json',\n },\n tracing: {\n correlationId: GuidHelper.generate(),\n startTime: Date.now(),\n spanId: GuidHelper.generate(),\n },\n }\n return await requestContext.runAsync(syntheticContext, next)\n },\n }))\n }\n\n if (!container.isRegistered(TOKENS.HTTP_DISPATCHER)) {\n container.addSingleton(\n TOKENS.HTTP_DISPATCHER,\n (c) =>\n new HttpDispatcher<TRegistry>(\n c.resolve(TOKENS.REQUEST_CONTEXT) as IRequestContext<RequestContext, TRegistry>,\n c.resolve(TOKENS.MIDDLEWARE),\n c.resolve(TOKENS.SERVICE_PROXY),\n ),\n )\n }\n }\n}\n","import type { IConfigurationService } from '@xeno-js/shared'\nimport type { IAppBuilder, IXenoApplication, XenoPlugin, XenoRegistry } from '@xeno-js/shared'\n\nexport const definePlugin = <\n TKind extends string,\n TRegistry extends XenoRegistry = XenoRegistry,\n TCtx = unknown,\n>(\n kind: TKind,\n fn: (\n builder: IAppBuilder<TRegistry, IXenoApplication<TRegistry>>,\n config: IConfigurationService,\n ctx?: TCtx,\n ) => unknown,\n): XenoPlugin<TKind, TRegistry, TCtx> => {\n Object.defineProperty(fn, '__kind', { value: kind, writable: false })\n return fn as XenoPlugin<TKind, TRegistry, TCtx>\n}\n","import type { IConfigurationService, SetupAction } from '@xeno-js/shared'\nimport type {\n AuthModuleOptions,\n AuthPlugin,\n IAppBuilder,\n IXenoApplication,\n XenoRegistry,\n} from '@xeno-js/shared'\n\nimport { AuthModule } from '../modules/auth.module'\nimport { definePlugin } from './define.plugin'\n\n/**\n * @description Generic plugin to register any custom authentication implementation into Xeno.JS.\n * It delegates the registration to the Core AuthModule.\n *\n * @param configurator Either the AuthModuleOptions object or a factory receiving the configuration service.\n * @returns A XenoPlugin ready to be passed to builder.addAuth(...)\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 const withAuth = <TRegistry extends XenoRegistry = XenoRegistry>(\n setup: SetupAction<AuthModuleOptions<TRegistry>, IConfigurationService>,\n): AuthPlugin<TRegistry> => {\n return definePlugin(\n 'auth',\n (\n builder: IAppBuilder<TRegistry, IXenoApplication<TRegistry>>,\n config: IConfigurationService,\n ) => {\n const options = {} as AuthModuleOptions<TRegistry>\n setup(options, config)\n builder.addModule('AuthModule', async () => new AuthModule<TRegistry>(), options, 2)\n },\n )\n}\n","// ==========================================\n// 3. AUTHORIZATION (AuthZ)\n// ==========================================\n\nimport type { IConfigurationService, Optional, SetupAction } from '@xeno-js/shared'\nimport type {\n AuthorizationOptions,\n IAppBuilder,\n IPipelineSetup,\n IXenoApplication,\n PipelinePlugin,\n XenoRegistry,\n} from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\nimport { definePlugin } from './define.plugin'\n\nexport const withAuthZ = <TRegistry extends XenoRegistry = XenoRegistry>(\n setup: SetupAction<AuthorizationOptions<TRegistry>, IConfigurationService>,\n): PipelinePlugin<TRegistry> => {\n return definePlugin(\n 'pipeline',\n (\n _builder: IAppBuilder<TRegistry, IXenoApplication<TRegistry>>,\n config: IConfigurationService,\n context: Optional<IPipelineSetup<TRegistry>>,\n ) => {\n if (!Guards.isDefined(context)) throw new Error('Pipeline setup is not available.')\n\n const options: AuthorizationOptions<TRegistry> = {\n policies: undefined,\n }\n setup(options, config)\n\n context.authzOpts = options\n },\n )\n}\n","// ==========================================\n// 5. CONCURRENCY RETRY (PER-INTENT)\n// ==========================================\nimport type {\n ConcurrencyOptions,\n IAppBuilder,\n IPipelineSetup,\n IXenoApplication,\n PipelinePlugin,\n XenoRegistry,\n} from '@xeno-js/shared'\nimport {\n Guards,\n type IConfigurationService,\n type Optional,\n type SetupAction,\n} from '@xeno-js/shared'\n\nimport { ConcurrencyRetryPipeline } from '@/application'\n\nimport { definePlugin } from './define.plugin'\n\nexport const withConcurrency = <TRegistry extends XenoRegistry = XenoRegistry>(\n setup?: SetupAction<ConcurrencyOptions, IConfigurationService>,\n): PipelinePlugin<TRegistry> => {\n return definePlugin(\n 'pipeline',\n (\n _builder: IAppBuilder<TRegistry, IXenoApplication<TRegistry>>,\n config: IConfigurationService,\n context: Optional<IPipelineSetup<TRegistry>>,\n ) => {\n if (!Guards.isDefined(context)) throw new Error('Pipeline setup is not available.')\n const options: ConcurrencyOptions = {}\n if (Guards.isDefined(setup)) setup(options, config)\n context.addCommand(new ConcurrencyRetryPipeline(options), 70)\n },\n )\n}\n","import type {\n HttpConfig,\n HttpPlugin,\n IAppBuilder,\n IXenoApplication,\n XenoRegistry,\n} from '@xeno-js/shared'\nimport { Guards, type IConfigurationService } from '@xeno-js/shared'\n\nimport { HttpCoreModule } from '../modules/http-core.module'\nimport { definePlugin } from './define.plugin'\n\n/**\n * @description Generic plugin to register any custom authentication implementation into Xeno.JS.\n * It delegates the registration to the Core AuthModule.\n *\n * @param configurator Either the AuthModuleOptions object or a factory receiving the configuration service.\n * @returns A XenoPlugin ready to be passed to builder.addAuth(...)\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 const withCustomHttp = <TRegistry extends XenoRegistry = XenoRegistry>(\n config: HttpConfig<TRegistry>,\n): HttpPlugin<TRegistry> => {\n return definePlugin(\n 'http',\n (\n builder: IAppBuilder<TRegistry, IXenoApplication<TRegistry>>,\n _config: IConfigurationService,\n ) => {\n const clientEntries = Guards.isArray(config.clients) ? config.clients : [config.clients]\n\n const entries = clientEntries.map((item) => {\n if (!Guards.isDefined(item.client)) {\n throw new Error(\n `[withCustomHttp Error]: 'client' instance is required for registration '${item.name ?? 'default'}'.`,\n )\n }\n\n return {\n name: item.name ?? 'default',\n client: item.client,\n resilience: item.resilience,\n }\n })\n\n builder.addModule('HttpCoreModule', async () => new HttpCoreModule<TRegistry>(), {\n clients: entries,\n })\n },\n )\n}\n","import type {\n HttpCoreConfig,\n IModule,\n IServiceContainer,\n IServiceScope,\n XenoRegistry,\n} from '@xeno-js/shared'\nimport { Guards, type IServiceResilience, type Optional } from '@xeno-js/shared'\nimport { TOKENS } from '@xeno-js/shared'\n\nimport { RemoteDataSource } from '../datasources'\nimport { HttpClientFactory } from '../factories/http.factory'\nimport { NoOpResilienceService } from '../services/resiliences'\n\n/**\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.\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 HttpCoreModule<TRegistry extends XenoRegistry = XenoRegistry> implements IModule<\n TRegistry,\n HttpCoreConfig<TRegistry>\n> {\n public async configure(\n container: IServiceContainer<TRegistry>,\n opts: HttpCoreConfig<TRegistry>,\n ): Promise<void> {\n const factory = new HttpClientFactory()\n\n for (const entry of opts.clients) {\n const clientName = entry.name ?? 'default'\n const resilience = this.getResilienceService(container, entry.resilience)\n const dataSource = new RemoteDataSource(entry.client(container), resilience)\n factory.add(clientName, dataSource)\n }\n\n container.addSingleton(TOKENS.HTTP_CLIENT_FACTORY, () => factory)\n }\n\n private getResilienceService(\n container: IServiceContainer<TRegistry>,\n resilience?: Optional<(scope: IServiceScope<TRegistry>) => IServiceResilience>,\n ) {\n if (!Guards.isDefined(resilience)) {\n return new NoOpResilienceService()\n } else {\n return resilience(container)\n }\n }\n}\n","import type {\n HttpBaseRequest,\n HttpMethod,\n HttpRequest,\n IHttpClient,\n IRemoteDataSource,\n IServiceResilience,\n Optional,\n ResultType,\n} from '@xeno-js/shared'\nimport { AppError, Result } from '@xeno-js/shared'\n\n/**\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.\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 RemoteDataSource implements IRemoteDataSource {\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.\n * These dependencies are injected into the class, allowing for greater flexibility and testability.\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.\n * @param _httpClient An instance of an agnostic HTTP client that implements the IHttpClient interface, used for sending HTTP requests to remote endpoints.\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.\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 constructor(\n private readonly _httpClient: IHttpClient,\n private readonly _resilienceService: IServiceResilience,\n ) {}\n\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.\n * @param endpoint The URL or endpoint to which the HTTP request is sent.\n * @param options The HttpRequest options that specify the HTTP method, headers, query parameters, body, and other request configurations.\n * @returns A Promise that resolves to a ResultType containing either the successful response data or an error if the request fails.\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 async send<TResponse, TBody = unknown>(\n endpoint: string,\n options: HttpRequest<TBody>,\n ): Promise<ResultType<TResponse>> {\n const response = await this._resilienceService.execute(async () => {\n switch (options.method) {\n case 'GET':\n return await this._httpClient.get<TResponse>(endpoint, options)\n case 'POST':\n return await this._httpClient.post<TResponse, TBody>(endpoint, options.body, options)\n case 'PUT':\n return await this._httpClient.put<TResponse, TBody>(endpoint, options.body, options)\n case 'PATCH':\n return await this._httpClient.patch<TResponse, TBody>(endpoint, options.body, options)\n case 'DELETE':\n return await this._httpClient.delete<TResponse>(endpoint, options)\n default:\n throw AppError.notSupported(\n this.constructor.name,\n `Unsupported HTTP method: ${options.method}`,\n )\n }\n }, options.signal)\n\n return Result.ok(response.data)\n }\n\n protected setOptions<T>(\n request: Optional<HttpBaseRequest>,\n method: HttpMethod,\n body: Optional<T> = undefined,\n ): HttpRequest<T> {\n return {\n query: request?.query,\n signal: request?.signal,\n timeoutMs: request?.timeoutMs,\n headers: request?.headers,\n responseType: request?.responseType,\n method,\n body,\n }\n }\n\n public async get<TResponse>(\n endpoint: string,\n request?: HttpBaseRequest,\n ): Promise<ResultType<TResponse>> {\n const options = this.setOptions(request, 'GET')\n\n return await this.send<TResponse>(endpoint, options)\n }\n\n public async post<TResponse, TBody = unknown>(\n endpoint: string,\n body: TBody,\n request?: HttpBaseRequest,\n ): Promise<ResultType<TResponse>> {\n const options = this.setOptions(request, 'POST', body)\n\n return await this.send<TResponse, TBody>(endpoint, options)\n }\n\n public async put<TResponse, TBody = unknown>(\n endpoint: string,\n body: TBody,\n request?: HttpBaseRequest,\n ): Promise<ResultType<TResponse>> {\n const options = this.setOptions(request, 'PUT', body)\n\n return await this.send<TResponse, TBody>(endpoint, options)\n }\n\n public async patch<TResponse, TBody = unknown>(\n endpoint: string,\n body: TBody,\n request?: HttpBaseRequest,\n ): Promise<ResultType<TResponse>> {\n const options = this.setOptions(request, 'PATCH', body)\n\n return await this.send<TResponse, TBody>(endpoint, options)\n }\n\n public async delete<TResponse>(\n endpoint: string,\n request?: HttpBaseRequest,\n ): Promise<ResultType<TResponse>> {\n const options = this.setOptions(request, 'DELETE')\n\n return await this.send<TResponse>(endpoint, options)\n }\n}\n","import type { IHttpClientFactory } from '@xeno-js/shared'\nimport { AppError, Guards, type IRemoteDataSource } from '@xeno-js/shared'\n\nexport class HttpClientFactory implements IHttpClientFactory {\n private readonly _clients = new Map<string, IRemoteDataSource>()\n\n public add(name: string, client: IRemoteDataSource): void {\n if (this._clients.has(name)) {\n throw new Error(`[HttpClientFactory Error]: Client '${name}' already registered.`)\n }\n this._clients.set(name, client)\n }\n\n public get(name = 'default'): IRemoteDataSource {\n const client = this._clients.get(name)\n if (!Guards.isDefined(client)) {\n const available = Array.from(this._clients.keys()).join(', ') ?? 'none'\n throw AppError.notFound(\n 'HttpClientFactory',\n `[HttpClientFactory Error]: Client '${name}' not found. Available clients: [${available}].`,\n )\n }\n return client\n }\n}\n","import type { IServiceResilience, Optional } from '@xeno-js/shared'\nimport { AppError } from '@xeno-js/shared'\n\n/**\n * @description No-Op (Pass-Through) of IServiceResilience.\n * Using when resilience pattern is not required\n */\nexport class NoOpResilienceService implements IServiceResilience {\n public async execute<T>(operation: () => Promise<T>, signal?: Optional<AbortSignal>): Promise<T> {\n AppError.throwIfAborted(signal, 'NoOpResilienceService.execute')\n return await operation()\n }\n}\n","import type {\n IAppBuilder,\n IdempotencyOptions,\n IPipelineSetup,\n IXenoApplication,\n PipelinePlugin,\n XenoRegistry,\n} from '@xeno-js/shared'\nimport {\n Guards,\n type IConfigurationService,\n type Optional,\n type SetupAction,\n} from '@xeno-js/shared'\n\nimport { definePlugin } from './define.plugin'\n\n// ==========================================\n// 4. IDEMPOTENCY (PER-INTENT)\n// ==========================================\nexport const withIdempotency = <TRegistry extends XenoRegistry = XenoRegistry>(\n setup?: SetupAction<IdempotencyOptions, IConfigurationService>,\n): PipelinePlugin<TRegistry> => {\n return definePlugin(\n 'pipeline',\n (\n _builder: IAppBuilder<TRegistry, IXenoApplication<TRegistry>>,\n config: IConfigurationService,\n context: Optional<IPipelineSetup<TRegistry>>,\n ) => {\n if (!Guards.isDefined(context)) throw new Error('Pipeline setup is not available.')\n\n const options: IdempotencyOptions = {}\n if (Guards.isDefined(setup)) setup(options, config)\n\n context.idempotencyOpts = options\n },\n )\n}\n","import type {\n IAppBuilder,\n IdentityEnrichmentOptions,\n IPipelineSetup,\n IXenoApplication,\n PipelinePlugin,\n XenoRegistry,\n} from '@xeno-js/shared'\nimport {\n Guards,\n type IConfigurationService,\n type Optional,\n type SetupAction,\n} from '@xeno-js/shared'\n\nimport { definePlugin } from './define.plugin'\n\n// ==========================================\n// 5. IDENTITY ENRICHMENT\n// ==========================================\nexport const withEnrichmentIdentity = <TRegistry extends XenoRegistry = XenoRegistry>(\n setup?: SetupAction<IdentityEnrichmentOptions, IConfigurationService>,\n): PipelinePlugin<TRegistry> => {\n return definePlugin(\n 'pipeline',\n (\n _builder: IAppBuilder<TRegistry, IXenoApplication<TRegistry>>,\n config: IConfigurationService,\n context: Optional<IPipelineSetup<TRegistry>>,\n ) => {\n if (!Guards.isDefined(context)) throw new Error('Pipeline setup is not available.')\n\n const options: IdentityEnrichmentOptions = {}\n if (Guards.isDefined(setup)) setup(options, config)\n\n context.identityEnrichmentOpts = options\n },\n )\n}\n","import type { IConfigurationService, LogLevel, SetupAction } from '@xeno-js/shared'\nimport type {\n IAppBuilder,\n ILoggerSetup,\n IXenoApplication,\n LoggerPlugin,\n XenoRegistry,\n} from '@xeno-js/shared'\nimport { Guards, LOG_LEVEL } from '@xeno-js/shared'\n\nimport { definePlugin } from './define.plugin'\n\ninterface ConsoleOptions {\n isEnabled?: boolean\n level?: LogLevel\n}\n\n/**\n * @description Plugin for configuring the logger in the application.\n *\n * @param builder - The application builder instance.\n * @param config - The configuration service instance.\n * @returns void\n *\n * @author Xeno\n */\nexport const withConsoleLogger = <TRegistry extends XenoRegistry = XenoRegistry>(\n setup: SetupAction<ConsoleOptions, IConfigurationService>,\n): LoggerPlugin<TRegistry> => {\n return definePlugin(\n 'logger',\n (\n _builder: IAppBuilder<TRegistry, IXenoApplication<TRegistry>>,\n config: IConfigurationService,\n ctx?: ILoggerSetup<TRegistry>,\n ) => {\n if (!Guards.isDefined(ctx)) throw new Error('LoggerSetup is not defined.')\n const options: ConsoleOptions = {\n isEnabled: true,\n level: LOG_LEVEL.DEBUG,\n }\n setup(options, config)\n\n ctx.addConsole(options.isEnabled ?? true, options.level)\n },\n )\n}\n","import type {\n IAppBuilder,\n IPipelineSetup,\n IXenoApplication,\n PerformanceOptions,\n PipelinePlugin,\n XenoRegistry,\n} from '@xeno-js/shared'\nimport {\n Guards,\n type IConfigurationService,\n type Optional,\n type SetupAction,\n} from '@xeno-js/shared'\nimport { TOKENS } from '@xeno-js/shared'\n\nimport { PerformancePipeline } from '@/application'\n\nimport { definePlugin } from './define.plugin'\n\n// ==========================================\n// 6. PERFORMANCE (PER-INTENT)\n// ==========================================\nexport const withPerformance = <TRegistry extends XenoRegistry = XenoRegistry>(\n setup?: SetupAction<PerformanceOptions, IConfigurationService>,\n): PipelinePlugin<TRegistry> => {\n return definePlugin(\n 'pipeline',\n (\n builder: IAppBuilder<TRegistry, IXenoApplication<TRegistry>>,\n config: IConfigurationService,\n context: Optional<IPipelineSetup<TRegistry>>,\n ) => {\n if (!Guards.isDefined(context)) throw new Error('Pipeline setup is not available.')\n\n const options: PerformanceOptions = {}\n if (Guards.isDefined(setup)) setup(options, config)\n\n const logger = builder.resolve(TOKENS.LOGGER)\n context.addCommon(\n new PerformancePipeline(logger, options?.intentThresholdMs, options?.thresholdMs ?? 500),\n 20,\n )\n },\n )\n}\n","// ==========================================\n// 7. QUERY CACHING\nimport type { IConfigurationService, Optional } from '@xeno-js/shared'\nimport type {\n IAppBuilder,\n IPipelineSetup,\n IXenoApplication,\n PipelinePlugin,\n XenoRegistry,\n} from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\nimport { definePlugin } from './define.plugin'\n\n// ==========================================\nexport const withQueryCaching = <\n TRegistry extends XenoRegistry = XenoRegistry,\n>(): PipelinePlugin<TRegistry> => {\n return definePlugin(\n 'pipeline',\n (\n _builder: IAppBuilder<TRegistry, IXenoApplication<TRegistry>>,\n _config: IConfigurationService,\n context: Optional<IPipelineSetup<TRegistry>>,\n ) => {\n if (!Guards.isDefined(context)) throw new Error('Pipeline setup is not available.')\n\n context.addQuery()\n },\n )\n}\n","import type {\n IAppBuilder,\n IPipelineSetup,\n IXenoApplication,\n PipelinePlugin,\n XenoRegistry,\n} from '@xeno-js/shared'\nimport {\n Guards,\n type IConfigurationService,\n type IRequest,\n type IStrategy,\n type Optional,\n type SetupAction,\n} from '@xeno-js/shared'\n\nimport { ValidationPipeline } from '@/application'\n\nimport { definePlugin } from './define.plugin'\n\n// ==========================================\n// 2. CUSTOM VALIDATION\n// ==========================================\nexport const withValidation = <TRegistry extends XenoRegistry = XenoRegistry>(\n setup: SetupAction<IStrategy<IRequest, boolean>[], IConfigurationService>,\n): PipelinePlugin<TRegistry> => {\n return definePlugin(\n 'pipeline',\n (\n _builder: IAppBuilder<TRegistry, IXenoApplication<TRegistry>>,\n config: IConfigurationService,\n context: Optional<IPipelineSetup<TRegistry>>,\n ) => {\n if (!Guards.isDefined(context)) throw new Error('Pipeline setup is not available.')\n\n const strategies: IStrategy<IRequest, boolean>[] = []\n setup(strategies, config)\n\n if (Guards.isNullOrEmpty(strategies)) return\n const validationPipeline = new ValidationPipeline(strategies)\n context.addCommon(validationPipeline, 50)\n },\n )\n}\n","import type {\n Identity,\n Optional,\n RequestContext,\n ResponseDto,\n XenoIncomingRequest,\n} from '@xeno-js/shared'\nimport type {\n IHttpDispatcher,\n IRequestContext,\n IServiceContainer,\n IXenoApplication,\n NativeListenOptions,\n ServicesProxy,\n XenoRegistry,\n} from '@xeno-js/shared'\nimport { AppError, Guards, GUEST, GuidHelper } from '@xeno-js/shared'\nimport { TOKENS } from '@xeno-js/shared'\n\nexport class XenoApplication<\n TRegistry extends XenoRegistry = XenoRegistry,\n> implements IXenoApplication<TRegistry> {\n constructor(protected readonly _container: IServiceContainer<TRegistry>) {}\n\n /**\n * @description Resolve the services proxy\n * @returns The services proxy\n */\n public getServices(): ServicesProxy<TRegistry> {\n const container = this._container\n return new Proxy({} as ServicesProxy<TRegistry>, {\n get(_target, prop: string | symbol) {\n return container.resolve(prop as keyof TRegistry)\n },\n })\n }\n\n /**\n * @description Resolve the services proxy for the current request scope.\n * @returns {ServicesProxy<TRegistry>} The services proxy.\n */\n public getScopedServices(): ServicesProxy<TRegistry> {\n const serviceProxy = this._container.resolve(TOKENS.SERVICE_PROXY)\n const requestContext = this._container.resolve(TOKENS.REQUEST_CONTEXT) as IRequestContext<\n RequestContext,\n TRegistry\n >\n const scope = requestContext.getScope()\n if (!Guards.isDefined(scope)) {\n throw AppError.notFound(\n '[XenoApplication Error]',\n 'Active scope not found.\\n' +\n 'Please use the \"runInScope\" or \"handle\" method for tasks outside the HTTP transport.',\n )\n }\n return serviceProxy.getServiceProxy<TRegistry>(scope)\n }\n\n /**\n * @description Run the given operation in a new scope.\n * @param {Function} operation The operation to run.\n * @param {Partial<RequestContext>} [ctx] The request context.\n * @returns {Promise<T>} The result of the operation.\n */\n public async runInScope<T>(\n operation: (services: ServicesProxy<TRegistry>) => Promise<T>,\n ctx: Optional<Partial<RequestContext>> = undefined,\n ): Promise<T> {\n const requestContext = this._container.resolve(TOKENS.REQUEST_CONTEXT) as IRequestContext<\n RequestContext,\n TRegistry\n >\n\n const syntheticContext: RequestContext = {\n identity: ctx?.identity ?? (GUEST as unknown as Identity),\n network: ctx?.network ?? {\n requestId: GuidHelper.generate(),\n clientIp: '127.0.0.1',\n path: 'internal://scope-runner',\n formatIndicator: 'application/json',\n },\n tracing: ctx?.tracing ?? {\n correlationId: GuidHelper.generate(),\n startTime: Date.now(),\n spanId: GuidHelper.generate(),\n },\n messaging: ctx?.messaging,\n }\n\n return await requestContext.runAsync(syntheticContext, async () => {\n const scope = requestContext.getScope()!\n const serviceProxy = this._container.resolve(TOKENS.SERVICE_PROXY)\n const services = serviceProxy.getServiceProxy<TRegistry>(scope)\n return await operation(services)\n })\n }\n\n /**\n * @description Runs a controller operation in the context of a request.\n * Use it only if middlewares are registered in the container.\n * @param req The XenoIncomingRequest request object.\n * @param token The token of the controller operation to run.\n * @param input The input to the controller operation.\n * @returns A promise that resolves to the output of the controller operation.\n */\n public async handle<TInput, TOutput, K extends keyof TRegistry>(\n req: XenoIncomingRequest,\n token: K,\n input?: Optional<TInput>,\n ): Promise<ResponseDto<TOutput>> {\n const dispatcher = this._container.resolve(TOKENS.HTTP_DISPATCHER) as IHttpDispatcher<TRegistry>\n const adapter = this._container.resolve(TOKENS.HTTP_ADAPTER)\n const extendedRequest = adapter.adapt(req)\n return await dispatcher.handle(extendedRequest, token, input)\n }\n\n /**\n * @description Resolves the HTTP server and starts listening on the specified port.\n * @param options The options for the HTTP server.\n * @returns A promise that resolves to the result of the HTTP server listen method.\n */\n public async listen(options?: NativeListenOptions): Promise<unknown> {\n const server = this._container.resolve(TOKENS.HTTP_SERVER)\n const opts = this._container.resolve(TOKENS.SERVER_OPTIONS_FACTORY).create(options)\n return await server.listen(opts)\n }\n}\n","import type { IMapper, IReadDao, IReadDataSource, ResultType } from '@xeno-js/shared'\nimport type { Optional, UserContext } from '@xeno-js/shared'\nimport { AppError, Result } from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\n/**\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.\n * @template T - The type of the entity that the DAO will manage.\n * @template TDto - The type of the Data Transfer Object (DTO) used for data access.\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 abstract class ReadDao<T, TDto> implements IReadDao<T> {\n /**\n * Constructs a new ReadDao instance.\n * @param _dataSource An instance of IReadDataSource used to execute SQL queries and commands for data access.\n * @param _mapper An instance of IMapper used to convert between entities and DTOs.\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 constructor(\n protected readonly _dataSource: IReadDataSource<TDto>,\n protected readonly _mapper: IMapper<T, TDto>,\n ) {}\n\n public async findById(\n id: string | number,\n ctx: UserContext,\n signal: Optional<AbortSignal>,\n ): Promise<ResultType<Optional<T>>> {\n AppError.throwIfAborted(signal, 'ReadDao.findById')\n const result = await this._dataSource.findById(id, ctx, signal)\n if (Guards.isNullOrEmpty(result)) return Result.ok()\n\n const entity = this._mapper.toEntity(result)\n return Result.ok(entity)\n }\n\n public async findAll(ctx: UserContext, signal: Optional<AbortSignal>): Promise<ResultType<T[]>> {\n AppError.throwIfAborted(signal, 'ReadDao.findAll')\n const results = await this._dataSource.findAll(ctx, signal)\n const entities = results.map((result) => this._mapper.toEntity(result))\n return Result.ok(entities)\n }\n}\n","import type { IMapper, IRepository, IWriteDataSource, ResultType } from '@xeno-js/shared'\nimport type { Optional, UserContext } from '@xeno-js/shared'\nimport { AppError, Result } from '@xeno-js/shared'\nimport { Guards } from '@xeno-js/shared'\n\n/**\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.\n * @template T - The type of the entity that the repository will manage.\n * @template TDto - The type of the Data Transfer Object (DTO) used for data access.\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 abstract class Repository<T, TDto> implements IRepository<T> {\n /**\n * Constructs a new Repository instance.\n * @param _dataSource An instance of IWriteDataSource used to execute SQL queries and commands for data access.\n * @param _mapper An instance of IMapper used to convert between entities and DTOs.\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 constructor(\n protected readonly _dataSource: IWriteDataSource<TDto>,\n protected readonly _mapper: IMapper<T, TDto>,\n ) {}\n\n public async findById(\n id: string | number,\n ctx: UserContext,\n signal: Optional<AbortSignal>,\n ): Promise<ResultType<Optional<T>>> {\n AppError.throwIfAborted(signal, 'Repository.findById')\n\n const result = await this._dataSource.findById(id, ctx, signal)\n if (Guards.isNullOrEmpty(result)) return Result.ok()\n\n const entity = this._mapper.toEntity(result)\n return Result.ok(entity)\n }\n\n public async findAll(ctx: UserContext, signal: Optional<AbortSignal>): Promise<ResultType<T[]>> {\n AppError.throwIfAborted(signal, 'Repository.findAll')\n\n const results = await this._dataSource.findAll(ctx, signal)\n const entities = results.map((result) => this._mapper.toEntity(result))\n return Result.ok(entities)\n }\n\n public async save(entity: T, signal: Optional<AbortSignal>): Promise<ResultType<void>> {\n const dto = this._mapper.toDto(entity)\n\n AppError.throwIfAborted(signal, 'Repository.save')\n\n await this._dataSource.insert(dto, signal)\n return Result.ok()\n }\n\n public async delete(\n entity: T,\n ctx: UserContext,\n signal: Optional<AbortSignal>,\n ): Promise<ResultType<void>> {\n const dto = this._mapper.toDto(entity)\n\n AppError.throwIfAborted(signal, 'Repository.delete')\n\n await this._dataSource.delete(dto, ctx, signal)\n return Result.ok()\n }\n\n public async update(\n id: string | number,\n entity: Partial<T>,\n ctx: UserContext,\n signal: Optional<AbortSignal>,\n ): Promise<ResultType<void>> {\n const dto = this._mapper.toPartialDto(entity)\n\n AppError.throwIfAborted(signal, 'Repository.update')\n\n await this._dataSource.update(id, dto, ctx, signal)\n return Result.ok()\n }\n}\n","import type { NativeRouteDefinition, XenoRegistry } from '@xeno-js/shared'\n\n/**\n * @description Add CORS headers to a route definition.\n * Remember to add CORS middleware to your application during bootstrap.\n *\n * @param route The route to add CORS headers to.\n * @param allowOrigins Array of allowed origins (eg. ['https://example.com'] or ['*']).\n * @param withCredentials Whether to allow credentials. Default: true.\n * @returns The route definition with CORS headers added.\n */\nexport function withCors<TRegistry extends XenoRegistry = XenoRegistry>(\n route: NativeRouteDefinition<TRegistry>,\n allowOrigins: string[],\n withCredentials = true,\n): NativeRouteDefinition<TRegistry> {\n return {\n ...route,\n security: {\n ...route.security,\n allowOrigins,\n withCredentials,\n },\n }\n}\n\n/**\n * @description Disable CSRF protection for a route definition.\n * Use this if you need to allow cross-origin requests without CSRF protection. (eg. for Server to Server or a Webhook)\n *\n * @param route The route to disable CSRF protection for.\n * @returns The route definition with CSRF protection disabled.\n */\nexport function withoutCsrf<TRegistry extends XenoRegistry = XenoRegistry>(\n route: NativeRouteDefinition<TRegistry>,\n): NativeRouteDefinition<TRegistry> {\n return {\n ...route,\n security: {\n ...route.security,\n withCsrf: false,\n },\n }\n}\n\n/**\n * @description Allow CSRF protection for a route definition.\n * Remember to add CSRF middleware to your application during bootstrap.\n *\n * (Methods POST/PUT/PATCH/DELETE have a default CSRF protection if you added it during bootstrap, use this function if you want to force it for another method).\n *\n * @param route The route to disable CSRF protection for.\n * @returns The route definition with CSRF protection disabled.\n */\nexport function withCsrf<TRegistry extends XenoRegistry = XenoRegistry>(\n route: NativeRouteDefinition<TRegistry>,\n): NativeRouteDefinition<TRegistry> {\n return {\n ...route,\n security: {\n ...route.security,\n withCsrf: true,\n },\n }\n}\n","export {\n BaseAuthorizationStrategy,\n BaseHandler,\n Command,\n Query,\n SchemaValidationStrategy,\n Specification,\n ValidationPipeline,\n} from './application'\nexport {\n AuthModule,\n CacheModule,\n ContextModule,\n DbModule,\n HttpServerModule,\n LoggerModule,\n ReadDao,\n Repository,\n XenoAppBuilder,\n} from './infrastructure'\nexport * from './infrastructure/http/native-route.helper'\nexport * from './infrastructure/plugin'\nexport { BaseController } from './presentation'\nexport * from '@xeno-js/shared'\n"],"mappings":";;;;;;;;;;;;;;;;AAAA,IAYa;AAZb;AAAA;AAAA;AAYO,IAAM,2BAAN,MAA8D;AAAA,MACnE,MAAa,kBACX,OACA,kBACc;AACd,cAAM,EAAE,SAAS,OAAO,IAAI,MAAM,OAAO,SAAS;AAElD,cAAM,QAAQ,OAAO,gBAAgB;AAErC,cAAM,WAAW,MAAM,IAAI,CAAC,SAAS,MAAM,IAAI,CAAC;AAEhD,eAAO,QAAQ,IAAI,QAAQ;AAAA,MAC7B;AAAA,IACF;AAAA;AAA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AAK,YAAY,OAAO,IAAI,KAAK,KAAK,MAAM;AAClD,WAAOC,SAAO,GAAG;AAAA,EACnB;AACF;;;AC/EO,SAAS,SACd,OACA,cACA,kBAAkB,MACgB;AAClC,SAAO;AAAA,IACL,GAAG;AAAA,IACH,UAAU;AAAA,MACR,GAAG,MAAM;AAAA,MACT;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;AASO,SAAS,YACd,OACkC;AAClC,SAAO;AAAA,IACL,GAAG;AAAA,IACH,UAAU;AAAA,MACR,GAAG,MAAM;AAAA,MACT,UAAU;AAAA,IACZ;AAAA,EACF;AACF;AAWO,SAAS,SACd,OACkC;AAClC,SAAO;AAAA,IACL,GAAG;AAAA,IACH,UAAU;AAAA,MACR,GAAG,MAAM;AAAA,MACT,UAAU;AAAA,IACZ;AAAA,EACF;AACF;;;ACzCA,cAAc;","names":["Guards","AppError","Result","AppError","ERROR_CODES","Result","STATUS_CODES","AppError","Result","ERROR_CODE_MESSAGES","ERROR_CODES","STATUS_CODES","AppError","Result","Guards","Guards","AppError","Result","Guards","AppError","Result","Guards","Guards","Result","AppError","AppError","Result","Guards","Guards","Result","AppError","AppError","Result","Guards","Guards","Result","AppError","AppError","Result","Guards","GuidHelper","Guards","GuidHelper","Result","AppError","Result","AppError","Result","Result","Guards","Result","REQUEST_TYPE","Result","Guards","Result","GUEST","Guards","GuidHelper","Guards","LOG_LEVEL","TOKENS","Guards","Guards","Guards","Guards","TOKENS","Guards","Guards","Guards","HttpHelper","Guards","Guards","HttpHelper","Guards","HttpHelper","Guards","GuidHelper","HttpHelper","Guards","Guards","TOKENS","Guards","TOKENS","Guards","StringHelper","Guards","Guards","Guards","TOKENS","Guards","TOKENS","TOKENS","TOKENS","Guards","LOG_LEVEL","TOKENS","Guards","LOG_LEVEL","LoggerUtils","Guards","TOKENS","LOG_LEVEL","TOKENS","Guards","Guards","TOKENS","AppError","Guards","Result","Guards","Guards","HttpHelper","Guards","TOKENS","Guards","NodeRequestContextFactory","Guards","LOG_LEVEL","TOKENS","Guards","IDEMPOTENCY_CONSTANTS","Guards","TOKENS","LoggerUtils","LOG_LEVEL","Guards","Guards","TOKENS","AppError","Guards","TOKENS","Guards","TOKENS","RoutePatternHelper","Guards","HttpHelper","RoutePatternHelper","STATUS_CODES","RoutePatternHelper","TOKENS","Guards","Guards","LOG_LEVEL","Guards","LoggerUtils","Guards","LOG_LEVEL","TOKENS","GuidHelper","HttpHelper","ERROR_CODE_MESSAGES","ERROR_CODES","GuidHelper","HttpHelper","STATUS_CODES","ERROR_CODE_MESSAGES","ERROR_CODES","Guards","GuidHelper","HttpHelper","STATUS_CODES","GuidHelper","HttpHelper","STATUS_CODES","Guards","TOKENS","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","ERROR_CODE_MESSAGES","ERROR_CODES","GUEST","GuidHelper","HttpHelper","STATUS_CODES","Guards","GuidHelper","GUEST","HttpHelper","ERROR_CODES","ERROR_CODE_MESSAGES","STATUS_CODES","Guards","TOKENS","LoggerUtils","LOG_LEVEL","Guards","GUEST","GuidHelper","TOKENS","TOKENS","GUEST","GuidHelper","Guards","Guards","Guards","Guards","Guards","Guards","TOKENS","AppError","Result","AppError","Guards","AppError","TOKENS","Guards","Guards","Guards","Guards","Guards","Guards","Guards","LOG_LEVEL","Guards","LOG_LEVEL","Guards","TOKENS","Guards","TOKENS","Guards","Guards","Guards","Guards","AppError","Guards","GUEST","GuidHelper","TOKENS","TOKENS","Guards","LOG_LEVEL","PLimitConcurrencyService","AppError","Result","Guards","AppError","Result","Guards"]}
|