lazy-compilation-web.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. "use strict";
  2. /* global __resourceQuery */
  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. errorHandlers.add(onError);
  53. var value = activeKeys.get(data) || 0;
  54. activeKeys.set(data, value + 1);
  55. if (value === 0) {
  56. updateEventSource();
  57. }
  58. if (!options.active && !options.module.hot) {
  59. console.log(
  60. "Hot Module Replacement is not enabled. Waiting for process restart..."
  61. );
  62. }
  63. return function () {
  64. errorHandlers.delete(onError);
  65. setTimeout(function () {
  66. var value = activeKeys.get(data);
  67. if (value === 1) {
  68. activeKeys.delete(data);
  69. updateEventSource();
  70. } else {
  71. activeKeys.set(data, value - 1);
  72. }
  73. }, 1000);
  74. };
  75. };
  76. /**
  77. * @param {string} value new url value
  78. */
  79. exports.setUrl = function (value) {
  80. urlBase = value;
  81. };