MCPcopy
hub / github.com/vercel/next.js / connectHMR

Function connectHMR

turbopack/crates/turbopack-cli/js/src/entry/websocket.ts:39–95  ·  view source on GitHub ↗
(options: HMROptions)

Source from the content-addressed store, hash-verified

37
38// This is not used by Next.js, but it is used by the standalone turbopack-cli
39export function connectHMR(options: HMROptions) {
40 const { timeout = 5 * 1000 } = options
41
42 function init() {
43 if (source) source.close()
44
45 console.log('[HMR] connecting...')
46
47 function handleOnline() {
48 const connected = { type: 'turbopack-connected' as const }
49 messageCallbacks.forEach((cb) => {
50 cb(connected)
51 })
52
53 if (options.log) console.log('[HMR] connected')
54 // lastActivity = Date.now()
55 }
56
57 function handleMessage(event: MessageEvent) {
58 // lastActivity = Date.now()
59
60 const message = {
61 type: 'turbopack-message' as const,
62 data: JSON.parse(event.data),
63 }
64 messageCallbacks.forEach((cb) => {
65 cb(message)
66 })
67 }
68
69 // let timer: NodeJS.Timeout
70
71 function handleDisconnect() {
72 source.close()
73 setTimeout(init, timeout)
74 }
75
76 const { hostname, port } = location
77 const protocol = getSocketProtocol(options.assetPrefix || '')
78 const assetPrefix = options.assetPrefix.replace(/^\/+/, '')
79
80 let url = `${protocol}://${hostname}:${port}${
81 assetPrefix ? `/${assetPrefix}` : ''
82 }`
83
84 if (assetPrefix.startsWith('http')) {
85 url = `${protocol}://${assetPrefix.split('://')[1]}`
86 }
87
88 source = new window.WebSocket(`${url}${options.path}`)
89 source.onopen = handleOnline
90 source.onerror = handleDisconnect
91 source.onmessage = handleMessage
92 }
93
94 init()
95}

Callers 1

initializeHMRFunction · 0.90

Calls 1

initFunction · 0.70

Tested by

no test coverage detected