版博士V2.0程序
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

1 год назад
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. import { EventEmitter } from 'node:events';
  2. import c from 'picocolors';
  3. import createDebug from 'debug';
  4. function createHmrEmitter() {
  5. const emitter = new EventEmitter();
  6. return emitter;
  7. }
  8. function viteNodeHmrPlugin() {
  9. const emitter = createHmrEmitter();
  10. return {
  11. name: "vite-node:hmr",
  12. configureServer(server) {
  13. const _send = server.ws.send;
  14. server.emitter = emitter;
  15. server.ws.send = function(payload) {
  16. _send(payload);
  17. emitter.emit("message", payload);
  18. };
  19. }
  20. };
  21. }
  22. const debugHmr = createDebug("vite-node:hmr");
  23. const cache = /* @__PURE__ */ new WeakMap();
  24. function getCache(runner) {
  25. if (!cache.has(runner)) {
  26. cache.set(runner, {
  27. hotModulesMap: /* @__PURE__ */ new Map(),
  28. dataMap: /* @__PURE__ */ new Map(),
  29. disposeMap: /* @__PURE__ */ new Map(),
  30. pruneMap: /* @__PURE__ */ new Map(),
  31. customListenersMap: /* @__PURE__ */ new Map(),
  32. ctxToListenersMap: /* @__PURE__ */ new Map(),
  33. messageBuffer: [],
  34. isFirstUpdate: false,
  35. pending: false,
  36. queued: []
  37. });
  38. }
  39. return cache.get(runner);
  40. }
  41. function sendMessageBuffer(runner, emitter) {
  42. const maps = getCache(runner);
  43. maps.messageBuffer.forEach((msg) => emitter.emit("custom", msg));
  44. maps.messageBuffer.length = 0;
  45. }
  46. async function reload(runner, files) {
  47. Array.from(runner.moduleCache.keys()).forEach((fsPath) => {
  48. if (!fsPath.includes("node_modules"))
  49. runner.moduleCache.delete(fsPath);
  50. });
  51. return Promise.all(files.map((file) => runner.executeId(file)));
  52. }
  53. function notifyListeners(runner, event, data) {
  54. const maps = getCache(runner);
  55. const cbs = maps.customListenersMap.get(event);
  56. if (cbs)
  57. cbs.forEach((cb) => cb(data));
  58. }
  59. async function queueUpdate(runner, p) {
  60. const maps = getCache(runner);
  61. maps.queued.push(p);
  62. if (!maps.pending) {
  63. maps.pending = true;
  64. await Promise.resolve();
  65. maps.pending = false;
  66. const loading = [...maps.queued];
  67. maps.queued = [];
  68. (await Promise.all(loading)).forEach((fn) => fn && fn());
  69. }
  70. }
  71. async function fetchUpdate(runner, { path, acceptedPath }) {
  72. const maps = getCache(runner);
  73. const mod = maps.hotModulesMap.get(path);
  74. if (!mod) {
  75. return;
  76. }
  77. const moduleMap = /* @__PURE__ */ new Map();
  78. const isSelfUpdate = path === acceptedPath;
  79. const modulesToUpdate = /* @__PURE__ */ new Set();
  80. if (isSelfUpdate) {
  81. modulesToUpdate.add(path);
  82. } else {
  83. for (const { deps } of mod.callbacks) {
  84. deps.forEach((dep) => {
  85. if (acceptedPath === dep)
  86. modulesToUpdate.add(dep);
  87. });
  88. }
  89. }
  90. const qualifiedCallbacks = mod.callbacks.filter(({ deps }) => {
  91. return deps.some((dep) => modulesToUpdate.has(dep));
  92. });
  93. await Promise.all(
  94. Array.from(modulesToUpdate).map(async (dep) => {
  95. const disposer = maps.disposeMap.get(dep);
  96. if (disposer)
  97. await disposer(maps.dataMap.get(dep));
  98. try {
  99. const newMod = await reload(runner, [dep]);
  100. moduleMap.set(dep, newMod);
  101. } catch (e) {
  102. warnFailedFetch(e, dep);
  103. }
  104. })
  105. );
  106. return () => {
  107. for (const { deps, fn } of qualifiedCallbacks)
  108. fn(deps.map((dep) => moduleMap.get(dep)));
  109. const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`;
  110. console.log(`${c.cyan("[vite-node]")} hot updated: ${loggedPath}`);
  111. };
  112. }
  113. function warnFailedFetch(err, path) {
  114. if (!err.message.match("fetch"))
  115. console.error(err);
  116. console.error(
  117. `[hmr] Failed to reload ${path}. This could be due to syntax errors or importing non-existent modules. (see errors above)`
  118. );
  119. }
  120. async function handleMessage(runner, emitter, files, payload) {
  121. const maps = getCache(runner);
  122. switch (payload.type) {
  123. case "connected":
  124. sendMessageBuffer(runner, emitter);
  125. break;
  126. case "update":
  127. notifyListeners(runner, "vite:beforeUpdate", payload);
  128. if (maps.isFirstUpdate) {
  129. reload(runner, files);
  130. maps.isFirstUpdate = true;
  131. }
  132. payload.updates.forEach((update) => {
  133. if (update.type === "js-update") {
  134. queueUpdate(runner, fetchUpdate(runner, update));
  135. } else {
  136. console.error(`${c.cyan("[vite-node]")} no support css hmr.}`);
  137. }
  138. });
  139. break;
  140. case "full-reload":
  141. notifyListeners(runner, "vite:beforeFullReload", payload);
  142. maps.customListenersMap.delete("vite:beforeFullReload");
  143. reload(runner, files);
  144. break;
  145. case "prune":
  146. notifyListeners(runner, "vite:beforePrune", payload);
  147. payload.paths.forEach((path) => {
  148. const fn = maps.pruneMap.get(path);
  149. if (fn)
  150. fn(maps.dataMap.get(path));
  151. });
  152. break;
  153. case "error": {
  154. notifyListeners(runner, "vite:error", payload);
  155. const err = payload.err;
  156. console.error(`${c.cyan("[vite-node]")} Internal Server Error
  157. ${err.message}
  158. ${err.stack}`);
  159. break;
  160. }
  161. }
  162. }
  163. function createHotContext(runner, emitter, files, ownerPath) {
  164. debugHmr("createHotContext", ownerPath);
  165. const maps = getCache(runner);
  166. if (!maps.dataMap.has(ownerPath))
  167. maps.dataMap.set(ownerPath, {});
  168. const mod = maps.hotModulesMap.get(ownerPath);
  169. if (mod)
  170. mod.callbacks = [];
  171. const newListeners = /* @__PURE__ */ new Map();
  172. maps.ctxToListenersMap.set(ownerPath, newListeners);
  173. function acceptDeps(deps, callback = () => {
  174. }) {
  175. const mod2 = maps.hotModulesMap.get(ownerPath) || {
  176. id: ownerPath,
  177. callbacks: []
  178. };
  179. mod2.callbacks.push({
  180. deps,
  181. fn: callback
  182. });
  183. maps.hotModulesMap.set(ownerPath, mod2);
  184. }
  185. const hot = {
  186. get data() {
  187. return maps.dataMap.get(ownerPath);
  188. },
  189. acceptExports(_, callback) {
  190. acceptDeps([ownerPath], callback && (([mod2]) => callback(mod2)));
  191. },
  192. accept(deps, callback) {
  193. if (typeof deps === "function" || !deps) {
  194. acceptDeps([ownerPath], ([mod2]) => deps && deps(mod2));
  195. } else if (typeof deps === "string") {
  196. acceptDeps([deps], ([mod2]) => callback && callback(mod2));
  197. } else if (Array.isArray(deps)) {
  198. acceptDeps(deps, callback);
  199. } else {
  200. throw new TypeError("invalid hot.accept() usage.");
  201. }
  202. },
  203. dispose(cb) {
  204. maps.disposeMap.set(ownerPath, cb);
  205. },
  206. prune(cb) {
  207. maps.pruneMap.set(ownerPath, cb);
  208. },
  209. invalidate() {
  210. notifyListeners(runner, "vite:invalidate", { path: ownerPath, message: void 0 });
  211. return reload(runner, files);
  212. },
  213. on(event, cb) {
  214. const addToMap = (map) => {
  215. const existing = map.get(event) || [];
  216. existing.push(cb);
  217. map.set(event, existing);
  218. };
  219. addToMap(maps.customListenersMap);
  220. addToMap(newListeners);
  221. },
  222. send(event, data) {
  223. maps.messageBuffer.push(JSON.stringify({ type: "custom", event, data }));
  224. sendMessageBuffer(runner, emitter);
  225. }
  226. };
  227. return hot;
  228. }
  229. export { createHmrEmitter as a, createHotContext as c, getCache as g, handleMessage as h, reload as r, sendMessageBuffer as s, viteNodeHmrPlugin as v };