Skip to content

feat: add SSE (Server-Sent Events) support - #59

Merged
cc-hearts merged 3 commits into
mainfrom
feature/sse-support
Jun 23, 2026
Merged

feat: add SSE (Server-Sent Events) support#59
cc-hearts merged 3 commits into
mainfrom
feature/sse-support

Conversation

@cc-hearts

Copy link
Copy Markdown
Member

PR: feat: add SSE (Server-Sent Events) support

Summary

Added SSE (Server-Sent Events) support to the Request class, enabling streaming HTTP connections with a clean, composable API.

Motivation

Previously, the Request class only supported standard HTTP requests without streaming capabilities. This PR adds SSE support, which is essential for:

  • Real-time data streaming (e.g., live feeds, notifications)
  • AI chat completions (e.g., GPT streaming responses)
  • Server-sent updates without polling

Key Features

1. Based on Fetch API (not native EventSource)

Unlike the browser's native EventSource, this implementation:

  • ✅ Supports custom Headers (e.g., Authorization)
  • ✅ Supports POST requests
  • ✅ Supports all HTTP methods
  • ✅ Works in Node.js environments

2. New Types Added

// SSE message eventinterfaceSSEMessageEvent{event?: string// Event type (from `event:` field)data: string// Message dataid?: string// Last event ID (from `id:` field)retry?: number// Retry interval in milliseconds}// SSE callback handlersinterfaceSSECallbacks{onMessage?: (event: SSEMessageEvent)=>voidonOpen?: ()=>voidonError?: (error: unknown)=>voidonClose?: ()=>void}// SSE configurationinterfaceSSEConfigextendsSSECallbacks{sse: trueheaders?: Record<string,string>data?: unknown}

3. New Method: sse()

constapi=newRequest('https://api.example.com')// GET SSEconsthandle=api.sse('/events',{onMessage(event){console.log('Received:',event.data)},onOpen(){console.log('Connection opened')},onError(error){console.error('Error:',error)},onClose(){console.log('Connection closed')}})// Cancel connectionhandle.abort()

4. POST SSE Example (AI Streaming)

consthandle=api.sse('/chat/completions',{method: 'POST',data: {prompt: 'Hello',model: 'gpt-4'},onMessage(event){constdata=JSON.parse(event.data)console.log('AI reply:',data.content)}})

5. Interceptor Support

SSE requests automatically include headers added by request interceptors:

constaddAuth: RequestInterceptor=(config)=>({
...config,headers: {
...config.headers,Authorization: `Bearer ${getToken()}`}})api.useRequestInterceptor(addAuth)// This SSE request will include the Authorization headerapi.sse('/protected/events',{ ... })

Implementation Details

SSE Parser

  • Properly handles the SSE protocol specification
  • Supports multi-line data fields
  • Handles comments (lines starting with :)
  • Properly parses event:, data:, id:, and retry: fields

Memory Management

  • Uses AbortController for clean cancellation
  • Properly cleans up resources on connection close
  • Handles errors without memory leaks

Testing

The implementation has been tested with:

  • ✅ TypeScript compilation (no type errors)
  • ✅ Build process completes successfully
  • ✅ Documentation generation works

Breaking Changes

None. This is a purely additive feature.

Documentation

Updated both English and Chinese README files with:

  • Basic usage examples
  • POST SSE examples
  • Interceptor integration examples
  • Type definitions reference

Checklist

  • Code follows the existing code style
  • TypeScript types are properly defined
  • Documentation is updated
  • Build passes successfully
  • No breaking changes
  • Commit message follows conventional commits format

PR Link

Create PR: https://github.com/cenova-labs/utils/pull/new/feature/sse-support

- Add SSEMessageEvent, SSECallbacks, SSEConfig types
- Add parseSSEStream method for parsing SSE response
- Add sse() convenience method for creating SSE connections
- Support custom headers (unlike native EventSource)
- Support POST requests and all HTTP methods
- Support interceptors integration
- Update README with SSE examples (EN & ZH)
- Remove docs directory (now auto-generated by CI)
- Accept main branch changes for .gitignore and doc.yaml
- Refactored SSE promise handling to avoid circular dependency
- Used variable to store abort handler for proper cleanup
@cc-hearts
cc-hearts merged commit 8baa4cf into mainJun 23, 2026
4 checks passed
@cc-hearts
cc-hearts deleted the feature/sse-support branch June 23, 2026 08:56
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@cc-hearts