client.mjs 18 KB

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