10
0

overlay.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
  2. function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
  3. function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
  4. function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
  5. function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
  6. // The error overlay is inspired (and mostly copied) from Create React App (https://github.com/facebookincubator/create-react-app)
  7. // They, in turn, got inspired by webpack-hot-middleware (https://github.com/glenjamin/webpack-hot-middleware).
  8. import ansiHTML from "ansi-html-community";
  9. /**
  10. * @type {(input: string, position: number) => string}
  11. */
  12. var getCodePoint = String.prototype.codePointAt ? function (input, position) {
  13. return input.codePointAt(position);
  14. } : function (input, position) {
  15. return (input.charCodeAt(position) - 0xd800) * 0x400 + input.charCodeAt(position + 1) - 0xdc00 + 0x10000;
  16. };
  17. /**
  18. * @param {string} macroText
  19. * @param {RegExp} macroRegExp
  20. * @param {(input: string) => string} macroReplacer
  21. * @returns {string}
  22. */
  23. var replaceUsingRegExp = function replaceUsingRegExp(macroText, macroRegExp, macroReplacer) {
  24. macroRegExp.lastIndex = 0;
  25. var replaceMatch = macroRegExp.exec(macroText);
  26. var replaceResult;
  27. if (replaceMatch) {
  28. replaceResult = "";
  29. var replaceLastIndex = 0;
  30. do {
  31. if (replaceLastIndex !== replaceMatch.index) {
  32. replaceResult += macroText.substring(replaceLastIndex, replaceMatch.index);
  33. }
  34. var replaceInput = replaceMatch[0];
  35. replaceResult += macroReplacer(replaceInput);
  36. replaceLastIndex = replaceMatch.index + replaceInput.length;
  37. // eslint-disable-next-line no-cond-assign
  38. } while (replaceMatch = macroRegExp.exec(macroText));
  39. if (replaceLastIndex !== macroText.length) {
  40. replaceResult += macroText.substring(replaceLastIndex);
  41. }
  42. } else {
  43. replaceResult = macroText;
  44. }
  45. return replaceResult;
  46. };
  47. var references = {
  48. "<": "&lt;",
  49. ">": "&gt;",
  50. '"': "&quot;",
  51. "'": "&apos;",
  52. "&": "&amp;"
  53. };
  54. /**
  55. * @param {string} text text
  56. * @returns {string}
  57. */
  58. function encode(text) {
  59. if (!text) {
  60. return "";
  61. }
  62. return replaceUsingRegExp(text, /[<>'"&]/g, function (input) {
  63. var result = references[input];
  64. if (!result) {
  65. var code = input.length > 1 ? getCodePoint(input, 0) : input.charCodeAt(0);
  66. result = "&#".concat(code, ";");
  67. }
  68. return result;
  69. });
  70. }
  71. /**
  72. * @typedef {Object} StateDefinitions
  73. * @property {{[event: string]: { target: string; actions?: Array<string> }}} [on]
  74. */
  75. /**
  76. * @typedef {Object} Options
  77. * @property {{[state: string]: StateDefinitions}} states
  78. * @property {object} context;
  79. * @property {string} initial
  80. */
  81. /**
  82. * @typedef {Object} Implementation
  83. * @property {{[actionName: string]: (ctx: object, event: any) => object}} actions
  84. */
  85. /**
  86. * A simplified `createMachine` from `@xstate/fsm` with the following differences:
  87. *
  88. * - the returned machine is technically a "service". No `interpret(machine).start()` is needed.
  89. * - the state definition only support `on` and target must be declared with { target: 'nextState', actions: [] } explicitly.
  90. * - event passed to `send` must be an object with `type` property.
  91. * - actions implementation will be [assign action](https://xstate.js.org/docs/guides/context.html#assign-action) if you return any value.
  92. * Do not return anything if you just want to invoke side effect.
  93. *
  94. * The goal of this custom function is to avoid installing the entire `'xstate/fsm'` package, while enabling modeling using
  95. * state machine. You can copy the first parameter into the editor at https://stately.ai/viz to visualize the state machine.
  96. *
  97. * @param {Options} options
  98. * @param {Implementation} implementation
  99. */
  100. function createMachine(_ref, _ref2) {
  101. var states = _ref.states,
  102. context = _ref.context,
  103. initial = _ref.initial;
  104. var actions = _ref2.actions;
  105. var currentState = initial;
  106. var currentContext = context;
  107. return {
  108. send: function send(event) {
  109. var currentStateOn = states[currentState].on;
  110. var transitionConfig = currentStateOn && currentStateOn[event.type];
  111. if (transitionConfig) {
  112. currentState = transitionConfig.target;
  113. if (transitionConfig.actions) {
  114. transitionConfig.actions.forEach(function (actName) {
  115. var actionImpl = actions[actName];
  116. var nextContextValue = actionImpl && actionImpl(currentContext, event);
  117. if (nextContextValue) {
  118. currentContext = _objectSpread(_objectSpread({}, currentContext), nextContextValue);
  119. }
  120. });
  121. }
  122. }
  123. }
  124. };
  125. }
  126. /**
  127. * @typedef {Object} ShowOverlayData
  128. * @property {'warning' | 'error'} level
  129. * @property {Array<string | { moduleIdentifier?: string, moduleName?: string, loc?: string, message?: string }>} messages
  130. * @property {'build' | 'runtime'} messageSource
  131. */
  132. /**
  133. * @typedef {Object} CreateOverlayMachineOptions
  134. * @property {(data: ShowOverlayData) => void} showOverlay
  135. * @property {() => void} hideOverlay
  136. */
  137. /**
  138. * @param {CreateOverlayMachineOptions} options
  139. */
  140. var createOverlayMachine = function createOverlayMachine(options) {
  141. var hideOverlay = options.hideOverlay,
  142. showOverlay = options.showOverlay;
  143. return createMachine({
  144. initial: "hidden",
  145. context: {
  146. level: "error",
  147. messages: [],
  148. messageSource: "build"
  149. },
  150. states: {
  151. hidden: {
  152. on: {
  153. BUILD_ERROR: {
  154. target: "displayBuildError",
  155. actions: ["setMessages", "showOverlay"]
  156. },
  157. RUNTIME_ERROR: {
  158. target: "displayRuntimeError",
  159. actions: ["setMessages", "showOverlay"]
  160. }
  161. }
  162. },
  163. displayBuildError: {
  164. on: {
  165. DISMISS: {
  166. target: "hidden",
  167. actions: ["dismissMessages", "hideOverlay"]
  168. },
  169. BUILD_ERROR: {
  170. target: "displayBuildError",
  171. actions: ["appendMessages", "showOverlay"]
  172. }
  173. }
  174. },
  175. displayRuntimeError: {
  176. on: {
  177. DISMISS: {
  178. target: "hidden",
  179. actions: ["dismissMessages", "hideOverlay"]
  180. },
  181. RUNTIME_ERROR: {
  182. target: "displayRuntimeError",
  183. actions: ["appendMessages", "showOverlay"]
  184. },
  185. BUILD_ERROR: {
  186. target: "displayBuildError",
  187. actions: ["setMessages", "showOverlay"]
  188. }
  189. }
  190. }
  191. }
  192. }, {
  193. actions: {
  194. dismissMessages: function dismissMessages() {
  195. return {
  196. messages: [],
  197. level: "error",
  198. messageSource: "build"
  199. };
  200. },
  201. appendMessages: function appendMessages(context, event) {
  202. return {
  203. messages: context.messages.concat(event.messages),
  204. level: event.level || context.level,
  205. messageSource: event.type === "RUNTIME_ERROR" ? "runtime" : "build"
  206. };
  207. },
  208. setMessages: function setMessages(context, event) {
  209. return {
  210. messages: event.messages,
  211. level: event.level || context.level,
  212. messageSource: event.type === "RUNTIME_ERROR" ? "runtime" : "build"
  213. };
  214. },
  215. hideOverlay: hideOverlay,
  216. showOverlay: showOverlay
  217. }
  218. });
  219. };
  220. /**
  221. *
  222. * @param {Error} error
  223. */
  224. var parseErrorToStacks = function parseErrorToStacks(error) {
  225. if (!error || !(error instanceof Error)) {
  226. throw new Error("parseErrorToStacks expects Error object");
  227. }
  228. if (typeof error.stack === "string") {
  229. return error.stack.split("\n").filter(function (stack) {
  230. return stack !== "Error: ".concat(error.message);
  231. });
  232. }
  233. };
  234. /**
  235. * @callback ErrorCallback
  236. * @param {ErrorEvent} error
  237. * @returns {void}
  238. */
  239. /**
  240. * @param {ErrorCallback} callback
  241. */
  242. var listenToRuntimeError = function listenToRuntimeError(callback) {
  243. window.addEventListener("error", callback);
  244. return function cleanup() {
  245. window.removeEventListener("error", callback);
  246. };
  247. };
  248. /**
  249. * @callback UnhandledRejectionCallback
  250. * @param {PromiseRejectionEvent} rejectionEvent
  251. * @returns {void}
  252. */
  253. /**
  254. * @param {UnhandledRejectionCallback} callback
  255. */
  256. var listenToUnhandledRejection = function listenToUnhandledRejection(callback) {
  257. window.addEventListener("unhandledrejection", callback);
  258. return function cleanup() {
  259. window.removeEventListener("unhandledrejection", callback);
  260. };
  261. };
  262. // Styles are inspired by `react-error-overlay`
  263. var msgStyles = {
  264. error: {
  265. backgroundColor: "rgba(206, 17, 38, 0.1)",
  266. color: "#fccfcf"
  267. },
  268. warning: {
  269. backgroundColor: "rgba(251, 245, 180, 0.1)",
  270. color: "#fbf5b4"
  271. }
  272. };
  273. var iframeStyle = {
  274. position: "fixed",
  275. top: 0,
  276. left: 0,
  277. right: 0,
  278. bottom: 0,
  279. width: "100vw",
  280. height: "100vh",
  281. border: "none",
  282. "z-index": 9999999999
  283. };
  284. var containerStyle = {
  285. position: "fixed",
  286. boxSizing: "border-box",
  287. left: 0,
  288. top: 0,
  289. right: 0,
  290. bottom: 0,
  291. width: "100vw",
  292. height: "100vh",
  293. fontSize: "large",
  294. padding: "2rem 2rem 4rem 2rem",
  295. lineHeight: "1.2",
  296. whiteSpace: "pre-wrap",
  297. overflow: "auto",
  298. backgroundColor: "rgba(0, 0, 0, 0.9)",
  299. color: "white"
  300. };
  301. var headerStyle = {
  302. color: "#e83b46",
  303. fontSize: "2em",
  304. whiteSpace: "pre-wrap",
  305. fontFamily: "sans-serif",
  306. margin: "0 2rem 2rem 0",
  307. flex: "0 0 auto",
  308. maxHeight: "50%",
  309. overflow: "auto"
  310. };
  311. var dismissButtonStyle = {
  312. color: "#ffffff",
  313. lineHeight: "1rem",
  314. fontSize: "1.5rem",
  315. padding: "1rem",
  316. cursor: "pointer",
  317. position: "absolute",
  318. right: 0,
  319. top: 0,
  320. backgroundColor: "transparent",
  321. border: "none"
  322. };
  323. var msgTypeStyle = {
  324. color: "#e83b46",
  325. fontSize: "1.2em",
  326. marginBottom: "1rem",
  327. fontFamily: "sans-serif"
  328. };
  329. var msgTextStyle = {
  330. lineHeight: "1.5",
  331. fontSize: "1rem",
  332. fontFamily: "Menlo, Consolas, monospace"
  333. };
  334. // ANSI HTML
  335. var colors = {
  336. reset: ["transparent", "transparent"],
  337. black: "181818",
  338. red: "E36049",
  339. green: "B3CB74",
  340. yellow: "FFD080",
  341. blue: "7CAFC2",
  342. magenta: "7FACCA",
  343. cyan: "C3C2EF",
  344. lightgrey: "EBE7E3",
  345. darkgrey: "6D7891"
  346. };
  347. ansiHTML.setColors(colors);
  348. /**
  349. * @param {string} type
  350. * @param {string | { file?: string, moduleName?: string, loc?: string, message?: string; stack?: string[] }} item
  351. * @returns {{ header: string, body: string }}
  352. */
  353. var formatProblem = function formatProblem(type, item) {
  354. var header = type === "warning" ? "WARNING" : "ERROR";
  355. var body = "";
  356. if (typeof item === "string") {
  357. body += item;
  358. } else {
  359. var file = item.file || "";
  360. // eslint-disable-next-line no-nested-ternary
  361. var moduleName = item.moduleName ? item.moduleName.indexOf("!") !== -1 ? "".concat(item.moduleName.replace(/^(\s|\S)*!/, ""), " (").concat(item.moduleName, ")") : "".concat(item.moduleName) : "";
  362. var loc = item.loc;
  363. header += "".concat(moduleName || file ? " in ".concat(moduleName ? "".concat(moduleName).concat(file ? " (".concat(file, ")") : "") : file).concat(loc ? " ".concat(loc) : "") : "");
  364. body += item.message || "";
  365. }
  366. if (Array.isArray(item.stack)) {
  367. item.stack.forEach(function (stack) {
  368. if (typeof stack === "string") {
  369. body += "\r\n".concat(stack);
  370. }
  371. });
  372. }
  373. return {
  374. header: header,
  375. body: body
  376. };
  377. };
  378. /**
  379. * @typedef {Object} CreateOverlayOptions
  380. * @property {string | null} trustedTypesPolicyName
  381. * @property {boolean | (error: Error) => void} [catchRuntimeError]
  382. */
  383. /**
  384. *
  385. * @param {CreateOverlayOptions} options
  386. */
  387. var createOverlay = function createOverlay(options) {
  388. /** @type {HTMLIFrameElement | null | undefined} */
  389. var iframeContainerElement;
  390. /** @type {HTMLDivElement | null | undefined} */
  391. var containerElement;
  392. /** @type {HTMLDivElement | null | undefined} */
  393. var headerElement;
  394. /** @type {Array<(element: HTMLDivElement) => void>} */
  395. var onLoadQueue = [];
  396. /** @type {TrustedTypePolicy | undefined} */
  397. var overlayTrustedTypesPolicy;
  398. /**
  399. *
  400. * @param {HTMLElement} element
  401. * @param {CSSStyleDeclaration} style
  402. */
  403. function applyStyle(element, style) {
  404. Object.keys(style).forEach(function (prop) {
  405. element.style[prop] = style[prop];
  406. });
  407. }
  408. /**
  409. * @param {string | null} trustedTypesPolicyName
  410. */
  411. function createContainer(trustedTypesPolicyName) {
  412. // Enable Trusted Types if they are available in the current browser.
  413. if (window.trustedTypes) {
  414. overlayTrustedTypesPolicy = window.trustedTypes.createPolicy(trustedTypesPolicyName || "webpack-dev-server#overlay", {
  415. createHTML: function createHTML(value) {
  416. return value;
  417. }
  418. });
  419. }
  420. iframeContainerElement = document.createElement("iframe");
  421. iframeContainerElement.id = "webpack-dev-server-client-overlay";
  422. iframeContainerElement.src = "about:blank";
  423. applyStyle(iframeContainerElement, iframeStyle);
  424. iframeContainerElement.onload = function () {
  425. var contentElement = /** @type {Document} */
  426. (/** @type {HTMLIFrameElement} */
  427. iframeContainerElement.contentDocument).createElement("div");
  428. containerElement = /** @type {Document} */
  429. (/** @type {HTMLIFrameElement} */
  430. iframeContainerElement.contentDocument).createElement("div");
  431. contentElement.id = "webpack-dev-server-client-overlay-div";
  432. applyStyle(contentElement, containerStyle);
  433. headerElement = document.createElement("div");
  434. headerElement.innerText = "Compiled with problems:";
  435. applyStyle(headerElement, headerStyle);
  436. var closeButtonElement = document.createElement("button");
  437. applyStyle(closeButtonElement, dismissButtonStyle);
  438. closeButtonElement.innerText = "×";
  439. closeButtonElement.ariaLabel = "Dismiss";
  440. closeButtonElement.addEventListener("click", function () {
  441. // eslint-disable-next-line no-use-before-define
  442. overlayService.send({
  443. type: "DISMISS"
  444. });
  445. });
  446. contentElement.appendChild(headerElement);
  447. contentElement.appendChild(closeButtonElement);
  448. contentElement.appendChild(containerElement);
  449. /** @type {Document} */
  450. (/** @type {HTMLIFrameElement} */
  451. iframeContainerElement.contentDocument).body.appendChild(contentElement);
  452. onLoadQueue.forEach(function (onLoad) {
  453. onLoad(/** @type {HTMLDivElement} */contentElement);
  454. });
  455. onLoadQueue = [];
  456. /** @type {HTMLIFrameElement} */
  457. iframeContainerElement.onload = null;
  458. };
  459. document.body.appendChild(iframeContainerElement);
  460. }
  461. /**
  462. * @param {(element: HTMLDivElement) => void} callback
  463. * @param {string | null} trustedTypesPolicyName
  464. */
  465. function ensureOverlayExists(callback, trustedTypesPolicyName) {
  466. if (containerElement) {
  467. containerElement.innerHTML = overlayTrustedTypesPolicy ? overlayTrustedTypesPolicy.createHTML("") : "";
  468. // Everything is ready, call the callback right away.
  469. callback(containerElement);
  470. return;
  471. }
  472. onLoadQueue.push(callback);
  473. if (iframeContainerElement) {
  474. return;
  475. }
  476. createContainer(trustedTypesPolicyName);
  477. }
  478. // Successful compilation.
  479. function hide() {
  480. if (!iframeContainerElement) {
  481. return;
  482. }
  483. // Clean up and reset internal state.
  484. document.body.removeChild(iframeContainerElement);
  485. iframeContainerElement = null;
  486. containerElement = null;
  487. }
  488. // Compilation with errors (e.g. syntax error or missing modules).
  489. /**
  490. * @param {string} type
  491. * @param {Array<string | { moduleIdentifier?: string, moduleName?: string, loc?: string, message?: string }>} messages
  492. * @param {string | null} trustedTypesPolicyName
  493. * @param {'build' | 'runtime'} messageSource
  494. */
  495. function show(type, messages, trustedTypesPolicyName, messageSource) {
  496. ensureOverlayExists(function () {
  497. headerElement.innerText = messageSource === "runtime" ? "Uncaught runtime errors:" : "Compiled with problems:";
  498. messages.forEach(function (message) {
  499. var entryElement = document.createElement("div");
  500. var msgStyle = type === "warning" ? msgStyles.warning : msgStyles.error;
  501. applyStyle(entryElement, _objectSpread(_objectSpread({}, msgStyle), {}, {
  502. padding: "1rem 1rem 1.5rem 1rem"
  503. }));
  504. var typeElement = document.createElement("div");
  505. var _formatProblem = formatProblem(type, message),
  506. header = _formatProblem.header,
  507. body = _formatProblem.body;
  508. typeElement.innerText = header;
  509. applyStyle(typeElement, msgTypeStyle);
  510. if (message.moduleIdentifier) {
  511. applyStyle(typeElement, {
  512. cursor: "pointer"
  513. });
  514. // element.dataset not supported in IE
  515. typeElement.setAttribute("data-can-open", true);
  516. typeElement.addEventListener("click", function () {
  517. fetch("/webpack-dev-server/open-editor?fileName=".concat(message.moduleIdentifier));
  518. });
  519. }
  520. // Make it look similar to our terminal.
  521. var text = ansiHTML(encode(body));
  522. var messageTextNode = document.createElement("div");
  523. applyStyle(messageTextNode, msgTextStyle);
  524. messageTextNode.innerHTML = overlayTrustedTypesPolicy ? overlayTrustedTypesPolicy.createHTML(text) : text;
  525. entryElement.appendChild(typeElement);
  526. entryElement.appendChild(messageTextNode);
  527. /** @type {HTMLDivElement} */
  528. containerElement.appendChild(entryElement);
  529. });
  530. }, trustedTypesPolicyName);
  531. }
  532. var overlayService = createOverlayMachine({
  533. showOverlay: function showOverlay(_ref3) {
  534. var _ref3$level = _ref3.level,
  535. level = _ref3$level === void 0 ? "error" : _ref3$level,
  536. messages = _ref3.messages,
  537. messageSource = _ref3.messageSource;
  538. return show(level, messages, options.trustedTypesPolicyName, messageSource);
  539. },
  540. hideOverlay: hide
  541. });
  542. if (options.catchRuntimeError) {
  543. /**
  544. * @param {Error | undefined} error
  545. * @param {string} fallbackMessage
  546. */
  547. var handleError = function handleError(error, fallbackMessage) {
  548. var errorObject = error instanceof Error ? error : new Error(error || fallbackMessage);
  549. var shouldDisplay = typeof options.catchRuntimeError === "function" ? options.catchRuntimeError(errorObject) : true;
  550. if (shouldDisplay) {
  551. overlayService.send({
  552. type: "RUNTIME_ERROR",
  553. messages: [{
  554. message: errorObject.message,
  555. stack: parseErrorToStacks(errorObject)
  556. }]
  557. });
  558. }
  559. };
  560. listenToRuntimeError(function (errorEvent) {
  561. // error property may be empty in older browser like IE
  562. var error = errorEvent.error,
  563. message = errorEvent.message;
  564. if (!error && !message) {
  565. return;
  566. }
  567. handleError(error, message);
  568. });
  569. listenToUnhandledRejection(function (promiseRejectionEvent) {
  570. var reason = promiseRejectionEvent.reason;
  571. handleError(reason, "Unknown promise rejection reason");
  572. });
  573. }
  574. return overlayService;
  575. };
  576. export { formatProblem, createOverlay };