{"version":3,"file":"errorRecovery.mjs","sources":["../../../src/lib/utils/errorRecovery.ts"],"sourcesContent":["/**\n * @file Error Recovery\n * @description Enterprise-grade error recovery strategies with fallbacks,\n * graceful degradation, and automatic recovery mechanisms\n */\n\nimport { normalizeError, type AppError, type ErrorCategory } from '../monitoring/errorTypes';\nimport { ErrorReporter } from '../monitoring/ErrorReporter';\n\n/**\n * Recovery strategy types\n */\nexport type RecoveryStrategy =\n  | 'retry'\n  | 'fallback'\n  | 'cache'\n  | 'degrade'\n  | 'skip'\n  | 'escalate';\n\n/**\n * Recovery context\n */\nexport interface RecoveryContext {\n  error: AppError;\n  operation: string;\n  attempts: number;\n  startTime: number;\n  metadata?: Record<string, unknown>;\n}\n\n/**\n * Recovery result\n */\nexport interface RecoveryResult<T> {\n  success: boolean;\n  value?: T;\n  strategy: RecoveryStrategy;\n  recovered: boolean;\n  error?: AppError;\n}\n\n/**\n * Recovery handler function\n */\nexport type RecoveryHandler<T> = (\n  context: RecoveryContext\n) => Promise<RecoveryResult<T>> | RecoveryResult<T>;\n\n/**\n * Recovery configuration\n */\nexport interface RecoveryConfig<T> {\n  /** Maximum recovery attempts */\n  maxAttempts?: number;\n  /** Strategies to try in order */\n  strategies?: RecoveryStrategy[];\n  /** Custom handlers for each strategy */\n  handlers?: Partial<Record<RecoveryStrategy, RecoveryHandler<T>>>;\n  /** Fallback value */\n  fallbackValue?: T | (() => T | Promise<T>);\n  /** Cache key for cache strategy */\n  cacheKey?: string;\n  /** Degraded functionality */\n  degradedFn?: () => T | Promise<T>;\n  /** Should escalate condition */\n  shouldEscalate?: (error: AppError, attempts: number) => boolean;\n  /** On recovery callback */\n  onRecovery?: (result: RecoveryResult<T>, context: RecoveryContext) => void;\n}\n\n/**\n * Error recovery manager\n */\nexport class ErrorRecovery<T> {\n  private config: Required<Omit<RecoveryConfig<T>, 'handlers' | 'cacheKey' | 'degradedFn' | 'fallbackValue' | 'shouldEscalate' | 'onRecovery'>> & RecoveryConfig<T>;\n  private cache: Map<string, { value: T; timestamp: number }> = new Map();\n  private readonly CACHE_TTL = 5 * 60 * 1000; // 5 minutes\n\n  constructor(config: RecoveryConfig<T> = {}) {\n    this.config = {\n      maxAttempts: config.maxAttempts ?? 3,\n      strategies: config.strategies ?? ['retry', 'fallback', 'cache', 'degrade', 'escalate'],\n      handlers: config.handlers,\n      fallbackValue: config.fallbackValue,\n      cacheKey: config.cacheKey,\n      degradedFn: config.degradedFn,\n      shouldEscalate: config.shouldEscalate,\n      onRecovery: config.onRecovery,\n    };\n  }\n\n  /**\n   * Execute operation with recovery\n   */\n  async execute(\n    operation: () => Promise<T>,\n    operationName: string,\n    metadata?: Record<string, unknown>\n  ): Promise<T> {\n    const startTime = Date.now();\n    let lastError: AppError | null = null;\n\n    for (let attempt = 1; attempt <= this.config.maxAttempts; attempt++) {\n      try {\n        const result = await operation();\n\n        // Cache successful result\n        if (this.config.cacheKey !== undefined && this.config.cacheKey !== '') {\n          this.cache.set(this.config.cacheKey, { value: result, timestamp: Date.now() });\n        }\n\n        return result;\n      } catch (error) {\n        lastError = normalizeError(error);\n\n        // Create recovery context\n        const context: RecoveryContext = {\n          error: lastError,\n          operation: operationName,\n          attempts: attempt,\n          startTime,\n          metadata,\n        };\n\n        // Try recovery strategies\n        for (const strategy of this.config.strategies) {\n          const result = await this.tryStrategy(strategy, context);\n\n          if (result.success) {\n            this.config.onRecovery?.(result, context);\n            return result.value as T;\n          }\n        }\n      }\n    }\n\n    // All recovery attempts failed\n    const errorToThrow = lastError ?? new Error('All recovery attempts failed');\n    ErrorReporter.reportError(errorToThrow, {\n      action: 'recovery_failed',\n      metadata: {\n        operation: operationName,\n        attempts: this.config.maxAttempts,\n      },\n    });\n\n    if (errorToThrow instanceof Error) {\n      throw errorToThrow;\n    }\n    const errorMessage = typeof errorToThrow === 'object' && errorToThrow !== null\n      ? JSON.stringify(errorToThrow)\n      : String(errorToThrow);\n    throw new Error(`Recovery failed: ${errorMessage}`);\n  }\n\n  /**\n   * Clear cache\n   */\n  clearCache(): void {\n    this.cache.clear();\n  }\n\n  /**\n   * Try a specific recovery strategy\n   */\n  private async tryStrategy(\n    strategy: RecoveryStrategy,\n    context: RecoveryContext\n  ): Promise<RecoveryResult<T>> {\n    // Check for custom handler first\n    const customHandler = this.config.handlers?.[strategy];\n    if (customHandler) {\n      return customHandler(context);\n    }\n\n    // Use default handlers\n    switch (strategy) {\n      case 'retry':\n        return this.retryStrategy(context);\n\n      case 'fallback':\n        return this.fallbackStrategy(context);\n\n      case 'cache':\n        return this.cacheStrategy(context);\n\n      case 'degrade':\n        return this.degradeStrategy(context);\n\n      case 'skip':\n        return this.skipStrategy(context);\n\n      case 'escalate':\n        return this.escalateStrategy(context);\n\n      default:\n        return { success: false, strategy, recovered: false };\n    }\n  }\n\n  /**\n   * Retry strategy\n   */\n  private retryStrategy(context: RecoveryContext): RecoveryResult<T> {\n    // Retry is handled by the main execute loop\n    // This strategy just signals that retry is possible\n    const isRetryable = this.isRetryableError(context.error);\n    return {\n      success: false,\n      strategy: 'retry',\n      recovered: false,\n      error: isRetryable ? undefined : context.error,\n    };\n  }\n\n  /**\n   * Fallback strategy\n   */\n  private async fallbackStrategy(_context: RecoveryContext): Promise<RecoveryResult<T>> {\n    if (this.config.fallbackValue === undefined) {\n      return { success: false, strategy: 'fallback', recovered: false };\n    }\n\n    try {\n      const value =\n        typeof this.config.fallbackValue === 'function'\n          ? await (this.config.fallbackValue as () => T | Promise<T>)()\n          : this.config.fallbackValue;\n\n      return {\n        success: true,\n        value,\n        strategy: 'fallback',\n        recovered: true,\n      };\n    } catch {\n      return { success: false, strategy: 'fallback', recovered: false };\n    }\n  }\n\n  /**\n   * Cache strategy\n   */\n  private cacheStrategy(_context: RecoveryContext): RecoveryResult<T> {\n    if (this.config.cacheKey === undefined || this.config.cacheKey === '') {\n      return { success: false, strategy: 'cache', recovered: false };\n    }\n\n    const cached = this.cache.get(this.config.cacheKey);\n    if (cached && Date.now() - cached.timestamp < this.CACHE_TTL) {\n      return {\n        success: true,\n        value: cached.value,\n        strategy: 'cache',\n        recovered: true,\n      };\n    }\n\n    return { success: false, strategy: 'cache', recovered: false };\n  }\n\n  /**\n   * Degrade strategy\n   */\n  private async degradeStrategy(_context: RecoveryContext): Promise<RecoveryResult<T>> {\n    if (!this.config.degradedFn) {\n      return { success: false, strategy: 'degrade', recovered: false };\n    }\n\n    try {\n      const value = await this.config.degradedFn();\n      return {\n        success: true,\n        value,\n        strategy: 'degrade',\n        recovered: true,\n      };\n    } catch {\n      return { success: false, strategy: 'degrade', recovered: false };\n    }\n  }\n\n  /**\n   * Skip strategy\n   */\n  private skipStrategy(_context: RecoveryContext): RecoveryResult<T> {\n    // Skip just returns success with undefined value\n    // Used when the operation is optional\n    return {\n      success: true,\n      value: undefined as unknown as T,\n      strategy: 'skip',\n      recovered: true,\n    };\n  }\n\n  /**\n   * Escalate strategy\n   */\n  private escalateStrategy(context: RecoveryContext): RecoveryResult<T> {\n    const shouldEscalate =\n      this.config.shouldEscalate?.(context.error, context.attempts) ??\n      context.error.severity === 'critical';\n\n    if (shouldEscalate) {\n      // Report escalated error\n      ErrorReporter.reportError(context.error, {\n        action: 'escalated',\n        metadata: {\n          operation: context.operation,\n          attempts: context.attempts,\n        },\n      });\n    }\n\n    return { success: false, strategy: 'escalate', recovered: false };\n  }\n\n  /**\n   * Check if error is retryable\n   */\n  private isRetryableError(error: AppError): boolean {\n    const retryableCategories: ErrorCategory[] = [\n      'network',\n      'timeout',\n      'rate_limit',\n      'server',\n    ];\n    return retryableCategories.includes(error.category);\n  }\n}\n\n/**\n * Recovery builder for fluent configuration\n */\nexport class RecoveryBuilder<T> {\n  private config: RecoveryConfig<T> = {};\n\n  /**\n   * Set max attempts\n   */\n  maxAttempts(n: number): RecoveryBuilder<T> {\n    this.config.maxAttempts = n;\n    return this;\n  }\n\n  /**\n   * Set strategies\n   */\n  strategies(...strategies: RecoveryStrategy[]): RecoveryBuilder<T> {\n    this.config.strategies = strategies;\n    return this;\n  }\n\n  /**\n   * Set fallback value\n   */\n  fallback(value: T | (() => T | Promise<T>)): RecoveryBuilder<T> {\n    this.config.fallbackValue = value;\n    return this;\n  }\n\n  /**\n   * Set cache key\n   */\n  cache(key: string): RecoveryBuilder<T> {\n    this.config.cacheKey = key;\n    return this;\n  }\n\n  /**\n   * Set degraded function\n   */\n  degrade(fn: () => T | Promise<T>): RecoveryBuilder<T> {\n    this.config.degradedFn = fn;\n    return this;\n  }\n\n  /**\n   * Set custom handler\n   */\n  handler(strategy: RecoveryStrategy, handler: RecoveryHandler<T>): RecoveryBuilder<T> {\n    this.config.handlers ??= {};\n    this.config.handlers[strategy] = handler;\n    return this;\n  }\n\n  /**\n   * Set recovery callback\n   */\n  onRecovery(\n    callback: (result: RecoveryResult<T>, context: RecoveryContext) => void\n  ): RecoveryBuilder<T> {\n    this.config.onRecovery = callback;\n    return this;\n  }\n\n  /**\n   * Build the recovery manager\n   */\n  build(): ErrorRecovery<T> {\n    return new ErrorRecovery<T>(this.config);\n  }\n\n  /**\n   * Execute with configured recovery\n   */\n  async execute(\n    operation: () => Promise<T>,\n    operationName: string,\n    metadata?: Record<string, unknown>\n  ): Promise<T> {\n    return this.build().execute(operation, operationName, metadata);\n  }\n}\n\n/**\n * Create a recovery builder\n */\nexport function recover<T>(): RecoveryBuilder<T> {\n  return new RecoveryBuilder<T>();\n}\n\n/**\n * Graceful degradation wrapper\n */\nexport async function withGracefulDegradation<T>(\n  primaryFn: () => Promise<T>,\n  fallbackFn: () => T | Promise<T>,\n  options?: {\n    shouldDegrade?: (error: unknown) => boolean;\n    onDegrade?: (error: unknown) => void;\n  }\n): Promise<{ value: T; degraded: boolean }> {\n  try {\n    const value = await primaryFn();\n    return { value, degraded: false };\n  } catch (error) {\n    const shouldDegrade = options?.shouldDegrade?.(error) ?? true;\n\n    if (shouldDegrade) {\n      options?.onDegrade?.(error);\n      const value = await fallbackFn();\n      return { value, degraded: true };\n    }\n\n    throw error;\n  }\n}\n\n/**\n * Circuit breaker with fallback\n */\nexport function withCircuitFallback<T>(\n  primaryFn: () => Promise<T>,\n  fallbackFn: () => T | Promise<T>,\n  options?: {\n    failureThreshold?: number;\n    resetTimeout?: number;\n  }\n): () => Promise<T> {\n  let failures = 0;\n  let lastFailure = 0;\n  const threshold = options?.failureThreshold ?? 5;\n  const resetTimeout = options?.resetTimeout ?? 30000;\n\n  return async () => {\n    // Check if circuit should be half-open\n    if (failures >= threshold) {\n      if (Date.now() - lastFailure < resetTimeout) {\n        // Circuit open - use fallback\n        return fallbackFn();\n      }\n      // Try to reset\n      failures = Math.floor(failures / 2);\n    }\n\n    try {\n      const result = await primaryFn();\n      failures = 0;\n      return result;\n    } catch (error) {\n      failures++;\n      lastFailure = Date.now();\n\n      if (failures >= threshold) {\n        return fallbackFn();\n      }\n\n      throw error;\n    }\n  };\n}\n\n/**\n * Stale-while-revalidate pattern\n */\nexport function staleWhileRevalidate<T>(\n  fetchFn: () => Promise<T>,\n  options: {\n    cacheKey: string;\n    staleTime?: number;\n    maxAge?: number;\n    storage?: Storage;\n  }\n): () => Promise<T> {\n  const staleTime = options.staleTime ?? 60000; // 1 minute\n  const maxAge = options.maxAge ?? 3600000; // 1 hour\n  const storage = options.storage ?? (typeof localStorage !== 'undefined' ? localStorage : null);\n\n  const getCached = (): { value: T; timestamp: number } | null => {\n    if (!storage) return null;\n    try {\n      const cached = storage.getItem(options.cacheKey);\n      if (cached === null || cached === '') return null;\n      const parsed: unknown = JSON.parse(cached);\n      if (\n        typeof parsed === 'object' &&\n        parsed !== null &&\n        'value' in parsed &&\n        'timestamp' in parsed &&\n        typeof (parsed as { timestamp: unknown }).timestamp === 'number'\n      ) {\n        return parsed as { value: T; timestamp: number };\n      }\n      return null;\n    } catch {\n      return null;\n    }\n  };\n\n  const setCached = (value: T): void => {\n    if (!storage) return;\n    try {\n      storage.setItem(\n        options.cacheKey,\n        JSON.stringify({ value, timestamp: Date.now() })\n      );\n    } catch {\n      // Storage full or unavailable\n    }\n  };\n\n  return async () => {\n    const cached = getCached();\n    const now = Date.now();\n\n    // If we have fresh cached data, return it immediately\n    if (cached && now - cached.timestamp < staleTime) {\n      return cached.value;\n    }\n\n    // If we have stale (but not expired) cached data\n    if (cached && now - cached.timestamp < maxAge) {\n      // Return stale data immediately\n      // Revalidate in background\n      fetchFn()\n        .then(setCached)\n        .catch(() => {}); // Ignore revalidation errors\n\n      return cached.value;\n    }\n\n    // No valid cache - fetch fresh data\n    const value = await fetchFn();\n    setCached(value);\n    return value;\n  };\n}\n\n/**\n * Automatic retry with exponential backoff\n */\nexport async function autoRetry<T>(\n  fn: () => Promise<T>,\n  options?: {\n    maxAttempts?: number;\n    baseDelay?: number;\n    maxDelay?: number;\n    shouldRetry?: (error: unknown, attempt: number) => boolean;\n    onRetry?: (error: unknown, attempt: number, delay: number) => void;\n  }\n): Promise<T> {\n  const maxAttempts = options?.maxAttempts ?? 3;\n  const baseDelay = options?.baseDelay ?? 1000;\n  const maxDelay = options?.maxDelay ?? 30000;\n  const shouldRetry = options?.shouldRetry ?? (() => true);\n\n  let lastError: unknown;\n\n  for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n    try {\n      return await fn();\n    } catch (error) {\n      lastError = error;\n\n      if (attempt >= maxAttempts || !shouldRetry(error, attempt)) {\n        break;\n      }\n\n      const delay = Math.min(baseDelay * Math.pow(2, attempt - 1), maxDelay);\n      options?.onRetry?.(error, attempt, delay);\n\n      await new Promise((resolve) => setTimeout(resolve, delay));\n    }\n  }\n\n  throw lastError;\n}\n\n/**\n * Safe async operation wrapper\n */\nexport async function safe<T>(\n  fn: () => Promise<T>\n): Promise<[T, null] | [null, Error]> {\n  try {\n    const result = await fn();\n    return [result, null];\n  } catch (error) {\n    return [null, error instanceof Error ? error : new Error(String(error))];\n  }\n}\n\n/**\n * Safe sync operation wrapper\n */\nexport function safeSync<T>(fn: () => T): [T, null] | [null, Error] {\n  try {\n    const result = fn();\n    return [result, null];\n  } catch (error) {\n    return [null, error instanceof Error ? error : new Error(String(error))];\n  }\n}\n"],"names":["ErrorRecovery","config","operation","operationName","metadata","startTime","lastError","attempt","result","error","normalizeError","context","strategy","errorToThrow","ErrorReporter","errorMessage","customHandler","_context","cached","RecoveryBuilder","n","strategies","value","key","fn","handler","callback","recover","withGracefulDegradation","primaryFn","fallbackFn","options","withCircuitFallback","failures","lastFailure","threshold","resetTimeout","staleWhileRevalidate","fetchFn","staleTime","maxAge","storage","getCached","parsed","setCached","now","autoRetry","maxAttempts","baseDelay","maxDelay","shouldRetry","delay","resolve","safe","safeSync"],"mappings":";;AA0EO,MAAMA,EAAiB;AAAA,EACpB;AAAA,EACA,4BAA0D,IAAA;AAAA,EACjD,YAAY,MAAS;AAAA;AAAA,EAEtC,YAAYC,IAA4B,IAAI;AAC1C,SAAK,SAAS;AAAA,MACZ,aAAaA,EAAO,eAAe;AAAA,MACnC,YAAYA,EAAO,cAAc,CAAC,SAAS,YAAY,SAAS,WAAW,UAAU;AAAA,MACrF,UAAUA,EAAO;AAAA,MACjB,eAAeA,EAAO;AAAA,MACtB,UAAUA,EAAO;AAAA,MACjB,YAAYA,EAAO;AAAA,MACnB,gBAAgBA,EAAO;AAAA,MACvB,YAAYA,EAAO;AAAA,IAAA;AAAA,EAEvB;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,QACJC,GACAC,GACAC,GACY;AACZ,UAAMC,IAAY,KAAK,IAAA;AACvB,QAAIC,IAA6B;AAEjC,aAASC,IAAU,GAAGA,KAAW,KAAK,OAAO,aAAaA;AACxD,UAAI;AACF,cAAMC,IAAS,MAAMN,EAAA;AAGrB,eAAI,KAAK,OAAO,aAAa,UAAa,KAAK,OAAO,aAAa,MACjE,KAAK,MAAM,IAAI,KAAK,OAAO,UAAU,EAAE,OAAOM,GAAQ,WAAW,KAAK,IAAA,EAAI,CAAG,GAGxEA;AAAA,MACT,SAASC,GAAO;AACd,QAAAH,IAAYI,EAAeD,CAAK;AAGhC,cAAME,IAA2B;AAAA,UAC/B,OAAOL;AAAA,UACP,WAA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