silphius/app/websocket.js
2024-11-04 12:39:06 -06:00

39 lines
1.1 KiB
JavaScript

import {WebSocketServer} from 'ws';
import {singleton} from '@/lib/singleton.js';
let wss = singleton('cha0s-remix$$wss');
if (!wss) {
wss = new WebSocketServer({
clientTracking: !!import.meta.hot,
noServer: true,
});
wss.on('connection', async (websocket, request) => {
const {routes} = await import('./websocket-routes.js');
const {pathname} = new URL(request.url, 'https://example.com');
const M = routes[`./websocket${'/' === pathname ? '/_index' : pathname}.js`];
if (!M) {
websocket.close(1008, 'does not exist');
return;
}
const {handleConnection} = await M();
handleConnection(websocket, request);
});
singleton.set('cha0s-remix$$wss', wss);
}
export function handleUpgrade(request, socket, head) {
wss.handleUpgrade(request, socket, head, (websocket) => {
wss.emit('connection', websocket, request);
});
}
if (import.meta.hot) {
import.meta.hot.on('vite:beforeUpdate', async () => {
for (const websocket of wss.clients) {
websocket.close(1001, 'hmr');
}
});
import.meta.hot.accept();
}