'use strict';

// src/core/result/constants/result.constants.ts
var ErrorCodes = {
  FAILURE: "FAILURE",
  UNEXPECTED: "UNEXPECTED",
  UNAUTHORIZED: "UNAUTHORIZED",
  FORBIDDEN: "FORBIDDEN",
  ALREADY: "ALREADY",
  NOT_FOUND: "NOT_FOUND",
  BAD_PREREQUISITES: "BAD_PREREQUISITES",
  BAD_PARAMETERS: "BAD_PARAMETERS",
  CANCELLED: "CANCELLED",
  TIMEOUT: "TIMEOUT",
  NO_CONNECTION: "NO_CONNECTION",
  NOT_IMPLEMENTED: "NOT_IMPLEMENTED",
  RATE_LIMITED: "RATE_LIMITED",
  CIRCUIT_OPEN: "CIRCUIT_OPEN",
  BULKHEAD_REJECTED: "BULKHEAD_REJECTED",
  VALIDATION_ERROR: "VALIDATION_ERROR",
  CONFLICT: "CONFLICT",
  UNKNOWN: "UNKNOWN",
  MAP_ERROR: "MAP_ERROR",
  SERVICE_ERROR: "SERVICE_ERROR",
  OPERATION_CANCELLED: "OPERATION_CANCELLED",
  SERVICE_NOT_RUNNING: "SERVICE_NOT_RUNNING",
  INVALID_STATE: "INVALID_STATE",
  START_FAILED: "START_FAILED",
  STOP_FAILED: "STOP_FAILED"
};
var DefaultMessages = {
  [ErrorCodes.FAILURE]: "Operation failed",
  [ErrorCodes.UNEXPECTED]: "An unexpected error occurred",
  [ErrorCodes.UNAUTHORIZED]: "Unauthorized access",
  [ErrorCodes.FORBIDDEN]: "Access forbidden",
  [ErrorCodes.ALREADY]: "Operation already completed",
  [ErrorCodes.NOT_FOUND]: "Resource not found",
  [ErrorCodes.BAD_PREREQUISITES]: "Prerequisites not met",
  [ErrorCodes.BAD_PARAMETERS]: "Invalid parameters",
  [ErrorCodes.CANCELLED]: "Operation cancelled",
  [ErrorCodes.TIMEOUT]: "Operation timed out",
  [ErrorCodes.NO_CONNECTION]: "No connection available",
  [ErrorCodes.NOT_IMPLEMENTED]: "Operation not implemented",
  [ErrorCodes.RATE_LIMITED]: "Rate limit exceeded",
  [ErrorCodes.CIRCUIT_OPEN]: "Circuit breaker is open",
  [ErrorCodes.BULKHEAD_REJECTED]: "Bulkhead rejected request",
  [ErrorCodes.VALIDATION_ERROR]: "Validation failed",
  [ErrorCodes.CONFLICT]: "Resource conflict",
  [ErrorCodes.UNKNOWN]: "Unknown error"
};
var HttpStatusCodes = {
  OK: 200,
  CREATED: 201,
  ACCEPTED: 202,
  NO_CONTENT: 204,
  BAD_REQUEST: 400,
  UNAUTHORIZED: 401,
  FORBIDDEN: 403,
  NOT_FOUND: 404,
  REQUEST_TIMEOUT: 408,
  CONFLICT: 409,
  PRECONDITION_FAILED: 412,
  TOO_MANY_REQUESTS: 429,
  CLIENT_CLOSED_REQUEST: 499,
  INTERNAL_SERVER_ERROR: 500,
  NOT_IMPLEMENTED: 501,
  SERVICE_UNAVAILABLE: 503
};
var TimingDefaults = {
  DEFAULT_TIMEOUT_MS: 3e4,
  DEFAULT_RETRY_DELAY_MS: 100,
  DEFAULT_MAX_RETRY_DELAY_MS: 3e4,
  DEFAULT_CIRCUIT_RESET_MS: 3e4,
  DEFAULT_RATE_LIMIT_WINDOW_MS: 6e4,
  DEFAULT_LOCK_TIMEOUT_MS: 3e4,
  DEFAULT_RECOVERY_DELAY_MS: 5e3,
  DEFAULT_CACHE_TTL_MS: 3e5
};
var RetryDefaults = {
  MAX_ATTEMPTS: 3,
  BACKOFF_MULTIPLIER: 2,
  JITTER_FACTOR: 0.1,
  MAX_JITTER_FACTOR: 0.5
};
var CircuitBreakerDefaults = {
  FAILURE_THRESHOLD: 5,
  SUCCESS_THRESHOLD: 2,
  HALF_OPEN_MAX_ATTEMPTS: 3,
  SAMPLING_DURATION_MS: 6e4
};
var BulkheadDefaults = {
  MAX_CONCURRENT: 10,
  MAX_QUEUE_SIZE: 100,
  QUEUE_TIMEOUT_MS: 3e4
};
var RateLimitDefaults = {
  REQUESTS_PER_WINDOW: 100,
  WINDOW_SIZE_MS: 6e4,
  BUCKET_CAPACITY: 100,
  REFILL_RATE: 10
};
var ServiceDefaults = {
  INSTANCE_KEY: "default",
  STREAMING_NAMESPACE: "/",
  MAX_RECOVERY_ATTEMPTS: 3,
  AUTO_RECOVER: true,
  ENABLE_STREAMING: false
};

// src/core/result/enums/ResultStatus.ts
var ResultStatus = /* @__PURE__ */ ((ResultStatus3) => {
  ResultStatus3["NONE"] = "NONE";
  ResultStatus3["SUCCESS"] = "SUCCESS";
  ResultStatus3["FAILURE"] = "FAILURE";
  ResultStatus3["UNEXPECTED"] = "UNEXPECTED";
  ResultStatus3["PENDING"] = "PENDING";
  ResultStatus3["TIMEOUT"] = "TIMEOUT";
  ResultStatus3["UNAUTHORIZED"] = "UNAUTHORIZED";
  ResultStatus3["ALREADY"] = "ALREADY";
  ResultStatus3["VALIDATION_ERROR"] = "VALIDATION_ERROR";
  ResultStatus3["NOT_FOUND"] = "NOT_FOUND";
  ResultStatus3["BAD_PREREQUISITES"] = "BAD_PREREQUISITES";
  ResultStatus3["BAD_PARAMETERS"] = "BAD_PARAMETERS";
  ResultStatus3["CANCELLED"] = "CANCELLED";
  ResultStatus3["RATE_LIMITED"] = "RATE_LIMITED";
  ResultStatus3["SERVICE_UNAVAILABLE"] = "SERVICE_UNAVAILABLE";
  ResultStatus3["NO_CONNECTION"] = "NO_CONNECTION";
  ResultStatus3["NOT_IMPLEMENTED"] = "NOT_IMPLEMENTED";
  ResultStatus3["FORBIDDEN"] = "FORBIDDEN";
  ResultStatus3["CONFLICT"] = "CONFLICT";
  ResultStatus3["CIRCUIT_OPEN"] = "CIRCUIT_OPEN";
  ResultStatus3["BULKHEAD_REJECTED"] = "BULKHEAD_REJECTED";
  return ResultStatus3;
})(ResultStatus || {});
function isSuccessStatus(status) {
  return status === "SUCCESS" /* SUCCESS */;
}
function isNotSuccessStatus(status) {
  return status !== "SUCCESS" /* SUCCESS */;
}
function isUnexpectedStatus(status) {
  return status === "UNEXPECTED" /* UNEXPECTED */;
}
function isValidationErrorStatus(status) {
  return status === "VALIDATION_ERROR" /* VALIDATION_ERROR */ || status === "BAD_PARAMETERS" /* BAD_PARAMETERS */ || status === "BAD_PREREQUISITES" /* BAD_PREREQUISITES */;
}
function isNetworkErrorStatus(status) {
  return status === "NO_CONNECTION" /* NO_CONNECTION */ || status === "TIMEOUT" /* TIMEOUT */ || status === "SERVICE_UNAVAILABLE" /* SERVICE_UNAVAILABLE */;
}
function isRetryableStatus(status) {
  return status === "TIMEOUT" /* TIMEOUT */ || status === "RATE_LIMITED" /* RATE_LIMITED */ || status === "SERVICE_UNAVAILABLE" /* SERVICE_UNAVAILABLE */ || status === "NO_CONNECTION" /* NO_CONNECTION */ || status === "CIRCUIT_OPEN" /* CIRCUIT_OPEN */ || status === "BULKHEAD_REJECTED" /* BULKHEAD_REJECTED */;
}
function isTerminalStatus(status) {
  return status === "FAILURE" /* FAILURE */ || status === "UNAUTHORIZED" /* UNAUTHORIZED */ || status === "FORBIDDEN" /* FORBIDDEN */ || status === "VALIDATION_ERROR" /* VALIDATION_ERROR */ || status === "BAD_PARAMETERS" /* BAD_PARAMETERS */ || status === "BAD_PREREQUISITES" /* BAD_PREREQUISITES */ || status === "NOT_FOUND" /* NOT_FOUND */ || status === "ALREADY" /* ALREADY */ || status === "CONFLICT" /* CONFLICT */ || status === "CANCELLED" /* CANCELLED */ || status === "NOT_IMPLEMENTED" /* NOT_IMPLEMENTED */;
}
function isUnauthorizedStatus(status) {
  return status === "UNAUTHORIZED" /* UNAUTHORIZED */;
}
function isForbiddenStatus(status) {
  return status === "FORBIDDEN" /* FORBIDDEN */;
}
function isNotFoundStatus(status) {
  return status === "NOT_FOUND" /* NOT_FOUND */;
}
function isAlreadyStatus(status) {
  return status === "ALREADY" /* ALREADY */;
}
function isCancelledStatus(status) {
  return status === "CANCELLED" /* CANCELLED */;
}
function isTimeoutStatus(status) {
  return status === "TIMEOUT" /* TIMEOUT */;
}
function isPendingStatus(status) {
  return status === "PENDING" /* PENDING */;
}
function isNotImplementedStatus(status) {
  return status === "NOT_IMPLEMENTED" /* NOT_IMPLEMENTED */;
}
function isRateLimitedStatus(status) {
  return status === "RATE_LIMITED" /* RATE_LIMITED */;
}
function isCircuitOpenStatus(status) {
  return status === "CIRCUIT_OPEN" /* CIRCUIT_OPEN */;
}
function isBulkheadRejectedStatus(status) {
  return status === "BULKHEAD_REJECTED" /* BULKHEAD_REJECTED */;
}
function toHttpStatusCode(status) {
  const mapping = {
    ["NONE" /* NONE */]: HttpStatusCodes.INTERNAL_SERVER_ERROR,
    ["SUCCESS" /* SUCCESS */]: HttpStatusCodes.OK,
    ["FAILURE" /* FAILURE */]: HttpStatusCodes.INTERNAL_SERVER_ERROR,
    ["UNEXPECTED" /* UNEXPECTED */]: HttpStatusCodes.INTERNAL_SERVER_ERROR,
    ["PENDING" /* PENDING */]: HttpStatusCodes.ACCEPTED,
    ["TIMEOUT" /* TIMEOUT */]: HttpStatusCodes.REQUEST_TIMEOUT,
    ["UNAUTHORIZED" /* UNAUTHORIZED */]: HttpStatusCodes.UNAUTHORIZED,
    ["FORBIDDEN" /* FORBIDDEN */]: HttpStatusCodes.FORBIDDEN,
    ["ALREADY" /* ALREADY */]: HttpStatusCodes.CONFLICT,
    ["CONFLICT" /* CONFLICT */]: HttpStatusCodes.CONFLICT,
    ["VALIDATION_ERROR" /* VALIDATION_ERROR */]: HttpStatusCodes.BAD_REQUEST,
    ["NOT_FOUND" /* NOT_FOUND */]: HttpStatusCodes.NOT_FOUND,
    ["BAD_PREREQUISITES" /* BAD_PREREQUISITES */]: HttpStatusCodes.PRECONDITION_FAILED,
    ["BAD_PARAMETERS" /* BAD_PARAMETERS */]: HttpStatusCodes.BAD_REQUEST,
    ["CANCELLED" /* CANCELLED */]: HttpStatusCodes.CLIENT_CLOSED_REQUEST,
    ["RATE_LIMITED" /* RATE_LIMITED */]: HttpStatusCodes.TOO_MANY_REQUESTS,
    ["SERVICE_UNAVAILABLE" /* SERVICE_UNAVAILABLE */]: HttpStatusCodes.SERVICE_UNAVAILABLE,
    ["NO_CONNECTION" /* NO_CONNECTION */]: HttpStatusCodes.SERVICE_UNAVAILABLE,
    ["NOT_IMPLEMENTED" /* NOT_IMPLEMENTED */]: HttpStatusCodes.NOT_IMPLEMENTED,
    ["CIRCUIT_OPEN" /* CIRCUIT_OPEN */]: HttpStatusCodes.SERVICE_UNAVAILABLE,
    ["BULKHEAD_REJECTED" /* BULKHEAD_REJECTED */]: HttpStatusCodes.SERVICE_UNAVAILABLE
  };
  return mapping[status] ?? HttpStatusCodes.INTERNAL_SERVER_ERROR;
}

// src/core/result/interfaces/IAggregatedError.ts
function isAggregatedError(error) {
  return error !== void 0 && "errors" in error && Array.isArray(error.errors);
}

// src/core/result/interfaces/IRetryOptions.ts
var DefaultRetryOptions = {
  maxAttempts: 3,
  baseDelayMs: 100,
  maxDelayMs: 3e4,
  backoffMultiplier: 2,
  jitterFactor: 0.1
};

// src/core/result/value-objects/PaginationInfo.ts
var PaginationInfo = class _PaginationInfo {
  /**
   * Current page number (1-indexed).
   * @readonly
   */
  page;
  /**
   * Number of items per page.
   * @readonly
   */
  pageSize;
  /**
   * Total number of items across all pages.
   * @readonly
   */
  totalItems;
  /**
   * Total number of pages.
   * @readonly
   */
  totalPages;
  /**
   * Whether there is a next page.
   * @readonly
   */
  hasNextPage;
  /**
   * Whether there is a previous page.
   * @readonly
   */
  hasPreviousPage;
  /**
   * Creates a new PaginationInfo instance.
   *
   * @param page - Current page number (1-indexed).
   * @param pageSize - Number of items per page.
   * @param totalItems - Total number of items across all pages.
   * @private
   */
  constructor(page, pageSize, totalItems) {
    this.page = page;
    this.pageSize = pageSize;
    this.totalItems = totalItems;
    this.totalPages = Math.ceil(totalItems / pageSize);
    this.hasNextPage = page < this.totalPages;
    this.hasPreviousPage = page > 1;
  }
  // ═══════════════════════════════════════════════════════════════════════════
  // Static Factory Methods
  // ═══════════════════════════════════════════════════════════════════════════
  /**
   * Creates a new PaginationInfo from parameters.
   *
   * @param page - Current page number (1-indexed).
   * @param pageSize - Items per page.
   * @param totalItems - Total items across all pages.
   * @returns New PaginationInfo instance.
   */
  static create(page, pageSize, totalItems) {
    return new _PaginationInfo(page, pageSize, totalItems);
  }
  /**
   * Creates an empty PaginationInfo (no items).
   *
   * @param pageSize - Items per page (default: 10).
   * @returns Empty PaginationInfo.
   */
  static empty(pageSize = 10) {
    return new _PaginationInfo(1, pageSize, 0);
  }
  /**
   * Creates PaginationInfo from offset-based pagination.
   *
   * @param offset - Number of items to skip.
   * @param limit - Number of items per page.
   * @param totalItems - Total items.
   * @returns PaginationInfo with calculated page.
   */
  static fromOffset(offset, limit, totalItems) {
    const page = Math.floor(offset / limit) + 1;
    return new _PaginationInfo(page, limit, totalItems);
  }
  // ═══════════════════════════════════════════════════════════════════════════
  // Computed Properties
  // ═══════════════════════════════════════════════════════════════════════════
  /**
   * Gets the offset for database queries.
   * @returns Number of items to skip.
   */
  get offset() {
    return (this.page - 1) * this.pageSize;
  }
  /**
   * Gets the limit for database queries.
   * @returns Number of items to take.
   */
  get limit() {
    return this.pageSize;
  }
  /**
   * Gets the first item number on the current page (1-indexed).
   * @returns First item number.
   */
  get firstItem() {
    if (this.totalItems === 0) return 0;
    return this.offset + 1;
  }
  /**
   * Gets the last item number on the current page (1-indexed).
   * @returns Last item number.
   */
  get lastItem() {
    return Math.min(this.offset + this.pageSize, this.totalItems);
  }
  /**
   * Whether there are any items.
   * @returns True if totalItems > 0.
   */
  get hasItems() {
    return this.totalItems > 0;
  }
  // ═══════════════════════════════════════════════════════════════════════════
  // Navigation Methods
  // ═══════════════════════════════════════════════════════════════════════════
  /**
   * Gets pagination for next page.
   * @returns PaginationInfo for next page or this if no next page.
   */
  nextPage() {
    if (!this.hasNextPage) return this;
    return new _PaginationInfo(this.page + 1, this.pageSize, this.totalItems);
  }
  /**
   * Gets pagination for previous page.
   * @returns PaginationInfo for previous page or this if no previous page.
   */
  previousPage() {
    if (!this.hasPreviousPage) return this;
    return new _PaginationInfo(this.page - 1, this.pageSize, this.totalItems);
  }
  /**
   * Gets pagination for first page.
   * @returns PaginationInfo for first page.
   */
  firstPage() {
    return new _PaginationInfo(1, this.pageSize, this.totalItems);
  }
  /**
   * Gets pagination for last page.
   * @returns PaginationInfo for last page.
   */
  lastPage() {
    return new _PaginationInfo(this.totalPages || 1, this.pageSize, this.totalItems);
  }
  /**
   * Gets pagination for a specific page.
   * @param page - Target page number.
   * @returns PaginationInfo for specified page, clamped to valid range.
   */
  goToPage(page) {
    const clampedPage = Math.max(1, Math.min(page, this.totalPages || 1));
    return new _PaginationInfo(clampedPage, this.pageSize, this.totalItems);
  }
  // ═══════════════════════════════════════════════════════════════════════════
  // Serialization
  // ═══════════════════════════════════════════════════════════════════════════
  /**
   * Converts to plain object.
   * @returns Plain object representation.
   */
  toJSON() {
    return {
      page: this.page,
      pageSize: this.pageSize,
      totalItems: this.totalItems,
      totalPages: this.totalPages,
      hasNextPage: this.hasNextPage,
      hasPreviousPage: this.hasPreviousPage
    };
  }
  /**
   * Creates from plain object.
   * @param dto - Plain object representation.
   * @returns PaginationInfo instance.
   */
  static fromJSON(dto) {
    return new _PaginationInfo(dto.page, dto.pageSize, dto.totalItems);
  }
  /**
   * Checks equality with another PaginationInfo.
   * @param other - PaginationInfo to compare.
   * @returns True if all values are equal.
   */
  equals(other) {
    return this.page === other.page && this.pageSize === other.pageSize && this.totalItems === other.totalItems;
  }
  /**
   * String representation.
   * @returns Formatted string.
   */
  toString() {
    return `Page ${this.page} of ${this.totalPages} (${this.totalItems} items)`;
  }
};

// src/core/result/exceptions/ResultException.ts
var ResultException = class _ResultException extends Error {
  /**
   * Unique identifier for this error type.
   * @readonly
   */
  name = "ResultException";
  /**
   * The result status that caused this exception.
   * @readonly
   */
  status;
  /**
   * The reason/message for the failure.
   * @readonly
   */
  reason;
  /**
   * Structured error details.
   * @readonly
   */
  errorDetail;
  /**
   * The original exception if this was caused by an unexpected error.
   * @readonly
   */
  innerError;
  /**
   * Additional data associated with the result.
   * @readonly
   */
  data;
  /**
   * Correlation ID for tracing.
   * @readonly
   */
  correlationId;
  /**
   * Creates a new ResultException.
   *
   * @param status - The result status that caused this exception.
   * @param error - Optional structured error details.
   * @param innerError - Optional inner exception that caused this error.
   * @param data - Optional additional data associated with the result.
   */
  constructor(status, error, innerError, data) {
    const message = error?.message ?? `Operation failed with status: ${status}`;
    super(message);
    this.status = status;
    this.reason = error?.message;
    this.errorDetail = error;
    this.innerError = innerError;
    this.data = data;
    this.correlationId = error?.correlationId;
    if ("captureStackTrace" in Error && typeof Error.captureStackTrace === "function") {
      Error.captureStackTrace(this, _ResultException);
    }
    Object.setPrototypeOf(this, _ResultException.prototype);
  }
  // ═══════════════════════════════════════════════════════════════════════════
  // Static Factory Methods
  // ═══════════════════════════════════════════════════════════════════════════
  /**
   * Creates a ResultException from an unexpected error.
   *
   * @param error - The original error that occurred.
   * @param correlationId - Optional correlation ID for tracing.
   * @returns New ResultException with UNEXPECTED status.
   */
  static fromError(error, correlationId) {
    return new _ResultException(
      "UNEXPECTED" /* UNEXPECTED */,
      {
        code: ErrorCodes.UNEXPECTED,
        message: error.message,
        details: { name: error.name, stack: error.stack },
        timestamp: Date.now(),
        correlationId
      },
      error
    );
  }
  /**
   * Creates a not found exception.
   *
   * @param resourceType - Type of resource that was not found.
   * @param identifier - Identifier of the resource.
   * @param correlationId - Optional correlation ID for tracing.
   * @returns New ResultException with NOT_FOUND status.
   */
  static notFound(resourceType, identifier, correlationId) {
    return new _ResultException("NOT_FOUND" /* NOT_FOUND */, {
      code: ErrorCodes.NOT_FOUND,
      message: `${resourceType} with identifier '${identifier}' was not found`,
      details: { resourceType, identifier },
      timestamp: Date.now(),
      correlationId
    });
  }
  /**
   * Creates a validation exception.
   *
   * @param message - Validation error message.
   * @param details - Optional validation details.
   * @param correlationId - Optional correlation ID for tracing.
   * @returns New ResultException with VALIDATION_ERROR status.
   */
  static validationError(message, details, correlationId) {
    return new _ResultException("VALIDATION_ERROR" /* VALIDATION_ERROR */, {
      code: ErrorCodes.VALIDATION_ERROR,
      message,
      details,
      timestamp: Date.now(),
      correlationId
    });
  }
  /**
   * Creates an unauthorized exception.
   *
   * @param message - Optional custom message.
   * @param correlationId - Optional correlation ID for tracing.
   * @returns New ResultException with UNAUTHORIZED status.
   */
  static unauthorized(message = "Unauthorized access", correlationId) {
    return new _ResultException("UNAUTHORIZED" /* UNAUTHORIZED */, {
      code: ErrorCodes.UNAUTHORIZED,
      message,
      timestamp: Date.now(),
      correlationId
    });
  }
  /**
   * Creates a forbidden exception.
   *
   * @param message - Optional custom message.
   * @param correlationId - Optional correlation ID for tracing.
   * @returns New ResultException with FORBIDDEN status.
   */
  static forbidden(message = "Access forbidden", correlationId) {
    return new _ResultException("FORBIDDEN" /* FORBIDDEN */, {
      code: ErrorCodes.FORBIDDEN,
      message,
      timestamp: Date.now(),
      correlationId
    });
  }
  /**
   * Creates a timeout exception.
   *
   * @param operation - Name of the operation that timed out.
   * @param timeoutMs - Timeout duration in milliseconds.
   * @param correlationId - Optional correlation ID for tracing.
   * @returns New ResultException with TIMEOUT status.
   */
  static timeout(operation, timeoutMs, correlationId) {
    return new _ResultException("TIMEOUT" /* TIMEOUT */, {
      code: ErrorCodes.TIMEOUT,
      message: `Operation '${operation}' timed out after ${timeoutMs}ms`,
      details: { operation, timeoutMs },
      timestamp: Date.now(),
      correlationId
    });
  }
  // ═══════════════════════════════════════════════════════════════════════════
  // Type Guard
  // ═══════════════════════════════════════════════════════════════════════════
  /**
   * Type guard to check if an error is a ResultException.
   *
   * @param error - Error to check.
   * @returns True if error is a ResultException.
   */
  static isResultException(error) {
    return error instanceof _ResultException || error instanceof Error && error.name === "ResultException";
  }
  // ═══════════════════════════════════════════════════════════════════════════
  // Instance Methods
  // ═══════════════════════════════════════════════════════════════════════════
  /**
   * Gets the full error chain as a string.
   *
   * @returns Formatted error chain including inner errors.
   */
  getFullMessage() {
    let message = `[${this.status}] ${this.message}`;
    if (this.innerError) {
      message += `
  Caused by: ${this.innerError.message}`;
    }
    return message;
  }
  /**
   * Converts to a plain object for serialization.
   *
   * @returns Plain object representation suitable for JSON serialization.
   */
  toJSON() {
    return {
      name: this.name,
      status: this.status,
      message: this.message,
      reason: this.reason,
      errorDetail: this.errorDetail,
      correlationId: this.correlationId,
      data: this.data,
      stack: this.stack,
      innerError: this.innerError ? { name: this.innerError.name, message: this.innerError.message, stack: this.innerError.stack } : void 0
    };
  }
  toString() {
    return this.getFullMessage();
  }
};

// src/core/result/entities/Result.ts
var metricsListeners = /* @__PURE__ */ new Set();
function onResultMetrics(listener) {
  metricsListeners.add(listener);
  return () => metricsListeners.delete(listener);
}
function emitMetrics(metrics) {
  for (const listener of metricsListeners) {
    try {
      listener(metrics);
    } catch {
    }
  }
}
var Result = class _Result {
  // ═══════════════════════════════════════════════════════════════════════════
  // Instance Properties
  // ═══════════════════════════════════════════════════════════════════════════
  /** Whether the operation was successful. */
  success;
  /** The result status. */
  status;
  /** The success data (only present if success is true). */
  data;
  /** Error information (only present if success is false). */
  error;
  /** The reason in text why a not succeeded result occurred. */
  reason;
  /** Optional correlation ID for tracing. */
  correlationId;
  /** Timestamp when the result was created. */
  timestamp;
  /** The original exception if unexpected error. */
  exception;
  /** Duration of the operation in milliseconds (if tracked). */
  durationMs;
  // ═══════════════════════════════════════════════════════════════════════════
  // Constructor (private - use factory methods)
  // ═══════════════════════════════════════════════════════════════════════════
  constructor(success, status, data, error, correlationId, reason, exception, durationMs) {
    this.success = success;
    this.status = status;
    this.data = data;
    this.error = error;
    this.correlationId = correlationId ?? error?.correlationId;
    this.reason = reason ?? error?.message;
    this.exception = exception;
    this.timestamp = Date.now();
    this.durationMs = durationMs;
    emitMetrics({
      status: this.status,
      success: this.success,
      durationMs: this.durationMs ?? 0,
      correlationId: this.correlationId,
      retryable: isRetryableStatus(this.status),
      timestamp: this.timestamp
    });
  }
  // ═══════════════════════════════════════════════════════════════════════════
  // Static Shortcuts (C# Pattern)
  // ═══════════════════════════════════════════════════════════════════════════
  /** Creates a successful void result. */
  static get Success() {
    return new _Result(true, "SUCCESS" /* SUCCESS */, void 0);
  }
  /** Creates a failed void result. */
  static get Failure() {
    return new _Result(false, "FAILURE" /* FAILURE */, void 0, {
      code: ErrorCodes.FAILURE,
      message: DefaultMessages[ErrorCodes.FAILURE],
      timestamp: Date.now()
    });
  }
  /** Creates an unexpected error void result. */
  static get Unexpected() {
    return new _Result(false, "UNEXPECTED" /* UNEXPECTED */, void 0, {
      code: ErrorCodes.UNEXPECTED,
      message: DefaultMessages[ErrorCodes.UNEXPECTED],
      timestamp: Date.now()
    });
  }
  /** Creates an unauthorized void result. */
  static get Unauthorized() {
    return new _Result(false, "UNAUTHORIZED" /* UNAUTHORIZED */, void 0, {
      code: ErrorCodes.UNAUTHORIZED,
      message: DefaultMessages[ErrorCodes.UNAUTHORIZED],
      timestamp: Date.now()
    });
  }
  /** Creates a forbidden void result. */
  static get Forbidden() {
    return new _Result(false, "FORBIDDEN" /* FORBIDDEN */, void 0, {
      code: ErrorCodes.FORBIDDEN,
      message: DefaultMessages[ErrorCodes.FORBIDDEN],
      timestamp: Date.now()
    });
  }
  /** Creates an already-completed void result. */
  static get Already() {
    return new _Result(false, "ALREADY" /* ALREADY */, void 0, {
      code: ErrorCodes.ALREADY,
      message: DefaultMessages[ErrorCodes.ALREADY],
      timestamp: Date.now()
    });
  }
  /** Creates a not found void result. */
  static get NotFound() {
    return new _Result(false, "NOT_FOUND" /* NOT_FOUND */, void 0, {
      code: ErrorCodes.NOT_FOUND,
      message: DefaultMessages[ErrorCodes.NOT_FOUND],
      timestamp: Date.now()
    });
  }
  /** Creates a bad prerequisites void result. */
  static get BadPrerequisites() {
    return new _Result(false, "BAD_PREREQUISITES" /* BAD_PREREQUISITES */, void 0, {
      code: ErrorCodes.BAD_PREREQUISITES,
      message: DefaultMessages[ErrorCodes.BAD_PREREQUISITES],
      timestamp: Date.now()
    });
  }
  /** Creates a bad parameters void result. */
  static get BadParameters() {
    return new _Result(false, "BAD_PARAMETERS" /* BAD_PARAMETERS */, void 0, {
      code: ErrorCodes.BAD_PARAMETERS,
      message: DefaultMessages[ErrorCodes.BAD_PARAMETERS],
      timestamp: Date.now()
    });
  }
  /** Creates a cancelled void result. */
  static get Cancelled() {
    return new _Result(false, "CANCELLED" /* CANCELLED */, void 0, {
      code: ErrorCodes.CANCELLED,
      message: DefaultMessages[ErrorCodes.CANCELLED],
      timestamp: Date.now()
    });
  }
  /** Creates a timeout void result. */
  static get Timeout() {
    return new _Result(false, "TIMEOUT" /* TIMEOUT */, void 0, {
      code: ErrorCodes.TIMEOUT,
      message: DefaultMessages[ErrorCodes.TIMEOUT],
      timestamp: Date.now()
    });
  }
  /** Creates a no connection void result. */
  static get NoConnection() {
    return new _Result(false, "NO_CONNECTION" /* NO_CONNECTION */, void 0, {
      code: ErrorCodes.NO_CONNECTION,
      message: DefaultMessages[ErrorCodes.NO_CONNECTION],
      timestamp: Date.now()
    });
  }
  /** Creates a not implemented void result. */
  static get NotImplemented() {
    return new _Result(false, "NOT_IMPLEMENTED" /* NOT_IMPLEMENTED */, void 0, {
      code: ErrorCodes.NOT_IMPLEMENTED,
      message: DefaultMessages[ErrorCodes.NOT_IMPLEMENTED],
      timestamp: Date.now()
    });
  }
  /** Creates a rate limited void result. */
  static get RateLimited() {
    return new _Result(false, "RATE_LIMITED" /* RATE_LIMITED */, void 0, {
      code: ErrorCodes.RATE_LIMITED,
      message: DefaultMessages[ErrorCodes.RATE_LIMITED],
      timestamp: Date.now()
    });
  }
  /** Creates a circuit open void result. */
  static get CircuitOpen() {
    return new _Result(false, "CIRCUIT_OPEN" /* CIRCUIT_OPEN */, void 0, {
      code: ErrorCodes.CIRCUIT_OPEN,
      message: DefaultMessages[ErrorCodes.CIRCUIT_OPEN],
      timestamp: Date.now()
    });
  }
  /** Creates a bulkhead rejected void result. */
  static get BulkheadRejected() {
    return new _Result(false, "BULKHEAD_REJECTED" /* BULKHEAD_REJECTED */, void 0, {
      code: ErrorCodes.BULKHEAD_REJECTED,
      message: DefaultMessages[ErrorCodes.BULKHEAD_REJECTED],
      timestamp: Date.now()
    });
  }
  // ═══════════════════════════════════════════════════════════════════════════
  // Static Factory Methods
  // ═══════════════════════════════════════════════════════════════════════════
  /**
   * Creates a successful result with data.
   *
   * @param data - The success data.
   * @param correlationId - Optional correlation ID.
   * @param durationMs - Optional operation duration.
   * @returns New success Result.
   */
  static ok(data, correlationId, durationMs) {
    return new _Result(
      true,
      "SUCCESS" /* SUCCESS */,
      data,
      void 0,
      correlationId,
      void 0,
      void 0,
      durationMs
    );
  }
  /**
   * Creates a failed result with error details.
   *
   * @param error - Error details.
   * @param status - Result status (default: FAILURE).
   * @returns New failure Result.
   */
  static fail(error, status = "FAILURE" /* FAILURE */) {
    return new _Result(false, status, void 0, error, error.correlationId);
  }
  /**
   * Creates a failed result from an Error object.
   *
   * @param error - The error object.
   * @param code - Optional error code.
   * @param correlationId - Optional correlation ID.
   * @returns New failure Result with UNEXPECTED status.
   */
  static fromError(error, code, correlationId) {
    return new _Result(
      false,
      "UNEXPECTED" /* UNEXPECTED */,
      void 0,
      {
        code: code ?? ErrorCodes.UNEXPECTED,
        message: error.message,
        details: { name: error.name, stack: error.stack },
        timestamp: Date.now(),
        correlationId
      },
      correlationId,
      error.message,
      error
    );
  }
  /**
   * Creates a Result from another Result (copy constructor).
   *
   * @param result - Source result.
   * @returns New Result with same properties.
   */
  static from(result) {
    return new _Result(
      result.success,
      result.status,
      result.data,
      result.error,
      result.correlationId,
      result.reason,
      result.exception,
      result.durationMs
    );
  }
  /**
   * Wraps an async operation and converts exceptions to Results.
   *
   * @param action - The async action to execute.
   * @param correlationId - Optional correlation ID.
   * @returns Promise of Result.
   */
  static async tryAsync(action, correlationId) {
    const startTime = Date.now();
    try {
      const data = await action();
      return _Result.ok(data, correlationId, Date.now() - startTime);
    } catch (error) {
      return _Result.fromError(error, void 0, correlationId);
    }
  }
  /**
   * Wraps a sync operation and converts exceptions to Results.
   *
   * @param action - The sync action to execute.
   * @param correlationId - Optional correlation ID.
   * @returns Result.
   */
  static try(action, correlationId) {
    const startTime = Date.now();
    try {
      const data = action();
      return _Result.ok(data, correlationId, Date.now() - startTime);
    } catch (error) {
      return _Result.fromError(error, void 0, correlationId);
    }
  }
  // ═══════════════════════════════════════════════════════════════════════════
  // Static Method Aliases (Backward Compatibility)
  // ═══════════════════════════════════════════════════════════════════════════
  /**
   * Creates a successful result with data.
   * Alias for Result.ok() for backward compatibility.
   *
   * @param data - The success data.
   * @param correlationId - Optional correlation ID.
   * @returns New success Result.
   */
  static success(data, correlationId) {
    return _Result.ok(data, correlationId);
  }
  /**
   * Creates a failed result.
   * Alias for Result.fail()/fromError() for backward compatibility.
   *
   * @param error - Error object, string message, or error details.
   * @returns New failure Result.
   */
  static failure(error) {
    if (error instanceof Error) {
      return _Result.fail({
        code: ErrorCodes.FAILURE,
        message: error.message,
        details: { name: error.name, stack: error.stack },
        timestamp: Date.now()
      });
    }
    if (typeof error === "string") {
      return _Result.fail({ code: ErrorCodes.FAILURE, message: error, timestamp: Date.now() });
    }
    return _Result.fail(error);
  }
  // ═══════════════════════════════════════════════════════════════════════════
  // Generic Typed Failure Factory Methods
  // ═══════════════════════════════════════════════════════════════════════════
  /**
   * Creates a bad parameters failure with the specified type.
   * Use this instead of Result.BadParameters.withReason() for proper typing.
   *
   * @param reason - The error reason message.
   * @returns New failure Result with BAD_PARAMETERS status.
   *
   * @example
   * ```typescript
   * function divide(a: number, b: number): Result<number> {
   *     if (b === 0) {
   *         return Result.badParameters('Cannot divide by zero');
   *     }
   *     return Result.ok(a / b);
   * }
   * ```
   */
  static badParameters(reason) {
    return _Result.fail({
      code: ErrorCodes.BAD_PARAMETERS,
      message: reason,
      timestamp: Date.now()
    }, "BAD_PARAMETERS" /* BAD_PARAMETERS */);
  }
  /**
   * Creates a not found failure with the specified type.
   *
   * @param reason - The error reason message.
   * @returns New failure Result with NOT_FOUND status.
   */
  static notFound(reason) {
    return _Result.fail({
      code: ErrorCodes.NOT_FOUND,
      message: reason,
      timestamp: Date.now()
    }, "NOT_FOUND" /* NOT_FOUND */);
  }
  /**
   * Creates an unauthorized failure with the specified type.
   *
   * @param reason - The error reason message.
   * @returns New failure Result with UNAUTHORIZED status.
   */
  static unauthorized(reason) {
    return _Result.fail({
      code: ErrorCodes.UNAUTHORIZED,
      message: reason,
      timestamp: Date.now()
    }, "UNAUTHORIZED" /* UNAUTHORIZED */);
  }
  /**
   * Creates a bad prerequisites failure with the specified type.
   *
   * @param reason - The error reason message.
   * @returns New failure Result with BAD_PREREQUISITES status.
   */
  static badPrerequisites(reason) {
    return _Result.fail({
      code: ErrorCodes.BAD_PREREQUISITES,
      message: reason,
      timestamp: Date.now()
    }, "BAD_PREREQUISITES" /* BAD_PREREQUISITES */);
  }
  /**
   * Creates an unexpected error failure with the specified type.
   *
   * @param reason - The error reason message.
   * @returns New failure Result with UNEXPECTED status.
   */
  static unexpected(reason) {
    return _Result.fail({
      code: ErrorCodes.UNEXPECTED,
      message: reason,
      timestamp: Date.now()
    }, "UNEXPECTED" /* UNEXPECTED */);
  }
  /**
   * Combines multiple results into a single result containing an array.
   * If any result is a failure, returns the first failure.
   *
   * @param results - Array of results to combine.
   * @returns Combined Result with array of values, or first failure.
   */
  static combine(results) {
    if (results.length === 0) {
      return _Result.ok([]);
    }
    const firstFailure = results.find((r) => !r.isSuccess);
    if (firstFailure) {
      return _Result.fail(
        firstFailure.error ?? { code: ErrorCodes.FAILURE, message: "Unknown error", timestamp: Date.now() },
        firstFailure.status
      );
    }
    const values = results.map((r) => r.data);
    return _Result.ok(values);
  }
  /**
   * Combines multiple results, collecting ALL errors instead of stopping at first.
   * Useful for batch validation where all errors should be reported.
   *
   * @param results - Array of results to combine.
   * @returns Combined Result with array of values, or aggregated failure.
   *
   * @example
   * ```typescript
   * const results = [validateName(input), validateEmail(input), validateAge(input)];
   * const combined = Result.combineAll(results);
   * if (combined.isNotSuccess) {
   *     // combined.error.details.errors contains all individual errors
   *     console.log(`${combined.error.details.errorCount} validation errors`);
   * }
   * ```
   */
  static combineAll(results) {
    if (results.length === 0) {
      return _Result.ok([]);
    }
    const failures = results.filter((r) => !r.isSuccess);
    if (failures.length === 0) {
      const values = results.map((r) => r.data);
      return _Result.ok(values);
    }
    const errors = failures.map((f) => f.error);
    const aggregatedError = {
      code: ErrorCodes.VALIDATION_ERROR,
      message: `${failures.length} error(s) occurred`,
      details: {
        errors,
        errorCount: failures.length
      },
      timestamp: Date.now()
    };
    return _Result.fail(aggregatedError, "VALIDATION_ERROR" /* VALIDATION_ERROR */);
  }
  /**
   * Creates a Result from a nullable value.
   * Returns success if value is not null/undefined, failure otherwise.
   *
   * @param value - The possibly null/undefined value.
   * @param errorMessage - Error message if value is null/undefined.
   * @returns Success Result with value, or failure Result.
   */
  static fromNullable(value, errorMessage) {
    if (value === null || value === void 0) {
      return _Result.fail({ code: ErrorCodes.FAILURE, message: errorMessage, timestamp: Date.now() });
    }
    return _Result.ok(value);
  }
  /**
   * Creates a Result from a Promise.
   * Resolves to success if promise resolves, failure if it rejects.
   *
   * @param promise - The promise to convert.
   * @returns Promise resolving to Result.
   */
  static async fromPromise(promise) {
    return _Result.tryAsync(() => promise);
  }
  // ═══════════════════════════════════════════════════════════════════════════
  // Computed Properties
  // ═══════════════════════════════════════════════════════════════════════════
  get isSuccess() {
    return this.success && isSuccessStatus(this.status);
  }
  get isNotSuccess() {
    return !this.isSuccess;
  }
  get isFailure() {
    return this.status === "FAILURE" /* FAILURE */;
  }
  get isUnexpected() {
    return this.status === "UNEXPECTED" /* UNEXPECTED */;
  }
  get isUnauthorized() {
    return this.status === "UNAUTHORIZED" /* UNAUTHORIZED */;
  }
  get isForbidden() {
    return this.status === "FORBIDDEN" /* FORBIDDEN */;
  }
  get isAlready() {
    return this.status === "ALREADY" /* ALREADY */;
  }
  get isNotFound() {
    return this.status === "NOT_FOUND" /* NOT_FOUND */;
  }
  get isBadPrerequisites() {
    return this.status === "BAD_PREREQUISITES" /* BAD_PREREQUISITES */;
  }
  get isBadParameters() {
    return this.status === "BAD_PARAMETERS" /* BAD_PARAMETERS */;
  }
  get isCancelled() {
    return this.status === "CANCELLED" /* CANCELLED */;
  }
  get isTimeout() {
    return this.status === "TIMEOUT" /* TIMEOUT */;
  }
  get isNoConnection() {
    return this.status === "NO_CONNECTION" /* NO_CONNECTION */;
  }
  get isNotImplemented() {
    return this.status === "NOT_IMPLEMENTED" /* NOT_IMPLEMENTED */;
  }
  get isRateLimited() {
    return this.status === "RATE_LIMITED" /* RATE_LIMITED */;
  }
  get isCircuitOpen() {
    return this.status === "CIRCUIT_OPEN" /* CIRCUIT_OPEN */;
  }
  get isBulkheadRejected() {
    return this.status === "BULKHEAD_REJECTED" /* BULKHEAD_REJECTED */;
  }
  get isRetryable() {
    return isRetryableStatus(this.status);
  }
  get hasData() {
    return this.data !== void 0 && this.data !== null;
  }
  get httpStatusCode() {
    if (this.isSuccess) {
      return this.hasData ? 200 : 204;
    }
    return toHttpStatusCode(this.status);
  }
  // ═══════════════════════════════════════════════════════════════════════════
  // Fluent Methods (returns new immutable instances)
  // ═══════════════════════════════════════════════════════════════════════════
  withReason(reason) {
    return new _Result(
      this.success,
      this.status,
      this.data,
      this.error ? { ...this.error, message: reason } : { code: this.status, message: reason, timestamp: Date.now() },
      this.correlationId,
      reason,
      this.exception,
      this.durationMs
    );
  }
  addReason(reason) {
    const newReason = this.reason ? `${reason}
${this.reason}` : reason;
    return this.withReason(newReason);
  }
  withStatus(status) {
    return new _Result(
      isSuccessStatus(status),
      status,
      this.data,
      this.error,
      this.correlationId,
      this.reason,
      this.exception,
      this.durationMs
    );
  }
  withData(data) {
    return new _Result(
      this.success,
      this.status,
      data,
      this.error,
      this.correlationId,
      this.reason,
      this.exception,
      this.durationMs
    );
  }
  withException(exception) {
    return new _Result(
      this.success,
      this.status,
      this.data,
      this.error,
      this.correlationId,
      this.reason,
      exception,
      this.durationMs
    );
  }
  withCorrelationId(correlationId) {
    return new _Result(
      this.success,
      this.status,
      this.data,
      this.error ? { ...this.error, correlationId } : void 0,
      correlationId,
      this.reason,
      this.exception,
      this.durationMs
    );
  }
  withError(error) {
    return new _Result(
      false,
      this.status,
      this.data,
      error,
      error.correlationId ?? this.correlationId,
      error.message,
      this.exception,
      this.durationMs
    );
  }
  // ═══════════════════════════════════════════════════════════════════════════
  // Railway-Oriented Programming
  // ═══════════════════════════════════════════════════════════════════════════
  whenSuccess(fn) {
    if (this.isNotSuccess) {
      return _Result.fail(this.error, this.status);
    }
    return fn(this);
  }
  async whenSuccessAsync(fn) {
    if (this.isNotSuccess) {
      return _Result.fail(this.error, this.status);
    }
    return fn(this);
  }
  onFailure(fn) {
    if (this.isNotSuccess) {
      fn(this);
    }
    return this;
  }
  onSuccess(fn) {
    if (this.isSuccess && this.data !== void 0) {
      fn(this.data);
    }
    return this;
  }
  map(mapper) {
    if (this.success && this.data !== void 0) {
      return _Result.ok(mapper(this.data), this.correlationId, this.durationMs);
    }
    return _Result.fail(this.error, this.status);
  }
  async mapAsync(mapper) {
    if (this.success && this.data !== void 0) {
      try {
        const mapped = await mapper(this.data);
        return _Result.ok(mapped, this.correlationId, this.durationMs);
      } catch (error) {
        return _Result.fromError(error, ErrorCodes.MAP_ERROR, this.correlationId);
      }
    }
    return _Result.fail(this.error, this.status);
  }
  flatMap(mapper) {
    if (this.success && this.data !== void 0) {
      return mapper(this.data);
    }
    return _Result.fail(this.error, this.status);
  }
  async flatMapAsync(mapper) {
    if (this.success && this.data !== void 0) {
      return mapper(this.data);
    }
    return _Result.fail(this.error, this.status);
  }
  match(onSuccess, onFailure) {
    if (this.isSuccess && this.data !== void 0) {
      return onSuccess(this.data);
    }
    return onFailure(this.error ?? { code: ErrorCodes.UNKNOWN, message: DefaultMessages[ErrorCodes.UNKNOWN], timestamp: Date.now() });
  }
  // ═══════════════════════════════════════════════════════════════════════════
  // Data Access Methods
  // ═══════════════════════════════════════════════════════════════════════════
  getOrThrow() {
    if (!this.success || this.data === void 0) {
      throw this.toException();
    }
    return this.data;
  }
  getOrDefault(defaultValue) {
    return this.success && this.data !== void 0 ? this.data : defaultValue;
  }
  getOrNull() {
    return this.success && this.data !== void 0 ? this.data : null;
  }
  getOrElse(factory) {
    return this.success && this.data !== void 0 ? this.data : factory();
  }
  // ═══════════════════════════════════════════════════════════════════════════
  // Instance Aliases (Backward Compatibility)
  // ═══════════════════════════════════════════════════════════════════════════
  /**
   * Gets the success data.
   * Alias for 'data' property for backward compatibility.
   *
   * @returns The data value, or undefined if failure.
   */
  get value() {
    return this.data;
  }
  /**
   * Gets the success data or throws if failure.
   * Alias for getOrThrow() for backward compatibility.
   *
   * @returns The data value.
   * @throws ResultException if result is not successful or data is undefined.
   */
  getValue() {
    return this.getOrThrow();
  }
  /**
   * Gets the success data or returns default value.
   * Alias for getOrDefault() for backward compatibility.
   *
   * @param defaultValue - Value to return if failure.
   * @returns The data value or default.
   */
  getValueOrDefault(defaultValue) {
    return this.getOrDefault(defaultValue);
  }
  /**
   * Gets the error or null if successful.
   * Alias for error property for backward compatibility.
   *
   * @returns The error detail or null.
   */
  getError() {
    return this.error ?? null;
  }
  /**
   * Folds the result into a single value.
   * Alias for match() for backward compatibility.
   *
   * @param onSuccess - Function to apply if successful.
   * @param onFailure - Function to apply if failed.
   * @returns The result of the applied function.
   */
  fold(onSuccess, onFailure) {
    return this.match(onSuccess, onFailure);
  }
  /**
   * Executes a side effect on success.
   * Alias for onSuccess() for backward compatibility.
   *
   * @param fn - Function to execute with the data.
   * @returns This result for chaining.
   */
  tap(fn) {
    return this.onSuccess(fn);
  }
  /**
   * Executes a side effect on failure.
   *
   * @param fn - Function to execute with the error.
   * @returns This result for chaining.
   */
  tapError(fn) {
    if (!this.isSuccess && this.error) {
      fn(this.error);
    }
    return this;
  }
  /**
   * Maps the error to a different error.
   *
   * @param mapper - Error transformation function.
   * @returns Result with mapped error, or unchanged if successful.
   */
  mapError(mapper) {
    if (!this.isSuccess && this.error) {
      return _Result.fail(mapper(this.error), this.status);
    }
    return this;
  }
  /**
   * Combines this result with another using a combiner function.
   *
   * @param other - The other result to combine with.
   * @param combiner - Function to combine the two values.
   * @returns Combined result, or first failure encountered.
   */
  combineWith(other, combiner) {
    if (!this.isSuccess) {
      return _Result.fail(this.error, this.status);
    }
    if (!other.isSuccess) {
      return _Result.fail(other.error, other.status);
    }
    return _Result.ok(combiner(this.data, other.data));
  }
  // ═══════════════════════════════════════════════════════════════════════════
  // Exception Conversion
  // ═══════════════════════════════════════════════════════════════════════════
  toException() {
    return new ResultException(this.status, this.error, this.exception, this.data);
  }
  toVoid() {
    return new _Result(
      this.success,
      this.status,
      void 0,
      this.error,
      this.correlationId,
      this.reason,
      this.exception,
      this.durationMs
    );
  }
  // ═══════════════════════════════════════════════════════════════════════════
  // Serialization
  // ═══════════════════════════════════════════════════════════════════════════
  toJSON() {
    return {
      success: this.success,
      status: this.status,
      data: this.data,
      error: this.error,
      reason: this.reason,
      correlationId: this.correlationId,
      timestamp: this.timestamp,
      durationMs: this.durationMs
    };
  }
  static fromJSON(json) {
    if (json.success && json.data !== void 0) {
      return _Result.ok(json.data, json.correlationId);
    }
    if (json.error) {
      return _Result.fail(json.error, json.status);
    }
    return _Result.fail({ code: ErrorCodes.UNKNOWN, message: "Invalid result JSON", timestamp: Date.now() });
  }
  toString() {
    const parts = [this.status];
    if (this.reason) parts.push(this.reason);
    if (this.hasData) parts.push(`Data: ${typeof this.data}`);
    if (this.durationMs !== void 0) parts.push(`Duration: ${this.durationMs}ms`);
    return parts.join(" - ");
  }
};
function successResult(data) {
  return Result.ok(data);
}
function errorResult(code, message, details) {
  return Result.fail({ code, message, details, timestamp: Date.now() });
}

// src/core/result/entities/PagedResult.ts
var PagedResult = class _PagedResult {
  // ═══════════════════════════════════════════════════════════════════════════
  // Properties
  // ═══════════════════════════════════════════════════════════════════════════
  /**
   * The underlying Result.
   * @private
   */
  _result;
  /**
   * Pagination metadata.
   * @readonly
   */
  pagination;
  // ═══════════════════════════════════════════════════════════════════════════
  // Constructor
  // ═══════════════════════════════════════════════════════════════════════════
  /**
   * Creates a new PagedResult.
   *
   * @param result - The underlying Result containing the array of items.
   * @param pagination - Optional pagination metadata.
   * @private
   */
  constructor(result, pagination) {
    this._result = result;
    this.pagination = pagination;
  }
  // ═══════════════════════════════════════════════════════════════════════════
  // Delegated Properties
  // ═══════════════════════════════════════════════════════════════════════════
  get success() {
    return this._result.success;
  }
  get status() {
    return this._result.status;
  }
  get data() {
    return this._result.data;
  }
  get error() {
    return this._result.error;
  }
  get reason() {
    return this._result.reason;
  }
  get correlationId() {
    return this._result.correlationId;
  }
  get timestamp() {
    return this._result.timestamp;
  }
  get isSuccess() {
    return this._result.isSuccess;
  }
  get isNotSuccess() {
    return this._result.isNotSuccess;
  }
  get hasData() {
    return this._result.hasData;
  }
  get count() {
    return this._result.data?.length ?? 0;
  }
  get isEmpty() {
    return this.count === 0;
  }
  // ═══════════════════════════════════════════════════════════════════════════
  // Static Factory Methods
  // ═══════════════════════════════════════════════════════════════════════════
  /**
   * Creates a successful paged result.
   *
   * @param data - Array of items for the current page.
   * @param pagination - Pagination metadata.
   * @param correlationId - Optional correlation ID for tracing.
   * @returns New successful PagedResult.
   */
  static ok(data, pagination, correlationId) {
    return new _PagedResult(Result.ok(data, correlationId), pagination);
  }
  /**
   * Creates a successful paged result with calculated pagination.
   *
   * @param data - Array of items for the current page.
   * @param page - Current page number (1-indexed).
   * @param pageSize - Items per page.
   * @param totalItems - Total items across all pages.
   * @param correlationId - Optional correlation ID for tracing.
   * @returns New successful PagedResult with calculated pagination.
   */
  static okWithPagination(data, page, pageSize, totalItems, correlationId) {
    const pagination = PaginationInfo.create(page, pageSize, totalItems);
    return _PagedResult.ok(data, pagination, correlationId);
  }
  /**
   * Creates an empty successful paged result.
   *
   * @param page - Current page number (default: 1).
   * @param pageSize - Items per page (default: 10).
   * @param correlationId - Optional correlation ID for tracing.
   * @returns Empty PagedResult.
   */
  static empty(page = 1, pageSize = 10, correlationId) {
    return _PagedResult.okWithPagination([], page, pageSize, 0, correlationId);
  }
  /**
   * Creates a failed paged result.
   *
   * @param error - Error details.
   * @param status - Result status (default: FAILURE).
   * @returns New failed PagedResult.
   */
  static fail(error, status = "FAILURE" /* FAILURE */) {
    return new _PagedResult(Result.fail(error, status), void 0);
  }
  /**
   * Creates a PagedResult from an existing Result<T[]>.
   *
   * @param result - Existing array result.
   * @param pagination - Optional pagination metadata.
   * @returns New PagedResult wrapping the result.
   */
  static fromResult(result, pagination) {
    return new _PagedResult(result, pagination);
  }
  // ═══════════════════════════════════════════════════════════════════════════
  // Instance Methods
  // ═══════════════════════════════════════════════════════════════════════════
  getOrThrow() {
    return this._result.getOrThrow();
  }
  getOrDefault(defaultValue) {
    return this._result.getOrDefault(defaultValue);
  }
  getOrEmpty() {
    return this._result.getOrDefault([]);
  }
  map(mapper) {
    if (this.isSuccess && this.data) {
      const mappedData = this.data.map(mapper);
      return _PagedResult.ok(mappedData, this.pagination, this.correlationId);
    }
    return _PagedResult.fail(this.error, this.status);
  }
  filter(predicate) {
    if (this.isSuccess && this.data) {
      const filteredData = this.data.filter(predicate);
      return new _PagedResult(Result.ok(filteredData, this.correlationId), this.pagination);
    }
    return this;
  }
  toResult() {
    return this._result;
  }
  toVoid() {
    return this._result.toVoid();
  }
  // ═══════════════════════════════════════════════════════════════════════════
  // Serialization
  // ═══════════════════════════════════════════════════════════════════════════
  toJSON() {
    return {
      ...this._result.toJSON(),
      pagination: this.pagination?.toJSON()
    };
  }
  static fromJSON(json) {
    if (json.success && json.data !== void 0 && json.pagination) {
      return _PagedResult.ok(json.data, PaginationInfo.fromJSON(json.pagination), json.correlationId);
    }
    if (json.error) {
      return _PagedResult.fail(json.error, json.status);
    }
    return _PagedResult.fail({ code: "UNKNOWN", message: "Invalid result JSON", timestamp: Date.now() });
  }
  toString() {
    if (this.isSuccess) {
      return `PagedResult: ${this.count} items (page ${this.pagination?.page ?? 1} of ${this.pagination?.totalPages ?? 1})`;
    }
    return `PagedResult: ${this.status} - ${this.reason}`;
  }
};

// src/core/result/dtos/ExceptionDto.ts
function toExceptionDto(error, includeStack = false) {
  const dto = {
    name: error.name,
    message: error.message
  };
  if (includeStack && error.stack) {
    return { ...dto, stack: error.stack };
  }
  if (error.cause) {
    return {
      ...dto,
      innerException: toExceptionDto(error.cause, includeStack)
    };
  }
  return dto;
}

// src/core/result/dtos/ResultDto.ts
function toResultDto(result, includeStack = false) {
  const dto = {
    status: result.status,
    reason: result.reason,
    code: result.error?.code,
    correlationId: result.correlationId,
    timestamp: result.timestamp,
    data: result.data
  };
  if (result.exception) {
    return {
      ...dto,
      exception: toExceptionDto(result.exception, includeStack)
    };
  }
  return dto;
}
function getHttpStatusCode(result) {
  if (result.isSuccess) {
    return result.hasData ? HttpStatusCodes.OK : HttpStatusCodes.NO_CONTENT;
  }
  return toHttpStatusCode(result.status);
}
function createApiResponse(result, includeStack = false) {
  return {
    statusCode: getHttpStatusCode(result),
    body: toResultDto(result, includeStack)
  };
}

// src/core/result/dtos/PagedResultDto.ts
function toPagedResultDto(result, includeStack = false) {
  const baseDto = toResultDto(result.toResult(), includeStack);
  return {
    ...baseDto,
    pagination: result.pagination?.toJSON()
  };
}
function fromPagedResultDto(dto) {
  if (dto.status === "SUCCESS" /* SUCCESS */ && dto.data !== void 0 && dto.pagination) {
    return PagedResult.ok(dto.data, PaginationInfo.fromJSON(dto.pagination), dto.correlationId);
  }
  const error = {
    code: dto.code ?? dto.status,
    message: dto.reason ?? "Unknown error",
    timestamp: dto.timestamp,
    correlationId: dto.correlationId
  };
  return PagedResult.fail(error, dto.status);
}
function createPagedApiResponse(result, includeStack = false) {
  return {
    statusCode: getHttpStatusCode(result.toResult()),
    body: toPagedResultDto(result, includeStack)
  };
}

// src/core/result/utilities/ErrorDetailFactory.ts
function createErrorDetail(error, code = ErrorCodes.UNKNOWN, correlationId) {
  const base = {
    code,
    message: error.message,
    details: {
      name: error.name,
      stack: error.stack
    },
    timestamp: Date.now()
  };
  return correlationId ? { ...base, correlationId } : base;
}
function createValidationError(field, message, value, correlationId) {
  const base = {
    code: ErrorCodes.VALIDATION_ERROR,
    message: `Validation failed for '${field}': ${message}`,
    field,
    details: { field, value, validationMessage: message },
    timestamp: Date.now()
  };
  return correlationId ? { ...base, correlationId } : base;
}
function createNotFoundError(resourceType, identifier, correlationId) {
  const base = {
    code: ErrorCodes.NOT_FOUND,
    message: `${resourceType} with identifier '${identifier}' was not found`,
    resourceType,
    resourceId: identifier,
    details: { resourceType, identifier },
    timestamp: Date.now()
  };
  return correlationId ? { ...base, correlationId } : base;
}
function createTimeoutError(operation, timeoutMs, correlationId) {
  const base = {
    code: ErrorCodes.TIMEOUT,
    message: `Operation '${operation}' timed out after ${timeoutMs}ms`,
    details: { operation, timeoutMs },
    timestamp: Date.now()
  };
  return correlationId ? { ...base, correlationId } : base;
}
function createRateLimitedError(limit, windowMs, retryAfterMs, correlationId) {
  const base = {
    code: ErrorCodes.RATE_LIMITED,
    message: `Rate limit exceeded: ${limit} requests per ${windowMs}ms. Retry after ${retryAfterMs}ms.`,
    details: { limit, windowMs, retryAfterMs },
    timestamp: Date.now()
  };
  return correlationId ? { ...base, correlationId } : base;
}
function createCircuitOpenError(circuitName, resetTimeMs, correlationId) {
  const base = {
    code: ErrorCodes.CIRCUIT_OPEN,
    message: `Circuit '${circuitName}' is open. Service is temporarily unavailable.`,
    details: { circuitName, resetTimeMs, retryAfterMs: resetTimeMs },
    timestamp: Date.now()
  };
  return correlationId ? { ...base, correlationId } : base;
}
function createBulkheadRejectedError(bulkheadName, maxConcurrent, correlationId) {
  const base = {
    code: ErrorCodes.BULKHEAD_REJECTED,
    message: `Bulkhead '${bulkheadName}' rejected request. Maximum concurrent requests (${maxConcurrent}) reached.`,
    details: { bulkheadName, maxConcurrent },
    timestamp: Date.now()
  };
  return correlationId ? { ...base, correlationId } : base;
}
function createUnauthorizedError(reason = "Authentication required", correlationId) {
  const base = {
    code: ErrorCodes.UNAUTHORIZED,
    message: reason,
    details: { reason },
    timestamp: Date.now()
  };
  return correlationId ? { ...base, correlationId } : base;
}
function createForbiddenError(resource, action, correlationId) {
  const base = {
    code: ErrorCodes.FORBIDDEN,
    message: `Access denied: Cannot ${action} on ${resource}`,
    details: { resource, action },
    timestamp: Date.now()
  };
  return correlationId ? { ...base, correlationId } : base;
}
function createConflictError(resourceType, identifier, reason, correlationId) {
  const base = {
    code: ErrorCodes.CONFLICT,
    message: `Conflict: ${resourceType} '${identifier}' - ${reason}`,
    resourceType,
    resourceId: identifier,
    details: { resourceType, identifier, reason },
    timestamp: Date.now()
  };
  return correlationId ? { ...base, correlationId } : base;
}
function chainError(error, innerError) {
  return {
    ...error,
    innerError
  };
}
function withAISuggestions(error, suggestions, auditId) {
  return {
    ...error,
    aiSuggestions: suggestions,
    auditId
  };
}
function createAggregatedError(errors, message, correlationId) {
  const base = {
    code: ErrorCodes.VALIDATION_ERROR,
    message: message ?? `${errors.length} error(s) occurred`,
    details: {
      errors,
      errorCount: errors.length
    },
    timestamp: Date.now()
  };
  return correlationId ? { ...base, correlationId } : base;
}

// src/core/result/utilities/SafeExecute.ts
function safeExecute(fn, options = {}) {
  const { correlationId, errorCode = ErrorCodes.UNEXPECTED, onError } = options;
  try {
    return fn();
  } catch (error) {
    const err = error;
    onError?.(err, correlationId);
    return Result.fail(
      createErrorDetail(err, errorCode, correlationId),
      "UNEXPECTED" /* UNEXPECTED */
    );
  }
}
async function safeExecuteAsync(fn, options = {}) {
  const { correlationId, errorCode = ErrorCodes.UNEXPECTED, onError } = options;
  try {
    return await fn();
  } catch (error) {
    const err = error;
    onError?.(err, correlationId);
    return Result.fail(
      createErrorDetail(err, errorCode, correlationId),
      "UNEXPECTED" /* UNEXPECTED */
    );
  }
}
function tryExecute(fn, options = {}) {
  const { correlationId, errorCode = ErrorCodes.UNEXPECTED, onError } = options;
  try {
    const data = fn();
    return Result.ok(data, correlationId);
  } catch (error) {
    const err = error;
    onError?.(err, correlationId);
    return Result.fail(
      createErrorDetail(err, errorCode, correlationId),
      "UNEXPECTED" /* UNEXPECTED */
    );
  }
}
async function tryExecuteAsync(fn, options = {}) {
  const { correlationId, errorCode = ErrorCodes.UNEXPECTED, onError } = options;
  const startTime = Date.now();
  try {
    const data = await fn();
    return Result.ok(data, correlationId, Date.now() - startTime);
  } catch (error) {
    const err = error;
    onError?.(err, correlationId);
    return Result.fail(
      createErrorDetail(err, errorCode, correlationId),
      "UNEXPECTED" /* UNEXPECTED */
    );
  }
}
function logResult(result, logger, operationName = "Operation") {
  if (result.isSuccess) {
    logger.debug(`${operationName} completed successfully`, {
      status: result.status,
      correlationId: result.correlationId,
      durationMs: result.durationMs
    });
    return;
  }
  const context = {
    status: result.status,
    reason: result.reason,
    error: result.error,
    correlationId: result.correlationId
  };
  switch (result.status) {
    case "UNEXPECTED" /* UNEXPECTED */:
      logger.critical(`${operationName} failed unexpectedly`, context);
      break;
    case "TIMEOUT" /* TIMEOUT */:
    case "NO_CONNECTION" /* NO_CONNECTION */:
    case "SERVICE_UNAVAILABLE" /* SERVICE_UNAVAILABLE */:
    case "CIRCUIT_OPEN" /* CIRCUIT_OPEN */:
      logger.error(`${operationName} failed with transient error`, context);
      break;
    case "UNAUTHORIZED" /* UNAUTHORIZED */:
    case "FORBIDDEN" /* FORBIDDEN */:
      logger.warn(`${operationName} failed with auth error`, context);
      break;
    case "NOT_FOUND" /* NOT_FOUND */:
    case "VALIDATION_ERROR" /* VALIDATION_ERROR */:
    case "BAD_PARAMETERS" /* BAD_PARAMETERS */:
    case "BAD_PREREQUISITES" /* BAD_PREREQUISITES */:
      logger.info(`${operationName} failed with expected error`, context);
      break;
    default:
      logger.error(`${operationName} failed`, context);
  }
}
async function safeExecuteWithLog(fn, logger, operationName, options = {}) {
  const result = await safeExecuteAsync(fn, {
    ...options,
    onError: (error, correlationId) => {
      logger.critical(`${operationName} threw exception: ${error.message}`, {
        error: error.name,
        stack: error.stack,
        correlationId
      });
      options.onError?.(error, correlationId);
    }
  });
  logResult(result, logger, operationName);
  return result;
}

// src/core/result/utilities/RetryHelper.ts
async function retryWithResult(operation, options) {
  const config = {
    ...DefaultRetryOptions,
    ...options
  };
  let lastResult;
  let attempt = 0;
  while (attempt < config.maxAttempts) {
    attempt++;
    lastResult = await operation();
    if (lastResult.isSuccess) {
      return lastResult;
    }
    const isLastAttempt = attempt >= config.maxAttempts;
    const canRetry = isRetryableStatus(lastResult.status);
    if (isLastAttempt || !canRetry) {
      break;
    }
    const exponentialDelay = config.baseDelayMs * Math.pow(config.backoffMultiplier, attempt - 1);
    const cappedDelay = Math.min(exponentialDelay, config.maxDelayMs);
    const jitter = cappedDelay * config.jitterFactor * (Math.random() * 2 - 1);
    const delayMs = Math.max(0, Math.round(cappedDelay + jitter));
    if (options?.onRetry && lastResult.error) {
      options.onRetry(attempt + 1, lastResult.error, delayMs);
    }
    await delay(delayMs);
  }
  return lastResult;
}
function delay(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

exports.BulkheadDefaults = BulkheadDefaults;
exports.CircuitBreakerDefaults = CircuitBreakerDefaults;
exports.DefaultMessages = DefaultMessages;
exports.DefaultRetryOptions = DefaultRetryOptions;
exports.ErrorCodes = ErrorCodes;
exports.HttpStatusCodes = HttpStatusCodes;
exports.PagedResult = PagedResult;
exports.PaginationInfo = PaginationInfo;
exports.RateLimitDefaults = RateLimitDefaults;
exports.Result = Result;
exports.ResultException = ResultException;
exports.ResultStatus = ResultStatus;
exports.RetryDefaults = RetryDefaults;
exports.ServiceDefaults = ServiceDefaults;
exports.TimingDefaults = TimingDefaults;
exports.chainError = chainError;
exports.createAggregatedError = createAggregatedError;
exports.createApiResponse = createApiResponse;
exports.createBulkheadRejectedError = createBulkheadRejectedError;
exports.createCircuitOpenError = createCircuitOpenError;
exports.createConflictError = createConflictError;
exports.createErrorDetail = createErrorDetail;
exports.createForbiddenError = createForbiddenError;
exports.createNotFoundError = createNotFoundError;
exports.createPagedApiResponse = createPagedApiResponse;
exports.createRateLimitedError = createRateLimitedError;
exports.createTimeoutError = createTimeoutError;
exports.createUnauthorizedError = createUnauthorizedError;
exports.createValidationError = createValidationError;
exports.errorResult = errorResult;
exports.fromPagedResultDto = fromPagedResultDto;
exports.getHttpStatusCode = getHttpStatusCode;
exports.isAggregatedError = isAggregatedError;
exports.isAlreadyStatus = isAlreadyStatus;
exports.isBulkheadRejectedStatus = isBulkheadRejectedStatus;
exports.isCancelledStatus = isCancelledStatus;
exports.isCircuitOpenStatus = isCircuitOpenStatus;
exports.isForbiddenStatus = isForbiddenStatus;
exports.isNetworkErrorStatus = isNetworkErrorStatus;
exports.isNotFoundStatus = isNotFoundStatus;
exports.isNotImplementedStatus = isNotImplementedStatus;
exports.isNotSuccessStatus = isNotSuccessStatus;
exports.isPendingStatus = isPendingStatus;
exports.isRateLimitedStatus = isRateLimitedStatus;
exports.isRetryableStatus = isRetryableStatus;
exports.isSuccessStatus = isSuccessStatus;
exports.isTerminalStatus = isTerminalStatus;
exports.isTimeoutStatus = isTimeoutStatus;
exports.isUnauthorizedStatus = isUnauthorizedStatus;
exports.isUnexpectedStatus = isUnexpectedStatus;
exports.isValidationErrorStatus = isValidationErrorStatus;
exports.logResult = logResult;
exports.onResultMetrics = onResultMetrics;
exports.retryWithResult = retryWithResult;
exports.safeExecute = safeExecute;
exports.safeExecuteAsync = safeExecuteAsync;
exports.safeExecuteWithLog = safeExecuteWithLog;
exports.successResult = successResult;
exports.toExceptionDto = toExceptionDto;
exports.toHttpStatusCode = toHttpStatusCode;
exports.toPagedResultDto = toPagedResultDto;
exports.toResultDto = toResultDto;
exports.tryExecute = tryExecute;
exports.tryExecuteAsync = tryExecuteAsync;
exports.withAISuggestions = withAISuggestions;
//# sourceMappingURL=index.js.map
//# sourceMappingURL=index.js.map