webpack/hot/lazy-compilation-web.js

84 lines
2.0 KiB
JavaScript
Raw Normal View History

2021-01-21 23:32:49 +08:00
/* global __resourceQuery */
"use strict";
2021-01-22 08:01:17 +08:00
if (typeof EventSource !== "function") {
2021-01-21 23:32:49 +08:00
throw new Error(
2021-01-22 08:01:17 +08:00
"Environment doesn't support lazy compilation (requires EventSource)"
2021-01-21 23:32:49 +08:00
);
}
var urlBase = decodeURIComponent(__resourceQuery.slice(1));
2023-05-15 23:49:46 +08:00
/** @type {EventSource | undefined} */
2021-01-21 23:32:49 +08:00
var activeEventSource;
var activeKeys = new Map();
2021-01-22 04:05:23 +08:00
var errorHandlers = new Set();
2021-01-21 23:32:49 +08:00
var updateEventSource = function updateEventSource() {
if (activeEventSource) activeEventSource.close();
2021-01-22 04:05:23 +08:00
if (activeKeys.size) {
activeEventSource = new EventSource(
urlBase + Array.from(activeKeys.keys()).join("@")
);
2023-05-15 23:49:46 +08:00
/**
* @this {EventSource}
* @param {Event & { message?: string, filename?: string, lineno?: number, colno?: number, error?: Error }} event event
*/
2021-01-22 04:05:23 +08:00
activeEventSource.onerror = function (event) {
errorHandlers.forEach(function (onError) {
onError(
new Error(
"Problem communicating active modules to the server: " +
event.message +
" " +
event.filename +
":" +
event.lineno +
":" +
event.colno +
" " +
event.error
)
);
});
};
} else {
activeEventSource = undefined;
}
2021-01-21 23:32:49 +08:00
};
2023-05-15 23:49:46 +08:00
/**
* @param {{ data: string, onError: (err: Error) => void, active: boolean, module: module }} options options
* @returns {() => void} function to destroy response
*/
2021-01-22 04:05:23 +08:00
exports.keepAlive = function (options) {
var data = options.data;
var onError = options.onError;
2021-01-22 08:01:17 +08:00
var active = options.active;
var module = options.module;
2021-01-22 04:05:23 +08:00
errorHandlers.add(onError);
var value = activeKeys.get(data) || 0;
activeKeys.set(data, value + 1);
2021-01-21 23:32:49 +08:00
if (value === 0) {
updateEventSource();
}
2021-01-22 08:01:17 +08:00
if (!active && !module.hot) {
console.log(
"Hot Module Replacement is not enabled. Waiting for process restart..."
);
}
2021-01-21 23:32:49 +08:00
return function () {
2021-01-22 04:05:23 +08:00
errorHandlers.delete(onError);
2021-01-21 23:32:49 +08:00
setTimeout(function () {
2021-01-22 04:05:23 +08:00
var value = activeKeys.get(data);
2021-01-21 23:32:49 +08:00
if (value === 1) {
2021-01-22 04:05:23 +08:00
activeKeys.delete(data);
2021-01-21 23:32:49 +08:00
updateEventSource();
} else {
2021-01-22 04:05:23 +08:00
activeKeys.set(data, value - 1);
2021-01-21 23:32:49 +08:00
}
}, 1000);
};
};