lazy-compilation-web.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /* global __resourceQuery */
  2. "use strict";
  3. if (typeof EventSource !== "function") {
  4. throw new Error(
  5. "Environment doesn't support lazy compilation (requires EventSource)"
  6. );
  7. }
  8. var urlBase = decodeURIComponent(__resourceQuery.slice(1));
  9. /** @type {EventSource | undefined} */
  10. var activeEventSource;
  11. var activeKeys = new Map();
  12. var errorHandlers = new Set();
  13. var updateEventSource = function updateEventSource() {
  14. if (activeEventSource) activeEventSource.close();
  15. if (activeKeys.size) {
  16. activeEventSource = new EventSource(
  17. urlBase + Array.from(activeKeys.keys()).join("@")
  18. );
  19. /**
  20. * @this {EventSource}
  21. * @param {Event & { message?: string, filename?: string, lineno?: number, colno?: number, error?: Error }} event event
  22. */
  23. activeEventSource.onerror = function (event) {
  24. errorHandlers.forEach(function (onError) {
  25. onError(
  26. new Error(
  27. "Problem communicating active modules to the server: " +
  28. event.message +
  29. " " +
  30. event.filename +
  31. ":" +
  32. event.lineno +
  33. ":" +
  34. event.colno +
  35. " " +
  36. event.error
  37. )
  38. );
  39. });
  40. };
  41. } else {
  42. activeEventSource = undefined;
  43. }
  44. };
  45. /**
  46. * @param {{ data: string, onError: (err: Error) => void, active: boolean, module: module }} options options
  47. * @returns {() => void} function to destroy response
  48. */
  49. exports.keepAlive = function (options) {
  50. var data = options.data;
  51. var onError = options.onError;
  52. var active = options.active;
  53. var module = options.module;
  54. errorHandlers.add(onError);
  55. var value = activeKeys.get(data) || 0;
  56. activeKeys.set(data, value + 1);
  57. if (value === 0) {
  58. updateEventSource();
  59. }
  60. if (!active && !module.hot) {
  61. console.log(
  62. "Hot Module Replacement is not enabled. Waiting for process restart..."
  63. );
  64. }
  65. return function () {
  66. errorHandlers.delete(onError);
  67. setTimeout(function () {
  68. var value = activeKeys.get(data);
  69. if (value === 1) {
  70. activeKeys.delete(data);
  71. updateEventSource();
  72. } else {
  73. activeKeys.set(data, value - 1);
  74. }
  75. }, 1000);
  76. };
  77. };