-
-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathws.ts
More file actions
60 lines (52 loc) · 1.63 KB
/
Copy pathws.ts
File metadata and controls
60 lines (52 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import type { WebSocket } from 'ws'
import type { ConnectionMeta } from '../shared/types'
import type { CreateServerFunctionsOptions } from './functions'
import type { ServerFunctions } from './rpc'
import { createRpcServer } from '@vitejs/devtools-rpc'
import { createWsRpcPreset } from '@vitejs/devtools-rpc/presets/ws/server'
import c from 'ansis'
import { getPort } from 'get-port-please'
import { MARK_CHECK } from './constants'
import { createServerFunctions } from './functions'
export interface CreateWsServerOptions extends CreateServerFunctionsOptions {
cwd: string
port?: number
}
export async function createWsServer(options: CreateWsServerOptions) {
const port = options.port ?? await getPort({ port: 7812, random: true })
const wsClients = new Set<WebSocket>()
const serverFunctions = await createServerFunctions(options)
const preset = createWsRpcPreset({
port: port!,
onConnected: (ws) => {
wsClients.add(ws)
console.log(c.green`${MARK_CHECK} Websocket client connected`)
},
onDisconnected: (ws) => {
wsClients.delete(ws)
console.log(c.red`${MARK_CHECK} Websocket client disconnected`)
},
})
const rpc = createRpcServer<ServerFunctions, ServerFunctions>(serverFunctions, {
preset,
rpcOptions: {
onError(error, name) {
console.error(c.red`⬢ RPC error on executing "${c.bold(name)}":`)
console.error(error)
throw error
},
},
})
const getMetadata = async (): Promise<ConnectionMeta> => {
return {
backend: 'websocket',
websocket: port,
}
}
return {
port,
rpc,
serverFunctions,
getMetadata,
}
}