-
-
Notifications
You must be signed in to change notification settings - Fork 77
Expand file tree
/
Copy pathws.ts
More file actions
68 lines (60 loc) · 1.9 KB
/
ws.ts
File metadata and controls
68 lines (60 loc) · 1.9 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
61
62
63
64
65
66
67
68
/* eslint-disable no-console */
import type { ConnectionMeta, DevToolsNodeContext, DevToolsRpcClientFunctions, DevToolsRpcServerFunctions } from '@vitejs/devtools-kit'
import type { WebSocket } from 'ws'
import type { RpcFunctionsHost } from './host-functions'
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'
export interface CreateWsServerOptions {
cwd: string
portWebSocket?: number
base?: string
context: DevToolsNodeContext
}
export async function createWsServer(options: CreateWsServerOptions) {
const rpcHost = options.context.rpc as unknown as RpcFunctionsHost
const port = options.portWebSocket ?? await getPort({ port: 7812, random: true })
const wsClients = new Set<WebSocket>()
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 rpcGroup = createRpcServer<DevToolsRpcClientFunctions, DevToolsRpcServerFunctions>(
rpcHost.functions,
{
preset,
rpcOptions: {
onFunctionError(error, name) {
console.error(c.red`⬢ RPC error on executing "${c.bold(name)}":`)
console.error(error)
},
onGeneralError(error) {
console.error(c.red`⬢ RPC error on executing rpc`)
console.error(error)
},
},
},
)
rpcHost.rpcGroup = rpcGroup
const getConnectionMeta = async (): Promise<ConnectionMeta> => {
return {
backend: 'websocket',
websocket: port,
}
}
return {
port,
rpc: rpcGroup,
rpcHost,
getConnectionMeta,
}
}