client.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  1. import './env';
  2. const template = /*html*/ `
  3. <style>
  4. :host {
  5. position: fixed;
  6. z-index: 99999;
  7. top: 0;
  8. left: 0;
  9. width: 100%;
  10. height: 100%;
  11. overflow-y: scroll;
  12. margin: 0;
  13. background: rgba(0, 0, 0, 0.66);
  14. --monospace: 'SFMono-Regular', Consolas,
  15. 'Liberation Mono', Menlo, Courier, monospace;
  16. --red: #ff5555;
  17. --yellow: #e2aa53;
  18. --purple: #cfa4ff;
  19. --cyan: #2dd9da;
  20. --dim: #c9c9c9;
  21. }
  22. .window {
  23. font-family: var(--monospace);
  24. line-height: 1.5;
  25. width: 800px;
  26. color: #d8d8d8;
  27. margin: 30px auto;
  28. padding: 25px 40px;
  29. position: relative;
  30. background: #181818;
  31. border-radius: 6px 6px 8px 8px;
  32. box-shadow: 0 19px 38px rgba(0,0,0,0.30), 0 15px 12px rgba(0,0,0,0.22);
  33. overflow: hidden;
  34. border-top: 8px solid var(--red);
  35. }
  36. pre {
  37. font-family: var(--monospace);
  38. font-size: 16px;
  39. margin-top: 0;
  40. margin-bottom: 1em;
  41. overflow-x: scroll;
  42. scrollbar-width: none;
  43. }
  44. pre::-webkit-scrollbar {
  45. display: none;
  46. }
  47. .message {
  48. line-height: 1.3;
  49. font-weight: 600;
  50. white-space: pre-wrap;
  51. }
  52. .message-body {
  53. color: var(--red);
  54. }
  55. .plugin {
  56. color: var(--purple);
  57. }
  58. .file {
  59. color: var(--cyan);
  60. margin-bottom: 0;
  61. white-space: pre-wrap;
  62. word-break: break-all;
  63. }
  64. .frame {
  65. color: var(--yellow);
  66. }
  67. .stack {
  68. font-size: 13px;
  69. color: var(--dim);
  70. }
  71. .tip {
  72. font-size: 13px;
  73. color: #999;
  74. border-top: 1px dotted #999;
  75. padding-top: 13px;
  76. }
  77. code {
  78. font-size: 13px;
  79. font-family: var(--monospace);
  80. color: var(--yellow);
  81. }
  82. .file-link {
  83. text-decoration: underline;
  84. cursor: pointer;
  85. }
  86. </style>
  87. <div class="window">
  88. <pre class="message"><span class="plugin"></span><span class="message-body"></span></pre>
  89. <pre class="file"></pre>
  90. <pre class="frame"></pre>
  91. <pre class="stack"></pre>
  92. <div class="tip">
  93. Click outside or fix the code to dismiss.<br>
  94. You can also disable this overlay with
  95. <code>hmr: { overlay: false }</code> in <code>vite.config.js.</code>
  96. </div>
  97. </div>
  98. `;
  99. const fileRE = /(?:[a-zA-Z]:\\|\/).*?:\d+:\d+/g;
  100. const codeframeRE = /^(?:>?\s+\d+\s+\|.*|\s+\|\s*\^.*)\r?\n/gm;
  101. class ErrorOverlay extends HTMLElement {
  102. constructor(err) {
  103. var _a;
  104. super();
  105. this.root = this.attachShadow({ mode: 'open' });
  106. this.root.innerHTML = template;
  107. codeframeRE.lastIndex = 0;
  108. const hasFrame = err.frame && codeframeRE.test(err.frame);
  109. const message = hasFrame
  110. ? err.message.replace(codeframeRE, '')
  111. : err.message;
  112. if (err.plugin) {
  113. this.text('.plugin', `[plugin:${err.plugin}] `);
  114. }
  115. this.text('.message-body', message.trim());
  116. const [file] = (((_a = err.loc) === null || _a === void 0 ? void 0 : _a.file) || err.id || 'unknown file').split(`?`);
  117. if (err.loc) {
  118. this.text('.file', `${file}:${err.loc.line}:${err.loc.column}`, true);
  119. }
  120. else if (err.id) {
  121. this.text('.file', file);
  122. }
  123. if (hasFrame) {
  124. this.text('.frame', err.frame.trim());
  125. }
  126. this.text('.stack', err.stack, true);
  127. this.root.querySelector('.window').addEventListener('click', (e) => {
  128. e.stopPropagation();
  129. });
  130. this.addEventListener('click', () => {
  131. this.close();
  132. });
  133. }
  134. text(selector, text, linkFiles = false) {
  135. const el = this.root.querySelector(selector);
  136. if (!linkFiles) {
  137. el.textContent = text;
  138. }
  139. else {
  140. let curIndex = 0;
  141. let match;
  142. while ((match = fileRE.exec(text))) {
  143. const { 0: file, index } = match;
  144. if (index != null) {
  145. const frag = text.slice(curIndex, index);
  146. el.appendChild(document.createTextNode(frag));
  147. const link = document.createElement('a');
  148. link.textContent = file;
  149. link.className = 'file-link';
  150. link.onclick = () => {
  151. fetch('/__open-in-editor?file=' + encodeURIComponent(file));
  152. };
  153. el.appendChild(link);
  154. curIndex += frag.length + file.length;
  155. }
  156. }
  157. }
  158. }
  159. close() {
  160. var _a;
  161. (_a = this.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(this);
  162. }
  163. }
  164. const overlayId = 'vite-error-overlay';
  165. customElements.define(overlayId, ErrorOverlay);
  166. console.log('[vite] connecting...');
  167. // use server configuration, then fallback to inference
  168. const socketProtocol = __HMR_PROTOCOL__ || (location.protocol === 'https:' ? 'wss' : 'ws');
  169. const socketHost = `${__HMR_HOSTNAME__ || location.hostname}:${__HMR_PORT__}`;
  170. const socket = new WebSocket(`${socketProtocol}://${socketHost}`, 'vite-hmr');
  171. const base = __BASE__ || '/';
  172. function warnFailedFetch(err, path) {
  173. if (!err.message.match('fetch')) {
  174. console.error(err);
  175. }
  176. console.error(`[hmr] Failed to reload ${path}. ` +
  177. `This could be due to syntax errors or importing non-existent ` +
  178. `modules. (see errors above)`);
  179. }
  180. // Listen for messages
  181. socket.addEventListener('message', async ({ data }) => {
  182. handleMessage(JSON.parse(data));
  183. });
  184. let isFirstUpdate = true;
  185. async function handleMessage(payload) {
  186. switch (payload.type) {
  187. case 'connected':
  188. console.log(`[vite] connected.`);
  189. // proxy(nginx, docker) hmr ws maybe caused timeout,
  190. // so send ping package let ws keep alive.
  191. setInterval(() => socket.send('ping'), __HMR_TIMEOUT__);
  192. break;
  193. case 'update':
  194. // if this is the first update and there's already an error overlay, it
  195. // means the page opened with existing server compile error and the whole
  196. // module script failed to load (since one of the nested imports is 500).
  197. // in this case a normal update won't work and a full reload is needed.
  198. if (isFirstUpdate && hasErrorOverlay()) {
  199. window.location.reload();
  200. return;
  201. }
  202. else {
  203. clearErrorOverlay();
  204. isFirstUpdate = false;
  205. }
  206. payload.updates.forEach((update) => {
  207. if (update.type === 'js-update') {
  208. queueUpdate(fetchUpdate(update));
  209. }
  210. else {
  211. // css-update
  212. // this is only sent when a css file referenced with <link> is updated
  213. let { path, timestamp } = update;
  214. path = path.replace(/\?.*/, '');
  215. // can't use querySelector with `[href*=]` here since the link may be
  216. // using relative paths so we need to use link.href to grab the full
  217. // URL for the include check.
  218. const el = [].slice.call(document.querySelectorAll(`link`)).find((e) => e.href.includes(path));
  219. if (el) {
  220. const newPath = `${path}${path.includes('?') ? '&' : '?'}t=${timestamp}`;
  221. el.href = new URL(newPath, el.href).href;
  222. }
  223. console.log(`[vite] css hot updated: ${path}`);
  224. }
  225. });
  226. break;
  227. case 'custom':
  228. const cbs = customListenersMap.get(payload.event);
  229. if (cbs) {
  230. cbs.forEach((cb) => cb(payload.data));
  231. }
  232. break;
  233. case 'full-reload':
  234. if (payload.path && payload.path.endsWith('.html')) {
  235. // if html file is edited, only reload the page if the browser is
  236. // currently on that page.
  237. const pagePath = location.pathname;
  238. const payloadPath = base + payload.path.slice(1);
  239. if (pagePath === payloadPath ||
  240. (pagePath.endsWith('/') && pagePath + 'index.html' === payloadPath)) {
  241. location.reload();
  242. }
  243. return;
  244. }
  245. else {
  246. location.reload();
  247. }
  248. break;
  249. case 'prune':
  250. // After an HMR update, some modules are no longer imported on the page
  251. // but they may have left behind side effects that need to be cleaned up
  252. // (.e.g style injections)
  253. // TODO Trigger their dispose callbacks.
  254. payload.paths.forEach((path) => {
  255. const fn = pruneMap.get(path);
  256. if (fn) {
  257. fn(dataMap.get(path));
  258. }
  259. });
  260. break;
  261. case 'error':
  262. const err = payload.err;
  263. if (enableOverlay) {
  264. createErrorOverlay(err);
  265. }
  266. else {
  267. console.error(`[vite] Internal Server Error\n${err.stack}`);
  268. }
  269. break;
  270. default:
  271. const check = payload;
  272. return check;
  273. }
  274. }
  275. const enableOverlay = __HMR_ENABLE_OVERLAY__;
  276. function createErrorOverlay(err) {
  277. if (!enableOverlay)
  278. return;
  279. clearErrorOverlay();
  280. document.body.appendChild(new ErrorOverlay(err));
  281. }
  282. function clearErrorOverlay() {
  283. document
  284. .querySelectorAll(overlayId)
  285. .forEach((n) => n.close());
  286. }
  287. function hasErrorOverlay() {
  288. return document.querySelectorAll(overlayId).length;
  289. }
  290. let pending = false;
  291. let queued = [];
  292. /**
  293. * buffer multiple hot updates triggered by the same src change
  294. * so that they are invoked in the same order they were sent.
  295. * (otherwise the order may be inconsistent because of the http request round trip)
  296. */
  297. async function queueUpdate(p) {
  298. queued.push(p);
  299. if (!pending) {
  300. pending = true;
  301. await Promise.resolve();
  302. pending = false;
  303. const loading = [...queued];
  304. queued = [];
  305. (await Promise.all(loading)).forEach((fn) => fn && fn());
  306. }
  307. }
  308. // ping server
  309. socket.addEventListener('close', ({ wasClean }) => {
  310. if (wasClean)
  311. return;
  312. console.log(`[vite] server connection lost. polling for restart...`);
  313. setInterval(() => {
  314. fetch(`${base}__vite_ping`)
  315. .then(() => {
  316. location.reload();
  317. })
  318. .catch((e) => {
  319. /* ignore */
  320. });
  321. }, 1000);
  322. });
  323. const sheetsMap = new Map();
  324. function updateStyle(id, content) {
  325. let style = sheetsMap.get(id);
  326. {
  327. if (style && !(style instanceof HTMLStyleElement)) {
  328. removeStyle(id);
  329. style = undefined;
  330. }
  331. if (!style) {
  332. style = document.createElement('style');
  333. style.setAttribute('type', 'text/css');
  334. style.innerHTML = content;
  335. document.head.appendChild(style);
  336. }
  337. else {
  338. style.innerHTML = content;
  339. }
  340. }
  341. sheetsMap.set(id, style);
  342. }
  343. function removeStyle(id) {
  344. let style = sheetsMap.get(id);
  345. if (style) {
  346. if (style instanceof CSSStyleSheet) {
  347. // @ts-ignore
  348. document.adoptedStyleSheets.indexOf(style);
  349. // @ts-ignore
  350. document.adoptedStyleSheets = document.adoptedStyleSheets.filter((s) => s !== style);
  351. }
  352. else {
  353. document.head.removeChild(style);
  354. }
  355. sheetsMap.delete(id);
  356. }
  357. }
  358. async function fetchUpdate({ path, acceptedPath, timestamp }) {
  359. const mod = hotModulesMap.get(path);
  360. if (!mod) {
  361. // In a code-splitting project,
  362. // it is common that the hot-updating module is not loaded yet.
  363. // https://github.com/vitejs/vite/issues/721
  364. return;
  365. }
  366. const moduleMap = new Map();
  367. const isSelfUpdate = path === acceptedPath;
  368. // make sure we only import each dep once
  369. const modulesToUpdate = new Set();
  370. if (isSelfUpdate) {
  371. // self update - only update self
  372. modulesToUpdate.add(path);
  373. }
  374. else {
  375. // dep update
  376. for (const { deps } of mod.callbacks) {
  377. deps.forEach((dep) => {
  378. if (acceptedPath === dep) {
  379. modulesToUpdate.add(dep);
  380. }
  381. });
  382. }
  383. }
  384. // determine the qualified callbacks before we re-import the modules
  385. const qualifiedCallbacks = mod.callbacks.filter(({ deps }) => {
  386. return deps.some((dep) => modulesToUpdate.has(dep));
  387. });
  388. await Promise.all(Array.from(modulesToUpdate).map(async (dep) => {
  389. const disposer = disposeMap.get(dep);
  390. if (disposer)
  391. await disposer(dataMap.get(dep));
  392. const [path, query] = dep.split(`?`);
  393. try {
  394. const newMod = await import(
  395. /* @vite-ignore */
  396. base +
  397. path.slice(1) +
  398. `?import&t=${timestamp}${query ? `&${query}` : ''}`);
  399. moduleMap.set(dep, newMod);
  400. }
  401. catch (e) {
  402. warnFailedFetch(e, dep);
  403. }
  404. }));
  405. return () => {
  406. for (const { deps, fn } of qualifiedCallbacks) {
  407. fn(deps.map((dep) => moduleMap.get(dep)));
  408. }
  409. const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`;
  410. console.log(`[vite] hot updated: ${loggedPath}`);
  411. };
  412. }
  413. const hotModulesMap = new Map();
  414. const disposeMap = new Map();
  415. const pruneMap = new Map();
  416. const dataMap = new Map();
  417. const customListenersMap = new Map();
  418. const ctxToListenersMap = new Map();
  419. const createHotContext = (ownerPath) => {
  420. if (!dataMap.has(ownerPath)) {
  421. dataMap.set(ownerPath, {});
  422. }
  423. // when a file is hot updated, a new context is created
  424. // clear its stale callbacks
  425. const mod = hotModulesMap.get(ownerPath);
  426. if (mod) {
  427. mod.callbacks = [];
  428. }
  429. // clear stale custom event listeners
  430. const staleListeners = ctxToListenersMap.get(ownerPath);
  431. if (staleListeners) {
  432. for (const [event, staleFns] of staleListeners) {
  433. const listeners = customListenersMap.get(event);
  434. if (listeners) {
  435. customListenersMap.set(event, listeners.filter((l) => !staleFns.includes(l)));
  436. }
  437. }
  438. }
  439. const newListeners = new Map();
  440. ctxToListenersMap.set(ownerPath, newListeners);
  441. function acceptDeps(deps, callback = () => { }) {
  442. const mod = hotModulesMap.get(ownerPath) || {
  443. id: ownerPath,
  444. callbacks: []
  445. };
  446. mod.callbacks.push({
  447. deps,
  448. fn: callback
  449. });
  450. hotModulesMap.set(ownerPath, mod);
  451. }
  452. const hot = {
  453. get data() {
  454. return dataMap.get(ownerPath);
  455. },
  456. accept(deps, callback) {
  457. if (typeof deps === 'function' || !deps) {
  458. // self-accept: hot.accept(() => {})
  459. acceptDeps([ownerPath], ([mod]) => deps && deps(mod));
  460. }
  461. else if (typeof deps === 'string') {
  462. // explicit deps
  463. acceptDeps([deps], ([mod]) => callback && callback(mod));
  464. }
  465. else if (Array.isArray(deps)) {
  466. acceptDeps(deps, callback);
  467. }
  468. else {
  469. throw new Error(`invalid hot.accept() usage.`);
  470. }
  471. },
  472. acceptDeps() {
  473. throw new Error(`hot.acceptDeps() is deprecated. ` +
  474. `Use hot.accept() with the same signature instead.`);
  475. },
  476. dispose(cb) {
  477. disposeMap.set(ownerPath, cb);
  478. },
  479. prune(cb) {
  480. pruneMap.set(ownerPath, cb);
  481. },
  482. // TODO
  483. decline() { },
  484. invalidate() {
  485. // TODO should tell the server to re-perform hmr propagation
  486. // from this module as root
  487. location.reload();
  488. },
  489. // custom events
  490. on(event, cb) {
  491. const addToMap = (map) => {
  492. const existing = map.get(event) || [];
  493. existing.push(cb);
  494. map.set(event, existing);
  495. };
  496. addToMap(customListenersMap);
  497. addToMap(newListeners);
  498. }
  499. };
  500. return hot;
  501. };
  502. function injectQuery(url, queryToInject) {
  503. // can't use pathname from URL since it may be relative like ../
  504. const pathname = url.replace(/#.*$/, '').replace(/\?.*$/, '');
  505. const { search, hash } = new URL(url, 'http://vitejs.dev');
  506. return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ''}${hash || ''}`;
  507. }
  508. export { createHotContext, injectQuery, removeStyle, updateStyle };