mirror of
https://github.com/hanzoai/next.js.git
synced 2026-10-30 14:46:38 +00:00
The HMR messages we send through the WebSocket to the browser were inconsistently called `message`, `msg`, `obj`, `payload`, or `action`. With this PR, we're streamlining the naming to consistently use `message` throughout the codebase. In addition, the discriminating property `action` is renamed to `type`, aligning it with Turbopack's own HMR messages. As an alternative, I considered naming them `action` instead, but this did not yield the desired consistency across the codebase. Ultimately, I decided to stick with `message` to avoid confusion and maintain alignment with Turbopack's terminology (see `@vercel/turbopack-ecmascript-runtime/browser/dev/hmr-client/hmr-client`).
58 lines
1.9 KiB
JavaScript
58 lines
1.9 KiB
JavaScript
let source;
|
|
const messageCallbacks = [];
|
|
function getSocketProtocol(assetPrefix) {
|
|
let protocol = location.protocol;
|
|
try {
|
|
protocol = new URL(assetPrefix).protocol;
|
|
} catch (_) {}
|
|
return protocol === "http:" ? "ws" : "wss";
|
|
}
|
|
export function addMessageListener(cb) {
|
|
messageCallbacks.push(cb);
|
|
}
|
|
export function sendMessage(data) {
|
|
if (!source || source.readyState !== source.OPEN) return;
|
|
return source.send(data);
|
|
}
|
|
export function connectHMR(options) {
|
|
const { timeout = 5 * 1000 } = options;
|
|
function init() {
|
|
if (source) source.close();
|
|
console.log("[HMR] connecting...");
|
|
function handleOnline() {
|
|
const connected = {
|
|
type: "turbopack-connected"
|
|
};
|
|
messageCallbacks.forEach((cb)=>{
|
|
cb(connected);
|
|
});
|
|
if (options.log) console.log("[HMR] connected");
|
|
}
|
|
function handleMessage(event) {
|
|
const message = {
|
|
type: "turbopack-message",
|
|
data: JSON.parse(event.data)
|
|
};
|
|
messageCallbacks.forEach((cb)=>{
|
|
cb(message);
|
|
});
|
|
}
|
|
function handleDisconnect() {
|
|
source.close();
|
|
setTimeout(init, timeout);
|
|
}
|
|
const { hostname, port } = location;
|
|
const protocol = getSocketProtocol(options.assetPrefix || "");
|
|
const assetPrefix = options.assetPrefix.replace(/^\/+/, "");
|
|
let url = `${protocol}://${hostname}:${port}${assetPrefix ? `/${assetPrefix}` : ""}`;
|
|
if (assetPrefix.startsWith("http")) {
|
|
url = `${protocol}://${assetPrefix.split("://")[1]}`;
|
|
}
|
|
source = new window.WebSocket(`${url}${options.path}`);
|
|
source.onopen = handleOnline;
|
|
source.onerror = handleDisconnect;
|
|
source.onmessage = handleMessage;
|
|
}
|
|
init();
|
|
}
|