{"version":3,"file":"types.mjs","sources":["../../../src/lib/streaming/types.ts"],"sourcesContent":["/**\n * @file Dynamic HTML Streaming Engine - Type Definitions\n * @description Comprehensive TypeScript type system for the streaming architecture.\n *\n * This module provides the foundational type definitions for the Dynamic HTML Streaming\n * Engine, implementing a priority-based streaming system with full lifecycle management,\n * backpressure handling, and React Suspense integration.\n *\n * @module streaming/types\n * @version 1.0.0\n * @author Harbor Framework Team\n */\n\nimport type React from 'react';\nimport type { ReactNode } from 'react';\n\n// ============================================================================\n// Core Enumerations\n// ============================================================================\n\n/**\n * Stream priority levels for content delivery ordering.\n *\n * @description\n * Priority levels determine the order in which stream chunks are processed\n * and delivered to the client. Higher priority content is streamed first\n * to optimize Time to First Contentful Paint (FCP) and Largest Contentful Paint (LCP).\n *\n * - `critical`: Above-the-fold content, navigation, and essential UI chrome\n * - `high`: Primary content visible without scrolling\n * - `normal`: Standard content that may require minimal scrolling\n * - `low`: Below-the-fold content, deferred widgets, and analytics\n *\n * @example\n * ```typescript\n * const config: StreamConfig = {\n *   priority: StreamPriority.Critical,\n *   deferMs: 0,\n * };\n * ```\n */\nexport enum StreamPriority {\n  Critical = 'critical',\n  High = 'high',\n  Normal = 'normal',\n  Low = 'low',\n}\n\n/**\n * Numeric priority values for queue ordering.\n * Lower values indicate higher priority (processed first).\n */\nexport const PRIORITY_VALUES: Record<StreamPriority, number> = {\n  [StreamPriority.Critical]: 0,\n  [StreamPriority.High]: 1,\n  [StreamPriority.Normal]: 2,\n  [StreamPriority.Low]: 3,\n} as const;\n\n/**\n * Stream lifecycle states representing the current operational status.\n *\n * @description\n * The streaming engine follows a state machine pattern with well-defined\n * transitions between states:\n *\n * ```\n * idle --> pending --> streaming --> completed\n *                  \\-> paused ->/\n *                  \\-> error\n *                  \\-> aborted\n * ```\n */\nexport enum StreamState {\n  /** Initial state before streaming begins */\n  Idle = 'idle',\n  /** Stream is queued and waiting to be processed */\n  Pending = 'pending',\n  /** Actively streaming content */\n  Streaming = 'streaming',\n  /** Temporarily paused, can be resumed */\n  Paused = 'paused',\n  /** Successfully completed all chunks */\n  Completed = 'completed',\n  /** Terminated due to an error */\n  Error = 'error',\n  /** Manually aborted by user or system */\n  Aborted = 'aborted',\n}\n\n/**\n * Backpressure strategy for handling buffer overflow situations.\n *\n * @description\n * When the stream buffer reaches capacity, the backpressure strategy\n * determines how the engine handles incoming data:\n *\n * - `pause`: Pause the source stream until buffer drains\n * - `drop`: Drop new chunks (lossy, but maintains flow)\n * - `buffer`: Dynamically expand buffer (memory intensive)\n * - `error`: Throw an error to halt processing\n */\nexport enum BackpressureStrategy {\n  Pause = 'pause',\n  Drop = 'drop',\n  Buffer = 'buffer',\n  Error = 'error',\n}\n\n// ============================================================================\n// Configuration Interfaces\n// ============================================================================\n\n/**\n * Configuration for individual stream boundaries.\n *\n * @description\n * StreamConfig defines the behavior of a single streaming boundary,\n * including priority, timing, and lifecycle callbacks.\n *\n * @example\n * ```typescript\n * const heroConfig: StreamConfig = {\n *   priority: StreamPriority.Critical,\n *   deferMs: 0,\n *   placeholder: <HeroSkeleton />,\n *   onStreamStart: () => performance.mark('hero-stream-start'),\n *   onStreamComplete: () => performance.measure('hero-stream', 'hero-stream-start'),\n * };\n * ```\n */\nexport interface StreamConfig {\n  /**\n   * Priority level for this stream boundary.\n   * @default StreamPriority.Normal\n   */\n  priority: StreamPriority | `${StreamPriority}`;\n\n  /**\n   * Delay in milliseconds before streaming begins.\n   * Useful for staggering non-critical content.\n   * @default 0\n   */\n  deferMs?: number;\n\n  /**\n   * Maximum time in milliseconds to wait for stream completion.\n   * After timeout, fallback content is rendered.\n   * @default 30000\n   */\n  timeoutMs?: number;\n\n  /**\n   * Placeholder content displayed during streaming.\n   * Should match the approximate dimensions of final content\n   * to prevent Cumulative Layout Shift (CLS).\n   */\n  placeholder?: ReactNode;\n\n  /**\n   * Fallback content for non-streaming environments\n   * or when streaming fails.\n   */\n  fallback?: ReactNode;\n\n  /**\n   * Enable server-side rendering integration.\n   * @default true\n   */\n  ssr?: boolean;\n\n  /**\n   * Callback invoked when streaming begins.\n   */\n  onStreamStart?: () => void;\n\n  /**\n   * Callback invoked when streaming completes successfully.\n   */\n  onStreamComplete?: () => void;\n\n  /**\n   * Callback invoked when streaming encounters an error.\n   * @param error - The error that occurred\n   */\n  onStreamError?: (error: StreamError) => void;\n\n  /**\n   * Callback invoked when stream is aborted.\n   * @param reason - The reason for abortion\n   */\n  onStreamAbort?: (reason: string) => void;\n}\n\n/**\n * Global streaming engine configuration.\n *\n * @description\n * EngineConfig controls the behavior of the entire streaming system,\n * including buffer management, concurrency limits, and debugging options.\n */\nexport interface EngineConfig {\n  /**\n   * Maximum number of concurrent streams.\n   * Higher values increase throughput but consume more memory.\n   * @default 6\n   */\n  maxConcurrentStreams: number;\n\n  /**\n   * Size of the chunk buffer in bytes.\n   * @default 65536 (64KB)\n   */\n  bufferSize: number;\n\n  /**\n   * High water mark for backpressure in bytes.\n   * When buffer exceeds this, backpressure is applied.\n   * @default 16384 (16KB)\n   */\n  highWaterMark: number;\n\n  /**\n   * Strategy for handling backpressure.\n   * @default BackpressureStrategy.Pause\n   */\n  backpressureStrategy: BackpressureStrategy;\n\n  /**\n   * Enable debug logging.\n   * @default false\n   */\n  debug: boolean;\n\n  /**\n   * Enable performance metrics collection.\n   * @default true\n   */\n  enableMetrics: boolean;\n\n  /**\n   * Custom chunk transformer function.\n   * Applied to each chunk before delivery.\n   */\n  chunkTransformer?: ChunkTransformer;\n\n  /**\n   * Global timeout for all streams in milliseconds.\n   * Individual stream timeouts take precedence.\n   * @default 60000 (1 minute)\n   */\n  globalTimeoutMs: number;\n\n  /**\n   * Enable automatic retry for failed chunks.\n   * @default true\n   */\n  enableRetry: boolean;\n\n  /**\n   * Maximum retry attempts for failed chunks.\n   * @default 3\n   */\n  maxRetries: number;\n\n  /**\n   * Base delay between retries in milliseconds.\n   * Uses exponential backoff.\n   * @default 1000\n   */\n  retryDelayMs: number;\n}\n\n/**\n * Default engine configuration values.\n */\nexport const DEFAULT_ENGINE_CONFIG: EngineConfig = {\n  maxConcurrentStreams: 6,\n  bufferSize: 65536,\n  highWaterMark: 16384,\n  backpressureStrategy: BackpressureStrategy.Pause,\n  debug: false,\n  enableMetrics: true,\n  globalTimeoutMs: 60000,\n  enableRetry: true,\n  maxRetries: 3,\n  retryDelayMs: 1000,\n} as const;\n\n// ============================================================================\n// Stream Data Structures\n// ============================================================================\n\n/**\n * Individual stream chunk with metadata.\n *\n * @description\n * Represents a single unit of data in the stream, along with\n * metadata for ordering, timing, and integrity verification.\n */\nexport interface StreamChunk {\n  /** Unique identifier for this chunk */\n  id: string;\n\n  /** Sequence number for ordering */\n  sequence: number;\n\n  /** The actual data payload */\n  data: string | Uint8Array;\n\n  /** Timestamp when chunk was created */\n  timestamp: number;\n\n  /** Size of the chunk in bytes */\n  size: number;\n\n  /** Whether this is the final chunk */\n  isFinal: boolean;\n\n  /** Optional checksum for integrity verification */\n  checksum?: string;\n\n  /** Parent stream boundary ID */\n  boundaryId: string;\n\n  /** Chunk-specific metadata */\n  metadata?: Record<string, unknown>;\n}\n\n/**\n * Stream boundary registration data.\n *\n * @description\n * Contains all information about a registered stream boundary,\n * used by the engine to manage and coordinate streams.\n */\nexport interface StreamBoundaryData {\n  /** Unique identifier for this boundary */\n  id: string;\n\n  /** Configuration for this boundary */\n  config: StreamConfig;\n\n  /** Current state of this stream */\n  state: StreamState;\n\n  /** Queue of chunks for this boundary */\n  chunks: StreamChunk[];\n\n  /** Total bytes received */\n  bytesReceived: number;\n\n  /** Total bytes delivered to client */\n  bytesDelivered: number;\n\n  /** Timestamp when streaming started */\n  startTime?: number;\n\n  /** Timestamp when streaming completed */\n  endTime?: number;\n\n  /** Last error encountered */\n  lastError?: StreamError;\n\n  /** Retry count for this boundary */\n  retryCount: number;\n\n  /** AbortController for this stream */\n  abortController: AbortController;\n}\n\n/**\n * Priority queue entry for stream scheduling.\n */\nexport interface QueueEntry {\n  /** Boundary ID */\n  boundaryId: string;\n\n  /** Priority value (lower = higher priority) */\n  priority: number;\n\n  /** Timestamp when queued */\n  queuedAt: number;\n\n  /** Scheduled execution time */\n  scheduledTime: number;\n}\n\n// ============================================================================\n// Error Handling\n// ============================================================================\n\n/**\n * Stream-specific error with context.\n *\n * @description\n * Extends the standard Error class with streaming-specific\n * information for debugging and error recovery.\n */\nexport interface StreamError {\n  /** Error code for programmatic handling */\n  code: StreamErrorCode;\n\n  /** Human-readable error message */\n  message: string;\n\n  /** Boundary ID where error occurred */\n  boundaryId?: string;\n\n  /** Chunk ID if error was chunk-specific */\n  chunkId?: string;\n\n  /** Original error if this wraps another error */\n  cause?: Error;\n\n  /** Whether this error is retryable */\n  retryable: boolean;\n\n  /** Timestamp when error occurred */\n  timestamp: number;\n\n  /** Stack trace for debugging */\n  stack?: string;\n}\n\n/**\n * Error codes for stream-specific errors.\n */\nexport enum StreamErrorCode {\n  /** Network-related error */\n  NetworkError = 'STREAM_NETWORK_ERROR',\n  /** Stream timeout exceeded */\n  TimeoutError = 'STREAM_TIMEOUT_ERROR',\n  /** Stream was aborted */\n  AbortError = 'STREAM_ABORT_ERROR',\n  /** Buffer overflow */\n  BufferOverflow = 'STREAM_BUFFER_OVERFLOW',\n  /** Invalid chunk data */\n  InvalidChunk = 'STREAM_INVALID_CHUNK',\n  /** Checksum mismatch */\n  ChecksumError = 'STREAM_CHECKSUM_ERROR',\n  /** Server error response */\n  ServerError = 'STREAM_SERVER_ERROR',\n  /** Unknown/generic error */\n  UnknownError = 'STREAM_UNKNOWN_ERROR',\n  /** Configuration error */\n  ConfigError = 'STREAM_CONFIG_ERROR',\n  /** State machine violation */\n  StateError = 'STREAM_STATE_ERROR',\n}\n\n/**\n * Factory function to create StreamError instances.\n */\nexport function createStreamError(\n  code: StreamErrorCode,\n  message: string,\n  options?: Partial<Omit<StreamError, 'code' | 'message' | 'timestamp'>>\n): StreamError {\n  return {\n    code,\n    message,\n    retryable: isRetryableError(code),\n    timestamp: Date.now(),\n    ...options,\n  };\n}\n\n/**\n * Determines if an error code represents a retryable condition.\n */\nexport function isRetryableError(code: StreamErrorCode): boolean {\n  return [\n    StreamErrorCode.NetworkError,\n    StreamErrorCode.TimeoutError,\n    StreamErrorCode.ServerError,\n  ].includes(code);\n}\n\n// ============================================================================\n// Metrics & Telemetry\n// ============================================================================\n\n/**\n * Streaming performance metrics.\n *\n * @description\n * Comprehensive metrics for monitoring streaming performance,\n * useful for debugging and optimization.\n */\nexport interface StreamMetrics {\n  /** Total number of active streams */\n  activeStreams: number;\n\n  /** Total number of completed streams */\n  completedStreams: number;\n\n  /** Total number of failed streams */\n  failedStreams: number;\n\n  /** Total bytes transferred across all streams */\n  totalBytesTransferred: number;\n\n  /** Current buffer utilization (0-1) */\n  bufferUtilization: number;\n\n  /** Average chunk latency in milliseconds */\n  averageChunkLatency: number;\n\n  /** Time to first chunk across all streams in milliseconds */\n  averageTimeToFirstChunk: number;\n\n  /** Streams per priority level */\n  streamsByPriority: Record<StreamPriority, number>;\n\n  /** Backpressure events count */\n  backpressureEvents: number;\n\n  /** Retry attempts count */\n  retryAttempts: number;\n\n  /** Timestamp of last metric update */\n  lastUpdated: number;\n\n  /** Per-boundary metrics */\n  boundaryMetrics: Map<string, BoundaryMetrics>;\n}\n\n/**\n * Metrics for an individual stream boundary.\n */\nexport interface BoundaryMetrics {\n  /** Boundary identifier */\n  boundaryId: string;\n\n  /** Time to first chunk in milliseconds */\n  timeToFirstChunk: number;\n\n  /** Time to completion in milliseconds */\n  timeToComplete: number;\n\n  /** Total chunks received */\n  chunksReceived: number;\n\n  /** Total bytes received */\n  bytesReceived: number;\n\n  /** Average chunk size in bytes */\n  averageChunkSize: number;\n\n  /** Number of retry attempts */\n  retries: number;\n\n  /** Whether stream completed successfully */\n  successful: boolean;\n}\n\n/**\n * Default empty metrics object.\n */\nexport const DEFAULT_METRICS: StreamMetrics = {\n  activeStreams: 0,\n  completedStreams: 0,\n  failedStreams: 0,\n  totalBytesTransferred: 0,\n  bufferUtilization: 0,\n  averageChunkLatency: 0,\n  averageTimeToFirstChunk: 0,\n  streamsByPriority: {\n    [StreamPriority.Critical]: 0,\n    [StreamPriority.High]: 0,\n    [StreamPriority.Normal]: 0,\n    [StreamPriority.Low]: 0,\n  },\n  backpressureEvents: 0,\n  retryAttempts: 0,\n  lastUpdated: 0,\n  boundaryMetrics: new Map(),\n} as const;\n\n// ============================================================================\n// Function Types\n// ============================================================================\n\n/**\n * Chunk transformer function type.\n * Applied to each chunk before delivery.\n */\nexport type ChunkTransformer = (\n  chunk: StreamChunk,\n  context: TransformContext\n) => StreamChunk | Promise<StreamChunk>;\n\n/**\n * Context provided to chunk transformers.\n */\nexport interface TransformContext {\n  /** Boundary ID for this chunk */\n  boundaryId: string;\n\n  /** Stream configuration */\n  config: StreamConfig;\n\n  /** Total chunks processed so far */\n  totalChunks: number;\n\n  /** Total bytes processed so far */\n  totalBytes: number;\n}\n\n/**\n * Stream event handler function type.\n */\nexport type StreamEventHandler<T = unknown> = (event: StreamEvent<T>) => void;\n\n/**\n * Stream event with typed payload.\n */\nexport interface StreamEvent<T = unknown> {\n  /** Event type */\n  type: StreamEventType;\n\n  /** Boundary ID */\n  boundaryId: string;\n\n  /** Event timestamp */\n  timestamp: number;\n\n  /** Event payload */\n  payload?: T;\n}\n\n/**\n * Stream event types.\n */\nexport enum StreamEventType {\n  Start = 'stream:start',\n  Chunk = 'stream:chunk',\n  Pause = 'stream:pause',\n  Resume = 'stream:resume',\n  Complete = 'stream:complete',\n  Error = 'stream:error',\n  Abort = 'stream:abort',\n  Backpressure = 'stream:backpressure',\n  Retry = 'stream:retry',\n  StateChange = 'stream:state-change',\n}\n\n// ============================================================================\n// React Component Types\n// ============================================================================\n\n/**\n * Props for the StreamBoundary component.\n */\nexport interface StreamBoundaryProps {\n  /** Unique identifier for this boundary */\n  id?: string;\n\n  /** Child content to stream */\n  children: ReactNode;\n\n  /** Stream priority level */\n  priority?: StreamPriority | `${StreamPriority}`;\n\n  /** Delay before streaming begins */\n  deferMs?: number;\n\n  /** Timeout for stream completion */\n  timeoutMs?: number;\n\n  /** Placeholder during streaming */\n  placeholder?: ReactNode;\n\n  /** Fallback for non-streaming environments */\n  fallback?: ReactNode;\n\n  /** Enable SSR integration */\n  ssr?: boolean;\n\n  /** Callback when streaming starts */\n  onStreamStart?: () => void;\n\n  /** Callback when streaming completes */\n  onStreamComplete?: () => void;\n\n  /** Callback when streaming errors */\n  onStreamError?: (error: StreamError) => void;\n\n  /** CSS class name */\n  className?: string;\n\n  /** Custom test ID for testing */\n  testId?: string;\n}\n\n/**\n * Props for the StreamProvider component.\n */\nexport interface StreamProviderProps {\n  /** Child components */\n  children: ReactNode;\n\n  /** Engine configuration overrides */\n  config?: Partial<EngineConfig>;\n\n  /** Enable debug mode */\n  debug?: boolean;\n\n  /** Enable metrics collection */\n  enableMetrics?: boolean;\n\n  /** Global error handler */\n  onError?: (error: StreamError) => void;\n\n  /** Metrics update callback */\n  onMetricsUpdate?: (metrics: StreamMetrics) => void;\n}\n\n/**\n * Stream context value provided by StreamProvider.\n */\nexport interface StreamContextValue {\n  /** Register a new stream boundary */\n  registerBoundary: (id: string, config: StreamConfig) => void;\n\n  /** Unregister a stream boundary */\n  unregisterBoundary: (id: string) => void;\n\n  /** Get current state of a boundary */\n  getBoundaryState: (id: string) => StreamState | null;\n\n  /** Start streaming for a boundary */\n  startStream: (id: string) => void;\n\n  /** Pause streaming for a boundary */\n  pauseStream: (id: string) => void;\n\n  /** Resume streaming for a boundary */\n  resumeStream: (id: string) => void;\n\n  /** Abort streaming for a boundary */\n  abortStream: (id: string, reason?: string) => void;\n\n  /** Get current metrics */\n  getMetrics: () => StreamMetrics;\n\n  /** Subscribe to stream events */\n  subscribe: (handler: StreamEventHandler) => () => void;\n\n  /** Current engine configuration */\n  config: EngineConfig;\n\n  /** Whether streaming is supported in current environment */\n  isStreamingSupported: boolean;\n\n  /** Whether currently in SSR context */\n  isSSR: boolean;\n}\n\n// ============================================================================\n// Hook Return Types\n// ============================================================================\n\n/**\n * Return type for useStream hook.\n */\nexport interface UseStreamResult {\n  /** Current stream state */\n  state: StreamState;\n\n  /** Whether stream is currently active */\n  isStreaming: boolean;\n\n  /** Whether stream has completed */\n  isComplete: boolean;\n\n  /** Whether stream has errored */\n  hasError: boolean;\n\n  /** Current error if any */\n  error: StreamError | null;\n\n  /** Progress (0-1) if determinable */\n  progress: number | null;\n\n  /** Start the stream */\n  start: () => void;\n\n  /** Pause the stream */\n  pause: () => void;\n\n  /** Resume the stream */\n  resume: () => void;\n\n  /** Abort the stream */\n  abort: (reason?: string) => void;\n\n  /** Reset the stream to initial state */\n  reset: () => void;\n}\n\n/**\n * Return type for useStreamStatus hook.\n */\nexport interface UseStreamStatusResult {\n  /** Current state for the boundary */\n  state: StreamState;\n\n  /** Human-readable status message */\n  statusMessage: string;\n\n  /** Whether the boundary is registered */\n  isRegistered: boolean;\n\n  /** Time elapsed since stream started in milliseconds */\n  elapsedTime: number | null;\n\n  /** Estimated time remaining in milliseconds */\n  estimatedTimeRemaining: number | null;\n\n  /** Bytes transferred */\n  bytesTransferred: number;\n\n  /** Number of chunks received */\n  chunksReceived: number;\n}\n\n/**\n * Return type for useStreamPriority hook.\n */\nexport interface UseStreamPriorityResult {\n  /** Current priority */\n  priority: StreamPriority;\n\n  /** Update priority */\n  setPriority: (priority: StreamPriority) => void;\n\n  /** Escalate priority to next higher level */\n  escalate: () => void;\n\n  /** Deescalate priority to next lower level */\n  deescalate: () => void;\n}\n\n/**\n * Options for useDeferredStream hook.\n */\nexport interface UseDeferredStreamOptions {\n  /** Defer until element is visible */\n  deferUntilVisible?: boolean;\n\n  /** Defer until browser is idle */\n  deferUntilIdle?: boolean;\n\n  /** Defer until specific event */\n  deferUntilEvent?: string;\n\n  /** Maximum defer time in milliseconds */\n  maxDeferMs?: number;\n\n  /** Intersection observer threshold for visibility */\n  visibilityThreshold?: number;\n}\n\n/**\n * Return type for useDeferredStream hook.\n */\nexport interface UseDeferredStreamResult {\n  /** Whether stream should be deferred */\n  isDeferred: boolean;\n\n  /** Trigger immediate streaming */\n  triggerNow: () => void;\n\n  /** Ref to attach to the element for visibility detection */\n  ref: React.RefObject<HTMLElement>;\n\n  /** Reason for deferral */\n  deferReason: DeferReason | null;\n}\n\n/**\n * Reasons for stream deferral.\n */\nexport enum DeferReason {\n  NotVisible = 'not-visible',\n  BrowserBusy = 'browser-busy',\n  WaitingForEvent = 'waiting-for-event',\n  TimeBased = 'time-based',\n  ManualHold = 'manual-hold',\n}\n\n// ============================================================================\n// Server Integration Types\n// ============================================================================\n\n/**\n * Server-side streaming context.\n */\nexport interface ServerStreamContext {\n  /** Write a chunk to the response stream */\n  write: (chunk: string | Uint8Array) => void;\n\n  /** Flush buffered content */\n  flush: () => void;\n\n  /** Signal that streaming is complete */\n  end: () => void;\n\n  /** Current nonce for CSP */\n  nonce?: string;\n\n  /** Request ID for correlation */\n  requestId: string;\n\n  /** Response headers to set */\n  headers: Map<string, string>;\n}\n\n/**\n * Streaming middleware options.\n */\nexport interface StreamingMiddlewareOptions {\n  /** Enable gzip compression */\n  compress?: boolean;\n\n  /** Minimum bytes before compression */\n  compressThreshold?: number;\n\n  /** Custom response headers */\n  headers?: Record<string, string>;\n\n  /** CSP nonce generator */\n  nonceGenerator?: () => string;\n\n  /** Request timeout in milliseconds */\n  timeoutMs?: number;\n\n  /** Enable early hints (103) */\n  enableEarlyHints?: boolean;\n\n  /** Error handler */\n  onError?: (error: Error) => void;\n}\n\n/**\n * Serialized stream state for hydration.\n */\nexport interface SerializedStreamState {\n  /** Boundary ID */\n  boundaryId: string;\n\n  /** Final state */\n  state: StreamState;\n\n  /** Serialized content */\n  content: string;\n\n  /** Checksum for validation */\n  checksum: string;\n\n  /** Server render timestamp */\n  serverTimestamp: number;\n\n  /** Additional metadata */\n  metadata?: Record<string, unknown>;\n}\n\n// ============================================================================\n// Utility Types\n// ============================================================================\n\n/**\n * Deep partial type utility.\n *\n * @deprecated Import from '../shared/type-utils' instead.\n * This re-export is provided for backward compatibility.\n */\nexport type { DeepPartial } from '../shared/type-utils';\n\n/**\n * Extract event payload type.\n */\nexport type StreamEventPayload<T extends StreamEventType> = T extends StreamEventType.Chunk\n  ? StreamChunk\n  : T extends StreamEventType.Error\n    ? StreamError\n    : T extends StreamEventType.StateChange\n      ? { from: StreamState; to: StreamState }\n      : T extends StreamEventType.Backpressure\n        ? { pressure: number }\n        : T extends StreamEventType.Retry\n          ? { attempt: number; maxAttempts: number }\n          : unknown;\n\n/**\n * Type guard for StreamError.\n */\nexport function isStreamError(error: unknown): error is StreamError {\n  return (\n    typeof error === 'object' &&\n    error !== null &&\n    'code' in error &&\n    'message' in error &&\n    'retryable' in error &&\n    Object.values(StreamErrorCode).includes((error as StreamError).code)\n  );\n}\n\n/**\n * Type guard for StreamChunk.\n */\nexport function isStreamChunk(chunk: unknown): chunk is StreamChunk {\n  return (\n    typeof chunk === 'object' &&\n    chunk !== null &&\n    'id' in chunk &&\n    'sequence' in chunk &&\n    'data' in chunk &&\n    'boundaryId' in chunk\n  );\n}\n"],"names":["StreamPriority","PRIORITY_VALUES","StreamState","BackpressureStrategy","DEFAULT_ENGINE_CONFIG","StreamErrorCode","createStreamError","code","message","options","isRetryableError","DEFAULT_METRICS","StreamEventType","DeferReason","isStreamError","error","isStreamChunk","chunk"],"mappings":"AAyCO,IAAKA,sBAAAA,OACVA,EAAA,WAAW,YACXA,EAAA,OAAO,QACPA,EAAA,SAAS,UACTA,EAAA,MAAM,OAJIA,IAAAA,KAAA,CAAA,CAAA;AAWL,MAAMC,IAAkD;AAAA,EAC5D,UAA0B;AAAA,EAC1B,MAAsB;AAAA,EACtB,QAAwB;AAAA,EACxB,KAAqB;AACxB;AAgBO,IAAKC,sBAAAA,OAEVA,EAAA,OAAO,QAEPA,EAAA,UAAU,WAEVA,EAAA,YAAY,aAEZA,EAAA,SAAS,UAETA,EAAA,YAAY,aAEZA,EAAA,QAAQ,SAERA,EAAA,UAAU,WAdAA,IAAAA,KAAA,CAAA,CAAA,GA6BAC,s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