You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1298 lines
52 KiB

  1. const VALID_ID_PREFIX = "/@id/", NULL_BYTE_PLACEHOLDER = "__x00__";
  2. let SOURCEMAPPING_URL = "sourceMa";
  3. SOURCEMAPPING_URL += "ppingURL";
  4. const ERR_OUTDATED_OPTIMIZED_DEP = "ERR_OUTDATED_OPTIMIZED_DEP", isWindows = typeof process < "u" && process.platform === "win32";
  5. function unwrapId(id) {
  6. return id.startsWith(VALID_ID_PREFIX) ? id.slice(VALID_ID_PREFIX.length).replace(NULL_BYTE_PLACEHOLDER, "\0") : id;
  7. }
  8. const windowsSlashRE = /\\/g;
  9. function slash(p) {
  10. return p.replace(windowsSlashRE, "/");
  11. }
  12. const postfixRE = /[?#].*$/;
  13. function cleanUrl(url) {
  14. return url.replace(postfixRE, "");
  15. }
  16. function isPrimitive(value) {
  17. return !value || typeof value != "object" && typeof value != "function";
  18. }
  19. const AsyncFunction = async function() {
  20. }.constructor;
  21. let asyncFunctionDeclarationPaddingLineCount;
  22. function getAsyncFunctionDeclarationPaddingLineCount() {
  23. if (typeof asyncFunctionDeclarationPaddingLineCount > "u") {
  24. const body = "/*code*/", source = new AsyncFunction("a", "b", body).toString();
  25. asyncFunctionDeclarationPaddingLineCount = source.slice(0, source.indexOf(body)).split(`
  26. `).length - 1;
  27. }
  28. return asyncFunctionDeclarationPaddingLineCount;
  29. }
  30. function promiseWithResolvers() {
  31. let resolve2, reject;
  32. return { promise: new Promise((_resolve, _reject) => {
  33. resolve2 = _resolve, reject = _reject;
  34. }), resolve: resolve2, reject };
  35. }
  36. const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
  37. function normalizeWindowsPath(input = "") {
  38. return input && input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
  39. }
  40. const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/, _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
  41. function cwd() {
  42. return typeof process < "u" && typeof process.cwd == "function" ? process.cwd().replace(/\\/g, "/") : "/";
  43. }
  44. const resolve = function(...arguments_) {
  45. arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
  46. let resolvedPath = "", resolvedAbsolute = !1;
  47. for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
  48. const path = index >= 0 ? arguments_[index] : cwd();
  49. !path || path.length === 0 || (resolvedPath = `${path}/${resolvedPath}`, resolvedAbsolute = isAbsolute(path));
  50. }
  51. return resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute), resolvedAbsolute && !isAbsolute(resolvedPath) ? `/${resolvedPath}` : resolvedPath.length > 0 ? resolvedPath : ".";
  52. };
  53. function normalizeString(path, allowAboveRoot) {
  54. let res = "", lastSegmentLength = 0, lastSlash = -1, dots = 0, char = null;
  55. for (let index = 0; index <= path.length; ++index) {
  56. if (index < path.length)
  57. char = path[index];
  58. else {
  59. if (char === "/")
  60. break;
  61. char = "/";
  62. }
  63. if (char === "/") {
  64. if (!(lastSlash === index - 1 || dots === 1)) if (dots === 2) {
  65. if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
  66. if (res.length > 2) {
  67. const lastSlashIndex = res.lastIndexOf("/");
  68. lastSlashIndex === -1 ? (res = "", lastSegmentLength = 0) : (res = res.slice(0, lastSlashIndex), lastSegmentLength = res.length - 1 - res.lastIndexOf("/")), lastSlash = index, dots = 0;
  69. continue;
  70. } else if (res.length > 0) {
  71. res = "", lastSegmentLength = 0, lastSlash = index, dots = 0;
  72. continue;
  73. }
  74. }
  75. allowAboveRoot && (res += res.length > 0 ? "/.." : "..", lastSegmentLength = 2);
  76. } else
  77. res.length > 0 ? res += `/${path.slice(lastSlash + 1, index)}` : res = path.slice(lastSlash + 1, index), lastSegmentLength = index - lastSlash - 1;
  78. lastSlash = index, dots = 0;
  79. } else char === "." && dots !== -1 ? ++dots : dots = -1;
  80. }
  81. return res;
  82. }
  83. const isAbsolute = function(p) {
  84. return _IS_ABSOLUTE_RE.test(p);
  85. }, dirname = function(p) {
  86. const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
  87. return segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0]) && (segments[0] += "/"), segments.join("/") || (isAbsolute(p) ? "/" : ".");
  88. }, decodeBase64 = typeof atob < "u" ? atob : (str) => Buffer.from(str, "base64").toString("utf-8"), CHAR_FORWARD_SLASH = 47, CHAR_BACKWARD_SLASH = 92, percentRegEx = /%/g, backslashRegEx = /\\/g, newlineRegEx = /\n/g, carriageReturnRegEx = /\r/g, tabRegEx = /\t/g, questionRegex = /\?/g, hashRegex = /#/g;
  89. function encodePathChars(filepath) {
  90. return filepath.indexOf("%") !== -1 && (filepath = filepath.replace(percentRegEx, "%25")), !isWindows && filepath.indexOf("\\") !== -1 && (filepath = filepath.replace(backslashRegEx, "%5C")), filepath.indexOf(`
  91. `) !== -1 && (filepath = filepath.replace(newlineRegEx, "%0A")), filepath.indexOf("\r") !== -1 && (filepath = filepath.replace(carriageReturnRegEx, "%0D")), filepath.indexOf(" ") !== -1 && (filepath = filepath.replace(tabRegEx, "%09")), filepath;
  92. }
  93. const posixDirname = dirname, posixResolve = resolve;
  94. function posixPathToFileHref(posixPath) {
  95. let resolved = posixResolve(posixPath);
  96. const filePathLast = posixPath.charCodeAt(posixPath.length - 1);
  97. return (filePathLast === CHAR_FORWARD_SLASH || isWindows && filePathLast === CHAR_BACKWARD_SLASH) && resolved[resolved.length - 1] !== "/" && (resolved += "/"), resolved = encodePathChars(resolved), resolved.indexOf("?") !== -1 && (resolved = resolved.replace(questionRegex, "%3F")), resolved.indexOf("#") !== -1 && (resolved = resolved.replace(hashRegex, "%23")), new URL(`file://${resolved}`).href;
  98. }
  99. function toWindowsPath(path) {
  100. return path.replace(/\//g, "\\");
  101. }
  102. const comma = 44, chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", intToChar = new Uint8Array(64), charToInt = new Uint8Array(128);
  103. for (let i = 0; i < chars.length; i++) {
  104. const c = chars.charCodeAt(i);
  105. intToChar[i] = c, charToInt[c] = i;
  106. }
  107. function decodeInteger(reader, relative) {
  108. let value = 0, shift = 0, integer = 0;
  109. do {
  110. const c = reader.next();
  111. integer = charToInt[c], value |= (integer & 31) << shift, shift += 5;
  112. } while (integer & 32);
  113. const shouldNegate = value & 1;
  114. return value >>>= 1, shouldNegate && (value = -2147483648 | -value), relative + value;
  115. }
  116. function hasMoreVlq(reader, max) {
  117. return reader.pos >= max ? !1 : reader.peek() !== comma;
  118. }
  119. class StringReader {
  120. constructor(buffer) {
  121. this.pos = 0, this.buffer = buffer;
  122. }
  123. next() {
  124. return this.buffer.charCodeAt(this.pos++);
  125. }
  126. peek() {
  127. return this.buffer.charCodeAt(this.pos);
  128. }
  129. indexOf(char) {
  130. const { buffer, pos } = this, idx = buffer.indexOf(char, pos);
  131. return idx === -1 ? buffer.length : idx;
  132. }
  133. }
  134. function decode(mappings) {
  135. const { length } = mappings, reader = new StringReader(mappings), decoded = [];
  136. let genColumn = 0, sourcesIndex = 0, sourceLine = 0, sourceColumn = 0, namesIndex = 0;
  137. do {
  138. const semi = reader.indexOf(";"), line = [];
  139. let sorted = !0, lastCol = 0;
  140. for (genColumn = 0; reader.pos < semi; ) {
  141. let seg;
  142. genColumn = decodeInteger(reader, genColumn), genColumn < lastCol && (sorted = !1), lastCol = genColumn, hasMoreVlq(reader, semi) ? (sourcesIndex = decodeInteger(reader, sourcesIndex), sourceLine = decodeInteger(reader, sourceLine), sourceColumn = decodeInteger(reader, sourceColumn), hasMoreVlq(reader, semi) ? (namesIndex = decodeInteger(reader, namesIndex), seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]) : seg = [genColumn, sourcesIndex, sourceLine, sourceColumn]) : seg = [genColumn], line.push(seg), reader.pos++;
  143. }
  144. sorted || sort(line), decoded.push(line), reader.pos = semi + 1;
  145. } while (reader.pos <= length);
  146. return decoded;
  147. }
  148. function sort(line) {
  149. line.sort(sortComparator);
  150. }
  151. function sortComparator(a, b) {
  152. return a[0] - b[0];
  153. }
  154. const COLUMN = 0, SOURCES_INDEX = 1, SOURCE_LINE = 2, SOURCE_COLUMN = 3, NAMES_INDEX = 4;
  155. let found = !1;
  156. function binarySearch(haystack, needle, low, high) {
  157. for (; low <= high; ) {
  158. const mid = low + (high - low >> 1), cmp = haystack[mid][COLUMN] - needle;
  159. if (cmp === 0)
  160. return found = !0, mid;
  161. cmp < 0 ? low = mid + 1 : high = mid - 1;
  162. }
  163. return found = !1, low - 1;
  164. }
  165. function upperBound(haystack, needle, index) {
  166. for (let i = index + 1; i < haystack.length && haystack[i][COLUMN] === needle; index = i++)
  167. ;
  168. return index;
  169. }
  170. function lowerBound(haystack, needle, index) {
  171. for (let i = index - 1; i >= 0 && haystack[i][COLUMN] === needle; index = i--)
  172. ;
  173. return index;
  174. }
  175. function memoizedBinarySearch(haystack, needle, state, key) {
  176. const { lastKey, lastNeedle, lastIndex } = state;
  177. let low = 0, high = haystack.length - 1;
  178. if (key === lastKey) {
  179. if (needle === lastNeedle)
  180. return found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle, lastIndex;
  181. needle >= lastNeedle ? low = lastIndex === -1 ? 0 : lastIndex : high = lastIndex;
  182. }
  183. return state.lastKey = key, state.lastNeedle = needle, state.lastIndex = binarySearch(haystack, needle, low, high);
  184. }
  185. const LINE_GTR_ZERO = "`line` must be greater than 0 (lines start at line 1)", COL_GTR_EQ_ZERO = "`column` must be greater than or equal to 0 (columns start at column 0)", LEAST_UPPER_BOUND = -1, GREATEST_LOWER_BOUND = 1;
  186. function cast(map) {
  187. return map;
  188. }
  189. function decodedMappings(map) {
  190. var _a;
  191. return (_a = map)._decoded || (_a._decoded = decode(map._encoded));
  192. }
  193. function originalPositionFor(map, needle) {
  194. let { line, column, bias } = needle;
  195. if (line--, line < 0)
  196. throw new Error(LINE_GTR_ZERO);
  197. if (column < 0)
  198. throw new Error(COL_GTR_EQ_ZERO);
  199. const decoded = decodedMappings(map);
  200. if (line >= decoded.length)
  201. return OMapping(null, null, null, null);
  202. const segments = decoded[line], index = traceSegmentInternal(segments, map._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND);
  203. if (index === -1)
  204. return OMapping(null, null, null, null);
  205. const segment = segments[index];
  206. if (segment.length === 1)
  207. return OMapping(null, null, null, null);
  208. const { names, resolvedSources } = map;
  209. return OMapping(resolvedSources[segment[SOURCES_INDEX]], segment[SOURCE_LINE] + 1, segment[SOURCE_COLUMN], segment.length === 5 ? names[segment[NAMES_INDEX]] : null);
  210. }
  211. function OMapping(source, line, column, name) {
  212. return { source, line, column, name };
  213. }
  214. function traceSegmentInternal(segments, memo, line, column, bias) {
  215. let index = memoizedBinarySearch(segments, column, memo, line);
  216. return found ? index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index) : bias === LEAST_UPPER_BOUND && index++, index === -1 || index === segments.length ? -1 : index;
  217. }
  218. class DecodedMap {
  219. constructor(map, from) {
  220. this.map = map;
  221. const { mappings, names, sources } = map;
  222. this.version = map.version, this.names = names || [], this._encoded = mappings || "", this._decodedMemo = memoizedState(), this.url = from, this.resolvedSources = (sources || []).map(
  223. (s) => posixResolve(s || "", from)
  224. );
  225. }
  226. _encoded;
  227. _decoded;
  228. _decodedMemo;
  229. url;
  230. version;
  231. names = [];
  232. resolvedSources;
  233. }
  234. function memoizedState() {
  235. return {
  236. lastKey: -1,
  237. lastNeedle: -1,
  238. lastIndex: -1
  239. };
  240. }
  241. function getOriginalPosition(map, needle) {
  242. const result = originalPositionFor(map, needle);
  243. return result.column == null ? null : result;
  244. }
  245. const MODULE_RUNNER_SOURCEMAPPING_REGEXP = new RegExp(
  246. `//# ${SOURCEMAPPING_URL}=data:application/json;base64,(.+)`
  247. );
  248. class EvaluatedModuleNode {
  249. constructor(id, url) {
  250. this.id = id, this.url = url, this.file = cleanUrl(id);
  251. }
  252. importers = /* @__PURE__ */ new Set();
  253. imports = /* @__PURE__ */ new Set();
  254. evaluated = !1;
  255. meta;
  256. promise;
  257. exports;
  258. file;
  259. map;
  260. }
  261. class EvaluatedModules {
  262. idToModuleMap = /* @__PURE__ */ new Map();
  263. fileToModulesMap = /* @__PURE__ */ new Map();
  264. urlToIdModuleMap = /* @__PURE__ */ new Map();
  265. /**
  266. * Returns the module node by the resolved module ID. Usually, module ID is
  267. * the file system path with query and/or hash. It can also be a virtual module.
  268. *
  269. * Module runner graph will have 1 to 1 mapping with the server module graph.
  270. * @param id Resolved module ID
  271. */
  272. getModuleById(id) {
  273. return this.idToModuleMap.get(id);
  274. }
  275. /**
  276. * Returns all modules related to the file system path. Different modules
  277. * might have different query parameters or hash, so it's possible to have
  278. * multiple modules for the same file.
  279. * @param file The file system path of the module
  280. */
  281. getModulesByFile(file) {
  282. return this.fileToModulesMap.get(file);
  283. }
  284. /**
  285. * Returns the module node by the URL that was used in the import statement.
  286. * Unlike module graph on the server, the URL is not resolved and is used as is.
  287. * @param url Server URL that was used in the import statement
  288. */
  289. getModuleByUrl(url) {
  290. return this.urlToIdModuleMap.get(unwrapId(url));
  291. }
  292. /**
  293. * Ensure that module is in the graph. If the module is already in the graph,
  294. * it will return the existing module node. Otherwise, it will create a new
  295. * module node and add it to the graph.
  296. * @param id Resolved module ID
  297. * @param url URL that was used in the import statement
  298. */
  299. ensureModule(id, url) {
  300. if (id = normalizeModuleId(id), this.idToModuleMap.has(id)) {
  301. const moduleNode2 = this.idToModuleMap.get(id);
  302. return this.urlToIdModuleMap.set(url, moduleNode2), moduleNode2;
  303. }
  304. const moduleNode = new EvaluatedModuleNode(id, url);
  305. this.idToModuleMap.set(id, moduleNode), this.urlToIdModuleMap.set(url, moduleNode);
  306. const fileModules = this.fileToModulesMap.get(moduleNode.file) || /* @__PURE__ */ new Set();
  307. return fileModules.add(moduleNode), this.fileToModulesMap.set(moduleNode.file, fileModules), moduleNode;
  308. }
  309. invalidateModule(node) {
  310. node.evaluated = !1, node.meta = void 0, node.map = void 0, node.promise = void 0, node.exports = void 0, node.imports.clear();
  311. }
  312. /**
  313. * Extracts the inlined source map from the module code and returns the decoded
  314. * source map. If the source map is not inlined, it will return null.
  315. * @param id Resolved module ID
  316. */
  317. getModuleSourceMapById(id) {
  318. const mod = this.getModuleById(id);
  319. if (!mod) return null;
  320. if (mod.map) return mod.map;
  321. if (!mod.meta || !("code" in mod.meta)) return null;
  322. const mapString = MODULE_RUNNER_SOURCEMAPPING_REGEXP.exec(
  323. mod.meta.code
  324. )?.[1];
  325. return mapString ? (mod.map = new DecodedMap(JSON.parse(decodeBase64(mapString)), mod.file), mod.map) : null;
  326. }
  327. clear() {
  328. this.idToModuleMap.clear(), this.fileToModulesMap.clear(), this.urlToIdModuleMap.clear();
  329. }
  330. }
  331. const prefixedBuiltins = /* @__PURE__ */ new Set([
  332. "node:sea",
  333. "node:sqlite",
  334. "node:test",
  335. "node:test/reporters"
  336. ]);
  337. function normalizeModuleId(file) {
  338. return prefixedBuiltins.has(file) ? file : slash(file).replace(/^\/@fs\//, isWindows ? "" : "/").replace(/^node:/, "").replace(/^\/+/, "/").replace(/^file:\//, "/");
  339. }
  340. class HMRContext {
  341. constructor(hmrClient, ownerPath) {
  342. this.hmrClient = hmrClient, this.ownerPath = ownerPath, hmrClient.dataMap.has(ownerPath) || hmrClient.dataMap.set(ownerPath, {});
  343. const mod = hmrClient.hotModulesMap.get(ownerPath);
  344. mod && (mod.callbacks = []);
  345. const staleListeners = hmrClient.ctxToListenersMap.get(ownerPath);
  346. if (staleListeners)
  347. for (const [event, staleFns] of staleListeners) {
  348. const listeners = hmrClient.customListenersMap.get(event);
  349. listeners && hmrClient.customListenersMap.set(
  350. event,
  351. listeners.filter((l) => !staleFns.includes(l))
  352. );
  353. }
  354. this.newListeners = /* @__PURE__ */ new Map(), hmrClient.ctxToListenersMap.set(ownerPath, this.newListeners);
  355. }
  356. newListeners;
  357. get data() {
  358. return this.hmrClient.dataMap.get(this.ownerPath);
  359. }
  360. accept(deps, callback) {
  361. if (typeof deps == "function" || !deps)
  362. this.acceptDeps([this.ownerPath], ([mod]) => deps?.(mod));
  363. else if (typeof deps == "string")
  364. this.acceptDeps([deps], ([mod]) => callback?.(mod));
  365. else if (Array.isArray(deps))
  366. this.acceptDeps(deps, callback);
  367. else
  368. throw new Error("invalid hot.accept() usage.");
  369. }
  370. // export names (first arg) are irrelevant on the client side, they're
  371. // extracted in the server for propagation
  372. acceptExports(_, callback) {
  373. this.acceptDeps([this.ownerPath], ([mod]) => callback?.(mod));
  374. }
  375. dispose(cb) {
  376. this.hmrClient.disposeMap.set(this.ownerPath, cb);
  377. }
  378. prune(cb) {
  379. this.hmrClient.pruneMap.set(this.ownerPath, cb);
  380. }
  381. // Kept for backward compatibility (#11036)
  382. // eslint-disable-next-line @typescript-eslint/no-empty-function
  383. decline() {
  384. }
  385. invalidate(message) {
  386. this.hmrClient.notifyListeners("vite:invalidate", {
  387. path: this.ownerPath,
  388. message
  389. }), this.send("vite:invalidate", {
  390. path: this.ownerPath,
  391. message
  392. }), this.hmrClient.logger.debug(
  393. `invalidate ${this.ownerPath}${message ? `: ${message}` : ""}`
  394. );
  395. }
  396. on(event, cb) {
  397. const addToMap = (map) => {
  398. const existing = map.get(event) || [];
  399. existing.push(cb), map.set(event, existing);
  400. };
  401. addToMap(this.hmrClient.customListenersMap), addToMap(this.newListeners);
  402. }
  403. off(event, cb) {
  404. const removeFromMap = (map) => {
  405. const existing = map.get(event);
  406. if (existing === void 0)
  407. return;
  408. const pruned = existing.filter((l) => l !== cb);
  409. if (pruned.length === 0) {
  410. map.delete(event);
  411. return;
  412. }
  413. map.set(event, pruned);
  414. };
  415. removeFromMap(this.hmrClient.customListenersMap), removeFromMap(this.newListeners);
  416. }
  417. send(event, data) {
  418. this.hmrClient.send({ type: "custom", event, data });
  419. }
  420. acceptDeps(deps, callback = () => {
  421. }) {
  422. const mod = this.hmrClient.hotModulesMap.get(this.ownerPath) || {
  423. id: this.ownerPath,
  424. callbacks: []
  425. };
  426. mod.callbacks.push({
  427. deps,
  428. fn: callback
  429. }), this.hmrClient.hotModulesMap.set(this.ownerPath, mod);
  430. }
  431. }
  432. class HMRClient {
  433. constructor(logger, transport, importUpdatedModule) {
  434. this.logger = logger, this.transport = transport, this.importUpdatedModule = importUpdatedModule;
  435. }
  436. hotModulesMap = /* @__PURE__ */ new Map();
  437. disposeMap = /* @__PURE__ */ new Map();
  438. pruneMap = /* @__PURE__ */ new Map();
  439. dataMap = /* @__PURE__ */ new Map();
  440. customListenersMap = /* @__PURE__ */ new Map();
  441. ctxToListenersMap = /* @__PURE__ */ new Map();
  442. async notifyListeners(event, data) {
  443. const cbs = this.customListenersMap.get(event);
  444. cbs && await Promise.allSettled(cbs.map((cb) => cb(data)));
  445. }
  446. send(payload) {
  447. this.transport.send(payload).catch((err) => {
  448. this.logger.error(err);
  449. });
  450. }
  451. clear() {
  452. this.hotModulesMap.clear(), this.disposeMap.clear(), this.pruneMap.clear(), this.dataMap.clear(), this.customListenersMap.clear(), this.ctxToListenersMap.clear();
  453. }
  454. // After an HMR update, some modules are no longer imported on the page
  455. // but they may have left behind side effects that need to be cleaned up
  456. // (e.g. style injections)
  457. async prunePaths(paths) {
  458. await Promise.all(
  459. paths.map((path) => {
  460. const disposer = this.disposeMap.get(path);
  461. if (disposer) return disposer(this.dataMap.get(path));
  462. })
  463. ), paths.forEach((path) => {
  464. const fn = this.pruneMap.get(path);
  465. fn && fn(this.dataMap.get(path));
  466. });
  467. }
  468. warnFailedUpdate(err, path) {
  469. err.message.includes("fetch") || this.logger.error(err), this.logger.error(
  470. `Failed to reload ${path}. This could be due to syntax errors or importing non-existent modules. (see errors above)`
  471. );
  472. }
  473. updateQueue = [];
  474. pendingUpdateQueue = !1;
  475. /**
  476. * buffer multiple hot updates triggered by the same src change
  477. * so that they are invoked in the same order they were sent.
  478. * (otherwise the order may be inconsistent because of the http request round trip)
  479. */
  480. async queueUpdate(payload) {
  481. if (this.updateQueue.push(this.fetchUpdate(payload)), !this.pendingUpdateQueue) {
  482. this.pendingUpdateQueue = !0, await Promise.resolve(), this.pendingUpdateQueue = !1;
  483. const loading = [...this.updateQueue];
  484. this.updateQueue = [], (await Promise.all(loading)).forEach((fn) => fn && fn());
  485. }
  486. }
  487. async fetchUpdate(update) {
  488. const { path, acceptedPath } = update, mod = this.hotModulesMap.get(path);
  489. if (!mod)
  490. return;
  491. let fetchedModule;
  492. const isSelfUpdate = path === acceptedPath, qualifiedCallbacks = mod.callbacks.filter(
  493. ({ deps }) => deps.includes(acceptedPath)
  494. );
  495. if (isSelfUpdate || qualifiedCallbacks.length > 0) {
  496. const disposer = this.disposeMap.get(acceptedPath);
  497. disposer && await disposer(this.dataMap.get(acceptedPath));
  498. try {
  499. fetchedModule = await this.importUpdatedModule(update);
  500. } catch (e) {
  501. this.warnFailedUpdate(e, acceptedPath);
  502. }
  503. }
  504. return () => {
  505. for (const { deps, fn } of qualifiedCallbacks)
  506. fn(
  507. deps.map((dep) => dep === acceptedPath ? fetchedModule : void 0)
  508. );
  509. const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`;
  510. this.logger.debug(`hot updated: ${loggedPath}`);
  511. };
  512. }
  513. }
  514. function analyzeImportedModDifference(mod, rawId, moduleType, metadata) {
  515. if (!metadata?.isDynamicImport && metadata?.importedNames?.length) {
  516. const missingBindings = metadata.importedNames.filter((s) => !(s in mod));
  517. if (missingBindings.length) {
  518. const lastBinding = missingBindings[missingBindings.length - 1];
  519. throw moduleType === "module" ? new SyntaxError(
  520. `[vite] The requested module '${rawId}' does not provide an export named '${lastBinding}'`
  521. ) : new SyntaxError(`[vite] Named export '${lastBinding}' not found. The requested module '${rawId}' is a CommonJS module, which may not support all module.exports as named exports.
  522. CommonJS modules can always be imported via the default export, for example using:
  523. import pkg from '${rawId}';
  524. const {${missingBindings.join(", ")}} = pkg;
  525. `);
  526. }
  527. }
  528. }
  529. let urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict", nanoid = (size = 21) => {
  530. let id = "", i = size | 0;
  531. for (; i--; )
  532. id += urlAlphabet[Math.random() * 64 | 0];
  533. return id;
  534. };
  535. function reviveInvokeError(e) {
  536. const error = new Error(e.message || "Unknown invoke error");
  537. return Object.assign(error, e, {
  538. // pass the whole error instead of just the stacktrace
  539. // so that it gets formatted nicely with console.log
  540. runnerError: new Error("RunnerError")
  541. }), error;
  542. }
  543. const createInvokeableTransport = (transport) => {
  544. if (transport.invoke)
  545. return {
  546. ...transport,
  547. async invoke(name, data) {
  548. const result = await transport.invoke({
  549. type: "custom",
  550. event: "vite:invoke",
  551. data: {
  552. id: "send",
  553. name,
  554. data
  555. }
  556. });
  557. if ("error" in result)
  558. throw reviveInvokeError(result.error);
  559. return result.result;
  560. }
  561. };
  562. if (!transport.send || !transport.connect)
  563. throw new Error(
  564. "transport must implement send and connect when invoke is not implemented"
  565. );
  566. const rpcPromises = /* @__PURE__ */ new Map();
  567. return {
  568. ...transport,
  569. connect({ onMessage, onDisconnection }) {
  570. return transport.connect({
  571. onMessage(payload) {
  572. if (payload.type === "custom" && payload.event === "vite:invoke") {
  573. const data = payload.data;
  574. if (data.id.startsWith("response:")) {
  575. const invokeId = data.id.slice(9), promise = rpcPromises.get(invokeId);
  576. if (!promise) return;
  577. promise.timeoutId && clearTimeout(promise.timeoutId), rpcPromises.delete(invokeId);
  578. const { error, result } = data.data;
  579. error ? promise.reject(error) : promise.resolve(result);
  580. return;
  581. }
  582. }
  583. onMessage(payload);
  584. },
  585. onDisconnection
  586. });
  587. },
  588. disconnect() {
  589. return rpcPromises.forEach((promise) => {
  590. promise.reject(
  591. new Error(
  592. `transport was disconnected, cannot call ${JSON.stringify(promise.name)}`
  593. )
  594. );
  595. }), rpcPromises.clear(), transport.disconnect?.();
  596. },
  597. send(data) {
  598. return transport.send(data);
  599. },
  600. async invoke(name, data) {
  601. const promiseId = nanoid(), wrappedData = {
  602. type: "custom",
  603. event: "vite:invoke",
  604. data: {
  605. name,
  606. id: `send:${promiseId}`,
  607. data
  608. }
  609. }, sendPromise = transport.send(wrappedData), { promise, resolve: resolve2, reject } = promiseWithResolvers(), timeout = transport.timeout ?? 6e4;
  610. let timeoutId;
  611. timeout > 0 && (timeoutId = setTimeout(() => {
  612. rpcPromises.delete(promiseId), reject(
  613. new Error(
  614. `transport invoke timed out after ${timeout}ms (data: ${JSON.stringify(wrappedData)})`
  615. )
  616. );
  617. }, timeout), timeoutId?.unref?.()), rpcPromises.set(promiseId, { resolve: resolve2, reject, name, timeoutId }), sendPromise && sendPromise.catch((err) => {
  618. clearTimeout(timeoutId), rpcPromises.delete(promiseId), reject(err);
  619. });
  620. try {
  621. return await promise;
  622. } catch (err) {
  623. throw reviveInvokeError(err);
  624. }
  625. }
  626. };
  627. }, normalizeModuleRunnerTransport = (transport) => {
  628. const invokeableTransport = createInvokeableTransport(transport);
  629. let isConnected = !invokeableTransport.connect, connectingPromise;
  630. return {
  631. ...transport,
  632. ...invokeableTransport.connect ? {
  633. async connect(onMessage) {
  634. if (isConnected) return;
  635. if (connectingPromise) {
  636. await connectingPromise;
  637. return;
  638. }
  639. const maybePromise = invokeableTransport.connect({
  640. onMessage: onMessage ?? (() => {
  641. }),
  642. onDisconnection() {
  643. isConnected = !1;
  644. }
  645. });
  646. maybePromise && (connectingPromise = maybePromise, await connectingPromise, connectingPromise = void 0), isConnected = !0;
  647. }
  648. } : {},
  649. ...invokeableTransport.disconnect ? {
  650. async disconnect() {
  651. isConnected && (connectingPromise && await connectingPromise, isConnected = !1, await invokeableTransport.disconnect());
  652. }
  653. } : {},
  654. async send(data) {
  655. if (invokeableTransport.send) {
  656. if (!isConnected)
  657. if (connectingPromise)
  658. await connectingPromise;
  659. else
  660. throw new Error("send was called before connect");
  661. await invokeableTransport.send(data);
  662. }
  663. },
  664. async invoke(name, data) {
  665. if (!isConnected)
  666. if (connectingPromise)
  667. await connectingPromise;
  668. else
  669. throw new Error("invoke was called before connect");
  670. return invokeableTransport.invoke(name, data);
  671. }
  672. };
  673. }, createWebSocketModuleRunnerTransport = (options) => {
  674. const pingInterval = options.pingInterval ?? 3e4;
  675. let ws, pingIntervalId;
  676. return {
  677. async connect({ onMessage, onDisconnection }) {
  678. const socket = options.createConnection();
  679. socket.addEventListener("message", async ({ data }) => {
  680. onMessage(JSON.parse(data));
  681. });
  682. let isOpened = socket.readyState === socket.OPEN;
  683. isOpened || await new Promise((resolve2, reject) => {
  684. socket.addEventListener(
  685. "open",
  686. () => {
  687. isOpened = !0, resolve2();
  688. },
  689. { once: !0 }
  690. ), socket.addEventListener("close", async () => {
  691. if (!isOpened) {
  692. reject(new Error("WebSocket closed without opened."));
  693. return;
  694. }
  695. onMessage({
  696. type: "custom",
  697. event: "vite:ws:disconnect",
  698. data: { webSocket: socket }
  699. }), onDisconnection();
  700. });
  701. }), onMessage({
  702. type: "custom",
  703. event: "vite:ws:connect",
  704. data: { webSocket: socket }
  705. }), ws = socket, pingIntervalId = setInterval(() => {
  706. socket.readyState === socket.OPEN && socket.send(JSON.stringify({ type: "ping" }));
  707. }, pingInterval);
  708. },
  709. disconnect() {
  710. clearInterval(pingIntervalId), ws?.close();
  711. },
  712. send(data) {
  713. ws.send(JSON.stringify(data));
  714. }
  715. };
  716. }, ssrModuleExportsKey = "__vite_ssr_exports__", ssrImportKey = "__vite_ssr_import__", ssrDynamicImportKey = "__vite_ssr_dynamic_import__", ssrExportAllKey = "__vite_ssr_exportAll__", ssrImportMetaKey = "__vite_ssr_import_meta__", noop = () => {
  717. }, silentConsole = {
  718. debug: noop,
  719. error: noop
  720. }, hmrLogger = {
  721. debug: (...msg) => console.log("[vite]", ...msg),
  722. error: (error) => console.log("[vite]", error)
  723. };
  724. function createHMRHandler(runner) {
  725. const queue = new Queue();
  726. return (payload) => queue.enqueue(() => handleHotPayload(runner, payload));
  727. }
  728. async function handleHotPayload(runner, payload) {
  729. const hmrClient = runner.hmrClient;
  730. if (!(!hmrClient || runner.isClosed()))
  731. switch (payload.type) {
  732. case "connected":
  733. hmrClient.logger.debug("connected.");
  734. break;
  735. case "update":
  736. await hmrClient.notifyListeners("vite:beforeUpdate", payload), await Promise.all(
  737. payload.updates.map(async (update) => {
  738. if (update.type === "js-update")
  739. return update.acceptedPath = unwrapId(update.acceptedPath), update.path = unwrapId(update.path), hmrClient.queueUpdate(update);
  740. hmrClient.logger.error("css hmr is not supported in runner mode.");
  741. })
  742. ), await hmrClient.notifyListeners("vite:afterUpdate", payload);
  743. break;
  744. case "custom": {
  745. await hmrClient.notifyListeners(payload.event, payload.data);
  746. break;
  747. }
  748. case "full-reload": {
  749. const { triggeredBy } = payload, clearEntrypointUrls = triggeredBy ? getModulesEntrypoints(
  750. runner,
  751. getModulesByFile(runner, slash(triggeredBy))
  752. ) : findAllEntrypoints(runner);
  753. if (!clearEntrypointUrls.size) break;
  754. hmrClient.logger.debug("program reload"), await hmrClient.notifyListeners("vite:beforeFullReload", payload), runner.evaluatedModules.clear();
  755. for (const url of clearEntrypointUrls)
  756. try {
  757. await runner.import(url);
  758. } catch (err) {
  759. err.code !== ERR_OUTDATED_OPTIMIZED_DEP && hmrClient.logger.error(
  760. `An error happened during full reload
  761. ${err.message}
  762. ${err.stack}`
  763. );
  764. }
  765. break;
  766. }
  767. case "prune":
  768. await hmrClient.notifyListeners("vite:beforePrune", payload), await hmrClient.prunePaths(payload.paths);
  769. break;
  770. case "error": {
  771. await hmrClient.notifyListeners("vite:error", payload);
  772. const err = payload.err;
  773. hmrClient.logger.error(
  774. `Internal Server Error
  775. ${err.message}
  776. ${err.stack}`
  777. );
  778. break;
  779. }
  780. case "ping":
  781. break;
  782. default:
  783. return payload;
  784. }
  785. }
  786. class Queue {
  787. queue = [];
  788. pending = !1;
  789. enqueue(promise) {
  790. return new Promise((resolve2, reject) => {
  791. this.queue.push({
  792. promise,
  793. resolve: resolve2,
  794. reject
  795. }), this.dequeue();
  796. });
  797. }
  798. dequeue() {
  799. if (this.pending)
  800. return !1;
  801. const item = this.queue.shift();
  802. return item ? (this.pending = !0, item.promise().then(item.resolve).catch(item.reject).finally(() => {
  803. this.pending = !1, this.dequeue();
  804. }), !0) : !1;
  805. }
  806. }
  807. function getModulesByFile(runner, file) {
  808. const nodes = runner.evaluatedModules.getModulesByFile(file);
  809. return nodes ? [...nodes].map((node) => node.id) : [];
  810. }
  811. function getModulesEntrypoints(runner, modules, visited = /* @__PURE__ */ new Set(), entrypoints = /* @__PURE__ */ new Set()) {
  812. for (const moduleId of modules) {
  813. if (visited.has(moduleId)) continue;
  814. visited.add(moduleId);
  815. const module = runner.evaluatedModules.getModuleById(moduleId);
  816. if (module) {
  817. if (!module.importers.size) {
  818. entrypoints.add(module.url);
  819. continue;
  820. }
  821. for (const importer of module.importers)
  822. getModulesEntrypoints(runner, [importer], visited, entrypoints);
  823. }
  824. }
  825. return entrypoints;
  826. }
  827. function findAllEntrypoints(runner, entrypoints = /* @__PURE__ */ new Set()) {
  828. for (const mod of runner.evaluatedModules.idToModuleMap.values())
  829. mod.importers.size || entrypoints.add(mod.url);
  830. return entrypoints;
  831. }
  832. const sourceMapCache = {}, fileContentsCache = {}, evaluatedModulesCache = /* @__PURE__ */ new Set(), retrieveFileHandlers = /* @__PURE__ */ new Set(), retrieveSourceMapHandlers = /* @__PURE__ */ new Set(), createExecHandlers = (handlers) => (...args) => {
  833. for (const handler of handlers) {
  834. const result = handler(...args);
  835. if (result) return result;
  836. }
  837. return null;
  838. }, retrieveFileFromHandlers = createExecHandlers(retrieveFileHandlers), retrieveSourceMapFromHandlers = createExecHandlers(
  839. retrieveSourceMapHandlers
  840. );
  841. let overridden = !1;
  842. const originalPrepare = Error.prepareStackTrace;
  843. function resetInterceptor(runner, options) {
  844. evaluatedModulesCache.delete(runner.evaluatedModules), options.retrieveFile && retrieveFileHandlers.delete(options.retrieveFile), options.retrieveSourceMap && retrieveSourceMapHandlers.delete(options.retrieveSourceMap), evaluatedModulesCache.size === 0 && (Error.prepareStackTrace = originalPrepare, overridden = !1);
  845. }
  846. function interceptStackTrace(runner, options = {}) {
  847. return overridden || (Error.prepareStackTrace = prepareStackTrace, overridden = !0), evaluatedModulesCache.add(runner.evaluatedModules), options.retrieveFile && retrieveFileHandlers.add(options.retrieveFile), options.retrieveSourceMap && retrieveSourceMapHandlers.add(options.retrieveSourceMap), () => resetInterceptor(runner, options);
  848. }
  849. function supportRelativeURL(file, url) {
  850. if (!file) return url;
  851. const dir = posixDirname(slash(file)), match = /^\w+:\/\/[^/]*/.exec(dir);
  852. let protocol = match ? match[0] : "";
  853. const startPath = dir.slice(protocol.length);
  854. return protocol && /^\/\w:/.test(startPath) ? (protocol += "/", protocol + slash(posixResolve(startPath, url))) : protocol + posixResolve(startPath, url);
  855. }
  856. function getRunnerSourceMap(position) {
  857. for (const moduleGraph of evaluatedModulesCache) {
  858. const sourceMap = moduleGraph.getModuleSourceMapById(position.source);
  859. if (sourceMap)
  860. return {
  861. url: position.source,
  862. map: sourceMap,
  863. vite: !0
  864. };
  865. }
  866. return null;
  867. }
  868. function retrieveFile(path) {
  869. if (path in fileContentsCache) return fileContentsCache[path];
  870. const content = retrieveFileFromHandlers(path);
  871. return typeof content == "string" ? (fileContentsCache[path] = content, content) : null;
  872. }
  873. function retrieveSourceMapURL(source) {
  874. const fileData = retrieveFile(source);
  875. if (!fileData) return null;
  876. const re = /\/\/[@#]\s*sourceMappingURL=([^\s'"]+)\s*$|\/\*[@#]\s*sourceMappingURL=[^\s*'"]+\s*\*\/\s*$/gm;
  877. let lastMatch, match;
  878. for (; match = re.exec(fileData); ) lastMatch = match;
  879. return lastMatch ? lastMatch[1] : null;
  880. }
  881. const reSourceMap = /^data:application\/json[^,]+base64,/;
  882. function retrieveSourceMap(source) {
  883. const urlAndMap = retrieveSourceMapFromHandlers(source);
  884. if (urlAndMap) return urlAndMap;
  885. let sourceMappingURL = retrieveSourceMapURL(source);
  886. if (!sourceMappingURL) return null;
  887. let sourceMapData;
  888. if (reSourceMap.test(sourceMappingURL)) {
  889. const rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(",") + 1);
  890. sourceMapData = Buffer.from(rawData, "base64").toString(), sourceMappingURL = source;
  891. } else
  892. sourceMappingURL = supportRelativeURL(source, sourceMappingURL), sourceMapData = retrieveFile(sourceMappingURL);
  893. return sourceMapData ? {
  894. url: sourceMappingURL,
  895. map: sourceMapData
  896. } : null;
  897. }
  898. function mapSourcePosition(position) {
  899. if (!position.source) return position;
  900. let sourceMap = getRunnerSourceMap(position);
  901. if (sourceMap || (sourceMap = sourceMapCache[position.source]), !sourceMap) {
  902. const urlAndMap = retrieveSourceMap(position.source);
  903. if (urlAndMap && urlAndMap.map) {
  904. const url = urlAndMap.url;
  905. sourceMap = sourceMapCache[position.source] = {
  906. url,
  907. map: new DecodedMap(
  908. typeof urlAndMap.map == "string" ? JSON.parse(urlAndMap.map) : urlAndMap.map,
  909. url
  910. )
  911. };
  912. const contents = sourceMap.map?.map.sourcesContent;
  913. sourceMap.map && contents && sourceMap.map.resolvedSources.forEach((source, i) => {
  914. const content = contents[i];
  915. if (content && source && url) {
  916. const contentUrl = supportRelativeURL(url, source);
  917. fileContentsCache[contentUrl] = content;
  918. }
  919. });
  920. } else
  921. sourceMap = sourceMapCache[position.source] = {
  922. url: null,
  923. map: null
  924. };
  925. }
  926. if (sourceMap.map && sourceMap.url) {
  927. const originalPosition = getOriginalPosition(sourceMap.map, position);
  928. if (originalPosition && originalPosition.source != null)
  929. return originalPosition.source = supportRelativeURL(
  930. sourceMap.url,
  931. originalPosition.source
  932. ), sourceMap.vite && (originalPosition._vite = !0), originalPosition;
  933. }
  934. return position;
  935. }
  936. function mapEvalOrigin(origin) {
  937. let match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin);
  938. if (match) {
  939. const position = mapSourcePosition({
  940. name: null,
  941. source: match[2],
  942. line: +match[3],
  943. column: +match[4] - 1
  944. });
  945. return `eval at ${match[1]} (${position.source}:${position.line}:${position.column + 1})`;
  946. }
  947. return match = /^eval at ([^(]+) \((.+)\)$/.exec(origin), match ? `eval at ${match[1]} (${mapEvalOrigin(match[2])})` : origin;
  948. }
  949. function CallSiteToString() {
  950. let fileName, fileLocation = "";
  951. if (this.isNative())
  952. fileLocation = "native";
  953. else {
  954. fileName = this.getScriptNameOrSourceURL(), !fileName && this.isEval() && (fileLocation = this.getEvalOrigin(), fileLocation += ", "), fileName ? fileLocation += fileName : fileLocation += "<anonymous>";
  955. const lineNumber = this.getLineNumber();
  956. if (lineNumber != null) {
  957. fileLocation += `:${lineNumber}`;
  958. const columnNumber = this.getColumnNumber();
  959. columnNumber && (fileLocation += `:${columnNumber}`);
  960. }
  961. }
  962. let line = "";
  963. const functionName = this.getFunctionName();
  964. let addSuffix = !0;
  965. const isConstructor = this.isConstructor();
  966. if (this.isToplevel() || isConstructor)
  967. isConstructor ? line += `new ${functionName || "<anonymous>"}` : functionName ? line += functionName : (line += fileLocation, addSuffix = !1);
  968. else {
  969. let typeName = this.getTypeName();
  970. typeName === "[object Object]" && (typeName = "null");
  971. const methodName = this.getMethodName();
  972. functionName ? (typeName && functionName.indexOf(typeName) !== 0 && (line += `${typeName}.`), line += functionName, methodName && functionName.indexOf(`.${methodName}`) !== functionName.length - methodName.length - 1 && (line += ` [as ${methodName}]`)) : line += `${typeName}.${methodName || "<anonymous>"}`;
  973. }
  974. return addSuffix && (line += ` (${fileLocation})`), line;
  975. }
  976. function cloneCallSite(frame) {
  977. const object = {};
  978. return Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach((name) => {
  979. const key = name;
  980. object[key] = /^(?:is|get)/.test(name) ? function() {
  981. return frame[key].call(frame);
  982. } : frame[key];
  983. }), object.toString = CallSiteToString, object;
  984. }
  985. function wrapCallSite(frame, state) {
  986. if (state === void 0 && (state = { nextPosition: null, curPosition: null }), frame.isNative())
  987. return state.curPosition = null, frame;
  988. const source = frame.getFileName() || frame.getScriptNameOrSourceURL();
  989. if (source) {
  990. const line = frame.getLineNumber();
  991. let column = frame.getColumnNumber() - 1;
  992. const headerLength = 62;
  993. line === 1 && column > headerLength && !frame.isEval() && (column -= headerLength);
  994. const position = mapSourcePosition({
  995. name: null,
  996. source,
  997. line,
  998. column
  999. });
  1000. state.curPosition = position, frame = cloneCallSite(frame);
  1001. const originalFunctionName = frame.getFunctionName;
  1002. return frame.getFunctionName = function() {
  1003. const name = state.nextPosition == null ? originalFunctionName() : state.nextPosition.name || originalFunctionName();
  1004. return name === "eval" && "_vite" in position ? null : name;
  1005. }, frame.getFileName = function() {
  1006. return position.source ?? void 0;
  1007. }, frame.getLineNumber = function() {
  1008. return position.line;
  1009. }, frame.getColumnNumber = function() {
  1010. return position.column + 1;
  1011. }, frame.getScriptNameOrSourceURL = function() {
  1012. return position.source;
  1013. }, frame;
  1014. }
  1015. let origin = frame.isEval() && frame.getEvalOrigin();
  1016. return origin && (origin = mapEvalOrigin(origin), frame = cloneCallSite(frame), frame.getEvalOrigin = function() {
  1017. return origin || void 0;
  1018. }), frame;
  1019. }
  1020. function prepareStackTrace(error, stack) {
  1021. const name = error.name || "Error", message = error.message || "", errorString = `${name}: ${message}`, state = { nextPosition: null, curPosition: null }, processedStack = [];
  1022. for (let i = stack.length - 1; i >= 0; i--)
  1023. processedStack.push(`
  1024. at ${wrapCallSite(stack[i], state)}`), state.nextPosition = state.curPosition;
  1025. return state.curPosition = state.nextPosition = null, errorString + processedStack.reverse().join("");
  1026. }
  1027. function enableSourceMapSupport(runner) {
  1028. if (runner.options.sourcemapInterceptor === "node") {
  1029. if (typeof process > "u")
  1030. throw new TypeError(
  1031. `Cannot use "sourcemapInterceptor: 'node'" because global "process" variable is not available.`
  1032. );
  1033. if (typeof process.setSourceMapsEnabled != "function")
  1034. throw new TypeError(
  1035. `Cannot use "sourcemapInterceptor: 'node'" because "process.setSourceMapsEnabled" function is not available. Please use Node >= 16.6.0.`
  1036. );
  1037. const isEnabledAlready = process.sourceMapsEnabled ?? !1;
  1038. return process.setSourceMapsEnabled(!0), () => !isEnabledAlready && process.setSourceMapsEnabled(!1);
  1039. }
  1040. return interceptStackTrace(
  1041. runner,
  1042. typeof runner.options.sourcemapInterceptor == "object" ? runner.options.sourcemapInterceptor : void 0
  1043. );
  1044. }
  1045. class ESModulesEvaluator {
  1046. startOffset = getAsyncFunctionDeclarationPaddingLineCount();
  1047. async runInlinedModule(context, code) {
  1048. await new AsyncFunction(
  1049. ssrModuleExportsKey,
  1050. ssrImportMetaKey,
  1051. ssrImportKey,
  1052. ssrDynamicImportKey,
  1053. ssrExportAllKey,
  1054. // source map should already be inlined by Vite
  1055. '"use strict";' + code
  1056. )(
  1057. context[ssrModuleExportsKey],
  1058. context[ssrImportMetaKey],
  1059. context[ssrImportKey],
  1060. context[ssrDynamicImportKey],
  1061. context[ssrExportAllKey]
  1062. ), Object.seal(context[ssrModuleExportsKey]);
  1063. }
  1064. runExternalModule(filepath) {
  1065. return import(filepath);
  1066. }
  1067. }
  1068. class ModuleRunner {
  1069. constructor(options, evaluator = new ESModulesEvaluator(), debug) {
  1070. if (this.options = options, this.evaluator = evaluator, this.debug = debug, this.evaluatedModules = options.evaluatedModules ?? new EvaluatedModules(), this.transport = normalizeModuleRunnerTransport(options.transport), options.hmr !== !1) {
  1071. const optionsHmr = options.hmr ?? !0, resolvedHmrLogger = optionsHmr === !0 || optionsHmr.logger === void 0 ? hmrLogger : optionsHmr.logger === !1 ? silentConsole : optionsHmr.logger;
  1072. if (this.hmrClient = new HMRClient(
  1073. resolvedHmrLogger,
  1074. this.transport,
  1075. ({ acceptedPath }) => this.import(acceptedPath)
  1076. ), !this.transport.connect)
  1077. throw new Error(
  1078. "HMR is not supported by this runner transport, but `hmr` option was set to true"
  1079. );
  1080. this.transport.connect(createHMRHandler(this));
  1081. } else
  1082. this.transport.connect?.();
  1083. options.sourcemapInterceptor !== !1 && (this.resetSourceMapSupport = enableSourceMapSupport(this));
  1084. }
  1085. evaluatedModules;
  1086. hmrClient;
  1087. envProxy = new Proxy({}, {
  1088. get(_, p) {
  1089. throw new Error(
  1090. `[module runner] Dynamic access of "import.meta.env" is not supported. Please, use "import.meta.env.${String(p)}" instead.`
  1091. );
  1092. }
  1093. });
  1094. transport;
  1095. resetSourceMapSupport;
  1096. concurrentModuleNodePromises = /* @__PURE__ */ new Map();
  1097. closed = !1;
  1098. /**
  1099. * URL to execute. Accepts file path, server path or id relative to the root.
  1100. */
  1101. async import(url) {
  1102. const fetchedModule = await this.cachedModule(url);
  1103. return await this.cachedRequest(url, fetchedModule);
  1104. }
  1105. /**
  1106. * Clear all caches including HMR listeners.
  1107. */
  1108. clearCache() {
  1109. this.evaluatedModules.clear(), this.hmrClient?.clear();
  1110. }
  1111. /**
  1112. * Clears all caches, removes all HMR listeners, and resets source map support.
  1113. * This method doesn't stop the HMR connection.
  1114. */
  1115. async close() {
  1116. this.resetSourceMapSupport?.(), this.clearCache(), this.hmrClient = void 0, this.closed = !0, await this.transport.disconnect?.();
  1117. }
  1118. /**
  1119. * Returns `true` if the runtime has been closed by calling `close()` method.
  1120. */
  1121. isClosed() {
  1122. return this.closed;
  1123. }
  1124. processImport(exports, fetchResult, metadata) {
  1125. if (!("externalize" in fetchResult))
  1126. return exports;
  1127. const { url, type } = fetchResult;
  1128. return type !== "module" && type !== "commonjs" || analyzeImportedModDifference(exports, url, type, metadata), exports;
  1129. }
  1130. isCircularModule(mod) {
  1131. for (const importedFile of mod.imports)
  1132. if (mod.importers.has(importedFile))
  1133. return !0;
  1134. return !1;
  1135. }
  1136. isCircularImport(importers, moduleUrl, visited = /* @__PURE__ */ new Set()) {
  1137. for (const importer of importers) {
  1138. if (visited.has(importer))
  1139. continue;
  1140. if (visited.add(importer), importer === moduleUrl)
  1141. return !0;
  1142. const mod = this.evaluatedModules.getModuleById(importer);
  1143. if (mod && mod.importers.size && this.isCircularImport(mod.importers, moduleUrl, visited))
  1144. return !0;
  1145. }
  1146. return !1;
  1147. }
  1148. async cachedRequest(url, mod, callstack = [], metadata) {
  1149. const meta = mod.meta, moduleId = meta.id, { importers } = mod, importee = callstack[callstack.length - 1];
  1150. if (importee && importers.add(importee), (callstack.includes(moduleId) || this.isCircularModule(mod) || this.isCircularImport(importers, moduleId)) && mod.exports)
  1151. return this.processImport(mod.exports, meta, metadata);
  1152. let debugTimer;
  1153. this.debug && (debugTimer = setTimeout(() => {
  1154. const getStack = () => `stack:
  1155. ${[...callstack, moduleId].reverse().map((p) => ` - ${p}`).join(`
  1156. `)}`;
  1157. this.debug(
  1158. `[module runner] module ${moduleId} takes over 2s to load.
  1159. ${getStack()}`
  1160. );
  1161. }, 2e3));
  1162. try {
  1163. if (mod.promise)
  1164. return this.processImport(await mod.promise, meta, metadata);
  1165. const promise = this.directRequest(url, mod, callstack);
  1166. return mod.promise = promise, mod.evaluated = !1, this.processImport(await promise, meta, metadata);
  1167. } finally {
  1168. mod.evaluated = !0, debugTimer && clearTimeout(debugTimer);
  1169. }
  1170. }
  1171. async cachedModule(url, importer) {
  1172. let cached = this.concurrentModuleNodePromises.get(url);
  1173. if (cached)
  1174. this.debug?.("[module runner] using cached module info for", url);
  1175. else {
  1176. const cachedModule = this.evaluatedModules.getModuleByUrl(url);
  1177. cached = this.getModuleInformation(url, importer, cachedModule).finally(
  1178. () => {
  1179. this.concurrentModuleNodePromises.delete(url);
  1180. }
  1181. ), this.concurrentModuleNodePromises.set(url, cached);
  1182. }
  1183. return cached;
  1184. }
  1185. async getModuleInformation(url, importer, cachedModule) {
  1186. if (this.closed)
  1187. throw new Error("Vite module runner has been closed.");
  1188. this.debug?.("[module runner] fetching", url);
  1189. const isCached = !!(typeof cachedModule == "object" && cachedModule.meta), fetchedModule = (
  1190. // fast return for established externalized pattern
  1191. url.startsWith("data:") ? { externalize: url, type: "builtin" } : await this.transport.invoke("fetchModule", [
  1192. url,
  1193. importer,
  1194. {
  1195. cached: isCached,
  1196. startOffset: this.evaluator.startOffset
  1197. }
  1198. ])
  1199. );
  1200. if ("cache" in fetchedModule) {
  1201. if (!cachedModule || !cachedModule.meta)
  1202. throw new Error(
  1203. `Module "${url}" was mistakenly invalidated during fetch phase.`
  1204. );
  1205. return cachedModule;
  1206. }
  1207. const moduleId = "externalize" in fetchedModule ? fetchedModule.externalize : fetchedModule.id, moduleUrl = "url" in fetchedModule ? fetchedModule.url : url, module = this.evaluatedModules.ensureModule(moduleId, moduleUrl);
  1208. return "invalidate" in fetchedModule && fetchedModule.invalidate && this.evaluatedModules.invalidateModule(module), fetchedModule.url = moduleUrl, fetchedModule.id = moduleId, module.meta = fetchedModule, module;
  1209. }
  1210. // override is allowed, consider this a public API
  1211. async directRequest(url, mod, _callstack) {
  1212. const fetchResult = mod.meta, moduleId = fetchResult.id, callstack = [..._callstack, moduleId], request = async (dep, metadata) => {
  1213. const importer = "file" in fetchResult && fetchResult.file || moduleId, depMod = await this.cachedModule(dep, importer);
  1214. return depMod.importers.add(moduleId), mod.imports.add(depMod.id), this.cachedRequest(dep, depMod, callstack, metadata);
  1215. }, dynamicRequest = async (dep) => (dep = String(dep), dep[0] === "." && (dep = posixResolve(posixDirname(url), dep)), request(dep, { isDynamicImport: !0 }));
  1216. if ("externalize" in fetchResult) {
  1217. const { externalize } = fetchResult;
  1218. this.debug?.("[module runner] externalizing", externalize);
  1219. const exports2 = await this.evaluator.runExternalModule(externalize);
  1220. return mod.exports = exports2, exports2;
  1221. }
  1222. const { code, file } = fetchResult;
  1223. if (code == null) {
  1224. const importer = callstack[callstack.length - 2];
  1225. throw new Error(
  1226. `[module runner] Failed to load "${url}"${importer ? ` imported from ${importer}` : ""}`
  1227. );
  1228. }
  1229. const modulePath = cleanUrl(file || moduleId), href = posixPathToFileHref(modulePath), filename = modulePath, dirname2 = posixDirname(modulePath), meta = {
  1230. filename: isWindows ? toWindowsPath(filename) : filename,
  1231. dirname: isWindows ? toWindowsPath(dirname2) : dirname2,
  1232. url: href,
  1233. env: this.envProxy,
  1234. resolve(_id, _parent) {
  1235. throw new Error(
  1236. '[module runner] "import.meta.resolve" is not supported.'
  1237. );
  1238. },
  1239. // should be replaced during transformation
  1240. glob() {
  1241. throw new Error(
  1242. '[module runner] "import.meta.glob" is statically replaced during file transformation. Make sure to reference it by the full name.'
  1243. );
  1244. }
  1245. }, exports = /* @__PURE__ */ Object.create(null);
  1246. Object.defineProperty(exports, Symbol.toStringTag, {
  1247. value: "Module",
  1248. enumerable: !1,
  1249. configurable: !1
  1250. }), mod.exports = exports;
  1251. let hotContext;
  1252. this.hmrClient && Object.defineProperty(meta, "hot", {
  1253. enumerable: !0,
  1254. get: () => {
  1255. if (!this.hmrClient)
  1256. throw new Error("[module runner] HMR client was closed.");
  1257. return this.debug?.("[module runner] creating hmr context for", mod.url), hotContext ||= new HMRContext(this.hmrClient, mod.url), hotContext;
  1258. },
  1259. set: (value) => {
  1260. hotContext = value;
  1261. }
  1262. });
  1263. const context = {
  1264. [ssrImportKey]: request,
  1265. [ssrDynamicImportKey]: dynamicRequest,
  1266. [ssrModuleExportsKey]: exports,
  1267. [ssrExportAllKey]: (obj) => exportAll(exports, obj),
  1268. [ssrImportMetaKey]: meta
  1269. };
  1270. return this.debug?.("[module runner] executing", href), await this.evaluator.runInlinedModule(context, code, mod), exports;
  1271. }
  1272. }
  1273. function exportAll(exports, sourceModule) {
  1274. if (exports !== sourceModule && !(isPrimitive(sourceModule) || Array.isArray(sourceModule) || sourceModule instanceof Promise)) {
  1275. for (const key in sourceModule)
  1276. if (key !== "default" && key !== "__esModule" && !(key in exports))
  1277. try {
  1278. Object.defineProperty(exports, key, {
  1279. enumerable: !0,
  1280. configurable: !0,
  1281. get: () => sourceModule[key]
  1282. });
  1283. } catch {
  1284. }
  1285. }
  1286. }
  1287. export {
  1288. ESModulesEvaluator,
  1289. EvaluatedModules,
  1290. ModuleRunner,
  1291. createWebSocketModuleRunnerTransport,
  1292. ssrDynamicImportKey,
  1293. ssrExportAllKey,
  1294. ssrImportKey,
  1295. ssrImportMetaKey,
  1296. ssrModuleExportsKey
  1297. };