@rineex/ddd 3.0.0 → 3.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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/application/errors/application.error.ts","../src/utils/deep-freeze.util.ts","../src/domain/entities/entity.ts","../src/domain/aggregates/aggregate-root.ts","../src/domain/base/primitive-vo.ts","../src/domain/base/vo.ts","../src/shared/domain/domain.error.ts","../src/shared/domain/errors/internal.error.ts","../src/shared/domain/errors/invalid-state.error.ts","../src/shared/domain/errors/invalid-value.error.ts","../src/shared/domain/errors/timeout.error.ts","../src/shared/domain/result.ts","../src/domain/errors/entity-validation.error.ts","../src/domain/errors/invalid-vo.error.ts","../src/domain/events/domain.event.ts","../src/domain/value-objects/id.vo.ts","../src/domain/value-objects/aggregate-id.vo.ts","../src/domain/value-objects/domain-id.vo.ts","../src/domain/value-objects/email.vo.ts","../src/gateway/constants/http-code.ts"],"sourcesContent":["interface ErrorParams {\n message: string;\n code: string;\n metadata?: Record<string, unknown>;\n isOperational?: boolean;\n cause?: Error;\n}\n\n/**\n * Abstract base class for application-level errors with structured error handling.\n *\n * Extends the native Error class to provide machine-readable error codes, HTTP status codes,\n * operational error classification, and optional metadata for better error tracking and client communication.\n *\n * @abstract\n * @extends {Error}\n *\n * @example\n * ```typescript\n * class UserNotFoundError extends ApplicationError {\n * constructor(userId: string) {\n * super({\n * code: HttpStatusMessage['404'],\n * isOperational: true,\n * message: `User with id ${userId} not found`,\n * metadata: { userId }\n * });\n * }\n * }\n * ```\n */\nexport abstract class ApplicationError extends Error {\n /** Optional cause (linked error) */\n public readonly cause?: Error | undefined;\n /** Machine-readable error code (e.g. `OTP_LOCKED`, `USER_NOT_FOUND`) */\n public readonly code: string;\n /** Operational vs programmer error flag */\n public readonly isOperational: boolean;\n /** Optional structured metadata for debugging or clients */\n public readonly metadata?: Record<string, unknown> | undefined;\n\n constructor({\n isOperational = false,\n metadata,\n message,\n cause,\n code,\n }: ErrorParams) {\n super(message);\n\n this.name = new.target.name;\n this.code = code;\n this.isOperational = isOperational;\n this.metadata = metadata;\n this.cause = cause;\n\n Error.captureStackTrace(this, new.target);\n }\n}\n","/**\n * Deeply freezes an object graph to enforce runtime immutability.\n * - Handles arrays\n * - Handles circular references\n * - Skips functions\n * - Skips already frozen objects\n *\n * Intended for aggregate and value object state only.\n */\nexport function deepFreeze<T>(\n value: T,\n seen = new WeakSet<object>(),\n): Readonly<T> {\n // Primitives, null, undefined\n if (value === null || typeof value !== 'object') {\n return value;\n }\n\n // Functions should never be frozen\n if (typeof value === 'function') {\n return value;\n }\n\n // Avoid re-processing\n if (Object.isFrozen(value)) {\n return value as Readonly<T>;\n }\n\n // Handle circular references\n if (seen.has(value)) {\n return value as Readonly<T>;\n }\n\n seen.add(value);\n\n if (Array.isArray(value)) {\n for (const item of value) {\n deepFreeze(item, seen);\n }\n } else {\n for (const key of Object.keys(value)) {\n deepFreeze((value as Record<string, unknown>)[key], seen);\n }\n }\n\n return Object.freeze(value) as Readonly<T>;\n}\n","import { deepFreeze } from '@/utils';\n\nimport { EntityId } from '../types';\n\n// export type Immutable<T> = {\n// readonly [K in keyof T]: Immutable<T[K]>;\n// };\n\nexport type Immutable<T> = T extends (...args: any[]) => any\n ? T\n : T extends Date\n ? T\n : T extends Map<infer K, infer V>\n ? ReadonlyMap<Immutable<K>, Immutable<V>>\n : T extends Set<infer U>\n ? ReadonlySet<Immutable<U>>\n : T extends object\n ? { readonly [K in keyof T]: Immutable<T[K]> }\n : T;\n\n/**\n * Configuration for the base Entity constructor.\n * Forces a single-object argument pattern to avoid positional argument errors.\n * @template ID - A type satisfying the EntityId interface.\n */\nexport interface EntityProps<ID extends EntityId, Props> {\n /** The unique identity of the entity */\n readonly id: ID;\n /** Optional creation timestamp; defaults to 'now' if not provided */\n readonly createdAt?: Date;\n\n props: Props;\n}\n\n/**\n * Abstract Base Entity for Domain-Driven Design (DDD).\n * This class provides the standard contract for entity equality and identity.\n * It intentionally avoids \"magic\" property bags to ensure V8 engine optimization\n * and better IDE intellisense.\n * @template ID - The specific Identity Value Object type.\n */\nexport abstract class Entity<ID extends EntityId, Props> {\n /** The timestamp when this entity was first instantiated/created */\n public readonly createdAt: Date;\n /** The immutable unique identifier for this entity */\n public readonly id: ID;\n\n /**\n * Read-only view of entity state.\n * External code can never mutate internal state.\n */\n protected get props(): Immutable<Props> {\n return this.#props as Immutable<Props>;\n }\n\n // protected props: Props;\n #props: Props;\n\n /**\n * Protected constructor to be called by subclasses.\n * @param params - Initial identity and metadata.\n */\n protected constructor(params: EntityProps<ID, Props>) {\n this.id = params.id;\n this.createdAt = params.createdAt ?? new Date();\n this.#props = deepFreeze(params.props);\n\n this.validate();\n }\n\n /**\n * Compares entities by identity.\n * In DDD, two entities are considered equal if their IDs match,\n * regardless of their other properties.\n * @param other - The entity to compare against.\n * @returns True if IDs are equal.\n */\n public equals(other?: Entity<ID, Props>): boolean {\n if (other == null) return false;\n if (this === other) return true;\n return this.id.equals(other.id);\n }\n\n /**\n * Converts the Entity into a plain Javascript object.\n * Subclasses must implement this to explicitly control serialization,\n * @returns A plain object representation of the entity.\n */\n public abstract toObject(): Record<string, unknown>;\n\n /**\n * Validates the current state of the entity against domain invariants.\n * This method should be called after construction and any mutation.\n * @throws {Error} Should throw a specific DomainError if validation fails.\n */\n public abstract validate(): void;\n\n protected mutate(updater: (current: Props) => Props): void {\n const next = updater(this.#props);\n\n this.#props = deepFreeze(next);\n this.validate();\n }\n}\n","import { Entity } from '../entities/entity';\nimport { DomainEvent } from '../events';\nimport { EntityId } from '../types';\n\n/**\n * Base class for aggregate roots in DDD, encapsulating domain events and validation.\n *\n * Aggregate roots are entities that serve as entry points to aggregates. They:\n * - Enforce invariants across the aggregate\n * - Manage domain events\n * - Define transaction boundaries\n *\n * @template ID - The type of the aggregate's identity (must extend EntityId)\n * @template P - The type of the aggregate's properties\n *\n * @example\n * ```typescript\n * interface UserProps {\n * email: string;\n * isActive: boolean;\n * }\n *\n * class User extends AggregateRoot<AggregateId, UserProps> {\n * // Implementation...\n * }\n * ```\n */\nexport abstract class AggregateRoot<ID extends EntityId, P> extends Entity<\n ID,\n P\n> {\n /**\n * Gets a read-only copy of the domain events.\n */\n get domainEvents(): readonly DomainEvent[] {\n return [...this._domainEvents];\n }\n\n /**\n * Internal list of domain events.\n */\n private readonly _domainEvents: DomainEvent[] = [];\n\n /**\n * Adds a domain event to the aggregate after validating invariants.\n * @param domainEvent The domain event to add.\n * @throws {EntityValidationError} If invariants are not met.\n */\n addEvent(domainEvent: DomainEvent): void {\n this._domainEvents.push(domainEvent);\n }\n\n public pullDomainEvents(): readonly DomainEvent[] {\n const events = [...this._domainEvents];\n this._domainEvents.length = 0;\n return events;\n }\n}\n","import { Primitive } from 'type-fest';\n\nimport { EntityId } from '../types';\n\n/**\n * Base class for primitive-based Value Objects.\n *\n * This class is intended for Value Objects that are represented by\n * a single primitive value (string, number, or boolean).\n *\n * Characteristics:\n * - Immutable by construction\n * - Cheap equality comparison\n * - No deep cloning or freezing\n * - Safe for serialization and logging\n *\n * Examples:\n * - AggregateId\n * - EmailAddress\n * - Username\n * - Slug\n */\nexport abstract class PrimitiveValueObject<\n T extends Primitive,\n> implements EntityId {\n /**\n * The underlying primitive value.\n * Guaranteed to be valid after construction.\n */\n get value(): T {\n return this.#value;\n }\n\n readonly #value: Readonly<T>;\n\n /**\n * Constructs a new PrimitiveValueObject.\n *\n * @param value - The primitive value to wrap\n * @throws Error if validation fails\n */\n protected constructor(value: T) {\n this.validate(value);\n this.#value = value;\n }\n\n /**\n * Compares two Value Objects for equality.\n *\n * Equality rules:\n * - Same concrete class\n * - Same primitive value (===)\n *\n * @param other - Another Value Object\n */\n public equals(other: any): boolean {\n if (other == null) return false;\n\n if (Object.getPrototypeOf(this) !== Object.getPrototypeOf(other)) {\n return false;\n }\n\n if (!(other instanceof PrimitiveValueObject)) return false;\n\n return this.#value === other.#value;\n }\n\n /**\n * Returns the primitive value.\n * Prefer explicit access over implicit coercion.\n * @deprecated - instead use instance.value\n */\n public getValue(): T {\n return this.#value;\n }\n\n /**\n * String representation.\n * Useful for logging and debugging.\n */\n public toString(): string {\n return String(this.#value);\n }\n\n /**\n * Domain invariant validation.\n * Must throw if the value is invalid.\n *\n * @param value - The value to validate\n */\n protected abstract validate(value: T): void;\n}\n","import deepEqual from 'fast-deep-equal/es6';\n\nimport { deepFreeze } from '@/utils/deep-freeze.util';\n\nexport abstract class ValueObject<T> {\n get value(): T {\n return this.props;\n }\n\n protected readonly props: Readonly<T>;\n\n protected constructor(props: T) {\n this.validate(props);\n this.props = deepFreeze(props);\n }\n\n /**\n * Type guard to check if an unknown object is an instance of ValueObject.\n * This is useful for runtime type checking.\n *\n * @param vo The object to check.\n * @returns True if the object is a ValueObject instance, false otherwise.\n */\n public static is(vo: unknown): vo is ValueObject<unknown> {\n return vo instanceof ValueObject;\n }\n\n /**\n * Deep equality comparison of ValueObjects\n */\n public equals(other?: ValueObject<T>): boolean {\n if (other == null) return false;\n\n // Check if they share the same constructor (Type check)\n if (Object.getPrototypeOf(this) !== Object.getPrototypeOf(other)) {\n return false;\n }\n\n return deepEqual(this.props, other.props);\n }\n\n /**\n * Standard for clean API integration and logging.\n */\n public toJSON(): T {\n return this.props;\n }\n\n /**\n * Useful for debugging and string-based indexing.\n */\n public toString(): string {\n return JSON.stringify(this.props);\n }\n\n /**\n * Validates the value object props\n * @throws InvalidValueObjectError if validation fails\n */\n protected abstract validate(props: T): void;\n}\n","import { EmptyObject } from 'type-fest';\n\nexport type Primitive = boolean | number | string | null | undefined;\n\nexport type Metadata<T = EmptyObject> =\n T extends Record<string, Primitive> ? T : EmptyObject;\n\n/**\n * Categories of domain errors based on the nature of the violation.\n *\n * @typedef {'DOMAIN.INVALID_STATE' | 'DOMAIN.INVALID_VALUE'} DomainErrorType\n *\n * @example\n * // DomainErrorType usage:\n * const errorType: DomainErrorType = 'DOMAIN.INVALID_STATE';\n */\nexport type DomainErrorType = 'DOMAIN.INVALID_STATE' | 'DOMAIN.INVALID_VALUE';\n\n// ============ TYPE UTILITIES ============\nexport type ValueOf<T> = T[keyof T];\nexport type UnionToIntersection<U> = (\n U extends any ? (k: U) => void : never\n) extends (k: infer I) => void\n ? I\n : never;\n\n/**\n * Interface for declaring domain error namespaces via declaration merging.\n * Projects extend this interface to add their own namespaces and error codes.\n *\n * @example\n * // In your project's type definition file (.d.ts):\n * declare module '@your-org/domain-errors' {\n * interface DomainErrorNamespaces {\n * USER: ['NOT_FOUND', 'INVALID_EMAIL', 'SUSPENDED'];\n * ORDER: ['NOT_FOUND', 'INVALID_STATUS', 'OUT_OF_STOCK'];\n * // Override default namespace (optional):\n * CORE: ['INTERNAL_ERROR', 'VALIDATION_FAILED', 'CONFIGURATION_ERROR'];\n * }\n * }\n *\n * @example\n * // This enables type-safe error codes:\n * const code: DomainErrorCode = 'USER.NOT_FOUND'; // ✅ Valid\n * const code: DomainErrorCode = 'USER.INVALID'; // ❌ TypeScript error\n */\nexport interface DomainErrorNamespaces {\n // Built-in core namespaces (available in all projects)\n DOMAIN: ['INVALID_VALUE', 'INVALID_STATE'];\n CORE: [\n 'INTERNAL_ERROR',\n 'VALIDATION_FAILED',\n 'CONFIGURATION_ERROR',\n 'NOT_IMPLEMENTED',\n ];\n SYSTEM: ['UNEXPECTED', 'TIMEOUT', 'NETWORK_ERROR', 'DEPENDENCY_ERROR'];\n}\n\n// ============ INFER TYPES FROM REGISTRY ============\ntype Namespace = keyof DomainErrorNamespaces;\ntype ErrorName<N extends Namespace> = DomainErrorNamespaces[N][number];\n\n/**\n * Union type of all valid domain error codes derived from registered namespaces.\n * Automatically updates when projects extend DomainErrorNamespaces.\n *\n * @example\n * // After extending DomainErrorNamespaces with USER namespace:\n * type ErrorCode = DomainErrorCode;\n * // Becomes: 'CORE.INTERNAL_ERROR' | 'CORE.VALIDATION_FAILED' |\n * // 'USER.NOT_FOUND' | 'USER.INVALID_EMAIL' | ...\n */\nexport type DomainErrorCode = {\n [N in Namespace]: `${Uppercase<string & N>}.${Uppercase<ErrorName<N>>}`;\n}[Namespace];\n\n// Extract namespace from code\nexport type ExtractNamespace<Code extends DomainErrorCode> =\n Code extends `${infer N}.${string}` ? N : never;\n\n// Extract error name from code\nexport type ExtractErrorName<Code extends DomainErrorCode> =\n Code extends `${string}.${infer E}` ? E : never;\n\n/**\n * Base class for all domain errors in a Domain-Driven Design architecture.\n *\n * Domain errors represent violations of business rules and domain invariants.\n * They are pure value objects without infrastructure concerns like IDs or timestamps.\n *\n * @typeParam Code - The specific error code from DomainErrorCode union\n * @typeParam Meta - Type of metadata associated with this error\n *\n * @example\n * // 1. First, declare your namespaces:\n * declare module '@your-org/domain-errors' {\n * interface DomainErrorNamespaces {\n * USER: ['NOT_FOUND', 'INVALID_EMAIL'];\n * }\n * }\n *\n * @example\n * // 2. Create a concrete domain error:\n * class UserNotFoundError extends DomainError<'USER.NOT_FOUND', { userId: string }> {\n * public readonly code = 'USER.NOT_FOUND' as const;\n * public readonly type: DomainErrorType = 'DOMAIN.INVALID_VALUE';\n *\n * constructor(userId: string) {\n * super(`User with ID '${userId}' not found`, { userId });\n * }\n * }\n *\n * @example\n * // 3. Usage in domain services:\n * class UserService {\n * async activateUser(userId: string): Promise<Result<User, DomainError>> {\n * const user = await this.repository.findById(userId);\n *\n * if (!user) {\n * return Result.failure(new UserNotFoundError(userId));\n * }\n *\n * if (user.isSuspended) {\n * return Result.failure(new UserSuspendedError(userId));\n * }\n *\n * // Business logic...\n * }\n * }\n *\n * @abstract\n */\nexport abstract class DomainError<\n Meta extends Record<string, Primitive> = EmptyObject,\n Code extends DomainErrorCode = DomainErrorCode,\n> {\n /**\n * Machine-readable error code in format: NAMESPACE.ERROR_NAME\n *\n * @remarks\n * - Must be uppercase (e.g., 'USER.NOT_FOUND')\n * - Namespace must be declared in DomainErrorNamespaces\n * - Error name must be in the namespace's array\n *\n * @example\n * public readonly code = 'USER.NOT_FOUND' as const;\n */\n public abstract readonly code: Code;\n /**\n * Human-readable error message describing the domain rule violation.\n * Should be meaningful to developers and potentially end-users.\n *\n * @remarks\n * - Avoid technical implementation details\n * - Focus on the business rule that was violated\n * - Can include values from metadata for context\n *\n * @example\n * // Good: \"Order amount $150 exceeds maximum limit of $100\"\n * // Bad: \"Amount validation failed: 150 > 100\"\n */\n public readonly message: string;\n\n /**\n * Immutable structured context providing additional information about the error.\n * Useful for debugging, logging, and creating detailed error messages.\n *\n * @remarks\n * - Values must be primitive types (string, number, boolean, etc.)\n * - Object is frozen to prevent mutation\n * - Type-safe based on the error code\n *\n * @example\n * // For UserNotFoundError:\n * { userId: 'usr_123', attemptedAction: 'activate' }\n *\n * @readonly\n */\n public readonly metadata: Readonly<Meta>;\n\n /**\n * Category of domain error indicating the nature of violation.\n *\n * @remarks\n * Use 'DOMAIN.INVALID_STATE' for state violations (e.g., \"Cannot checkout empty cart\")\n * Use 'DOMAIN.INVALID_VALUE' for value violations (e.g., \"Email format is invalid\")\n *\n * @example\n * public readonly type: DomainErrorType = 'DOMAIN.INVALID_VALUE';\n */\n public abstract readonly type: DomainErrorType;\n\n /** Get error name from error code */\n public get errorName(): ExtractErrorName<Code> {\n return this.code.split('.')[1] as ExtractErrorName<Code>;\n }\n\n // ============ COMPUTED PROPERTIES ============\n /** Get namespace from error code */\n public get namespace(): ExtractNamespace<Code> {\n return this.code.split('.')[0] as ExtractNamespace<Code>;\n }\n\n /**\n * Creates a new DomainError instance.\n *\n * @param message - Human-readable description of the domain rule violation\n * @param metadata - Optional structured context (primitive values only)\n *\n * @example\n * constructor(userId: string) {\n * super(`User with ID '${userId}' not found`, { userId });\n * }\n *\n * @example\n * constructor(amount: number, maxLimit: number) {\n * super(\n * `Order amount $${amount} exceeds maximum limit of $${maxLimit}`,\n * { amount, maxLimit }\n * );\n * }\n */\n protected constructor(\n message: string,\n ...args: keyof Meta extends never\n ? [] | [metadata?: Meta]\n : [metadata: Meta]\n ) {\n this.message = message;\n this.metadata = Object.freeze(args[0] ?? {}) as Readonly<Meta>;\n }\n\n /**\n * Serializes the error to a plain object for debugging, logging, or transport.\n * Does not include infrastructure concerns like stack traces or timestamps.\n *\n * @returns Plain object with error details\n *\n * @example\n * const error = new UserNotFoundError('usr_123');\n * const json = error.toJSON();\n * // Result:\n * // {\n * // code: 'USER.NOT_FOUND',\n * // message: \"User with ID 'usr_123' not found\",\n * // type: 'DOMAIN.INVALID_VALUE',\n * // metadata: { userId: 'usr_123' }\n * // }\n */\n public toObject() {\n return {\n metadata: this.metadata,\n message: this.message,\n code: this.code,\n type: this.type,\n };\n }\n\n /**\n * Returns a string representation of the error.\n * Format: [CODE] MESSAGE\n *\n * @returns Human-readable string representation\n *\n * @example\n * const error = new UserNotFoundError('usr_123');\n * console.log(error.toString());\n * // Output: [USER.NOT_FOUND] User with ID 'usr_123' not found\n *\n * @override\n */\n public toString(): string {\n return `[${this.code}] ${this.message}`;\n }\n}\n","import {\n DomainError,\n DomainErrorType,\n Metadata,\n Primitive,\n} from '../domain.error';\n\n/**\n * Default domain errors for common scenarios.\n * These errors are available across all projects using this module.\n */\n\n/**\n * Error thrown when an unexpected internal error occurs.\n * Typically used for programming bugs, invalid assumptions, or states that should never happen.\n *\n * @remarks\n * - Metadata is optional for empty metadata types and required if a non-empty type is provided.\n * - Useful for debugging, logging, and adding context to unexpected failures.\n *\n * @template T - Type of metadata object (must extend Record<string, Primitive>)\n *\n * @example\n * // Catch a programming error:\n * try {\n * complexBusinessLogic();\n * } catch (error) {\n * throw new InternalError(\n * 'Unexpected error in complexBusinessLogic',\n * { originalError: error.message, timestamp: Date.now() }\n * );\n * }\n *\n * @example\n * // Fallback for unhandled cases:\n * switch (status) {\n * case 'PENDING':\n * break;\n * case 'COMPLETED':\n * break;\n * default:\n * throw new InternalError(\n * `Unhandled status: ${status}`,\n * { status }\n * );\n * }\n *\n * @example\n * // With custom metadata type:\n * type ErrorMetadata = { userId: string; action: string };\n * throw new InternalError<ErrorMetadata>(\n * 'Failed to process user action',\n * { userId: 'usr_123', action: 'activate' }\n * );\n */\nexport class InternalError<\n T extends Record<string, Primitive> = Record<string, Primitive>,\n> extends DomainError<Metadata<T>> {\n /** @inheritdoc */\n public readonly code = 'CORE.INTERNAL_ERROR' as const;\n\n /** @inheritdoc */\n public readonly type: DomainErrorType = 'DOMAIN.INVALID_STATE';\n\n /**\n * Creates a new InternalError.\n *\n * @param message - Description of the internal error (defaults to 'An unexpected internal error occurred')\n * @param metadata - Optional debug information (primitive values only)\n *\n * @example\n * // Basic usage:\n * throw new InternalError('Something went wrong');\n *\n * @example\n * // With metadata:\n * throw new InternalError(\n * 'Database connection failed',\n * { host: 'localhost', port: 5432, retries: 3 }\n * );\n */\n constructor(\n message: string = 'An unexpected internal error occurred',\n metadata?: Metadata<T>,\n ) {\n super(message, metadata);\n }\n}\n","import {\n DomainError,\n DomainErrorCode,\n DomainErrorType,\n Primitive,\n} from '../domain.error';\n\n/**\n * Error thrown when an entity or aggregate is in an invalid state for the requested operation.\n * Use for state violations (e.g., \"Cannot checkout empty cart\", \"Cannot cancel completed order\").\n *\n * @example\n * // Prevent invalid state transitions:\n * if (order.status === 'COMPLETED') {\n * throw new InvalidStateError('Cannot cancel a completed order');\n * }\n *\n * @example\n * // With context:\n * if (!cart.hasItems()) {\n * throw new InvalidStateError('Cannot checkout empty cart');\n * }\n */\nexport class InvalidStateError extends DomainError<Record<string, Primitive>> {\n public code: DomainErrorCode = 'DOMAIN.INVALID_STATE';\n public type: DomainErrorType = 'DOMAIN.INVALID_STATE';\n\n constructor(message = 'invalid state') {\n super(message, {});\n }\n}\n","import {\n DomainError,\n DomainErrorCode,\n DomainErrorType,\n Metadata,\n Primitive,\n} from '../domain.error';\n\n/**\n * Error thrown when a value violates domain rules or constraints.\n * Use for value violations (e.g., \"Email format is invalid\", \"Age cannot be negative\").\n *\n * @template T - Type of metadata object (must extend Record<string, Primitive>)\n *\n * @example\n * // Basic usage:\n * if (age < 0) {\n * throw new InvalidValueError('Age cannot be negative');\n * }\n *\n * @example\n * // With metadata:\n * if (!isValidEmail(email)) {\n * throw new InvalidValueError(\n * 'Invalid email format',\n * { email, pattern: '^[^@]+@[^@]+\\\\.[^@]+$' }\n * );\n * }\n *\n * @example\n * // With custom metadata type:\n * type ValidationMetadata = { field: string; value: unknown; reason: string };\n * throw new InvalidValueError<ValidationMetadata>(\n * 'Validation failed',\n * { field: 'email', value: email, reason: 'Invalid format' }\n * );\n */\nexport class InvalidValueError<\n T extends Record<string, Primitive> = Record<string, Primitive>,\n> extends DomainError<Metadata<T>> {\n public code: DomainErrorCode = 'DOMAIN.INVALID_VALUE';\n public type: DomainErrorType = 'DOMAIN.INVALID_VALUE';\n\n constructor(msg = 'invalid value', meta?: Metadata<T>) {\n super(msg, meta);\n }\n}\n","import {\n DomainError,\n DomainErrorType,\n Metadata,\n Primitive,\n} from '../domain.error';\n\n/**\n * Error thrown when an operation times out.\n * Use for operations that exceed their allowed execution time.\n *\n * @template T - Type of metadata object (must extend Record<string, Primitive>)\n *\n * @example\n * // Operation timeout:\n * const timeout = setTimeout(() => {\n * throw new TimeoutError(\n * 'User registration timed out'\n * );\n * }, 5000);\n *\n * @example\n * // With Promise.race:\n * type Props = { url: string; timeoutMs: number };\n * async function fetchWithTimeout(url: string, timeoutMs: number) {\n * const timeoutPromise = new Promise<never>((_, reject) => {\n * setTimeout(() => {\n * reject(new TimeoutError<Props>(\n * `Request to ${url} timed out`,\n * { url, timeoutMs }\n * ));\n * }, timeoutMs);\n * });\n *\n * return await Promise.race([fetch(url), timeoutPromise]);\n * }\n *\n * @example\n * // With custom metadata:\n * throw new TimeoutError(\n * 'Database query timed out',\n * { query: 'SELECT * FROM users', timeout: 5000, retries: 3 }\n * );\n */\nexport class TimeoutError<\n T extends Record<string, Primitive> = Record<string, Primitive>,\n> extends DomainError<Metadata<T>> {\n /** @inheritdoc */\n public readonly code = 'SYSTEM.TIMEOUT' as const;\n\n /** @inheritdoc */\n public readonly type: DomainErrorType = 'DOMAIN.INVALID_STATE';\n\n /**\n * Creates a new TimeoutError.\n *\n * @param message - Description of the timeout\n * @param metadata - Optional timeout context\n */\n // eslint-disable-next-line @typescript-eslint/no-useless-constructor\n constructor(message: string, metadata?: Metadata<T>) {\n super(message, metadata);\n }\n}\n","import { DomainError } from './domain.error';\n\n/**\n * Represents the result of an operation, which can be either a success or a failure.\n *\n * This is a functional programming pattern that helps avoid throwing exceptions\n * and makes error handling explicit in the type system. It's commonly used in\n * Domain-Driven Design (DDD) to represent domain operation outcomes.\n *\n * @template T The type of a successful result.\n * @template E The type of the error in case of failure (defaults to DomainError).\n *\n * @example\n * ```typescript\n * // Creating a successful result\n * const success = Result.ok({ id: 1, name: 'John' });\n * if (success.isSuccess) {\n * const user = success.getValue(); // { id: 1, name: 'John' }\n * }\n *\n * // Creating a failed result\n * const failure = Result.fail(new InvalidUserError('User not found'));\n * if (failure.isFailure) {\n * const error = failure.getError(); // InvalidUserError instance\n * }\n * ```\n *\n * @example\n * ```typescript\n * // Using in a domain service\n * function createUser(name: string): Result<User, DomainError> {\n * if (!name || name.trim().length === 0) {\n * return Result.fail(new InvalidValueError('Name cannot be empty'));\n * }\n *\n * const user = new User(name);\n * return Result.ok(user);\n * }\n *\n * const result = createUser('John Doe');\n * if (result.isSuccess) {\n * console.log('User created:', result.getValue());\n * } else {\n * console.error('Failed:', result.getError()?.message);\n * }\n * ```\n *\n * @example\n * ```typescript\n * // Chaining operations\n * function validateEmail(email: string): Result<string, DomainError> {\n * if (!email.includes('@')) {\n * return Result.fail(new InvalidValueError('Invalid email format'));\n * }\n * return Result.ok(email);\n * }\n *\n * function createAccount(email: string): Result<Account, DomainError> {\n * const emailResult = validateEmail(email);\n * if (emailResult.isFailure) {\n * return emailResult; // Forward the error\n * }\n *\n * const account = new Account(emailResult.getValue()!);\n * return Result.ok(account);\n * }\n * ```\n *\n * @example\n * ```typescript\n * // Working with async operations\n * async function fetchUser(id: number): Promise<Result<User, DomainError>> {\n * try {\n * const user = await userRepository.findById(id);\n * if (!user) {\n * return Result.fail(new NotFoundError(`User ${id} not found`));\n * }\n * return Result.ok(user);\n * } catch (error) {\n * return Result.fail(new SystemError('Database connection failed'));\n * }\n * }\n *\n * const result = await fetchUser(123);\n * if (result.isSuccess) {\n * // Handle success\n * } else {\n * // Handle failure\n * }\n * ```\n */\nexport class Result<T, E> {\n /**\n * Indicates if the result is a failure.\n *\n * @example\n * ```typescript\n * const result = Result.fail(new Error('Something went wrong'));\n * if (result.isFailure) {\n * // Handle error case\n * console.error(result.getError());\n * }\n * ```\n */\n public readonly isFailure: boolean;\n\n /**\n * Indicates if the result is a success.\n *\n * @example\n * ```typescript\n * const result = Result.ok(42);\n * if (result.isSuccess) {\n * // Handle success case\n * const value = result.getValue(); // 42\n * }\n * ```\n */\n public readonly isSuccess: boolean;\n\n /**\n * The error, if any.\n * @private\n */\n private readonly _error?: E;\n\n /**\n * The value, if any.\n * @private\n */\n private readonly _value?: T;\n\n /**\n * Private constructor to enforce the use of static methods.\n * @param params.value The value on success.\n * @param params.error The error on failure.\n * @private\n */\n private constructor(params: { value?: T; error?: E }) {\n const hasError = params.error !== undefined;\n this.isFailure = hasError;\n this.isSuccess = !hasError;\n\n this._value = params.value;\n this._error = params.error;\n Object.freeze(this);\n }\n\n /**\n * Creates a failed result.\n *\n * @template T The type of a successful result (never for failure).\n * @template E The type of the error (defaults to DomainError).\n * @param error The error object.\n * @returns {Result<T, E>} A failed Result instance.\n *\n * @example\n * ```typescript\n * // With DomainError\n * class InvalidValueError extends DomainError {\n * public readonly code = 'DOMAIN.INVALID_VALUE' as const;\n * constructor(message: string) {\n * super({ message });\n * }\n * }\n *\n * const result = Result.fail(new InvalidValueError('Value must be positive'));\n * // result.isFailure === true\n * // result.getError() === InvalidValueError instance\n * ```\n *\n * @example\n * ```typescript\n * // With custom error type\n * interface ValidationError {\n * field: string;\n * message: string;\n * }\n *\n * const result = Result.fail<never, ValidationError>({\n * field: 'email',\n * message: 'Invalid email format'\n * });\n * ```\n *\n * @example\n * ```typescript\n * // In a validation function\n * function validateAge(age: number): Result<number, DomainError> {\n * if (age < 0) {\n * return Result.fail(new InvalidValueError('Age cannot be negative'));\n * }\n * if (age > 150) {\n * return Result.fail(new InvalidValueError('Age seems unrealistic'));\n * }\n * return Result.ok(age);\n * }\n * ```\n */\n public static fail<T = never, E = DomainError>(error: E): Result<T, E> {\n return new Result({ error });\n }\n\n /**\n * Creates a successful result.\n *\n * @template T The type of the successful result.\n * @template E The type of the error (never for success).\n * @param value The success value.\n * @returns {Result<T, E>} A successful Result instance.\n *\n * @example\n * ```typescript\n * // With primitive value\n * const result = Result.ok(42);\n * // result.isSuccess === true\n * // result.getValue() === 42\n * ```\n *\n * @example\n * ```typescript\n * // With object\n * const user = { id: 1, name: 'John', email: 'john@example.com' };\n * const result = Result.ok(user);\n * if (result.isSuccess) {\n * const savedUser = result.getValue(); // { id: 1, name: 'John', ... }\n * }\n * ```\n *\n * @example\n * ```typescript\n * // With domain entity\n * class User {\n * constructor(public readonly id: number, public readonly name: string) {}\n * }\n *\n * function createUser(name: string): Result<User, DomainError> {\n * const user = new User(Date.now(), name);\n * return Result.ok(user);\n * }\n *\n * const result = createUser('Alice');\n * if (result.isSuccess) {\n * console.log(`Created user: ${result.getValue()?.name}`);\n * }\n * ```\n *\n * @example\n * ```typescript\n * // With void/undefined (for operations that don't return a value)\n * function deleteUser(id: number): Result<void, DomainError> {\n * // ... deletion logic ...\n * return Result.ok(undefined);\n * }\n *\n * const result = deleteUser(123);\n * if (result.isSuccess) {\n * console.log('User deleted successfully');\n * }\n * ```\n */\n public static ok<T, E = never>(value: T): Result<T, E> {\n return new Result({ value });\n }\n\n /**\n * Returns the error if present, otherwise undefined.\n *\n * **Note:** Always check `isFailure` before calling this method to ensure\n * the result is actually a failure. This method will return `undefined` for\n * successful results.\n *\n * @returns {E | undefined} The error or undefined if successful.\n *\n * @example\n * ```typescript\n * const result = Result.fail(new InvalidValueError('Invalid input'));\n *\n * if (result.isFailure) {\n * const error = result.getError();\n * if (error) {\n * console.error(`Error code: ${error.code}, Message: ${error.message}`);\n * }\n * }\n * ```\n *\n * @example\n * ```typescript\n * // Safe error handling pattern\n * function handleResult<T>(result: Result<T, DomainError>): void {\n * if (result.isFailure) {\n * const error = result.getError();\n * if (error) {\n * // Log error with metadata\n * console.error({\n * code: error.code,\n * message: error.message,\n * metadata: error.metadata\n * });\n * }\n * }\n * }\n * ```\n */\n public getError(): E | undefined {\n return this._error;\n }\n\n /**\n * Returns the value if present, otherwise undefined.\n *\n * **Note:** Always check `isSuccess` before calling this method to ensure\n * the result is actually a success. This method will return `undefined` for\n * failed results.\n *\n * @returns {T | undefined} The value or undefined if failed.\n *\n * @example\n * ```typescript\n * const result = Result.ok({ id: 1, name: 'John' });\n *\n * if (result.isSuccess) {\n * const user = result.getValue();\n * if (user) {\n * console.log(`User: ${user.name} (ID: ${user.id})`);\n * }\n * }\n * ```\n *\n * @example\n * ```typescript\n * // Type-safe value extraction\n * function processUser(result: Result<User, DomainError>): void {\n * if (result.isSuccess) {\n * const user = result.getValue();\n * // TypeScript knows user is User | undefined here\n * if (user) {\n * // Process the user\n * userRepository.save(user);\n * }\n * }\n * }\n * ```\n *\n * @example\n * ```typescript\n * // Using non-null assertion (use with caution)\n * const result = Result.ok(42);\n * if (result.isSuccess) {\n * const value = result.getValue()!; // Safe because we checked isSuccess\n * console.log(value * 2); // 84\n * }\n * ```\n */\n public getValue(): T | undefined {\n return this._value;\n }\n\n /**\n * Type guard for failure.\n */\n public isFailureResult(): this is Result<never, E> {\n return this.isFailure;\n }\n\n /**\n * Type guard for success.\n */\n public isSuccessResult(): this is Result<T, never> {\n return this.isSuccess;\n }\n}\n","import {\n DomainError,\n DomainErrorCode,\n DomainErrorType,\n Metadata,\n Primitive,\n} from '@/shared';\n\ninterface ExtraProps extends Record<string, Primitive> {\n entityId?: string;\n entityType?: string;\n}\n\ntype Props = Metadata<ExtraProps>;\n/**\n * Custom error class for entity validation failures.\n */\nexport class EntityValidationError extends DomainError<Props> {\n public code: DomainErrorCode = 'CORE.VALIDATION_FAILED';\n public type: DomainErrorType = 'DOMAIN.INVALID_STATE';\n\n public constructor(message: string, props: Props) {\n super(message, props);\n }\n\n public static create(msg: string, props: Props) {\n return new EntityValidationError(msg, props);\n }\n}\n","import {\n DomainError,\n DomainErrorCode,\n DomainErrorType,\n Metadata,\n} from '@/shared';\n\ntype Params = {\n value: string;\n};\n\ntype Props = Metadata<Params>;\nexport class InvalidValueObjectError extends DomainError<Props> {\n public code = 'DOMAIN.INVALID_VALUE' as DomainErrorCode;\n public type: DomainErrorType = 'DOMAIN.INVALID_VALUE';\n\n public static create(\n msg = 'Provided value object is incorrect',\n meta?: Props,\n ) {\n return new InvalidValueObjectError(msg, meta);\n }\n}\n","import { randomUUID } from 'node:crypto';\n\nimport { deepFreeze } from '@/utils';\n\nimport { EntityId } from '../types';\n\ntype Primitive = boolean | number | string | null;\n\ntype Serializable =\n | Primitive\n | Serializable[]\n | { [key: string]: Serializable };\n\nexport type DomainEventPayload = Record<string, Serializable>;\n\nexport type UnixTimestampMillis = number;\n\ntype DomainEventProps<Payload, AggregateId extends EntityId> = {\n id?: string;\n aggregateId: AggregateId;\n schemaVersion: number;\n occurredAt: UnixTimestampMillis;\n payload: Payload;\n};\n\nexport type CreateEventProps<\n EventProps,\n ID extends EntityId,\n> = DomainEventProps<EventProps, ID>;\n\n// Abstract base class for domain events\nexport abstract class DomainEvent<\n AggregateId extends EntityId = EntityId,\n T extends DomainEventPayload = DomainEventPayload,\n> {\n public readonly aggregateId: AggregateId;\n\n public abstract readonly eventName: string;\n public readonly id: string;\n public readonly occurredAt: number;\n public readonly payload: Readonly<T>;\n public readonly schemaVersion: number;\n\n protected constructor(props: DomainEventProps<T, AggregateId>) {\n this.id = props.id ?? randomUUID();\n this.aggregateId = props.aggregateId;\n this.schemaVersion = props.schemaVersion;\n this.occurredAt = props.occurredAt;\n this.payload = deepFreeze(props.payload);\n }\n\n public toPrimitives(): Readonly<{\n id: string;\n eventName: string;\n aggregateId: string;\n schemaVersion: number;\n occurredAt: UnixTimestampMillis;\n payload: T;\n }> {\n return {\n aggregateId: this.aggregateId.toString(),\n schemaVersion: this.schemaVersion,\n occurredAt: this.occurredAt,\n eventName: this.eventName,\n payload: this.payload,\n id: this.id,\n };\n }\n}\n","import { v4 } from 'uuid';\nimport z from 'zod';\n\nimport { InvalidValueObjectError } from '../errors/invalid-vo.error';\nimport { PrimitiveValueObject } from '../base/primitive-vo';\n\n/**\n * Represents a UUID (Universally Unique Identifier) value object.\n *\n * This class extends PrimitiveValueObject to provide type-safe UUID handling\n * with validation using Zod schema. UUIDs are immutable and can be generated\n * randomly or created from string values.\n * @deprecated\n * @example\n * // Generate a new random UUID\n * const id = UUID.generate();\n *\n * @example\n * // Create UUID from an existing string\n * const id = UUID.fromString('550e8400-e29b-41d4-a716-446655440000');\n *\n * @throws {InvalidValueObjectError} When the provided string is not a valid UUID format\n */\nexport class UUID extends PrimitiveValueObject<string> {\n private static readonly schema = z.uuid();\n\n public constructor(value: string) {\n super(value);\n this.validate(value);\n }\n\n /**\n * Creates an UUID from an external string.\n * Use only for untrusted input.\n *\n * @param value - UUID string\n */\n public static fromString(value: string): UUID {\n return new this(value);\n }\n\n /**\n * Generates a new AggregateId.\n */\n public static generate<T extends typeof UUID>(this: T): InstanceType<T> {\n return new this(v4()) as InstanceType<T>;\n }\n\n protected validate(value: string): void {\n const result = UUID.schema.safeParse(value);\n\n if (!result.success) {\n throw InvalidValueObjectError.create(\n `Invalid ${this.constructor.name}: ${value}`,\n {\n value,\n },\n );\n }\n }\n}\n","import { UUID } from './id.vo';\n\n/**\n * AggregateId represents a strongly-typed aggregate identifier.\n *\n * - Backed by UUID v4\n * - Immutable\n * - Comparable only to AggregateId\n */\nexport class AggregateId extends UUID {}\n","import type { Tagged } from 'type-fest';\nimport { v4 } from 'uuid';\nimport z from 'zod';\n\nimport { InvalidValueObjectError } from '../errors/invalid-vo.error';\nimport { PrimitiveValueObject } from '../base/primitive-vo';\n\n/**\n * UUID is a branded string type.\n *\n * - Prevents accidental use of arbitrary strings\n * - Requires explicit validation or construction\n * - Zero runtime cost after creation\n */\n\nexport type UuID = Tagged<string, 'UUID'>;\n\n/**\n * Abstract base class for all domain identifiers.\n *\n * Responsibilities:\n * - Enforces that every DomainID wraps a primitive string value.\n * - Provides a type-safe static factory `fromString` for creating concrete IDs.\n * - Leaves domain-specific validation to subclasses via `validate`.\n *\n * Design Notes:\n * - The class cannot know how to validate the ID itself, because validation\n * rules differ between ID types (e.g., UUID v4, ULID, NanoID).\n * - Static factory uses `new this(value)` pattern; hence, base class is **not abstract** in TypeScript terms.\n * - Subclasses must implement `validate(value: string)` inherited from PrimitiveValueObject.\n *\n * Usage:\n * ```ts\n * class AuthAttemptId extends DomainID {\n * protected validate(value: string): void {\n * if (!isValidUuid(value)) {\n * throw new Error('Invalid AuthAttemptId');\n * }\n * }\n * }\n *\n * const id = AuthAttemptId.fromString('550e8400-e29b-41d4-a716-446655440000');\n * ```\n */\nexport abstract class DomainID extends PrimitiveValueObject<UuID> {\n public static schema = z.uuid();\n\n public constructor(value: string) {\n super(value as UuID);\n }\n\n /**\n * Creates a concrete DomainID from a trusted string value.\n *\n * - Validation is enforced in the subclass constructor.\n * - Intended for application or infrastructure layers to produce IDs.\n *\n * @template T - Concrete subclass of DomainID\n * @param this - The constructor of the concrete subclass\n * @param value - Raw string value of the ID\n * @returns Instance of the concrete DomainID subclass\n */\n public static fromString<T extends new (value: string) => DomainID>(\n this: T,\n value: string,\n ): InstanceType<T> {\n return new this(value) as InstanceType<T>;\n }\n\n public static generate<T extends new (value: string) => DomainID>(\n this: T,\n ): InstanceType<T> {\n return new this(v4()) as InstanceType<T>;\n }\n\n protected validate(value: UuID): void {\n const result = DomainID.schema.safeParse(value);\n\n if (!result.success) {\n throw InvalidValueObjectError.create(`Invalid UUID: ${value}`);\n }\n }\n}\n","import z from 'zod';\n\nimport { InvalidValueObjectError } from '../errors/invalid-vo.error';\nimport { PrimitiveValueObject } from '../base/primitive-vo';\n\nexport class Email extends PrimitiveValueObject<string> {\n private static readonly schema = z.email();\n\n public constructor(value: string) {\n super(value);\n this.validate(value);\n }\n\n public static fromString(value: string): Email {\n return new this(value);\n }\n\n protected validate(value: string): void {\n const result = Email.schema.safeParse(value);\n\n if (!result.success) {\n throw InvalidValueObjectError.create(\n `Invalid ${this.constructor.name}: ${value}`,\n {\n value,\n },\n );\n }\n }\n}\n","/**\n * HTTP status code catalog.\n *\n * This object provides a typed, immutable map of standard HTTP status names\n * to their numeric codes. Designed for server-side frameworks such as Fastify.\n *\n * - All identifiers use clear, canonical semantic names.\n * - Values are numeric status codes.\n * - Frozen to prevent runtime mutation.\n * - Exporting `HttpStatus` ensures type-safe usage across the codebase.\n * Usage:\n * ```ts\n * import { HttpStatus } from 'path-to-this-file';\n *\n * function handleRequest() {\n * return {\n * statusCode: HttpStatus.OK,\n * body: 'Success',\n * };\n * }\n * ```\n */\nexport const HttpStatus = Object.freeze({\n REQUEST_HEADER_FIELDS_TOO_LARGE: 431,\n NETWORK_AUTHENTICATION_REQUIRED: 511,\n NON_AUTHORITATIVE_INFORMATION: 203,\n PROXY_AUTHENTICATION_REQUIRED: 407,\n\n UNAVAILABLE_FOR_LEGAL_REASONS: 451,\n HTTP_VERSION_NOT_SUPPORTED: 505,\n BANDWIDTH_LIMIT_EXCEEDED: 509,\n VARIANT_ALSO_NEGOTIATES: 506,\n UNSUPPORTED_MEDIA_TYPE: 415,\n RANGE_NOT_SATISFIABLE: 416,\n PRECONDITION_REQUIRED: 428,\n INTERNAL_SERVER_ERROR: 500,\n UNPROCESSABLE_ENTITY: 422,\n INSUFFICIENT_STORAGE: 507,\n\n SWITCHING_PROTOCOLS: 101,\n PRECONDITION_FAILED: 412,\n MISDIRECTED_REQUEST: 421,\n SERVICE_UNAVAILABLE: 503,\n TEMPORARY_REDIRECT: 307,\n PERMANENT_REDIRECT: 308,\n METHOD_NOT_ALLOWED: 405,\n EXPECTATION_FAILED: 417,\n\n MOVED_PERMANENTLY: 301,\n PAYLOAD_TOO_LARGE: 413,\n FAILED_DEPENDENCY: 424,\n TOO_MANY_REQUESTS: 429,\n ALREADY_REPORTED: 208,\n MULTIPLE_CHOICES: 300,\n PAYMENT_REQUIRED: 402,\n UPGRADE_REQUIRED: 426,\n PARTIAL_CONTENT: 206,\n REQUEST_TIMEOUT: 408,\n LENGTH_REQUIRED: 411,\n NOT_IMPLEMENTED: 501,\n GATEWAY_TIMEOUT: 504,\n NOT_ACCEPTABLE: 406,\n RESET_CONTENT: 205,\n LOOP_DETECTED: 508,\n MULTI_STATUS: 207,\n NOT_MODIFIED: 304,\n UNAUTHORIZED: 401,\n URI_TOO_LONG: 414,\n NOT_EXTENDED: 510,\n EARLY_HINTS: 103,\n BAD_REQUEST: 400,\n IM_A_TEAPOT: 418,\n BAD_GATEWAY: 502,\n PROCESSING: 102,\n NO_CONTENT: 204,\n SEE_OTHER: 303,\n USE_PROXY: 305,\n\n FORBIDDEN: 403,\n NOT_FOUND: 404,\n TOO_EARLY: 425,\n CONTINUE: 100,\n ACCEPTED: 202,\n CONFLICT: 409,\n CREATED: 201,\n IM_USED: 226,\n LOCKED: 423,\n FOUND: 302,\n GONE: 410,\n OK: 200,\n} as const);\n\n/**\n * HTTP status messages mapped by numeric code.\n * Use for sending descriptive text in responses or logging.\n */\nexport const HttpStatusMessage = {\n 431: 'Request Header Fields Too Large',\n 511: 'Network Authentication Required',\n 203: 'Non-Authoritative Information',\n 407: 'Proxy Authentication Required',\n 451: 'Unavailable For Legal Reasons',\n 505: 'HTTP Version Not Supported',\n 509: 'Bandwidth Limit Exceeded',\n 506: 'Variant Also Negotiates',\n 415: 'Unsupported Media Type',\n 416: 'Range Not Satisfiable',\n 428: 'Precondition Required',\n 500: 'Internal Server Error',\n 422: 'Unprocessable Entity',\n 507: 'Insufficient Storage',\n 101: 'Switching Protocols',\n 412: 'Precondition Failed',\n 421: 'Misdirected Request',\n 503: 'Service Unavailable',\n 307: 'Temporary Redirect',\n 308: 'Permanent Redirect',\n 405: 'Method Not Allowed',\n 417: 'Expectation Failed',\n 301: 'Moved Permanently',\n 413: 'Payload Too Large',\n 424: 'Failed Dependency',\n 429: 'Too Many Requests',\n 208: 'Already Reported',\n 300: 'Multiple Choices',\n 402: 'Payment Required',\n 426: 'Upgrade Required',\n 206: 'Partial Content',\n 408: 'Request Timeout',\n 411: 'Length Required',\n 501: 'Not Implemented',\n 504: 'Gateway Timeout',\n 406: 'Not Acceptable',\n 205: 'Reset Content',\n 508: 'Loop Detected',\n 207: 'Multi-Status',\n 304: 'Not Modified',\n 401: 'Unauthorized',\n 414: 'URI Too Long',\n 418: \"I'm a Teapot\",\n 510: 'Not Extended',\n 103: 'Early Hints',\n 400: 'Bad Request',\n 502: 'Bad Gateway',\n 102: 'Processing',\n 204: 'No Content',\n 303: 'See Other',\n 305: 'Use Proxy',\n 403: 'Forbidden',\n 404: 'Not Found',\n 425: 'Too Early',\n 100: 'Continue',\n 202: 'Accepted',\n 226: \"I'm Used\",\n 409: 'Conflict',\n 201: 'Created',\n 423: 'Locked',\n 302: 'Found',\n 410: 'Gone',\n 200: 'OK',\n} as const;\n\nexport type HttpStatusCode = keyof typeof HttpStatusMessage;\n\nexport type HttpStatusMessage =\n (typeof HttpStatusMessage)[keyof typeof HttpStatusMessage];\n"],"mappings":"2UA+BO,IAAeA,EAAf,cAAwC,KAAM,CAUnD,YAAY,CACV,cAAAC,EAAgB,GAChB,SAAAC,EACA,QAAAC,EACA,MAAAC,EACA,KAAAC,CACF,EAAgB,CACd,MAAMF,CAAO,EAEb,KAAK,KAAO,WAAW,KACvB,KAAK,KAAOE,EACZ,KAAK,cAAgBJ,EACrB,KAAK,SAAWC,EAChB,KAAK,MAAQE,EAEb,MAAM,kBAAkB,KAAM,UAAU,CAC1C,CACF,ECjDO,SAASE,EACdC,EACAC,EAAO,IAAI,QACE,CAiBb,GAfID,IAAU,MAAQ,OAAOA,GAAU,UAKnC,OAAOA,GAAU,YAKjB,OAAO,SAASA,CAAK,GAKrBC,EA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AK,cACL,IAAK,cACL,IAAK,cACL,IAAK,aACL,IAAK,aACL,IAAK,YACL,IAAK,YACL,IAAK,YACL,IAAK,YACL,IAAK,YACL,IAAK,WACL,IAAK,WACL,IAAK,WACL,IAAK,WACL,IAAK,UACL,IAAK,SACL,IAAK,QACL,IAAK,OACL,IAAK,IACP","names":["ApplicationError","isOperational","metadata","message","cause","code","deepFreeze","value","seen","item","key","_props","Entity","params","__privateAdd","_a","__privateSet","deepFreeze","__privateGet","other","updater","next","AggregateRoot","Entity","domainEvent","events","_value","_PrimitiveValueObject","value","__privateAdd","__privateSet","__privateGet","other","PrimitiveValueObject","deepEqual","ValueObject","_ValueObject","props","deepFreeze","vo","other","deepEqual","DomainError","message","args","_a","InternalError","DomainError","message","metadata","InvalidStateError","DomainError","message","InvalidValueError","DomainError","msg","meta","TimeoutError","DomainError","message","metadata","Result","_Result","params","hasError","error","value","EntityValidationError","_EntityValidationError","DomainError","message","props","msg","InvalidValueObjectError","_InvalidValueObjectError","DomainError","msg","meta","randomUUID","DomainEvent","props","_a","randomUUID","deepFreeze","v4","z","_UUID","PrimitiveValueObject","value","v4","InvalidValueObjectError","z","UUID","AggregateId","UUID","v4","z","_DomainID","PrimitiveValueObject","value","v4","InvalidValueObjectError","z","DomainID","z","_Email","PrimitiveValueObject","value","InvalidValueObjectError","z","Email","HttpStatus","HttpStatusMessage"]}
1
+ {"version":3,"sources":["../src/application/errors/application.error.ts","../src/utils/deep-freeze.util.ts","../src/domain/entities/entity.ts","../src/domain/aggregates/aggregate-root.ts","../src/domain/base/primitive-vo.ts","../src/domain/base/vo.ts","../src/shared/domain/domain.error.ts","../src/shared/domain/errors/internal.error.ts","../src/shared/domain/errors/invalid-state.error.ts","../src/shared/domain/errors/invalid-value.error.ts","../src/shared/domain/errors/timeout.error.ts","../src/shared/domain/result.ts","../src/domain/errors/entity-validation.error.ts","../src/domain/errors/invalid-vo.error.ts","../src/domain/events/domain.event.ts","../src/domain/value-objects/id.vo.ts","../src/domain/value-objects/aggregate-id.vo.ts","../src/domain/value-objects/domain-id.vo.ts","../src/domain/value-objects/email.vo.ts","../src/gateway/constants/http-code.ts"],"sourcesContent":["interface ErrorParams {\n message: string;\n code: string;\n metadata?: Record<string, unknown>;\n isOperational?: boolean;\n cause?: Error;\n}\n\n/**\n * Abstract base class for application-level errors with structured error handling.\n *\n * Extends the native Error class to provide machine-readable error codes, HTTP status codes,\n * operational error classification, and optional metadata for better error tracking and client communication.\n *\n * @abstract\n * @extends {Error}\n *\n * @example\n * ```typescript\n * class UserNotFoundError extends ApplicationError {\n * constructor(userId: string) {\n * super({\n * code: HttpStatusMessage['404'],\n * isOperational: true,\n * message: `User with id ${userId} not found`,\n * metadata: { userId }\n * });\n * }\n * }\n * ```\n */\nexport abstract class ApplicationError extends Error {\n /** Optional cause (linked error) */\n public readonly cause?: Error | undefined;\n /** Machine-readable error code (e.g. `OTP_LOCKED`, `USER_NOT_FOUND`) */\n public readonly code: string;\n /** Operational vs programmer error flag */\n public readonly isOperational: boolean;\n /** Optional structured metadata for debugging or clients */\n public readonly metadata?: Record<string, unknown> | undefined;\n\n constructor({\n isOperational = false,\n metadata,\n message,\n cause,\n code,\n }: ErrorParams) {\n super(message);\n\n this.name = new.target.name;\n this.code = code;\n this.isOperational = isOperational;\n this.metadata = metadata;\n this.cause = cause;\n\n Error.captureStackTrace(this, new.target);\n }\n}\n","/**\n * Deeply freezes an object graph to enforce runtime immutability.\n * - Handles arrays\n * - Handles circular references\n * - Skips functions\n * - Skips already frozen objects\n *\n * Intended for aggregate and value object state only.\n */\nexport function deepFreeze<T>(\n value: T,\n seen = new WeakSet<object>(),\n): Readonly<T> {\n // Primitives, null, undefined\n if (value === null || typeof value !== 'object') {\n return value;\n }\n\n // Functions should never be frozen\n if (typeof value === 'function') {\n return value;\n }\n\n // Avoid re-processing\n if (Object.isFrozen(value)) {\n return value as Readonly<T>;\n }\n\n // Handle circular references\n if (seen.has(value)) {\n return value as Readonly<T>;\n }\n\n seen.add(value);\n\n if (Array.isArray(value)) {\n for (const item of value) {\n deepFreeze(item, seen);\n }\n } else {\n for (const key of Object.keys(value)) {\n deepFreeze((value as Record<string, unknown>)[key], seen);\n }\n }\n\n return Object.freeze(value) as Readonly<T>;\n}\n","import { deepFreeze } from '@/utils';\n\nimport { EntityId } from '../types';\n\n// export type Immutable<T> = {\n// readonly [K in keyof T]: Immutable<T[K]>;\n// };\n\nexport type Immutable<T> = T extends (...args: any[]) => any\n ? T\n : T extends Date\n ? T\n : T extends Map<infer K, infer V>\n ? ReadonlyMap<Immutable<K>, Immutable<V>>\n : T extends Set<infer U>\n ? ReadonlySet<Immutable<U>>\n : T extends object\n ? { readonly [K in keyof T]: Immutable<T[K]> }\n : T;\n\n/**\n * Configuration for the base Entity constructor.\n * Forces a single-object argument pattern to avoid positional argument errors.\n * @template ID - A type satisfying the EntityId interface.\n */\nexport interface EntityProps<ID extends EntityId, Props> {\n /** The unique identity of the entity */\n readonly id: ID;\n /** Optional creation timestamp; defaults to 'now' if not provided */\n readonly createdAt?: Date;\n\n props: Props;\n}\n\n/**\n * Abstract Base Entity for Domain-Driven Design (DDD).\n * This class provides the standard contract for entity equality and identity.\n * It intentionally avoids \"magic\" property bags to ensure V8 engine optimization\n * and better IDE intellisense.\n * @template ID - The specific Identity Value Object type.\n */\nexport abstract class Entity<ID extends EntityId, Props> {\n /** The timestamp when this entity was first instantiated/created */\n public readonly createdAt: Date;\n /** The immutable unique identifier for this entity */\n public readonly id: ID;\n\n /**\n * Read-only view of entity state.\n * External code can never mutate internal state.\n */\n protected get props(): Immutable<Props> {\n return this.#props as Immutable<Props>;\n }\n\n // protected props: Props;\n #props: Props;\n\n /**\n * Protected constructor to be called by subclasses.\n * @param params - Initial identity and metadata.\n */\n protected constructor(params: EntityProps<ID, Props>) {\n this.id = params.id;\n this.createdAt = params.createdAt ?? new Date();\n this.#props = deepFreeze(params.props);\n\n this.validate();\n }\n\n /**\n * Compares entities by identity.\n * In DDD, two entities are considered equal if their IDs match,\n * regardless of their other properties.\n * @param other - The entity to compare against.\n * @returns True if IDs are equal.\n */\n public equals(other?: Entity<ID, Props>): boolean {\n if (other == null) return false;\n if (this === other) return true;\n return this.id.equals(other.id);\n }\n\n /**\n * Converts the Entity into a plain Javascript object.\n * Subclasses must implement this to explicitly control serialization,\n * @returns A plain object representation of the entity.\n */\n public abstract toObject(): Record<string, unknown>;\n\n /**\n * Validates the current state of the entity against domain invariants.\n * This method should be called after construction and any mutation.\n * @throws {Error} Should throw a specific DomainError if validation fails.\n */\n public abstract validate(): void;\n\n protected mutate(updater: (current: Props) => Props): void {\n const next = updater(this.#props);\n\n this.#props = deepFreeze(next);\n this.validate();\n }\n}\n","import { Entity } from '../entities/entity';\nimport { DomainEvent } from '../events';\nimport { EntityId } from '../types';\n\n/**\n * Base class for aggregate roots in DDD, encapsulating domain events and validation.\n *\n * Aggregate roots are entities that serve as entry points to aggregates. They:\n * - Enforce invariants across the aggregate\n * - Manage domain events\n * - Define transaction boundaries\n *\n * @template ID - The type of the aggregate's identity (must extend EntityId)\n * @template P - The type of the aggregate's properties\n *\n * @example\n * ```typescript\n * interface UserProps {\n * email: string;\n * isActive: boolean;\n * }\n *\n * class User extends AggregateRoot<AggregateId, UserProps> {\n * // Implementation...\n * }\n * ```\n */\nexport abstract class AggregateRoot<ID extends EntityId, P> extends Entity<\n ID,\n P\n> {\n /**\n * Gets a read-only copy of the domain events.\n */\n get domainEvents(): readonly DomainEvent[] {\n return [...this._domainEvents];\n }\n\n /**\n * Internal list of domain events.\n */\n private readonly _domainEvents: DomainEvent[] = [];\n\n /**\n * Adds a domain event to the aggregate after validating invariants.\n * @param domainEvent The domain event to add.\n * @throws {EntityValidationError} If invariants are not met.\n */\n addEvent(domainEvent: DomainEvent): void {\n this._domainEvents.push(domainEvent);\n }\n\n public pullDomainEvents(): readonly DomainEvent[] {\n const events = [...this._domainEvents];\n this._domainEvents.length = 0;\n return events;\n }\n}\n","import { Primitive } from 'type-fest';\n\nimport { EntityId } from '../types';\n\n/**\n * Base class for primitive-based Value Objects.\n *\n * This class is intended for Value Objects that are represented by\n * a single primitive value (string, number, or boolean).\n *\n * Characteristics:\n * - Immutable by construction\n * - Cheap equality comparison\n * - No deep cloning or freezing\n * - Safe for serialization and logging\n *\n * Examples:\n * - AggregateId\n * - EmailAddress\n * - Username\n * - Slug\n */\nexport abstract class PrimitiveValueObject<\n T extends Primitive,\n> implements EntityId {\n /**\n * The underlying primitive value.\n * Guaranteed to be valid after construction.\n */\n get value(): T {\n return this.#value;\n }\n\n readonly #value: Readonly<T>;\n\n /**\n * Constructs a new PrimitiveValueObject.\n *\n * @param value - The primitive value to wrap\n * @throws Error if validation fails\n */\n protected constructor(value: T) {\n this.validate(value);\n this.#value = value;\n }\n\n /**\n * Compares two Value Objects for equality.\n *\n * Equality rules:\n * - Same concrete class\n * - Same primitive value (===)\n *\n * @param other - Another Value Object\n */\n public equals(other: any): boolean {\n if (other == null) return false;\n\n if (Object.getPrototypeOf(this) !== Object.getPrototypeOf(other)) {\n return false;\n }\n\n if (!(other instanceof PrimitiveValueObject)) return false;\n\n return this.#value === other.#value;\n }\n\n /**\n * Returns the primitive value.\n * Prefer explicit access over implicit coercion.\n * @deprecated - instead use instance.value\n */\n public getValue(): T {\n return this.#value;\n }\n\n /**\n * String representation.\n * Useful for logging and debugging.\n */\n public toString(): string {\n return String(this.#value);\n }\n\n /**\n * Domain invariant validation.\n * Must throw if the value is invalid.\n *\n * @param value - The value to validate\n */\n protected abstract validate(value: T): void;\n}\n","import deepEqual from 'fast-deep-equal/es6';\n\nimport { deepFreeze } from '@/utils/deep-freeze.util';\n\nexport abstract class ValueObject<T> {\n get value(): T {\n return this.props;\n }\n\n protected readonly props: Readonly<T>;\n\n protected constructor(props: T) {\n this.validate(props);\n this.props = deepFreeze(props);\n }\n\n /**\n * Type guard to check if an unknown object is an instance of ValueObject.\n * This is useful for runtime type checking.\n *\n * @param vo The object to check.\n * @returns True if the object is a ValueObject instance, false otherwise.\n */\n public static is(vo: unknown): vo is ValueObject<unknown> {\n return vo instanceof ValueObject;\n }\n\n /**\n * Deep equality comparison of ValueObjects\n */\n public equals(other?: ValueObject<T>): boolean {\n if (other == null) return false;\n\n // Check if they share the same constructor (Type check)\n if (Object.getPrototypeOf(this) !== Object.getPrototypeOf(other)) {\n return false;\n }\n\n return deepEqual(this.props, other.props);\n }\n\n /**\n * Standard for clean API integration and logging.\n */\n public toJSON(): T {\n return this.props;\n }\n\n /**\n * Useful for debugging and string-based indexing.\n */\n public toString(): string {\n return JSON.stringify(this.props);\n }\n\n /**\n * Validates the value object props\n * @throws InvalidValueObjectError if validation fails\n */\n protected abstract validate(props: T): void;\n}\n","import { EmptyObject } from 'type-fest';\n\n/**\n * Primitive types allowed in domain error metadata.\n * Used to ensure metadata is serializable and does not contain complex objects.\n */\nexport type Primitive = boolean | number | string | null | undefined;\n\n/**\n * Type for metadata objects. Ensures only primitive values are allowed.\n * Falls back to EmptyObject when T is not a record of primitives.\n *\n * @typeParam T - Expected metadata shape\n */\nexport type Metadata<T = EmptyObject> =\n T extends Record<string, Primitive> ? T : EmptyObject;\n\n/**\n * Categories of domain errors based on the nature of the violation.\n *\n * @typedef {'DOMAIN.INVALID_STATE' | 'DOMAIN.INVALID_VALUE'} DomainErrorType\n *\n * @example\n * // DomainErrorType usage:\n * const errorType: DomainErrorType = 'DOMAIN.INVALID_STATE';\n */\nexport type DomainErrorType = 'DOMAIN.INVALID_STATE' | 'DOMAIN.INVALID_VALUE';\n\n// ============ TYPE UTILITIES ============\n/** Extracts the union of all value types from an object type. */\nexport type ValueOf<T> = T[keyof T];\n/** Converts a union type to an intersection type. */\nexport type UnionToIntersection<U> = (\n U extends any ? (k: U) => void : never\n) extends (k: infer I) => void\n ? I\n : never;\n\n/**\n * Interface for declaring domain error namespaces via declaration merging.\n * Projects extend this interface to add their own namespaces and error codes.\n *\n * @example\n * // In your project's type definition file (.d.ts):\n * declare module '@your-org/domain-errors' {\n * interface DomainErrorNamespaces {\n * USER: ['NOT_FOUND', 'INVALID_EMAIL', 'SUSPENDED'];\n * ORDER: ['NOT_FOUND', 'INVALID_STATUS', 'OUT_OF_STOCK'];\n * // Override default namespace (optional):\n * CORE: ['INTERNAL_ERROR', 'VALIDATION_FAILED', 'CONFIGURATION_ERROR'];\n * }\n * }\n *\n * @example\n * // This enables type-safe error codes:\n * const code: DomainErrorCode = 'USER.NOT_FOUND'; // ✅ Valid\n * const code: DomainErrorCode = 'USER.INVALID'; // ❌ TypeScript error\n */\nexport interface DomainErrorNamespaces {\n // Built-in core namespaces (available in all projects)\n DOMAIN: ['INVALID_VALUE', 'INVALID_STATE'];\n CORE: [\n 'INTERNAL_ERROR',\n 'VALIDATION_FAILED',\n 'CONFIGURATION_ERROR',\n 'NOT_IMPLEMENTED',\n ];\n SYSTEM: ['UNEXPECTED', 'TIMEOUT', 'NETWORK_ERROR', 'DEPENDENCY_ERROR'];\n}\n\n// ============ INFER TYPES FROM REGISTRY ============\ntype Namespace = keyof DomainErrorNamespaces;\ntype ErrorName<N extends Namespace> = DomainErrorNamespaces[N][number];\n\n/**\n * Union type of all valid domain error codes derived from registered namespaces.\n * Automatically updates when projects extend DomainErrorNamespaces.\n *\n * @example\n * // After extending DomainErrorNamespaces with USER namespace:\n * type ErrorCode = DomainErrorCode;\n * // Becomes: 'CORE.INTERNAL_ERROR' | 'CORE.VALIDATION_FAILED' |\n * // 'USER.NOT_FOUND' | 'USER.INVALID_EMAIL' | ...\n */\nexport type DomainErrorCode = {\n [N in Namespace]: `${Uppercase<string & N>}.${Uppercase<ErrorName<N>>}`;\n}[Namespace];\n\n/**\n * Extracts the namespace part from a domain error code.\n *\n * @typeParam Code - Full error code (e.g. 'USER.NOT_FOUND')\n */\nexport type ExtractNamespace<Code extends DomainErrorCode> =\n Code extends `${infer N}.${string}` ? N : never;\n\n/**\n * Extracts the error name part from a domain error code.\n *\n * @typeParam Code - Full error code (e.g. 'USER.NOT_FOUND')\n */\nexport type ExtractErrorName<Code extends DomainErrorCode> =\n Code extends `${string}.${infer E}` ? E : never;\n\n/**\n * Base class for all domain errors in a Domain-Driven Design architecture.\n *\n * Domain errors represent violations of business rules and domain invariants.\n * They are pure value objects without infrastructure concerns like IDs or timestamps.\n *\n * @typeParam Code - The specific error code from DomainErrorCode union\n * @typeParam Meta - Type of metadata associated with this error\n *\n * @example\n * // 1. First, declare your namespaces:\n * declare module '@your-org/domain-errors' {\n * interface DomainErrorNamespaces {\n * USER: ['NOT_FOUND', 'INVALID_EMAIL'];\n * }\n * }\n *\n * @example\n * // 2. Create a concrete domain error:\n * class UserNotFoundError extends DomainError<'USER.NOT_FOUND', { userId: string }> {\n * public readonly code = 'USER.NOT_FOUND' as const;\n * public readonly type: DomainErrorType = 'DOMAIN.INVALID_VALUE';\n *\n * constructor(userId: string) {\n * super(`User with ID '${userId}' not found`, { userId });\n * }\n * }\n *\n * @example\n * // 3. Usage in domain services:\n * class UserService {\n * async activateUser(userId: string): Promise<Result<User, DomainError>> {\n * const user = await this.repository.findById(userId);\n *\n * if (!user) {\n * return Result.failure(new UserNotFoundError(userId));\n * }\n *\n * if (user.isSuspended) {\n * return Result.failure(new UserSuspendedError(userId));\n * }\n *\n * // Business logic...\n * }\n * }\n *\n * @abstract\n */\nexport abstract class DomainError<\n Meta extends Record<string, Primitive> = EmptyObject,\n Code extends DomainErrorCode = DomainErrorCode,\n> {\n /**\n * Machine-readable error code in format: NAMESPACE.ERROR_NAME\n *\n * @remarks\n * - Must be uppercase (e.g., 'USER.NOT_FOUND')\n * - Namespace must be declared in DomainErrorNamespaces\n * - Error name must be in the namespace's array\n *\n * @example\n * public readonly code = 'USER.NOT_FOUND' as const;\n */\n public abstract readonly code: Code;\n /**\n * Human-readable error message describing the domain rule violation.\n * Should be meaningful to developers and potentially end-users.\n *\n * @remarks\n * - Avoid technical implementation details\n * - Focus on the business rule that was violated\n * - Can include values from metadata for context\n *\n * @example\n * // Good: \"Order amount $150 exceeds maximum limit of $100\"\n * // Bad: \"Amount validation failed: 150 > 100\"\n */\n public readonly message: string;\n\n /**\n * Immutable structured context providing additional information about the error.\n * Useful for debugging, logging, and creating detailed error messages.\n *\n * @remarks\n * - Values must be primitive types (string, number, boolean, etc.)\n * - Object is frozen to prevent mutation\n * - Type-safe based on the error code\n *\n * @example\n * // For UserNotFoundError:\n * { userId: 'usr_123', attemptedAction: 'activate' }\n *\n * @readonly\n */\n public readonly metadata: Readonly<Meta>;\n\n /**\n * Category of domain error indicating the nature of violation.\n *\n * @remarks\n * Use 'DOMAIN.INVALID_STATE' for state violations (e.g., \"Cannot checkout empty cart\")\n * Use 'DOMAIN.INVALID_VALUE' for value violations (e.g., \"Email format is invalid\")\n *\n * @example\n * public readonly type: DomainErrorType = 'DOMAIN.INVALID_VALUE';\n */\n public abstract readonly type: DomainErrorType;\n\n /**\n * Error name portion of the code (e.g. 'NOT_FOUND' from 'USER.NOT_FOUND').\n */\n public get errorName(): ExtractErrorName<Code> {\n return this.code.split('.')[1] as ExtractErrorName<Code>;\n }\n\n // ============ COMPUTED PROPERTIES ============\n /**\n * Namespace portion of the code (e.g. 'USER' from 'USER.NOT_FOUND').\n */\n public get namespace(): ExtractNamespace<Code> {\n return this.code.split('.')[0] as ExtractNamespace<Code>;\n }\n\n /**\n * Creates a new DomainError instance.\n *\n * @param message - Human-readable description of the domain rule violation\n * @param metadata - Optional structured context (primitive values only)\n *\n * @example\n * constructor(userId: string) {\n * super(`User with ID '${userId}' not found`, { userId });\n * }\n *\n * @example\n * constructor(amount: number, maxLimit: number) {\n * super(\n * `Order amount $${amount} exceeds maximum limit of $${maxLimit}`,\n * { amount, maxLimit }\n * );\n * }\n */\n protected constructor(\n message: string,\n ...args: keyof Meta extends never\n ? [] | [metadata?: Meta]\n : [metadata: Meta]\n ) {\n this.message = message;\n this.metadata = Object.freeze(args[0] ?? {}) as Readonly<Meta>;\n }\n\n /**\n * Type guard to check if a value is a DomainError instance.\n *\n * @param error - Value to check (typically from catch block or unknown source)\n * @returns True if error is a DomainError instance, false otherwise\n *\n * @example\n * try {\n * await userService.activate(userId);\n * } catch (error) {\n * if (DomainError.isInstance(error)) {\n * // error is narrowed to DomainError\n * console.log(error.code, error.message);\n * } else {\n * throw error;\n * }\n * }\n *\n * @example\n * const result = await userService.findById(id);\n * if (Result.isFailure(result)) {\n * const err = result.error;\n * if (DomainError.isInstance(err)) {\n * return Result.failure(err);\n * }\n * }\n */\n public static isInstance(\n error: unknown,\n ): error is DomainError<Record<string, Primitive>, DomainErrorCode> {\n return error instanceof DomainError;\n }\n\n /**\n * Serializes the error to a plain object for debugging, logging, or transport.\n * Does not include infrastructure concerns like stack traces or timestamps.\n *\n * @returns Plain object with error details\n *\n * @example\n * const error = new UserNotFoundError('usr_123');\n * const json = error.toJSON();\n * // Result:\n * // {\n * // code: 'USER.NOT_FOUND',\n * // message: \"User with ID 'usr_123' not found\",\n * // type: 'DOMAIN.INVALID_VALUE',\n * // metadata: { userId: 'usr_123' }\n * // }\n */\n public toObject() {\n return {\n metadata: this.metadata,\n message: this.message,\n code: this.code,\n type: this.type,\n };\n }\n\n /**\n * Returns a string representation of the error.\n * Format: [CODE] MESSAGE\n *\n * @returns Human-readable string representation\n *\n * @example\n * const error = new UserNotFoundError('usr_123');\n * console.log(error.toString());\n * // Output: [USER.NOT_FOUND] User with ID 'usr_123' not found\n *\n * @override\n */\n public toString(): string {\n return `[${this.code}] ${this.message}`;\n }\n}\n","import {\n DomainError,\n DomainErrorType,\n Metadata,\n Primitive,\n} from '../domain.error';\n\n/**\n * Default domain errors for common scenarios.\n * These errors are available across all projects using this module.\n */\n\n/**\n * Error thrown when an unexpected internal error occurs.\n * Typically used for programming bugs, invalid assumptions, or states that should never happen.\n *\n * @remarks\n * - Metadata is optional for empty metadata types and required if a non-empty type is provided.\n * - Useful for debugging, logging, and adding context to unexpected failures.\n *\n * @template T - Type of metadata object (must extend Record<string, Primitive>)\n *\n * @example\n * // Catch a programming error:\n * try {\n * complexBusinessLogic();\n * } catch (error) {\n * throw new InternalError(\n * 'Unexpected error in complexBusinessLogic',\n * { originalError: error.message, timestamp: Date.now() }\n * );\n * }\n *\n * @example\n * // Fallback for unhandled cases:\n * switch (status) {\n * case 'PENDING':\n * break;\n * case 'COMPLETED':\n * break;\n * default:\n * throw new InternalError(\n * `Unhandled status: ${status}`,\n * { status }\n * );\n * }\n *\n * @example\n * // With custom metadata type:\n * type ErrorMetadata = { userId: string; action: string };\n * throw new InternalError<ErrorMetadata>(\n * 'Failed to process user action',\n * { userId: 'usr_123', action: 'activate' }\n * );\n */\nexport class InternalError<\n T extends Record<string, Primitive> = Record<string, Primitive>,\n> extends DomainError<Metadata<T>> {\n /** @inheritdoc */\n public readonly code = 'CORE.INTERNAL_ERROR' as const;\n\n /** @inheritdoc */\n public readonly type: DomainErrorType = 'DOMAIN.INVALID_STATE';\n\n /**\n * Creates a new InternalError.\n *\n * @param message - Description of the internal error (defaults to 'An unexpected internal error occurred')\n * @param metadata - Optional debug information (primitive values only)\n *\n * @example\n * // Basic usage:\n * throw new InternalError('Something went wrong');\n *\n * @example\n * // With metadata:\n * throw new InternalError(\n * 'Database connection failed',\n * { host: 'localhost', port: 5432, retries: 3 }\n * );\n */\n constructor(\n message: string = 'An unexpected internal error occurred',\n metadata?: Metadata<T>,\n ) {\n super(message, metadata);\n }\n}\n","import {\n DomainError,\n DomainErrorCode,\n DomainErrorType,\n Primitive,\n} from '../domain.error';\n\n/**\n * Error thrown when an entity or aggregate is in an invalid state for the requested operation.\n * Use for state violations (e.g., \"Cannot checkout empty cart\", \"Cannot cancel completed order\").\n *\n * @example\n * // Prevent invalid state transitions:\n * if (order.status === 'COMPLETED') {\n * throw new InvalidStateError('Cannot cancel a completed order');\n * }\n *\n * @example\n * // With context:\n * if (!cart.hasItems()) {\n * throw new InvalidStateError('Cannot checkout empty cart');\n * }\n */\nexport class InvalidStateError extends DomainError<Record<string, Primitive>> {\n public code: DomainErrorCode = 'DOMAIN.INVALID_STATE';\n public type: DomainErrorType = 'DOMAIN.INVALID_STATE';\n\n constructor(message = 'invalid state') {\n super(message, {});\n }\n}\n","import {\n DomainError,\n DomainErrorCode,\n DomainErrorType,\n Metadata,\n Primitive,\n} from '../domain.error';\n\n/**\n * Error thrown when a value violates domain rules or constraints.\n * Use for value violations (e.g., \"Email format is invalid\", \"Age cannot be negative\").\n *\n * @template T - Type of metadata object (must extend Record<string, Primitive>)\n *\n * @example\n * // Basic usage:\n * if (age < 0) {\n * throw new InvalidValueError('Age cannot be negative');\n * }\n *\n * @example\n * // With metadata:\n * if (!isValidEmail(email)) {\n * throw new InvalidValueError(\n * 'Invalid email format',\n * { email, pattern: '^[^@]+@[^@]+\\\\.[^@]+$' }\n * );\n * }\n *\n * @example\n * // With custom metadata type:\n * type ValidationMetadata = { field: string; value: unknown; reason: string };\n * throw new InvalidValueError<ValidationMetadata>(\n * 'Validation failed',\n * { field: 'email', value: email, reason: 'Invalid format' }\n * );\n */\nexport class InvalidValueError<\n T extends Record<string, Primitive> = Record<string, Primitive>,\n> extends DomainError<Metadata<T>> {\n public code: DomainErrorCode = 'DOMAIN.INVALID_VALUE';\n public type: DomainErrorType = 'DOMAIN.INVALID_VALUE';\n\n constructor(msg = 'invalid value', meta?: Metadata<T>) {\n super(msg, meta);\n }\n}\n","import {\n DomainError,\n DomainErrorType,\n Metadata,\n Primitive,\n} from '../domain.error';\n\n/**\n * Error thrown when an operation times out.\n * Use for operations that exceed their allowed execution time.\n *\n * @template T - Type of metadata object (must extend Record<string, Primitive>)\n *\n * @example\n * // Operation timeout:\n * const timeout = setTimeout(() => {\n * throw new TimeoutError(\n * 'User registration timed out'\n * );\n * }, 5000);\n *\n * @example\n * // With Promise.race:\n * type Props = { url: string; timeoutMs: number };\n * async function fetchWithTimeout(url: string, timeoutMs: number) {\n * const timeoutPromise = new Promise<never>((_, reject) => {\n * setTimeout(() => {\n * reject(new TimeoutError<Props>(\n * `Request to ${url} timed out`,\n * { url, timeoutMs }\n * ));\n * }, timeoutMs);\n * });\n *\n * return await Promise.race([fetch(url), timeoutPromise]);\n * }\n *\n * @example\n * // With custom metadata:\n * throw new TimeoutError(\n * 'Database query timed out',\n * { query: 'SELECT * FROM users', timeout: 5000, retries: 3 }\n * );\n */\nexport class TimeoutError<\n T extends Record<string, Primitive> = Record<string, Primitive>,\n> extends DomainError<Metadata<T>> {\n /** @inheritdoc */\n public readonly code = 'SYSTEM.TIMEOUT' as const;\n\n /** @inheritdoc */\n public readonly type: DomainErrorType = 'DOMAIN.INVALID_STATE';\n\n /**\n * Creates a new TimeoutError.\n *\n * @param message - Description of the timeout\n * @param metadata - Optional timeout context\n */\n // eslint-disable-next-line @typescript-eslint/no-useless-constructor\n constructor(message: string, metadata?: Metadata<T>) {\n super(message, metadata);\n }\n}\n","import { DomainError } from './domain.error';\n\n/**\n * Represents the result of an operation, which can be either a success or a failure.\n *\n * This is a functional programming pattern that helps avoid throwing exceptions\n * and makes error handling explicit in the type system. It's commonly used in\n * Domain-Driven Design (DDD) to represent domain operation outcomes.\n *\n * @template T The type of a successful result.\n * @template E The type of the error in case of failure (defaults to DomainError).\n *\n * @example\n * ```typescript\n * // Creating a successful result\n * const success = Result.ok({ id: 1, name: 'John' });\n * if (success.isSuccess) {\n * const user = success.getValue(); // { id: 1, name: 'John' }\n * }\n *\n * // Creating a failed result\n * const failure = Result.fail(new InvalidUserError('User not found'));\n * if (failure.isFailure) {\n * const error = failure.getError(); // InvalidUserError instance\n * }\n * ```\n *\n * @example\n * ```typescript\n * // Using in a domain service\n * function createUser(name: string): Result<User, DomainError> {\n * if (!name || name.trim().length === 0) {\n * return Result.fail(new InvalidValueError('Name cannot be empty'));\n * }\n *\n * const user = new User(name);\n * return Result.ok(user);\n * }\n *\n * const result = createUser('John Doe');\n * if (result.isSuccess) {\n * console.log('User created:', result.getValue());\n * } else {\n * console.error('Failed:', result.getError()?.message);\n * }\n * ```\n *\n * @example\n * ```typescript\n * // Chaining operations\n * function validateEmail(email: string): Result<string, DomainError> {\n * if (!email.includes('@')) {\n * return Result.fail(new InvalidValueError('Invalid email format'));\n * }\n * return Result.ok(email);\n * }\n *\n * function createAccount(email: string): Result<Account, DomainError> {\n * const emailResult = validateEmail(email);\n * if (emailResult.isFailure) {\n * return emailResult; // Forward the error\n * }\n *\n * const account = new Account(emailResult.getValue()!);\n * return Result.ok(account);\n * }\n * ```\n *\n * @example\n * ```typescript\n * // Working with async operations\n * async function fetchUser(id: number): Promise<Result<User, DomainError>> {\n * try {\n * const user = await userRepository.findById(id);\n * if (!user) {\n * return Result.fail(new NotFoundError(`User ${id} not found`));\n * }\n * return Result.ok(user);\n * } catch (error) {\n * return Result.fail(new SystemError('Database connection failed'));\n * }\n * }\n *\n * const result = await fetchUser(123);\n * if (result.isSuccess) {\n * // Handle success\n * } else {\n * // Handle failure\n * }\n * ```\n */\nexport class Result<T, E> {\n /**\n * Indicates if the result is a failure.\n *\n * @example\n * ```typescript\n * const result = Result.fail(new Error('Something went wrong'));\n * if (result.isFailure) {\n * // Handle error case\n * console.error(result.getError());\n * }\n * ```\n */\n public readonly isFailure: boolean;\n\n /**\n * Indicates if the result is a success.\n *\n * @example\n * ```typescript\n * const result = Result.ok(42);\n * if (result.isSuccess) {\n * // Handle success case\n * const value = result.getValue(); // 42\n * }\n * ```\n */\n public readonly isSuccess: boolean;\n\n /**\n * The error, if any.\n * @private\n */\n private readonly _error?: E;\n\n /**\n * The value, if any.\n * @private\n */\n private readonly _value?: T;\n\n /**\n * Private constructor to enforce the use of static methods.\n * @param params.value The value on success.\n * @param params.error The error on failure.\n * @private\n */\n private constructor(params: { value?: T; error?: E }) {\n const hasError = params.error !== undefined;\n this.isFailure = hasError;\n this.isSuccess = !hasError;\n\n this._value = params.value;\n this._error = params.error;\n Object.freeze(this);\n }\n\n /**\n * Creates a failed result.\n *\n * @template T The type of a successful result (never for failure).\n * @template E The type of the error (defaults to DomainError).\n * @param error The error object.\n * @returns {Result<T, E>} A failed Result instance.\n *\n * @example\n * ```typescript\n * // With DomainError\n * class InvalidValueError extends DomainError {\n * public readonly code = 'DOMAIN.INVALID_VALUE' as const;\n * constructor(message: string) {\n * super({ message });\n * }\n * }\n *\n * const result = Result.fail(new InvalidValueError('Value must be positive'));\n * // result.isFailure === true\n * // result.getError() === InvalidValueError instance\n * ```\n *\n * @example\n * ```typescript\n * // With custom error type\n * interface ValidationError {\n * field: string;\n * message: string;\n * }\n *\n * const result = Result.fail<never, ValidationError>({\n * field: 'email',\n * message: 'Invalid email format'\n * });\n * ```\n *\n * @example\n * ```typescript\n * // In a validation function\n * function validateAge(age: number): Result<number, DomainError> {\n * if (age < 0) {\n * return Result.fail(new InvalidValueError('Age cannot be negative'));\n * }\n * if (age > 150) {\n * return Result.fail(new InvalidValueError('Age seems unrealistic'));\n * }\n * return Result.ok(age);\n * }\n * ```\n */\n public static fail<T = never, E = DomainError>(error: E): Result<T, E> {\n return new Result({ error });\n }\n\n /**\n * Creates a successful result.\n *\n * @template T The type of the successful result.\n * @template E The type of the error (never for success).\n * @param value The success value.\n * @returns {Result<T, E>} A successful Result instance.\n *\n * @example\n * ```typescript\n * // With primitive value\n * const result = Result.ok(42);\n * // result.isSuccess === true\n * // result.getValue() === 42\n * ```\n *\n * @example\n * ```typescript\n * // With object\n * const user = { id: 1, name: 'John', email: 'john@example.com' };\n * const result = Result.ok(user);\n * if (result.isSuccess) {\n * const savedUser = result.getValue(); // { id: 1, name: 'John', ... }\n * }\n * ```\n *\n * @example\n * ```typescript\n * // With domain entity\n * class User {\n * constructor(public readonly id: number, public readonly name: string) {}\n * }\n *\n * function createUser(name: string): Result<User, DomainError> {\n * const user = new User(Date.now(), name);\n * return Result.ok(user);\n * }\n *\n * const result = createUser('Alice');\n * if (result.isSuccess) {\n * console.log(`Created user: ${result.getValue()?.name}`);\n * }\n * ```\n *\n * @example\n * ```typescript\n * // With void/undefined (for operations that don't return a value)\n * function deleteUser(id: number): Result<void, DomainError> {\n * // ... deletion logic ...\n * return Result.ok(undefined);\n * }\n *\n * const result = deleteUser(123);\n * if (result.isSuccess) {\n * console.log('User deleted successfully');\n * }\n * ```\n */\n public static ok<T, E = never>(value: T): Result<T, E> {\n return new Result({ value });\n }\n\n /**\n * Returns the error if present, otherwise undefined.\n *\n * **Note:** Always check `isFailure` before calling this method to ensure\n * the result is actually a failure. This method will return `undefined` for\n * successful results.\n *\n * @returns {E | undefined} The error or undefined if successful.\n *\n * @example\n * ```typescript\n * const result = Result.fail(new InvalidValueError('Invalid input'));\n *\n * if (result.isFailure) {\n * const error = result.getError();\n * if (error) {\n * console.error(`Error code: ${error.code}, Message: ${error.message}`);\n * }\n * }\n * ```\n *\n * @example\n * ```typescript\n * // Safe error handling pattern\n * function handleResult<T>(result: Result<T, DomainError>): void {\n * if (result.isFailure) {\n * const error = result.getError();\n * if (error) {\n * // Log error with metadata\n * console.error({\n * code: error.code,\n * message: error.message,\n * metadata: error.metadata\n * });\n * }\n * }\n * }\n * ```\n */\n public getError(): E | undefined {\n return this._error;\n }\n\n /**\n * Returns the value if present, otherwise undefined.\n *\n * **Note:** Always check `isSuccess` before calling this method to ensure\n * the result is actually a success. This method will return `undefined` for\n * failed results.\n *\n * @returns {T | undefined} The value or undefined if failed.\n *\n * @example\n * ```typescript\n * const result = Result.ok({ id: 1, name: 'John' });\n *\n * if (result.isSuccess) {\n * const user = result.getValue();\n * if (user) {\n * console.log(`User: ${user.name} (ID: ${user.id})`);\n * }\n * }\n * ```\n *\n * @example\n * ```typescript\n * // Type-safe value extraction\n * function processUser(result: Result<User, DomainError>): void {\n * if (result.isSuccess) {\n * const user = result.getValue();\n * // TypeScript knows user is User | undefined here\n * if (user) {\n * // Process the user\n * userRepository.save(user);\n * }\n * }\n * }\n * ```\n *\n * @example\n * ```typescript\n * // Using non-null assertion (use with caution)\n * const result = Result.ok(42);\n * if (result.isSuccess) {\n * const value = result.getValue()!; // Safe because we checked isSuccess\n * console.log(value * 2); // 84\n * }\n * ```\n */\n public getValue(): T | undefined {\n return this._value;\n }\n\n /**\n * Type guard for failure.\n */\n public isFailureResult(): this is Result<never, E> {\n return this.isFailure;\n }\n\n /**\n * Type guard for success.\n */\n public isSuccessResult(): this is Result<T, never> {\n return this.isSuccess;\n }\n}\n","import {\n DomainError,\n DomainErrorCode,\n DomainErrorType,\n Metadata,\n Primitive,\n} from '@/shared';\n\ninterface ExtraProps extends Record<string, Primitive> {\n entityId?: string;\n entityType?: string;\n}\n\ntype Props = Metadata<ExtraProps>;\n/**\n * Custom error class for entity validation failures.\n */\nexport class EntityValidationError extends DomainError<Props> {\n public code: DomainErrorCode = 'CORE.VALIDATION_FAILED';\n public type: DomainErrorType = 'DOMAIN.INVALID_STATE';\n\n public constructor(message: string, props: Props) {\n super(message, props);\n }\n\n public static create(msg: string, props: Props) {\n return new EntityValidationError(msg, props);\n }\n}\n","import {\n DomainError,\n DomainErrorCode,\n DomainErrorType,\n Metadata,\n} from '@/shared';\n\ntype Params = {\n value: string;\n};\n\ntype Props = Metadata<Params>;\nexport class InvalidValueObjectError extends DomainError<Props> {\n public code = 'DOMAIN.INVALID_VALUE' as DomainErrorCode;\n public type: DomainErrorType = 'DOMAIN.INVALID_VALUE';\n\n public static create(\n msg = 'Provided value object is incorrect',\n meta?: Props,\n ) {\n return new InvalidValueObjectError(msg, meta);\n }\n}\n","import { randomUUID } from 'node:crypto';\n\nimport { deepFreeze } from '@/utils';\n\nimport { EntityId } from '../types';\n\ntype Primitive = boolean | number | string | null;\n\ntype Serializable =\n | Primitive\n | Serializable[]\n | { [key: string]: Serializable };\n\nexport type DomainEventPayload = Record<string, Serializable>;\n\nexport type UnixTimestampMillis = number;\n\ntype DomainEventProps<Payload, AggregateId extends EntityId> = {\n id?: string;\n aggregateId: AggregateId;\n schemaVersion: number;\n occurredAt: UnixTimestampMillis;\n payload: Payload;\n};\n\nexport type CreateEventProps<\n EventProps,\n ID extends EntityId,\n> = DomainEventProps<EventProps, ID>;\n\n// Abstract base class for domain events\nexport abstract class DomainEvent<\n AggregateId extends EntityId = EntityId,\n T extends DomainEventPayload = DomainEventPayload,\n> {\n public readonly aggregateId: AggregateId;\n\n public abstract readonly eventName: string;\n public readonly id: string;\n public readonly occurredAt: number;\n public readonly payload: Readonly<T>;\n public readonly schemaVersion: number;\n\n protected constructor(props: DomainEventProps<T, AggregateId>) {\n this.id = props.id ?? randomUUID();\n this.aggregateId = props.aggregateId;\n this.schemaVersion = props.schemaVersion;\n this.occurredAt = props.occurredAt;\n this.payload = deepFreeze(props.payload);\n }\n\n public toPrimitives(): Readonly<{\n id: string;\n eventName: string;\n aggregateId: string;\n schemaVersion: number;\n occurredAt: UnixTimestampMillis;\n payload: T;\n }> {\n return {\n aggregateId: this.aggregateId.toString(),\n schemaVersion: this.schemaVersion,\n occurredAt: this.occurredAt,\n eventName: this.eventName,\n payload: this.payload,\n id: this.id,\n };\n }\n}\n","import { v4 } from 'uuid';\nimport z from 'zod';\n\nimport { InvalidValueObjectError } from '../errors/invalid-vo.error';\nimport { PrimitiveValueObject } from '../base/primitive-vo';\n\n/**\n * Represents a UUID (Universally Unique Identifier) value object.\n *\n * This class extends PrimitiveValueObject to provide type-safe UUID handling\n * with validation using Zod schema. UUIDs are immutable and can be generated\n * randomly or created from string values.\n * @deprecated\n * @example\n * // Generate a new random UUID\n * const id = UUID.generate();\n *\n * @example\n * // Create UUID from an existing string\n * const id = UUID.fromString('550e8400-e29b-41d4-a716-446655440000');\n *\n * @throws {InvalidValueObjectError} When the provided string is not a valid UUID format\n */\nexport class UUID extends PrimitiveValueObject<string> {\n private static readonly schema = z.uuid();\n\n public constructor(value: string) {\n super(value);\n this.validate(value);\n }\n\n /**\n * Creates an UUID from an external string.\n * Use only for untrusted input.\n *\n * @param value - UUID string\n */\n public static fromString(value: string): UUID {\n return new this(value);\n }\n\n /**\n * Generates a new AggregateId.\n */\n public static generate<T extends typeof UUID>(this: T): InstanceType<T> {\n return new this(v4()) as InstanceType<T>;\n }\n\n protected validate(value: string): void {\n const result = UUID.schema.safeParse(value);\n\n if (!result.success) {\n throw InvalidValueObjectError.create(\n `Invalid ${this.constructor.name}: ${value}`,\n {\n value,\n },\n );\n }\n }\n}\n","import { UUID } from './id.vo';\n\n/**\n * AggregateId represents a strongly-typed aggregate identifier.\n *\n * - Backed by UUID v4\n * - Immutable\n * - Comparable only to AggregateId\n */\nexport class AggregateId extends UUID {}\n","import type { Tagged } from 'type-fest';\nimport { v4 } from 'uuid';\nimport z from 'zod';\n\nimport { InvalidValueObjectError } from '../errors/invalid-vo.error';\nimport { PrimitiveValueObject } from '../base/primitive-vo';\n\n/**\n * UUID is a branded string type.\n *\n * - Prevents accidental use of arbitrary strings\n * - Requires explicit validation or construction\n * - Zero runtime cost after creation\n */\n\nexport type UuID = Tagged<string, 'UUID'>;\n\n/**\n * Abstract base class for all domain identifiers.\n *\n * Responsibilities:\n * - Enforces that every DomainID wraps a primitive string value.\n * - Provides a type-safe static factory `fromString` for creating concrete IDs.\n * - Leaves domain-specific validation to subclasses via `validate`.\n *\n * Design Notes:\n * - The class cannot know how to validate the ID itself, because validation\n * rules differ between ID types (e.g., UUID v4, ULID, NanoID).\n * - Static factory uses `new this(value)` pattern; hence, base class is **not abstract** in TypeScript terms.\n * - Subclasses must implement `validate(value: string)` inherited from PrimitiveValueObject.\n *\n * Usage:\n * ```ts\n * class AuthAttemptId extends DomainID {\n * protected validate(value: string): void {\n * if (!isValidUuid(value)) {\n * throw new Error('Invalid AuthAttemptId');\n * }\n * }\n * }\n *\n * const id = AuthAttemptId.fromString('550e8400-e29b-41d4-a716-446655440000');\n * ```\n */\nexport abstract class DomainID extends PrimitiveValueObject<UuID> {\n public static schema = z.uuid();\n\n public constructor(value: string) {\n super(value as UuID);\n }\n\n /**\n * Creates a concrete DomainID from a trusted string value.\n *\n * - Validation is enforced in the subclass constructor.\n * - Intended for application or infrastructure layers to produce IDs.\n *\n * @template T - Concrete subclass of DomainID\n * @param this - The constructor of the concrete subclass\n * @param value - Raw string value of the ID\n * @returns Instance of the concrete DomainID subclass\n */\n public static fromString<T extends new (value: string) => DomainID>(\n this: T,\n value: string,\n ): InstanceType<T> {\n return new this(value) as InstanceType<T>;\n }\n\n public static generate<T extends new (value: string) => DomainID>(\n this: T,\n ): InstanceType<T> {\n return new this(v4()) as InstanceType<T>;\n }\n\n protected validate(value: UuID): void {\n const result = DomainID.schema.safeParse(value);\n\n if (!result.success) {\n throw InvalidValueObjectError.create(`Invalid UUID: ${value}`);\n }\n }\n}\n","import z from 'zod';\n\nimport { InvalidValueObjectError } from '../errors/invalid-vo.error';\nimport { PrimitiveValueObject } from '../base/primitive-vo';\n\nexport class Email extends PrimitiveValueObject<string> {\n private static readonly schema = z.email();\n\n public constructor(value: string) {\n super(value);\n this.validate(value);\n }\n\n public static fromString(value: string): Email {\n return new this(value);\n }\n\n protected validate(value: string): void {\n const result = Email.schema.safeParse(value);\n\n if (!result.success) {\n throw InvalidValueObjectError.create(\n `Invalid ${this.constructor.name}: ${value}`,\n {\n value,\n },\n );\n }\n }\n}\n","/**\n * HTTP status code catalog.\n *\n * This object provides a typed, immutable map of standard HTTP status names\n * to their numeric codes. Designed for server-side frameworks such as Fastify.\n *\n * - All identifiers use clear, canonical semantic names.\n * - Values are numeric status codes.\n * - Frozen to prevent runtime mutation.\n * - Exporting `HttpStatus` ensures type-safe usage across the codebase.\n * Usage:\n * ```ts\n * import { HttpStatus } from 'path-to-this-file';\n *\n * function handleRequest() {\n * return {\n * statusCode: HttpStatus.OK,\n * body: 'Success',\n * };\n * }\n * ```\n */\nexport const HttpStatus = Object.freeze({\n REQUEST_HEADER_FIELDS_TOO_LARGE: 431,\n NETWORK_AUTHENTICATION_REQUIRED: 511,\n NON_AUTHORITATIVE_INFORMATION: 203,\n PROXY_AUTHENTICATION_REQUIRED: 407,\n\n UNAVAILABLE_FOR_LEGAL_REASONS: 451,\n HTTP_VERSION_NOT_SUPPORTED: 505,\n BANDWIDTH_LIMIT_EXCEEDED: 509,\n VARIANT_ALSO_NEGOTIATES: 506,\n UNSUPPORTED_MEDIA_TYPE: 415,\n RANGE_NOT_SATISFIABLE: 416,\n PRECONDITION_REQUIRED: 428,\n INTERNAL_SERVER_ERROR: 500,\n UNPROCESSABLE_ENTITY: 422,\n INSUFFICIENT_STORAGE: 507,\n\n SWITCHING_PROTOCOLS: 101,\n PRECONDITION_FAILED: 412,\n MISDIRECTED_REQUEST: 421,\n SERVICE_UNAVAILABLE: 503,\n TEMPORARY_REDIRECT: 307,\n PERMANENT_REDIRECT: 308,\n METHOD_NOT_ALLOWED: 405,\n EXPECTATION_FAILED: 417,\n\n MOVED_PERMANENTLY: 301,\n PAYLOAD_TOO_LARGE: 413,\n FAILED_DEPENDENCY: 424,\n TOO_MANY_REQUESTS: 429,\n ALREADY_REPORTED: 208,\n MULTIPLE_CHOICES: 300,\n PAYMENT_REQUIRED: 402,\n UPGRADE_REQUIRED: 426,\n PARTIAL_CONTENT: 206,\n REQUEST_TIMEOUT: 408,\n LENGTH_REQUIRED: 411,\n NOT_IMPLEMENTED: 501,\n GATEWAY_TIMEOUT: 504,\n NOT_ACCEPTABLE: 406,\n RESET_CONTENT: 205,\n LOOP_DETECTED: 508,\n MULTI_STATUS: 207,\n NOT_MODIFIED: 304,\n UNAUTHORIZED: 401,\n URI_TOO_LONG: 414,\n NOT_EXTENDED: 510,\n EARLY_HINTS: 103,\n BAD_REQUEST: 400,\n IM_A_TEAPOT: 418,\n BAD_GATEWAY: 502,\n PROCESSING: 102,\n NO_CONTENT: 204,\n SEE_OTHER: 303,\n USE_PROXY: 305,\n\n FORBIDDEN: 403,\n NOT_FOUND: 404,\n TOO_EARLY: 425,\n CONTINUE: 100,\n ACCEPTED: 202,\n CONFLICT: 409,\n CREATED: 201,\n IM_USED: 226,\n LOCKED: 423,\n FOUND: 302,\n GONE: 410,\n OK: 200,\n} as const);\n\n/**\n * HTTP status messages mapped by numeric code.\n * Use for sending descriptive text in responses or logging.\n */\nexport const HttpStatusMessage = {\n 431: 'Request Header Fields Too Large',\n 511: 'Network Authentication Required',\n 203: 'Non-Authoritative Information',\n 407: 'Proxy Authentication Required',\n 451: 'Unavailable For Legal Reasons',\n 505: 'HTTP Version Not Supported',\n 509: 'Bandwidth Limit Exceeded',\n 506: 'Variant Also Negotiates',\n 415: 'Unsupported Media Type',\n 416: 'Range Not Satisfiable',\n 428: 'Precondition Required',\n 500: 'Internal Server Error',\n 422: 'Unprocessable Entity',\n 507: 'Insufficient Storage',\n 101: 'Switching Protocols',\n 412: 'Precondition Failed',\n 421: 'Misdirected Request',\n 503: 'Service Unavailable',\n 307: 'Temporary Redirect',\n 308: 'Permanent Redirect',\n 405: 'Method Not Allowed',\n 417: 'Expectation Failed',\n 301: 'Moved Permanently',\n 413: 'Payload Too Large',\n 424: 'Failed Dependency',\n 429: 'Too Many Requests',\n 208: 'Already Reported',\n 300: 'Multiple Choices',\n 402: 'Payment Required',\n 426: 'Upgrade Required',\n 206: 'Partial Content',\n 408: 'Request Timeout',\n 411: 'Length Required',\n 501: 'Not Implemented',\n 504: 'Gateway Timeout',\n 406: 'Not Acceptable',\n 205: 'Reset Content',\n 508: 'Loop Detected',\n 207: 'Multi-Status',\n 304: 'Not Modified',\n 401: 'Unauthorized',\n 414: 'URI Too Long',\n 418: \"I'm a Teapot\",\n 510: 'Not Extended',\n 103: 'Early Hints',\n 400: 'Bad Request',\n 502: 'Bad Gateway',\n 102: 'Processing',\n 204: 'No Content',\n 303: 'See Other',\n 305: 'Use Proxy',\n 403: 'Forbidden',\n 404: 'Not Found',\n 425: 'Too Early',\n 100: 'Continue',\n 202: 'Accepted',\n 226: \"I'm Used\",\n 409: 'Conflict',\n 201: 'Created',\n 423: 'Locked',\n 302: 'Found',\n 410: 'Gone',\n 200: 'OK',\n} as const;\n\nexport type HttpStatusCode = keyof typeof HttpStatusMessage;\n\nexport type HttpStatusMessage =\n (typeof HttpStatusMessage)[keyof typeof HttpStatusMessage];\n"],"mappings":"2UA+BO,IAAeA,EAAf,cAAwC,KAAM,CAUnD,YAAY,CACV,cAAAC,EAAgB,GAChB,SAAAC,EACA,QAAAC,EACA,MAAAC,EACA,KAAAC,C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AAK,uBACL,IAAK,uBACL,IAAK,sBACL,IAAK,sBACL,IAAK,sBACL,IAAK,sBACL,IAAK,qBACL,IAAK,qBACL,IAAK,qBACL,IAAK,qBACL,IAAK,oBACL,IAAK,oBACL,IAAK,oBACL,IAAK,oBACL,IAAK,mBACL,IAAK,mBACL,IAAK,mBACL,IAAK,mBACL,IAAK,kBACL,IAAK,kBACL,IAAK,kBACL,IAAK,kBACL,IAAK,kBACL,IAAK,iBACL,IAAK,gBACL,IAAK,gBACL,IAAK,eACL,IAAK,eACL,IAAK,eACL,IAAK,eACL,IAAK,eACL,IAAK,eACL,IAAK,cACL,IAAK,cACL,IAAK,cACL,IAAK,aACL,IAAK,aACL,IAAK,YACL,IAAK,YACL,IAAK,YACL,IAAK,YACL,IAAK,YACL,IAAK,WACL,IAAK,WACL,IAAK,WACL,IAAK,WACL,IAAK,UACL,IAAK,SACL,IAAK,QACL,IAAK,OACL,IAAK,IACP","names":["ApplicationError","isOperational","metadata","message","cause","code","deepFreeze","value","seen","item","key","_props","Entity","params","__privateAdd","_a","__privateSet","deepFreeze","__privateGet","other","updater","next","AggregateRoot","Entity","domainEvent","events","_value","_PrimitiveValueObject","value","__privateAdd","__privateSet","__privateGet","other","PrimitiveValueObject","deepEqual","ValueObject","_ValueObject","props","deepFreeze","vo","other","deepEqual","DomainError","_DomainError","message","args","_a","error","InternalError","DomainError","message","metadata","InvalidStateError","DomainError","message","InvalidValueError","DomainError","msg","meta","TimeoutError","DomainError","message","metadata","Result","_Result","params","hasError","error","value","EntityValidationError","_EntityValidationError","DomainError","message","props","msg","InvalidValueObjectError","_InvalidValueObjectError","DomainError","msg","meta","randomUUID","DomainEvent","props","_a","randomUUID","deepFreeze","v4","z","_UUID","PrimitiveValueObject","value","v4","InvalidValueObjectError","z","UUID","AggregateId","UUID","v4","z","_DomainID","PrimitiveValueObject","value","v4","InvalidValueObjectError","z","DomainID","z","_Email","PrimitiveValueObject","value","InvalidValueObjectError","z","Email","HttpStatus","HttpStatusMessage"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rineex/ddd",
3
- "version": "3.0.0",
3
+ "version": "3.1.0",
4
4
  "description": "Domain Driven Design package for Rineex core modules",
5
5
  "author": "Rineex Team",
6
6
  "main": "./dist/index.js",