-
src/lib/api/sse-manager.js- SSE Connection Manager- User connection tracking
- Room/conversation management
- Broadcasting utilities
- Keep-alive mechanism
- Connection cleanup
-
src/lib/api/protocol.js- Protocol Utilities- Message type constants (all WebSocket types preserved)
- Message creation and validation helpers
- SSE formatting functions
-
src/lib/api/middleware/auth.js- Authentication Middleware- Request authentication
withAuth()wrapper for protected routes- Session validation
src/routes/api/events/+server.js- SSE endpoint for real-time updates
src/routes/api/messages/send/+server.js- Send messagessrc/routes/api/messages/load/+server.js- Load messages with pagination
src/routes/api/conversations/create/+server.js- Create conversationssrc/routes/api/conversations/load/+server.js- Load user conversationssrc/routes/api/conversations/join/+server.js- Join conversation room
src/routes/api/typing/start/+server.js- Start typing indicatorsrc/routes/api/typing/stop/+server.js- Stop typing indicator
src/lib/stores/chat.js- Complete refactor from WebSocket to SSE + POST- Replaced
WebSocketwithEventSourcefor receiving - Replaced
ws.send()withfetch()POST requests - Updated connection management for SSE
- Maintained all encryption logic
- Backward compatible exports (
wsChatalias) - 716 lines (down from 836 - 14% reduction)
- Replaced
WEBSOCKET_TO_POST_SSE_MIGRATION.md- Complete analysis of all changes neededWEBSOCKET_TO_SSE_IMPLEMENTATION_GUIDE.md- Implementation guide with code templates
-
Server.js Updates -
server.js- Remove WebSocket server initialization (lines 8-40)
- Remove upgrade handler
- Start SSE keep-alive:
sseManager.startKeepAlive(30000) - Update shutdown to cleanup SSE connections
-
Voice Call Endpoints - Need to create:
/api/calls/offer- Initiate call/api/calls/answer- Answer call/api/calls/decline- Decline call/api/calls/end- End call/api/calls/ice-candidate- Exchange ICE candidates
-
WebRTC Signaling Updates
src/lib/webrtc/ml-kem-call-manager.jssrc/lib/webrtc/webrtc-service.js- Decision needed: POST/SSE, WebRTC data channels, or hybrid approach
-
PWA Updates
src/lib/utils/pwa-session-manager.js- Update connection checkssrc/lib/utils/pwa-diagnostics.js- Update diagnostics for SSE
-
Locale Strings -
src/lib/locales/en.js- Update references from "WebSocket" to "API" or "real-time connection"
-
Cleanup
- Remove
wsdependency frompackage.json - Delete
src/routes/api/websocket/+server.js - Remove unused WebSocket files from
src/lib/websocket/
- Remove
-
Testing
- Create SSE connection tests
- Test all new API endpoints
- Test reconnection scenarios
- Test concurrent connections
- Update existing WebSocket tests
- Files Created: 13 (12 server + 1 client refactor)
- Files to Modify: ~8
- Files to Delete: ~13
- Estimated Remaining Effort: 1-2 days
- ✅
Refactor client-side store- COMPLETED - Update
server.jsto remove WebSocket and start SSE keep-alive - Write comprehensive tests for SSE + POST architecture
- Create voice call API endpoints
- Update WebRTC signaling
- Test thoroughly
- Clean up old WebSocket code
- SSE manager connection handling
- Protocol message formatting
- Authentication middleware
- SSE connection establishment
- Message sending via POST
- Message receiving via SSE
- Typing indicators
- Conversation management
- Multiple simultaneous connections
- Complete chat flow
- File uploads
- Voice/video calls
- PWA session restoration
-
TypeScript Errors: The TypeScript errors in JavaScript files are expected and can be ignored. This is a JavaScript project using JSDoc comments.
-
SSE Connection Limits: Browsers typically limit SSE connections to 6 per domain. This should be sufficient for most use cases.
-
WebRTC Signaling: The voice/video call signaling may need special consideration. Options:
- Use POST + SSE (simpler, may have latency)
- Use WebRTC data channels (more complex, lower latency)
- Hybrid: Keep WebSocket only for calls (easiest migration)
-
Backward Compatibility: Consider running both WebSocket and SSE in parallel during migration with a feature flag.
-
Performance: SSE + POST may have slightly higher latency for client→server messages compared to WebSocket, but should be negligible for chat applications.
// In src/lib/stores/chat.js (renamed from websocket-chat.js)
let eventSource = null;
function connect(token) {
const url = `/api/events`;
eventSource = new EventSource(url);
eventSource.addEventListener('NEW_MESSAGE', (event) => {
const message = JSON.parse(event.data);
handleNewMessage(message.data.message);
});
eventSource.addEventListener('error', (error) => {
console.error('SSE error:', error);
// Implement reconnection logic
});
}async function sendMessage(conversationId, content) {
const response = await fetch('/api/messages/send', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ conversationId, content })
});
return response.json();
}- Zero-Downtime Migration: Deploy SSE endpoints alongside WebSocket, use feature flag to switch
- Monitoring: Add logging for SSE connection counts, message delivery rates
- Scaling: SSE connections are stateful - consider sticky sessions or Redis for multi-server deployments
- Fallbacks: Implement polling fallback for environments that block SSE
- Simpler Architecture: Standard HTTP/REST instead of WebSocket protocol
- Better Compatibility: Works with more proxies and firewalls
- Easier Debugging: Standard HTTP tools work for POST requests
- HTTP/2 Multiplexing: Better performance with HTTP/2
- Easier Load Balancing: Standard HTTP load balancing works
- Cleaner Code: Separation of concerns (POST for sending, SSE for receiving)