{"version":3,"file":"StreamProvider.mjs","sources":["../../../src/lib/streaming/StreamProvider.tsx"],"sourcesContent":["/* @refresh reset */\n/**\n * @file Stream Provider Component\n * @description React context provider for the Dynamic HTML Streaming Engine.\n *\n * The StreamProvider establishes the streaming context for the component tree,\n * managing the streaming engine lifecycle, providing stream coordination,\n * and exposing streaming controls to child components.\n *\n * @module streaming/StreamProvider\n * @version 1.0.0\n * @author Harbor Framework Team\n *\n * @example\n * ```tsx\n * function App() {\n *   return (\n *     <StreamProvider\n *       config={{ maxConcurrentStreams: 4, debug: true }}\n *       onError={(error) => console.error('Stream error:', error)}\n *       onMetricsUpdate={(metrics) => analytics.track('stream_metrics', metrics)}\n *     >\n *       <AppContent />\n *     </StreamProvider>\n *   );\n * }\n * ```\n */\n\nimport {\n  Component,\n  type ComponentType,\n  createContext,\n  type DependencyList,\n  type ErrorInfo,\n  type FC,\n  type ReactElement,\n  type ReactNode,\n  useCallback,\n  useContext,\n  useEffect,\n  useMemo,\n  useRef,\n  useState,\n} from 'react';\n\nimport { createStreamingEngine, StreamingEngine, } from './streaming-engine';\n\nimport {\n  createStreamError,\n  DEFAULT_ENGINE_CONFIG,\n  DEFAULT_METRICS,\n  type EngineConfig,\n  type StreamConfig,\n  type StreamContextValue,\n  type StreamError,\n  StreamErrorCode,\n  type StreamEventHandler,\n  StreamEventType,\n  type StreamMetrics,\n  type StreamProviderProps,\n  type StreamState,\n} from './types';\n\n// ============================================================================\n// Context Definition\n// ============================================================================\n\n/**\n * React context for streaming functionality.\n * @internal\n */\nconst StreamContext = createContext<StreamContextValue | null>(null);\n\n/**\n * Display name for React DevTools.\n */\nStreamContext.displayName = 'StreamContext';\n\n// ============================================================================\n// Error Boundary for Stream Errors\n// ============================================================================\n\ninterface StreamErrorBoundaryProps {\n  children: ReactNode;\n  fallback?: ReactNode | ((error: StreamError, reset: () => void) => ReactNode);\n  onError?: (error: StreamError) => void;\n}\n\ninterface StreamErrorBoundaryState {\n  hasError: boolean;\n  error: StreamError | null;\n}\n\n/**\n * Error boundary specifically for stream-related errors.\n *\n * @description\n * Catches errors that occur during streaming and provides\n * graceful fallback rendering with recovery options.\n */\nclass StreamErrorBoundary extends Component<\n  StreamErrorBoundaryProps,\n  StreamErrorBoundaryState\n> {\n  constructor(props: StreamErrorBoundaryProps) {\n    super(props);\n    this.state = { hasError: false, error: null };\n  }\n\n  static getDerivedStateFromError(error: Error): StreamErrorBoundaryState {\n    const streamError = createStreamError(\n      StreamErrorCode.UnknownError,\n      error.message,\n      { cause: error, stack: error.stack }\n    );\n\n    return { hasError: true, error: streamError };\n  }\n\n  override componentDidCatch(error: Error, errorInfo: ErrorInfo): void {\n    const streamError = createStreamError(\n      StreamErrorCode.UnknownError,\n      error.message,\n      { cause: error, stack: errorInfo.componentStack ?? error.stack }\n    );\n\n    this.props.onError?.(streamError);\n\n    // Log in development\n    if (typeof process !== 'undefined' && process.env?.NODE_ENV === 'development') {\n      console.error('[StreamErrorBoundary] Caught error:', error);\n      console.error('[StreamErrorBoundary] Component stack:', errorInfo.componentStack);\n    }\n  }\n\n  override render(): ReactNode {\n    if (this.state.hasError && this.state.error) {\n      const { fallback } = this.props;\n\n      if (typeof fallback === 'function') {\n        return fallback(this.state.error, this.handleReset);\n      }\n\n      if (fallback !== undefined && fallback !== null) {\n        return fallback;\n      }\n\n      // Default fallback UI\n      return (\n        <div\n          role=\"alert\"\n          className=\"stream-error-boundary\"\n          style={{\n            padding: '1rem',\n            backgroundColor: '#fef2f2',\n            border: '1px solid #fecaca',\n            borderRadius: '0.375rem',\n          }}\n        >\n          <h3 style={{ color: '#dc2626', marginBottom: '0.5rem' }}>\n            Streaming Error\n          </h3>\n          <p style={{ color: '#7f1d1d', marginBottom: '0.5rem' }}>\n            {this.state.error.message}\n          </p>\n          <button\n            onClick={this.handleReset}\n            style={{\n              padding: '0.25rem 0.75rem',\n              backgroundColor: '#dc2626',\n              color: 'white',\n              border: 'none',\n              borderRadius: '0.25rem',\n              cursor: 'pointer',\n            }}\n          >\n            Retry\n          </button>\n        </div>\n      );\n    }\n\n    return this.props.children;\n  }\n\n  private handleReset = (): void => {\n    this.setState({ hasError: false, error: null });\n  };\n}\n\n// ============================================================================\n// Environment Detection\n// ============================================================================\n\n/**\n * Detects if code is running in a server-side environment.\n */\nfunction isServerEnvironment(): boolean {\n  return (\n    typeof window === 'undefined' ||\n    typeof document === 'undefined' ||\n    // Check for SSR frameworks\n    (typeof navigator !== 'undefined' && navigator.product === 'ReactNative')\n  );\n}\n\n/**\n * Checks if the current environment supports streaming APIs.\n */\nfunction isStreamingSupported(): boolean {\n  if (isServerEnvironment()) {\n    // Server always supports streaming\n    return true;\n  }\n\n  return StreamingEngine.isStreamingSupported();\n}\n\n// ============================================================================\n// Stream Provider Implementation\n// ============================================================================\n\n/**\n * Provider component for the Dynamic HTML Streaming Engine.\n *\n * @description\n * StreamProvider initializes and manages the streaming engine,\n * providing context to child components for stream registration,\n * control, and monitoring.\n *\n * Features:\n * - Automatic engine lifecycle management\n * - Global error handling with error boundaries\n * - Metrics collection and reporting\n * - SSR-aware initialization\n * - Graceful degradation for unsupported environments\n *\n * @example\n * ```tsx\n * // Basic usage\n * <StreamProvider>\n *   <App />\n * </StreamProvider>\n *\n * // With configuration\n * <StreamProvider\n *   config={{\n *     maxConcurrentStreams: 6,\n *     backpressureStrategy: BackpressureStrategy.Pause,\n *     debug: process.env.NODE_ENV === 'development',\n *   }}\n *   enableMetrics\n *   onError={(error) => errorReporter.capture(error)}\n *   onMetricsUpdate={(metrics) => performanceMonitor.record(metrics)}\n * >\n *   <App />\n * </StreamProvider>\n * ```\n */\nexport function StreamProvider({\n  children,\n  config: configOverrides,\n  debug = false,\n  enableMetrics = true,\n  onError,\n  onMetricsUpdate,\n}: StreamProviderProps): ReactElement {\n  // Merge configuration with defaults\n  const config = useMemo<EngineConfig>(\n    () => ({\n      ...DEFAULT_ENGINE_CONFIG,\n      ...configOverrides,\n      debug,\n      enableMetrics,\n    }),\n    [configOverrides, debug, enableMetrics]\n  );\n\n  // Environment detection\n  const isSSR = useMemo(() => isServerEnvironment(), []);\n  const supportsStreaming = useMemo(() => isStreamingSupported(), []);\n\n  // Engine reference (stable across renders)\n  const engineRef = useRef<StreamingEngine | null>(null);\n\n  // Metrics state for reactive updates\n  const [metrics, setMetrics] = useState<StreamMetrics>(DEFAULT_METRICS);\n\n  // Initialize engine\n  useEffect(() => {\n    if (!supportsStreaming && !isSSR) {\n      console.warn(\n        '[StreamProvider] Streaming APIs not supported in this environment. ' +\n        'Falling back to non-streaming mode.'\n      );\n      return undefined;\n    }\n\n    // Create engine if not already created\n    if (!engineRef.current) {\n      engineRef.current = createStreamingEngine(config);\n\n      // Subscribe to events for metrics and error handling\n      const unsubscribe = engineRef.current.subscribe((event) => {\n        // Update metrics\n        if (enableMetrics) {\n          const currentMetrics = engineRef.current?.getMetrics();\n          if (currentMetrics) {\n            setMetrics(currentMetrics);\n            onMetricsUpdate?.(currentMetrics);\n          }\n        }\n\n        // Handle errors\n        if (event.type === StreamEventType.Error && onError) {\n          onError(event.payload as StreamError);\n        }\n      });\n\n      // Cleanup on unmount\n      return () => {\n        unsubscribe();\n        engineRef.current?.dispose();\n        engineRef.current = null;\n      };\n    }\n    return undefined;\n  }, [config, enableMetrics, isSSR, onError, onMetricsUpdate, supportsStreaming]);\n\n  // ==========================================================================\n  // Context Value Methods\n  // ==========================================================================\n\n  const registerBoundary = useCallback((id: string, boundaryConfig: StreamConfig) => {\n    if (!engineRef.current) {\n      if (debug) {\n        console.warn(`[StreamProvider] Cannot register boundary \"${id}\" - engine not initialized`);\n      }\n      return;\n    }\n\n    try {\n      engineRef.current.registerBoundary(id, boundaryConfig);\n    } catch (error) {\n      if (debug) {\n        console.error(`[StreamProvider] Failed to register boundary \"${id}\":`, error);\n      }\n      throw error;\n    }\n  }, [debug]);\n\n  const unregisterBoundary = useCallback((id: string) => {\n    if (!engineRef.current) return;\n    engineRef.current.unregisterBoundary(id);\n  }, []);\n\n  const getBoundaryState = useCallback((id: string): StreamState | null => {\n    if (!engineRef.current) return null;\n    return engineRef.current.getState(id);\n  }, []);\n\n  const startStream = useCallback((id: string) => {\n    if (!engineRef.current) {\n      if (debug) {\n        console.warn(`[StreamProvider] Cannot start stream \"${id}\" - engine not initialized`);\n      }\n      return;\n    }\n\n    try {\n      engineRef.current.start(id);\n    } catch (error) {\n      if (debug) {\n        console.error(`[StreamProvider] Failed to start stream \"${id}\":`, error);\n      }\n    }\n  }, [debug]);\n\n  const pauseStream = useCallback((id: string) => {\n    if (!engineRef.current) return;\n    try {\n      engineRef.current.pause(id);\n    } catch (error) {\n      if (debug) {\n        console.error(`[StreamProvider] Failed to pause stream \"${id}\":`, error);\n      }\n    }\n  }, [debug]);\n\n  const resumeStream = useCallback((id: string) => {\n    if (!engineRef.current) return;\n    try {\n      engineRef.current.resume(id);\n    } catch (error) {\n      if (debug) {\n        console.error(`[StreamProvider] Failed to resume stream \"${id}\":`, error);\n      }\n    }\n  }, [debug]);\n\n  const abortStream = useCallback((id: string, reason?: string) => {\n    if (!engineRef.current) return;\n    engineRef.current.abort(id, reason);\n  }, []);\n\n  const getMetrics = useCallback((): StreamMetrics => {\n    return engineRef.current?.getMetrics() ?? metrics;\n  }, [metrics]);\n\n  const subscribe = useCallback((handler: StreamEventHandler): (() => void) => {\n    if (!engineRef.current) {\n      return () => {};\n    }\n    return engineRef.current.subscribe(handler);\n  }, []);\n\n  // ==========================================================================\n  // Context Value\n  // ==========================================================================\n\n  const contextValue = useMemo<StreamContextValue>(\n    () => ({\n      registerBoundary,\n      unregisterBoundary,\n      getBoundaryState,\n      startStream,\n      pauseStream,\n      resumeStream,\n      abortStream,\n      getMetrics,\n      subscribe,\n      config,\n      isStreamingSupported: supportsStreaming,\n      isSSR,\n    }),\n    [\n      registerBoundary,\n      unregisterBoundary,\n      getBoundaryState,\n      startStream,\n      pauseStream,\n      resumeStream,\n      abortStream,\n      getMetrics,\n      subscribe,\n      config,\n      supportsStreaming,\n      isSSR,\n    ]\n  );\n\n  // ==========================================================================\n  // Render\n  // ==========================================================================\n\n  return (\n    <StreamContext.Provider value={contextValue}>\n      <StreamErrorBoundary onError={onError}>\n        {children}\n      </StreamErrorBoundary>\n    </StreamContext.Provider>\n  );\n}\n\n// ============================================================================\n// Context Hook\n// ============================================================================\n\n/**\n * Hook to access the streaming context.\n *\n * @description\n * Provides access to all streaming functionality including\n * boundary registration, stream control, and metrics.\n *\n * @throws {Error} If used outside of a StreamProvider\n *\n * @example\n * ```tsx\n * function MyComponent() {\n *   const stream = useStreamContext();\n *\n *   useEffect(() => {\n *     stream.registerBoundary('my-content', {\n *       priority: StreamPriority.High,\n *     });\n *\n *     stream.startStream('my-content');\n *\n *     return () => stream.unregisterBoundary('my-content');\n *   }, [stream]);\n *\n *   return <div>My streaming content</div>;\n * }\n * ```\n */\n// eslint-disable-next-line react-refresh/only-export-components\nexport function useStreamContext(): StreamContextValue {\n  const context = useContext(StreamContext);\n\n  if (!context) {\n    throw new Error(\n      'useStreamContext must be used within a StreamProvider. ' +\n      'Wrap your component tree with <StreamProvider> to use streaming features.'\n    );\n  }\n\n  return context;\n}\n\n/**\n * Hook to optionally access streaming context.\n *\n * @description\n * Similar to useStreamContext but returns null instead of\n * throwing if used outside a StreamProvider. Useful for\n * components that can work with or without streaming.\n *\n * @example\n * ```tsx\n * function OptionalStreamingComponent() {\n *   const stream = useOptionalStreamContext();\n *\n *   if (!stream) {\n *     return <div>Non-streaming fallback</div>;\n *   }\n *\n *   return <div>Streaming enabled!</div>;\n * }\n * ```\n */\n// eslint-disable-next-line react-refresh/only-export-components\nexport function useOptionalStreamContext(): StreamContextValue | null {\n  return useContext(StreamContext);\n}\n\n// ============================================================================\n// Utility Hooks\n// ============================================================================\n\n/**\n * Hook to check if streaming is available.\n *\n * @description\n * Returns a boolean indicating whether streaming features\n * are available in the current environment.\n *\n * @example\n * ```tsx\n * function StreamingFeature() {\n *   const isAvailable = useStreamingAvailable();\n *\n *   if (!isAvailable) {\n *     return <StaticFallback />;\n *   }\n *\n *   return <StreamingContent />;\n * }\n * ```\n */\n// eslint-disable-next-line react-refresh/only-export-components\nexport function useStreamingAvailable(): boolean {\n  const context = useOptionalStreamContext();\n  return context?.isStreamingSupported ?? false;\n}\n\n/**\n * Hook to check if currently in SSR context.\n *\n * @description\n * Returns a boolean indicating whether the component\n * is currently rendering on the server.\n *\n * @example\n * ```tsx\n * function ServerAwareComponent() {\n *   const isSSR = useIsSSR();\n *\n *   if (isSSR) {\n *     return <ServerPlaceholder />;\n *   }\n *\n *   return <ClientContent />;\n * }\n * ```\n */\n// eslint-disable-next-line react-refresh/only-export-components\nexport function useIsSSR(): boolean {\n  const context = useOptionalStreamContext();\n  return context?.isSSR ?? isServerEnvironment();\n}\n\n/**\n * Hook to access current stream metrics.\n *\n * @description\n * Returns the current streaming metrics. The metrics are\n * updated reactively as streams progress.\n *\n * @example\n * ```tsx\n * function MetricsDashboard() {\n *   const metrics = useStreamMetrics();\n *\n *   return (\n *     <div>\n *       <p>Active streams: {metrics.activeStreams}</p>\n *       <p>Total bytes: {metrics.totalBytesTransferred}</p>\n *       <p>Buffer usage: {(metrics.bufferUtilization * 100).toFixed(1)}%</p>\n *     </div>\n *   );\n * }\n * ```\n */\n// eslint-disable-next-line react-refresh/only-export-components\nexport function useStreamMetrics(): StreamMetrics {\n  const context = useStreamContext();\n  const [metrics, setMetrics] = useState<StreamMetrics>(context.getMetrics);\n\n  useEffect(() => {\n\n\n    return context.subscribe(() => {\n      setMetrics(context.getMetrics());\n    });\n  }, [context]);\n\n  return metrics;\n}\n\n/**\n * Hook to subscribe to stream events.\n *\n * @description\n * Subscribes to stream events and calls the handler\n * when events occur. Automatically unsubscribes on unmount.\n *\n * @param handler - Event handler function\n * @param deps - Dependencies array for the handler\n *\n * @example\n * ```tsx\n * function EventLogger() {\n *   useStreamEvents((event) => {\n *     console.log(`Stream event: ${event.type} for ${event.boundaryId}`);\n *   }, []);\n *\n *   return null;\n * }\n * ```\n */\n// eslint-disable-next-line react-refresh/only-export-components\nexport function useStreamEvents(\n  handler: StreamEventHandler,\n  deps: DependencyList = []\n): void {\n  const context = useStreamContext();\n  // eslint-disable-next-line react-hooks/exhaustive-deps\n  const stableHandler = useCallback(handler, deps);\n\n  useEffect(() => {\n    return context.subscribe(stableHandler);\n  }, [context, stableHandler]);\n}\n\n// ============================================================================\n// HOC for Non-Hook Usage\n// ============================================================================\n\n/**\n * Props injected by withStream HOC.\n */\nexport interface WithStreamProps {\n  stream: StreamContextValue;\n}\n\n/**\n * Higher-order component for class components that need streaming access.\n *\n * @description\n * Wraps a class component and injects the stream context as a prop.\n * Prefer hooks for functional components.\n *\n * @example\n * ```tsx\n * interface MyComponentProps extends WithStreamProps {\n *   title: string;\n * }\n *\n * class MyComponent extends Component<MyComponentProps> {\n *   componentDidMount() {\n *     this.props.stream.registerBoundary('my-boundary', {\n *       priority: StreamPriority.Normal,\n *     });\n *   }\n *\n *   render() {\n *     return <div>{this.props.title}</div>;\n *   }\n * }\n *\n * export default withStream(MyComponent);\n * ```\n */\n// eslint-disable-next-line react-refresh/only-export-components\nexport function withStream<P extends WithStreamProps>(\n  WrappedComponent: ComponentType<P>\n): FC<Omit<P, keyof WithStreamProps>> {\n  const displayName = (WrappedComponent.displayName != null && WrappedComponent.displayName !== '') ? WrappedComponent.displayName : (WrappedComponent.name ?? 'Component');\n\n  const ComponentWithStream: FC<Omit<P, keyof WithStreamProps>> = (props) => {\n    const stream = useStreamContext();\n    return <WrappedComponent {...(props as P)} stream={stream} />;\n  };\n\n  ComponentWithStream.displayName = `withStream(${displayName})`;\n\n  return ComponentWithStream;\n}\n\n// ============================================================================\n// Exports\n// ============================================================================\n\n/* eslint-disable react-refresh/only-export-components */\nexport {\n  StreamContext,\n  StreamErrorBoundary,\n  isServerEnvironment,\n  isStreamingSupported,\n};\n"],"names":["StreamContext","createContext","StreamErrorBoundary","Component","props","error","createStreamError","StreamErrorCode","errorInfo","streamError","fallback","jsxs","jsx","isServerEnvironment","isStreamingSupported","StreamingEngine","StreamProvider","children","configOverrides","debug","enableMetrics","onError","onMetricsUpdate","config","useMemo","DEFAULT_ENGINE_CONFIG","isSSR","supportsStreaming","engineRef","useRef","metrics","setMetrics","useState","DEFAULT_METRICS","useEffect","createStreamingEngine","unsubscribe","event","currentMetrics","StreamEventType","registerBoundary","useCallback","id","boundaryConfig","unregisterBoundary","getBoundaryState","startStream","pauseStream","resumeStream","abortStream","reason","getMetrics","subscribe","handler","contextValue","useStreamContext","context","useContext","useOptionalStreamContext","useStreamingAvailable","useIsSSR","useStreamMetrics","useStreamEvents","deps","stableHandler","withStream","WrappedComponent","displayName","ComponentWithStream","stream"],"mappings":";;;;AAwEA,MAAMA,IAAgBC,EAAyC,IAAI;AAKnED,EAAc,cAAc;AAwB5B,MAAME,UAA4BC,EAGhC;AAAA,EACA,YAAYC,GAAiC;AAC3C,UAAMA,CAAK,GACX,KAAK,QAAQ,EAAE,UAAU,IAAO,OAAO,KAAA;AAAA,EACzC;AAAA,EAEA,OAAO,yBAAyBC,GAAwC;AAOtE,WAAO,EAAE,UAAU,IAAM,OANLC;AAAA,MAClBC,EAAgB;AAAA,MAChBF,EAAM;AAAA,MACN,EAAE,OAAOA,GAAO,OAAOA,EAAM,MAAA;AAAA,IAAM,EAGL;AAAA,EAClC;AAAA,EAES,kBAAkBA,GAAcG,GAA4B;AACnE,UAAMC,IAAcH;AAAA,MAClBC,EAAgB;AAAA,MAChBF,EAAM;AAAA,MACN,EAAE,OAAOA,GAAO,OAAOG,EAAU,kBAAkBH,EAAM,MAAA;AAAA,IAAM;AAGjE,SAAK,MAAM,UAAUI,CAAW,GAG5B,OAAO,UAAY,OAAe,QAAQ,KAAK,aAAa,kBAC9D,QAAQ,MAAM,uCAAuCJ,CAAK,GAC1D,QAAQ,MAAM,0CAA0CG,EAAU,cAAc;AAAA,EAEpF;AAAA,EAES,SAAoB;AAC3B,QAAI,KAAK,MAAM,YAAY,KAAK,MAAM,OAAO;AAC3C,YAAM,EAAE,UAAAE,MAAa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