runtime.js 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066
  1. const VALID_ID_PREFIX = "/@id/", NULL_BYTE_PLACEHOLDER = "__x00__";
  2. let SOURCEMAPPING_URL = "sourceMa";
  3. SOURCEMAPPING_URL += "ppingURL";
  4. const isWindows = typeof process < "u" && process.platform === "win32";
  5. function wrapId(id) {
  6. return id.startsWith(VALID_ID_PREFIX) ? id : VALID_ID_PREFIX + id.replace("\0", NULL_BYTE_PLACEHOLDER);
  7. }
  8. function unwrapId(id) {
  9. return id.startsWith(VALID_ID_PREFIX) ? id.slice(VALID_ID_PREFIX.length).replace(NULL_BYTE_PLACEHOLDER, "\0") : id;
  10. }
  11. const windowsSlashRE = /\\/g;
  12. function slash(p) {
  13. return p.replace(windowsSlashRE, "/");
  14. }
  15. const postfixRE = /[?#].*$/;
  16. function cleanUrl(url) {
  17. return url.replace(postfixRE, "");
  18. }
  19. function isPrimitive(value) {
  20. return !value || typeof value != "object" && typeof value != "function";
  21. }
  22. function withTrailingSlash(path) {
  23. return path[path.length - 1] !== "/" ? `${path}/` : path;
  24. }
  25. const AsyncFunction = async function() {
  26. }.constructor, _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
  27. function normalizeWindowsPath(input = "") {
  28. return input && input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
  29. }
  30. const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/, _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
  31. function cwd() {
  32. return typeof process < "u" && typeof process.cwd == "function" ? process.cwd().replace(/\\/g, "/") : "/";
  33. }
  34. const resolve = function(...arguments_) {
  35. arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
  36. let resolvedPath = "", resolvedAbsolute = !1;
  37. for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
  38. const path = index >= 0 ? arguments_[index] : cwd();
  39. !path || path.length === 0 || (resolvedPath = `${path}/${resolvedPath}`, resolvedAbsolute = isAbsolute(path));
  40. }
  41. return resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute), resolvedAbsolute && !isAbsolute(resolvedPath) ? `/${resolvedPath}` : resolvedPath.length > 0 ? resolvedPath : ".";
  42. };
  43. function normalizeString(path, allowAboveRoot) {
  44. let res = "", lastSegmentLength = 0, lastSlash = -1, dots = 0, char = null;
  45. for (let index = 0; index <= path.length; ++index) {
  46. if (index < path.length)
  47. char = path[index];
  48. else {
  49. if (char === "/")
  50. break;
  51. char = "/";
  52. }
  53. if (char === "/") {
  54. if (!(lastSlash === index - 1 || dots === 1)) if (dots === 2) {
  55. if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
  56. if (res.length > 2) {
  57. const lastSlashIndex = res.lastIndexOf("/");
  58. lastSlashIndex === -1 ? (res = "", lastSegmentLength = 0) : (res = res.slice(0, lastSlashIndex), lastSegmentLength = res.length - 1 - res.lastIndexOf("/")), lastSlash = index, dots = 0;
  59. continue;
  60. } else if (res.length > 0) {
  61. res = "", lastSegmentLength = 0, lastSlash = index, dots = 0;
  62. continue;
  63. }
  64. }
  65. allowAboveRoot && (res += res.length > 0 ? "/.." : "..", lastSegmentLength = 2);
  66. } else
  67. res.length > 0 ? res += `/${path.slice(lastSlash + 1, index)}` : res = path.slice(lastSlash + 1, index), lastSegmentLength = index - lastSlash - 1;
  68. lastSlash = index, dots = 0;
  69. } else char === "." && dots !== -1 ? ++dots : dots = -1;
  70. }
  71. return res;
  72. }
  73. const isAbsolute = function(p) {
  74. return _IS_ABSOLUTE_RE.test(p);
  75. }, dirname = function(p) {
  76. const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
  77. return segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0]) && (segments[0] += "/"), segments.join("/") || (isAbsolute(p) ? "/" : ".");
  78. }, 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;
  79. function encodePathChars(filepath) {
  80. return filepath.indexOf("%") !== -1 && (filepath = filepath.replace(percentRegEx, "%25")), !isWindows && filepath.indexOf("\\") !== -1 && (filepath = filepath.replace(backslashRegEx, "%5C")), filepath.indexOf(`
  81. `) !== -1 && (filepath = filepath.replace(newlineRegEx, "%0A")), filepath.indexOf("\r") !== -1 && (filepath = filepath.replace(carriageReturnRegEx, "%0D")), filepath.indexOf(" ") !== -1 && (filepath = filepath.replace(tabRegEx, "%09")), filepath;
  82. }
  83. const posixDirname = dirname, posixResolve = resolve;
  84. function posixPathToFileHref(posixPath) {
  85. let resolved = posixResolve(posixPath);
  86. const filePathLast = posixPath.charCodeAt(posixPath.length - 1);
  87. 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;
  88. }
  89. function toWindowsPath(path) {
  90. return path.replace(/\//g, "\\");
  91. }
  92. const comma = 44, chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", intToChar = new Uint8Array(64), charToInt = new Uint8Array(128);
  93. for (let i = 0; i < chars.length; i++) {
  94. const c = chars.charCodeAt(i);
  95. intToChar[i] = c, charToInt[c] = i;
  96. }
  97. function decodeInteger(reader, relative) {
  98. let value = 0, shift = 0, integer = 0;
  99. do {
  100. const c = reader.next();
  101. integer = charToInt[c], value |= (integer & 31) << shift, shift += 5;
  102. } while (integer & 32);
  103. const shouldNegate = value & 1;
  104. return value >>>= 1, shouldNegate && (value = -2147483648 | -value), relative + value;
  105. }
  106. function hasMoreVlq(reader, max) {
  107. return reader.pos >= max ? !1 : reader.peek() !== comma;
  108. }
  109. class StringReader {
  110. constructor(buffer) {
  111. this.pos = 0, this.buffer = buffer;
  112. }
  113. next() {
  114. return this.buffer.charCodeAt(this.pos++);
  115. }
  116. peek() {
  117. return this.buffer.charCodeAt(this.pos);
  118. }
  119. indexOf(char) {
  120. const { buffer, pos } = this, idx = buffer.indexOf(char, pos);
  121. return idx === -1 ? buffer.length : idx;
  122. }
  123. }
  124. function decode(mappings) {
  125. const { length } = mappings, reader = new StringReader(mappings), decoded = [];
  126. let genColumn = 0, sourcesIndex = 0, sourceLine = 0, sourceColumn = 0, namesIndex = 0;
  127. do {
  128. const semi = reader.indexOf(";"), line = [];
  129. let sorted = !0, lastCol = 0;
  130. for (genColumn = 0; reader.pos < semi; ) {
  131. let seg;
  132. 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++;
  133. }
  134. sorted || sort(line), decoded.push(line), reader.pos = semi + 1;
  135. } while (reader.pos <= length);
  136. return decoded;
  137. }
  138. function sort(line) {
  139. line.sort(sortComparator);
  140. }
  141. function sortComparator(a, b) {
  142. return a[0] - b[0];
  143. }
  144. const COLUMN = 0, SOURCES_INDEX = 1, SOURCE_LINE = 2, SOURCE_COLUMN = 3, NAMES_INDEX = 4;
  145. let found = !1;
  146. function binarySearch(haystack, needle, low, high) {
  147. for (; low <= high; ) {
  148. const mid = low + (high - low >> 1), cmp = haystack[mid][COLUMN] - needle;
  149. if (cmp === 0)
  150. return found = !0, mid;
  151. cmp < 0 ? low = mid + 1 : high = mid - 1;
  152. }
  153. return found = !1, low - 1;
  154. }
  155. function upperBound(haystack, needle, index) {
  156. for (let i = index + 1; i < haystack.length && haystack[i][COLUMN] === needle; index = i++)
  157. ;
  158. return index;
  159. }
  160. function lowerBound(haystack, needle, index) {
  161. for (let i = index - 1; i >= 0 && haystack[i][COLUMN] === needle; index = i--)
  162. ;
  163. return index;
  164. }
  165. function memoizedBinarySearch(haystack, needle, state, key) {
  166. const { lastKey, lastNeedle, lastIndex } = state;
  167. let low = 0, high = haystack.length - 1;
  168. if (key === lastKey) {
  169. if (needle === lastNeedle)
  170. return found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle, lastIndex;
  171. needle >= lastNeedle ? low = lastIndex === -1 ? 0 : lastIndex : high = lastIndex;
  172. }
  173. return state.lastKey = key, state.lastNeedle = needle, state.lastIndex = binarySearch(haystack, needle, low, high);
  174. }
  175. 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;
  176. function cast(map) {
  177. return map;
  178. }
  179. function decodedMappings(map) {
  180. var _a;
  181. return (_a = map)._decoded || (_a._decoded = decode(map._encoded));
  182. }
  183. function originalPositionFor(map, needle) {
  184. let { line, column, bias } = needle;
  185. if (line--, line < 0)
  186. throw new Error(LINE_GTR_ZERO);
  187. if (column < 0)
  188. throw new Error(COL_GTR_EQ_ZERO);
  189. const decoded = decodedMappings(map);
  190. if (line >= decoded.length)
  191. return OMapping(null, null, null, null);
  192. const segments = decoded[line], index = traceSegmentInternal(segments, map._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND);
  193. if (index === -1)
  194. return OMapping(null, null, null, null);
  195. const segment = segments[index];
  196. if (segment.length === 1)
  197. return OMapping(null, null, null, null);
  198. const { names, resolvedSources } = map;
  199. return OMapping(resolvedSources[segment[SOURCES_INDEX]], segment[SOURCE_LINE] + 1, segment[SOURCE_COLUMN], segment.length === 5 ? names[segment[NAMES_INDEX]] : null);
  200. }
  201. function OMapping(source, line, column, name) {
  202. return { source, line, column, name };
  203. }
  204. function traceSegmentInternal(segments, memo, line, column, bias) {
  205. let index = memoizedBinarySearch(segments, column, memo, line);
  206. return found ? index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index) : bias === LEAST_UPPER_BOUND && index++, index === -1 || index === segments.length ? -1 : index;
  207. }
  208. class DecodedMap {
  209. constructor(map, from) {
  210. this.map = map;
  211. const { mappings, names, sources } = map;
  212. this.version = map.version, this.names = names || [], this._encoded = mappings || "", this._decodedMemo = memoizedState(), this.url = from, this.resolvedSources = (sources || []).map(
  213. (s) => posixResolve(s || "", from)
  214. );
  215. }
  216. _encoded;
  217. _decoded;
  218. _decodedMemo;
  219. url;
  220. version;
  221. names = [];
  222. resolvedSources;
  223. }
  224. function memoizedState() {
  225. return {
  226. lastKey: -1,
  227. lastNeedle: -1,
  228. lastIndex: -1
  229. };
  230. }
  231. function getOriginalPosition(map, needle) {
  232. const result = originalPositionFor(map, needle);
  233. return result.column == null ? null : result;
  234. }
  235. const VITE_RUNTIME_SOURCEMAPPING_REGEXP = new RegExp(
  236. `//# ${SOURCEMAPPING_URL}=data:application/json;base64,(.+)`
  237. );
  238. class ModuleCacheMap extends Map {
  239. root;
  240. constructor(root, entries) {
  241. super(entries), this.root = withTrailingSlash(root);
  242. }
  243. normalize(fsPath) {
  244. return normalizeModuleId(fsPath, this.root);
  245. }
  246. /**
  247. * Assign partial data to the map
  248. */
  249. update(fsPath, mod) {
  250. return fsPath = this.normalize(fsPath), super.has(fsPath) ? Object.assign(super.get(fsPath), mod) : this.setByModuleId(fsPath, mod), this;
  251. }
  252. setByModuleId(modulePath, mod) {
  253. return super.set(modulePath, mod);
  254. }
  255. set(fsPath, mod) {
  256. return this.setByModuleId(this.normalize(fsPath), mod);
  257. }
  258. getByModuleId(modulePath) {
  259. super.has(modulePath) || this.setByModuleId(modulePath, {});
  260. const mod = super.get(modulePath);
  261. return mod.imports || Object.assign(mod, {
  262. imports: /* @__PURE__ */ new Set(),
  263. importers: /* @__PURE__ */ new Set()
  264. }), mod;
  265. }
  266. get(fsPath) {
  267. return this.getByModuleId(this.normalize(fsPath));
  268. }
  269. deleteByModuleId(modulePath) {
  270. return super.delete(modulePath);
  271. }
  272. delete(fsPath) {
  273. return this.deleteByModuleId(this.normalize(fsPath));
  274. }
  275. invalidate(id) {
  276. const module = this.get(id);
  277. module.evaluated = !1, module.meta = void 0, module.map = void 0, module.promise = void 0, module.exports = void 0, module.imports?.clear();
  278. }
  279. isImported({
  280. importedId,
  281. importedBy
  282. }, seen = /* @__PURE__ */ new Set()) {
  283. if (importedId = this.normalize(importedId), importedBy = this.normalize(importedBy), importedBy === importedId) return !0;
  284. if (seen.has(importedId)) return !1;
  285. seen.add(importedId);
  286. const importers = this.getByModuleId(importedId)?.importers;
  287. if (!importers) return !1;
  288. if (importers.has(importedBy)) return !0;
  289. for (const importer of importers)
  290. if (this.isImported({
  291. importedBy,
  292. importedId: importer
  293. }))
  294. return !0;
  295. return !1;
  296. }
  297. /**
  298. * Invalidate modules that dependent on the given modules, up to the main entry
  299. */
  300. invalidateDepTree(ids, invalidated = /* @__PURE__ */ new Set()) {
  301. for (const _id of ids) {
  302. const id = this.normalize(_id);
  303. if (invalidated.has(id)) continue;
  304. invalidated.add(id);
  305. const mod = super.get(id);
  306. mod?.importers && this.invalidateDepTree(mod.importers, invalidated), super.delete(id);
  307. }
  308. return invalidated;
  309. }
  310. /**
  311. * Invalidate dependency modules of the given modules, down to the bottom-level dependencies
  312. */
  313. invalidateSubDepTree(ids, invalidated = /* @__PURE__ */ new Set()) {
  314. for (const _id of ids) {
  315. const id = this.normalize(_id);
  316. if (invalidated.has(id)) continue;
  317. invalidated.add(id);
  318. const subIds = Array.from(super.entries()).filter(([, mod]) => mod.importers?.has(id)).map(([key]) => key);
  319. subIds.length && this.invalidateSubDepTree(subIds, invalidated), super.delete(id);
  320. }
  321. return invalidated;
  322. }
  323. getSourceMap(moduleId) {
  324. const mod = this.get(moduleId);
  325. if (mod.map) return mod.map;
  326. if (!mod.meta || !("code" in mod.meta)) return null;
  327. const mapString = VITE_RUNTIME_SOURCEMAPPING_REGEXP.exec(mod.meta.code)?.[1];
  328. if (!mapString) return null;
  329. const baseFile = mod.meta.file || moduleId.split("?")[0];
  330. return mod.map = new DecodedMap(JSON.parse(decodeBase64(mapString)), baseFile), mod.map;
  331. }
  332. }
  333. const prefixedBuiltins = /* @__PURE__ */ new Set(["node:test"]);
  334. function normalizeModuleId(file, root) {
  335. if (prefixedBuiltins.has(file)) return file;
  336. let unixFile = slash(file).replace(/^\/@fs\//, isWindows ? "" : "/").replace(/^node:/, "").replace(/^\/+/, "/");
  337. return unixFile.startsWith(root) && (unixFile = unixFile.slice(root.length - 1)), unixFile.replace(/^file:\//, "/");
  338. }
  339. class HMRContext {
  340. constructor(hmrClient, ownerPath) {
  341. this.hmrClient = hmrClient, this.ownerPath = ownerPath, hmrClient.dataMap.has(ownerPath) || hmrClient.dataMap.set(ownerPath, {});
  342. const mod = hmrClient.hotModulesMap.get(ownerPath);
  343. mod && (mod.callbacks = []);
  344. const staleListeners = hmrClient.ctxToListenersMap.get(ownerPath);
  345. if (staleListeners)
  346. for (const [event, staleFns] of staleListeners) {
  347. const listeners = hmrClient.customListenersMap.get(event);
  348. listeners && hmrClient.customListenersMap.set(
  349. event,
  350. listeners.filter((l) => !staleFns.includes(l))
  351. );
  352. }
  353. this.newListeners = /* @__PURE__ */ new Map(), hmrClient.ctxToListenersMap.set(ownerPath, this.newListeners);
  354. }
  355. newListeners;
  356. get data() {
  357. return this.hmrClient.dataMap.get(this.ownerPath);
  358. }
  359. accept(deps, callback) {
  360. if (typeof deps == "function" || !deps)
  361. this.acceptDeps([this.ownerPath], ([mod]) => deps?.(mod));
  362. else if (typeof deps == "string")
  363. this.acceptDeps([deps], ([mod]) => callback?.(mod));
  364. else if (Array.isArray(deps))
  365. this.acceptDeps(deps, callback);
  366. else
  367. throw new Error("invalid hot.accept() usage.");
  368. }
  369. // export names (first arg) are irrelevant on the client side, they're
  370. // extracted in the server for propagation
  371. acceptExports(_, callback) {
  372. this.acceptDeps([this.ownerPath], ([mod]) => callback?.(mod));
  373. }
  374. dispose(cb) {
  375. this.hmrClient.disposeMap.set(this.ownerPath, cb);
  376. }
  377. prune(cb) {
  378. this.hmrClient.pruneMap.set(this.ownerPath, cb);
  379. }
  380. // Kept for backward compatibility (#11036)
  381. // eslint-disable-next-line @typescript-eslint/no-empty-function
  382. decline() {
  383. }
  384. invalidate(message) {
  385. this.hmrClient.notifyListeners("vite:invalidate", {
  386. path: this.ownerPath,
  387. message
  388. }), this.send("vite:invalidate", { path: this.ownerPath, message }), this.hmrClient.logger.debug(
  389. `[vite] invalidate ${this.ownerPath}${message ? `: ${message}` : ""}`
  390. );
  391. }
  392. on(event, cb) {
  393. const addToMap = (map) => {
  394. const existing = map.get(event) || [];
  395. existing.push(cb), map.set(event, existing);
  396. };
  397. addToMap(this.hmrClient.customListenersMap), addToMap(this.newListeners);
  398. }
  399. off(event, cb) {
  400. const removeFromMap = (map) => {
  401. const existing = map.get(event);
  402. if (existing === void 0)
  403. return;
  404. const pruned = existing.filter((l) => l !== cb);
  405. if (pruned.length === 0) {
  406. map.delete(event);
  407. return;
  408. }
  409. map.set(event, pruned);
  410. };
  411. removeFromMap(this.hmrClient.customListenersMap), removeFromMap(this.newListeners);
  412. }
  413. send(event, data) {
  414. this.hmrClient.messenger.send(
  415. JSON.stringify({ type: "custom", event, data })
  416. );
  417. }
  418. acceptDeps(deps, callback = () => {
  419. }) {
  420. const mod = this.hmrClient.hotModulesMap.get(this.ownerPath) || {
  421. id: this.ownerPath,
  422. callbacks: []
  423. };
  424. mod.callbacks.push({
  425. deps,
  426. fn: callback
  427. }), this.hmrClient.hotModulesMap.set(this.ownerPath, mod);
  428. }
  429. }
  430. class HMRMessenger {
  431. constructor(connection) {
  432. this.connection = connection;
  433. }
  434. queue = [];
  435. send(message) {
  436. this.queue.push(message), this.flush();
  437. }
  438. flush() {
  439. this.connection.isReady() && (this.queue.forEach((msg) => this.connection.send(msg)), this.queue = []);
  440. }
  441. }
  442. class HMRClient {
  443. constructor(logger, connection, importUpdatedModule) {
  444. this.logger = logger, this.importUpdatedModule = importUpdatedModule, this.messenger = new HMRMessenger(connection);
  445. }
  446. hotModulesMap = /* @__PURE__ */ new Map();
  447. disposeMap = /* @__PURE__ */ new Map();
  448. pruneMap = /* @__PURE__ */ new Map();
  449. dataMap = /* @__PURE__ */ new Map();
  450. customListenersMap = /* @__PURE__ */ new Map();
  451. ctxToListenersMap = /* @__PURE__ */ new Map();
  452. messenger;
  453. async notifyListeners(event, data) {
  454. const cbs = this.customListenersMap.get(event);
  455. cbs && await Promise.allSettled(cbs.map((cb) => cb(data)));
  456. }
  457. clear() {
  458. this.hotModulesMap.clear(), this.disposeMap.clear(), this.pruneMap.clear(), this.dataMap.clear(), this.customListenersMap.clear(), this.ctxToListenersMap.clear();
  459. }
  460. // After an HMR update, some modules are no longer imported on the page
  461. // but they may have left behind side effects that need to be cleaned up
  462. // (.e.g style injections)
  463. async prunePaths(paths) {
  464. await Promise.all(
  465. paths.map((path) => {
  466. const disposer = this.disposeMap.get(path);
  467. if (disposer) return disposer(this.dataMap.get(path));
  468. })
  469. ), paths.forEach((path) => {
  470. const fn = this.pruneMap.get(path);
  471. fn && fn(this.dataMap.get(path));
  472. });
  473. }
  474. warnFailedUpdate(err, path) {
  475. err.message.includes("fetch") || this.logger.error(err), this.logger.error(
  476. `[hmr] Failed to reload ${path}. This could be due to syntax errors or importing non-existent modules. (see errors above)`
  477. );
  478. }
  479. updateQueue = [];
  480. pendingUpdateQueue = !1;
  481. /**
  482. * buffer multiple hot updates triggered by the same src change
  483. * so that they are invoked in the same order they were sent.
  484. * (otherwise the order may be inconsistent because of the http request round trip)
  485. */
  486. async queueUpdate(payload) {
  487. if (this.updateQueue.push(this.fetchUpdate(payload)), !this.pendingUpdateQueue) {
  488. this.pendingUpdateQueue = !0, await Promise.resolve(), this.pendingUpdateQueue = !1;
  489. const loading = [...this.updateQueue];
  490. this.updateQueue = [], (await Promise.all(loading)).forEach((fn) => fn && fn());
  491. }
  492. }
  493. async fetchUpdate(update) {
  494. const { path, acceptedPath } = update, mod = this.hotModulesMap.get(path);
  495. if (!mod)
  496. return;
  497. let fetchedModule;
  498. const isSelfUpdate = path === acceptedPath, qualifiedCallbacks = mod.callbacks.filter(
  499. ({ deps }) => deps.includes(acceptedPath)
  500. );
  501. if (isSelfUpdate || qualifiedCallbacks.length > 0) {
  502. const disposer = this.disposeMap.get(acceptedPath);
  503. disposer && await disposer(this.dataMap.get(acceptedPath));
  504. try {
  505. fetchedModule = await this.importUpdatedModule(update);
  506. } catch (e) {
  507. this.warnFailedUpdate(e, acceptedPath);
  508. }
  509. }
  510. return () => {
  511. for (const { deps, fn } of qualifiedCallbacks)
  512. fn(
  513. deps.map((dep) => dep === acceptedPath ? fetchedModule : void 0)
  514. );
  515. const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`;
  516. this.logger.debug(`[vite] hot updated: ${loggedPath}`);
  517. };
  518. }
  519. }
  520. function analyzeImportedModDifference(mod, rawId, moduleType, metadata) {
  521. if (!metadata?.isDynamicImport && metadata?.importedNames?.length) {
  522. const missingBindings = metadata.importedNames.filter((s) => !(s in mod));
  523. if (missingBindings.length) {
  524. const lastBinding = missingBindings[missingBindings.length - 1];
  525. throw moduleType === "module" ? new SyntaxError(
  526. `[vite] The requested module '${rawId}' does not provide an export named '${lastBinding}'`
  527. ) : 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.
  528. CommonJS modules can always be imported via the default export, for example using:
  529. import pkg from '${rawId}';
  530. const {${missingBindings.join(", ")}} = pkg;
  531. `);
  532. }
  533. }
  534. }
  535. const ssrModuleExportsKey = "__vite_ssr_exports__", ssrImportKey = "__vite_ssr_import__", ssrDynamicImportKey = "__vite_ssr_dynamic_import__", ssrExportAllKey = "__vite_ssr_exportAll__", ssrImportMetaKey = "__vite_ssr_import_meta__", noop = () => {
  536. }, silentConsole = {
  537. debug: noop,
  538. error: noop
  539. };
  540. function createHMRHandler(runtime) {
  541. const queue = new Queue();
  542. return (payload) => queue.enqueue(() => handleHMRPayload(runtime, payload));
  543. }
  544. async function handleHMRPayload(runtime, payload) {
  545. const hmrClient = runtime.hmrClient;
  546. if (!(!hmrClient || runtime.isDestroyed()))
  547. switch (payload.type) {
  548. case "connected":
  549. hmrClient.logger.debug("[vite] connected."), hmrClient.messenger.flush();
  550. break;
  551. case "update":
  552. await hmrClient.notifyListeners("vite:beforeUpdate", payload), await Promise.all(
  553. payload.updates.map(async (update) => {
  554. if (update.type === "js-update")
  555. return update.acceptedPath = unwrapId(update.acceptedPath), update.path = unwrapId(update.path), hmrClient.queueUpdate(update);
  556. hmrClient.logger.error(
  557. "[vite] css hmr is not supported in runtime mode."
  558. );
  559. })
  560. ), await hmrClient.notifyListeners("vite:afterUpdate", payload);
  561. break;
  562. case "custom": {
  563. await hmrClient.notifyListeners(payload.event, payload.data);
  564. break;
  565. }
  566. case "full-reload": {
  567. const { triggeredBy } = payload, clearEntrypoints = triggeredBy ? [...runtime.entrypoints].filter(
  568. (entrypoint) => runtime.moduleCache.isImported({
  569. importedId: triggeredBy,
  570. importedBy: entrypoint
  571. })
  572. ) : [...runtime.entrypoints];
  573. if (!clearEntrypoints.length) break;
  574. hmrClient.logger.debug("[vite] program reload"), await hmrClient.notifyListeners("vite:beforeFullReload", payload), runtime.moduleCache.clear();
  575. for (const id of clearEntrypoints)
  576. await runtime.executeUrl(id);
  577. break;
  578. }
  579. case "prune":
  580. await hmrClient.notifyListeners("vite:beforePrune", payload), await hmrClient.prunePaths(payload.paths);
  581. break;
  582. case "error": {
  583. await hmrClient.notifyListeners("vite:error", payload);
  584. const err = payload.err;
  585. hmrClient.logger.error(
  586. `[vite] Internal Server Error
  587. ${err.message}
  588. ${err.stack}`
  589. );
  590. break;
  591. }
  592. default:
  593. return payload;
  594. }
  595. }
  596. class Queue {
  597. queue = [];
  598. pending = !1;
  599. enqueue(promise) {
  600. return new Promise((resolve2, reject) => {
  601. this.queue.push({
  602. promise,
  603. resolve: resolve2,
  604. reject
  605. }), this.dequeue();
  606. });
  607. }
  608. dequeue() {
  609. if (this.pending)
  610. return !1;
  611. const item = this.queue.shift();
  612. return item ? (this.pending = !0, item.promise().then(item.resolve).catch(item.reject).finally(() => {
  613. this.pending = !1, this.dequeue();
  614. }), !0) : !1;
  615. }
  616. }
  617. const sourceMapCache = {}, fileContentsCache = {}, moduleGraphs = /* @__PURE__ */ new Set(), retrieveFileHandlers = /* @__PURE__ */ new Set(), retrieveSourceMapHandlers = /* @__PURE__ */ new Set(), createExecHandlers = (handlers) => (...args) => {
  618. for (const handler of handlers) {
  619. const result = handler(...args);
  620. if (result) return result;
  621. }
  622. return null;
  623. }, retrieveFileFromHandlers = createExecHandlers(retrieveFileHandlers), retrieveSourceMapFromHandlers = createExecHandlers(
  624. retrieveSourceMapHandlers
  625. );
  626. let overridden = !1;
  627. const originalPrepare = Error.prepareStackTrace;
  628. function resetInterceptor(runtime, options) {
  629. moduleGraphs.delete(runtime.moduleCache), options.retrieveFile && retrieveFileHandlers.delete(options.retrieveFile), options.retrieveSourceMap && retrieveSourceMapHandlers.delete(options.retrieveSourceMap), moduleGraphs.size === 0 && (Error.prepareStackTrace = originalPrepare, overridden = !1);
  630. }
  631. function interceptStackTrace(runtime, options = {}) {
  632. return overridden || (Error.prepareStackTrace = prepareStackTrace, overridden = !0), moduleGraphs.add(runtime.moduleCache), options.retrieveFile && retrieveFileHandlers.add(options.retrieveFile), options.retrieveSourceMap && retrieveSourceMapHandlers.add(options.retrieveSourceMap), () => resetInterceptor(runtime, options);
  633. }
  634. function supportRelativeURL(file, url) {
  635. if (!file) return url;
  636. const dir = posixDirname(slash(file)), match = /^\w+:\/\/[^/]*/.exec(dir);
  637. let protocol = match ? match[0] : "";
  638. const startPath = dir.slice(protocol.length);
  639. return protocol && /^\/\w:/.test(startPath) ? (protocol += "/", protocol + slash(posixResolve(startPath, url))) : protocol + posixResolve(startPath, url);
  640. }
  641. function getRuntimeSourceMap(position) {
  642. for (const moduleCache of moduleGraphs) {
  643. const sourceMap = moduleCache.getSourceMap(position.source);
  644. if (sourceMap)
  645. return {
  646. url: position.source,
  647. map: sourceMap,
  648. vite: !0
  649. };
  650. }
  651. return null;
  652. }
  653. function retrieveFile(path) {
  654. if (path in fileContentsCache) return fileContentsCache[path];
  655. const content = retrieveFileFromHandlers(path);
  656. return typeof content == "string" ? (fileContentsCache[path] = content, content) : null;
  657. }
  658. function retrieveSourceMapURL(source) {
  659. const fileData = retrieveFile(source);
  660. if (!fileData) return null;
  661. const re = /\/\/[@#]\s*sourceMappingURL=([^\s'"]+)\s*$|\/\*[@#]\s*sourceMappingURL=[^\s*'"]+\s*\*\/\s*$/gm;
  662. let lastMatch, match;
  663. for (; match = re.exec(fileData); ) lastMatch = match;
  664. return lastMatch ? lastMatch[1] : null;
  665. }
  666. const reSourceMap = /^data:application\/json[^,]+base64,/;
  667. function retrieveSourceMap(source) {
  668. const urlAndMap = retrieveSourceMapFromHandlers(source);
  669. if (urlAndMap) return urlAndMap;
  670. let sourceMappingURL = retrieveSourceMapURL(source);
  671. if (!sourceMappingURL) return null;
  672. let sourceMapData;
  673. if (reSourceMap.test(sourceMappingURL)) {
  674. const rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(",") + 1);
  675. sourceMapData = Buffer.from(rawData, "base64").toString(), sourceMappingURL = source;
  676. } else
  677. sourceMappingURL = supportRelativeURL(source, sourceMappingURL), sourceMapData = retrieveFile(sourceMappingURL);
  678. return sourceMapData ? {
  679. url: sourceMappingURL,
  680. map: sourceMapData
  681. } : null;
  682. }
  683. function mapSourcePosition(position) {
  684. if (!position.source) return position;
  685. let sourceMap = getRuntimeSourceMap(position);
  686. if (sourceMap || (sourceMap = sourceMapCache[position.source]), !sourceMap) {
  687. const urlAndMap = retrieveSourceMap(position.source);
  688. if (urlAndMap && urlAndMap.map) {
  689. const url = urlAndMap.url;
  690. sourceMap = sourceMapCache[position.source] = {
  691. url,
  692. map: new DecodedMap(
  693. typeof urlAndMap.map == "string" ? JSON.parse(urlAndMap.map) : urlAndMap.map,
  694. url
  695. )
  696. };
  697. const contents = sourceMap.map?.map.sourcesContent;
  698. sourceMap.map && contents && sourceMap.map.resolvedSources.forEach((source, i) => {
  699. const content = contents[i];
  700. if (content && source && url) {
  701. const contentUrl = supportRelativeURL(url, source);
  702. fileContentsCache[contentUrl] = content;
  703. }
  704. });
  705. } else
  706. sourceMap = sourceMapCache[position.source] = {
  707. url: null,
  708. map: null
  709. };
  710. }
  711. if (sourceMap && sourceMap.map && sourceMap.url) {
  712. const originalPosition = getOriginalPosition(sourceMap.map, position);
  713. if (originalPosition && originalPosition.source != null)
  714. return originalPosition.source = supportRelativeURL(
  715. sourceMap.url,
  716. originalPosition.source
  717. ), sourceMap.vite && (originalPosition._vite = !0), originalPosition;
  718. }
  719. return position;
  720. }
  721. function mapEvalOrigin(origin) {
  722. let match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin);
  723. if (match) {
  724. const position = mapSourcePosition({
  725. name: null,
  726. source: match[2],
  727. line: +match[3],
  728. column: +match[4] - 1
  729. });
  730. return `eval at ${match[1]} (${position.source}:${position.line}:${position.column + 1})`;
  731. }
  732. return match = /^eval at ([^(]+) \((.+)\)$/.exec(origin), match ? `eval at ${match[1]} (${mapEvalOrigin(match[2])})` : origin;
  733. }
  734. function CallSiteToString() {
  735. let fileName, fileLocation = "";
  736. if (this.isNative())
  737. fileLocation = "native";
  738. else {
  739. fileName = this.getScriptNameOrSourceURL(), !fileName && this.isEval() && (fileLocation = this.getEvalOrigin(), fileLocation += ", "), fileName ? fileLocation += fileName : fileLocation += "<anonymous>";
  740. const lineNumber = this.getLineNumber();
  741. if (lineNumber != null) {
  742. fileLocation += `:${lineNumber}`;
  743. const columnNumber = this.getColumnNumber();
  744. columnNumber && (fileLocation += `:${columnNumber}`);
  745. }
  746. }
  747. let line = "";
  748. const functionName = this.getFunctionName();
  749. let addSuffix = !0;
  750. const isConstructor = this.isConstructor();
  751. if (this.isToplevel() || isConstructor)
  752. isConstructor ? line += `new ${functionName || "<anonymous>"}` : functionName ? line += functionName : (line += fileLocation, addSuffix = !1);
  753. else {
  754. let typeName = this.getTypeName();
  755. typeName === "[object Object]" && (typeName = "null");
  756. const methodName = this.getMethodName();
  757. 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>"}`;
  758. }
  759. return addSuffix && (line += ` (${fileLocation})`), line;
  760. }
  761. function cloneCallSite(frame) {
  762. const object = {};
  763. return Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach((name) => {
  764. const key = name;
  765. object[key] = /^(?:is|get)/.test(name) ? function() {
  766. return frame[key].call(frame);
  767. } : frame[key];
  768. }), object.toString = CallSiteToString, object;
  769. }
  770. function wrapCallSite(frame, state) {
  771. if (state === void 0 && (state = { nextPosition: null, curPosition: null }), frame.isNative())
  772. return state.curPosition = null, frame;
  773. const source = frame.getFileName() || frame.getScriptNameOrSourceURL();
  774. if (source) {
  775. const line = frame.getLineNumber();
  776. let column = frame.getColumnNumber() - 1;
  777. const headerLength = 62;
  778. line === 1 && column > headerLength && !frame.isEval() && (column -= headerLength);
  779. const position = mapSourcePosition({
  780. name: null,
  781. source,
  782. line,
  783. column
  784. });
  785. state.curPosition = position, frame = cloneCallSite(frame);
  786. const originalFunctionName = frame.getFunctionName;
  787. return frame.getFunctionName = function() {
  788. const name = state.nextPosition == null ? originalFunctionName() : state.nextPosition.name || originalFunctionName();
  789. return name === "eval" && "_vite" in position ? null : name;
  790. }, frame.getFileName = function() {
  791. return position.source ?? void 0;
  792. }, frame.getLineNumber = function() {
  793. return position.line;
  794. }, frame.getColumnNumber = function() {
  795. return position.column + 1;
  796. }, frame.getScriptNameOrSourceURL = function() {
  797. return position.source;
  798. }, frame;
  799. }
  800. let origin = frame.isEval() && frame.getEvalOrigin();
  801. return origin && (origin = mapEvalOrigin(origin), frame = cloneCallSite(frame), frame.getEvalOrigin = function() {
  802. return origin || void 0;
  803. }), frame;
  804. }
  805. function prepareStackTrace(error, stack) {
  806. const name = error.name || "Error", message = error.message || "", errorString = `${name}: ${message}`, state = { nextPosition: null, curPosition: null }, processedStack = [];
  807. for (let i = stack.length - 1; i >= 0; i--)
  808. processedStack.push(`
  809. at ${wrapCallSite(stack[i], state)}`), state.nextPosition = state.curPosition;
  810. return state.curPosition = state.nextPosition = null, errorString + processedStack.reverse().join("");
  811. }
  812. function enableSourceMapSupport(runtime) {
  813. if (runtime.options.sourcemapInterceptor === "node") {
  814. if (typeof process > "u")
  815. throw new TypeError(
  816. `Cannot use "sourcemapInterceptor: 'node'" because global "process" variable is not available.`
  817. );
  818. if (typeof process.setSourceMapsEnabled != "function")
  819. throw new TypeError(
  820. `Cannot use "sourcemapInterceptor: 'node'" because "process.setSourceMapsEnabled" function is not available. Please use Node >= 16.6.0.`
  821. );
  822. const isEnabledAlready = process.sourceMapsEnabled ?? !1;
  823. return process.setSourceMapsEnabled(!0), () => !isEnabledAlready && process.setSourceMapsEnabled(!1);
  824. }
  825. return interceptStackTrace(
  826. runtime,
  827. typeof runtime.options.sourcemapInterceptor == "object" ? runtime.options.sourcemapInterceptor : void 0
  828. );
  829. }
  830. class ViteRuntime {
  831. constructor(options, runner, debug) {
  832. this.options = options, this.runner = runner, this.debug = debug, this.moduleCache = options.moduleCache ?? new ModuleCacheMap(options.root), typeof options.hmr == "object" && (this.hmrClient = new HMRClient(
  833. options.hmr.logger === !1 ? silentConsole : options.hmr.logger || console,
  834. options.hmr.connection,
  835. ({ acceptedPath, ssrInvalidates }) => (this.moduleCache.invalidate(acceptedPath), ssrInvalidates && this.invalidateFiles(ssrInvalidates), this.executeUrl(acceptedPath))
  836. ), options.hmr.connection.onUpdate(createHMRHandler(this))), options.sourcemapInterceptor !== !1 && (this._resetSourceMapSupport = enableSourceMapSupport(this));
  837. }
  838. /**
  839. * Holds the cache of modules
  840. * Keys of the map are ids
  841. */
  842. moduleCache;
  843. hmrClient;
  844. entrypoints = /* @__PURE__ */ new Set();
  845. idToUrlMap = /* @__PURE__ */ new Map();
  846. fileToIdMap = /* @__PURE__ */ new Map();
  847. envProxy = new Proxy({}, {
  848. get(_, p) {
  849. throw new Error(
  850. `[vite-runtime] Dynamic access of "import.meta.env" is not supported. Please, use "import.meta.env.${String(p)}" instead.`
  851. );
  852. }
  853. });
  854. _destroyed = !1;
  855. _resetSourceMapSupport;
  856. /**
  857. * URL to execute. Accepts file path, server path or id relative to the root.
  858. */
  859. async executeUrl(url) {
  860. url = this.normalizeEntryUrl(url);
  861. const fetchedModule = await this.cachedModule(url);
  862. return await this.cachedRequest(url, fetchedModule);
  863. }
  864. /**
  865. * Entrypoint URL to execute. Accepts file path, server path or id relative to the root.
  866. * In the case of a full reload triggered by HMR, this is the module that will be reloaded.
  867. * If this method is called multiple times, all entrypoints will be reloaded one at a time.
  868. */
  869. async executeEntrypoint(url) {
  870. url = this.normalizeEntryUrl(url);
  871. const fetchedModule = await this.cachedModule(url);
  872. return await this.cachedRequest(url, fetchedModule, [], {
  873. entrypoint: !0
  874. });
  875. }
  876. /**
  877. * Clear all caches including HMR listeners.
  878. */
  879. clearCache() {
  880. this.moduleCache.clear(), this.idToUrlMap.clear(), this.entrypoints.clear(), this.hmrClient?.clear();
  881. }
  882. /**
  883. * Clears all caches, removes all HMR listeners, and resets source map support.
  884. * This method doesn't stop the HMR connection.
  885. */
  886. async destroy() {
  887. this._resetSourceMapSupport?.(), this.clearCache(), this.hmrClient = void 0, this._destroyed = !0;
  888. }
  889. /**
  890. * Returns `true` if the runtime has been destroyed by calling `destroy()` method.
  891. */
  892. isDestroyed() {
  893. return this._destroyed;
  894. }
  895. invalidateFiles(files) {
  896. files.forEach((file) => {
  897. const ids = this.fileToIdMap.get(file);
  898. ids && ids.forEach((id) => this.moduleCache.invalidate(id));
  899. });
  900. }
  901. // we don't use moduleCache.normalize because this URL doesn't have to follow the same rules
  902. // this URL is something that user passes down manually, and is later resolved by fetchModule
  903. // moduleCache.normalize is used on resolved "file" property
  904. normalizeEntryUrl(url) {
  905. if (url[0] === ".")
  906. return url;
  907. url.startsWith("file://") && (url = url.slice(isWindows ? 8 : 7)), url = slash(url);
  908. const _root = this.options.root, root = _root[_root.length - 1] === "/" ? _root : `${_root}/`;
  909. return url.startsWith(root) ? url.slice(root.length - 1) : url[0] === "/" ? url : wrapId(url);
  910. }
  911. processImport(exports, fetchResult, metadata) {
  912. if (!("externalize" in fetchResult))
  913. return exports;
  914. const { id, type } = fetchResult;
  915. return type !== "module" && type !== "commonjs" || analyzeImportedModDifference(exports, id, type, metadata), exports;
  916. }
  917. async cachedRequest(id, fetchedModule, callstack = [], metadata) {
  918. const moduleId = fetchedModule.id;
  919. metadata?.entrypoint && this.entrypoints.add(moduleId);
  920. const mod = this.moduleCache.getByModuleId(moduleId), { imports, importers } = mod, importee = callstack[callstack.length - 1];
  921. if (importee && importers.add(importee), (callstack.includes(moduleId) || Array.from(imports.values()).some((i) => importers.has(i))) && mod.exports)
  922. return this.processImport(mod.exports, fetchedModule, metadata);
  923. let debugTimer;
  924. this.debug && (debugTimer = setTimeout(() => {
  925. const getStack = () => `stack:
  926. ${[...callstack, moduleId].reverse().map((p) => ` - ${p}`).join(`
  927. `)}`;
  928. this.debug(
  929. `[vite-runtime] module ${moduleId} takes over 2s to load.
  930. ${getStack()}`
  931. );
  932. }, 2e3));
  933. try {
  934. if (mod.promise)
  935. return this.processImport(await mod.promise, fetchedModule, metadata);
  936. const promise = this.directRequest(id, fetchedModule, callstack);
  937. return mod.promise = promise, mod.evaluated = !1, this.processImport(await promise, fetchedModule, metadata);
  938. } finally {
  939. mod.evaluated = !0, debugTimer && clearTimeout(debugTimer);
  940. }
  941. }
  942. async cachedModule(id, importer) {
  943. if (this._destroyed)
  944. throw new Error("[vite] Vite runtime has been destroyed.");
  945. const normalized = this.idToUrlMap.get(id);
  946. if (normalized) {
  947. const mod2 = this.moduleCache.getByModuleId(normalized);
  948. if (mod2.meta)
  949. return mod2.meta;
  950. }
  951. this.debug?.("[vite-runtime] fetching", id);
  952. const fetchedModule = id.startsWith("data:") ? { externalize: id, type: "builtin" } : await this.options.fetchModule(id, importer), idQuery = id.split("?")[1], query = idQuery ? `?${idQuery}` : "", file = "file" in fetchedModule ? fetchedModule.file : void 0, fullFile = file ? `${file}${query}` : id, moduleId = this.moduleCache.normalize(fullFile), mod = this.moduleCache.getByModuleId(moduleId);
  953. if (fetchedModule.id = moduleId, mod.meta = fetchedModule, file) {
  954. const fileModules = this.fileToIdMap.get(file) || [];
  955. fileModules.push(moduleId), this.fileToIdMap.set(file, fileModules);
  956. }
  957. return this.idToUrlMap.set(id, moduleId), this.idToUrlMap.set(unwrapId(id), moduleId), fetchedModule;
  958. }
  959. // override is allowed, consider this a public API
  960. async directRequest(id, fetchResult, _callstack) {
  961. const moduleId = fetchResult.id, callstack = [..._callstack, moduleId], mod = this.moduleCache.getByModuleId(moduleId), request = async (dep, metadata) => {
  962. const fetchedModule = await this.cachedModule(dep, moduleId);
  963. return this.moduleCache.getByModuleId(fetchedModule.id).importers.add(moduleId), mod.imports.add(fetchedModule.id), this.cachedRequest(dep, fetchedModule, callstack, metadata);
  964. }, dynamicRequest = async (dep) => (dep = String(dep), dep[0] === "." && (dep = posixResolve(posixDirname(id), dep)), request(dep, { isDynamicImport: !0 }));
  965. if ("externalize" in fetchResult) {
  966. const { externalize } = fetchResult;
  967. this.debug?.("[vite-runtime] externalizing", externalize);
  968. const exports2 = await this.runner.runExternalModule(externalize);
  969. return mod.exports = exports2, exports2;
  970. }
  971. const { code, file } = fetchResult;
  972. if (code == null) {
  973. const importer = callstack[callstack.length - 2];
  974. throw new Error(
  975. `[vite-runtime] Failed to load "${id}"${importer ? ` imported from ${importer}` : ""}`
  976. );
  977. }
  978. const modulePath = cleanUrl(file || moduleId), href = posixPathToFileHref(modulePath), filename = modulePath, dirname2 = posixDirname(modulePath), meta = {
  979. filename: isWindows ? toWindowsPath(filename) : filename,
  980. dirname: isWindows ? toWindowsPath(dirname2) : dirname2,
  981. url: href,
  982. env: this.envProxy,
  983. resolve(id2, parent) {
  984. throw new Error(
  985. '[vite-runtime] "import.meta.resolve" is not supported.'
  986. );
  987. },
  988. // should be replaced during transformation
  989. glob() {
  990. throw new Error('[vite-runtime] "import.meta.glob" is not supported.');
  991. }
  992. }, exports = /* @__PURE__ */ Object.create(null);
  993. Object.defineProperty(exports, Symbol.toStringTag, {
  994. value: "Module",
  995. enumerable: !1,
  996. configurable: !1
  997. }), mod.exports = exports;
  998. let hotContext;
  999. this.hmrClient && Object.defineProperty(meta, "hot", {
  1000. enumerable: !0,
  1001. get: () => {
  1002. if (!this.hmrClient)
  1003. throw new Error("[vite-runtime] HMR client was destroyed.");
  1004. return this.debug?.("[vite-runtime] creating hmr context for", moduleId), hotContext ||= new HMRContext(this.hmrClient, moduleId), hotContext;
  1005. },
  1006. set: (value) => {
  1007. hotContext = value;
  1008. }
  1009. });
  1010. const context = {
  1011. [ssrImportKey]: request,
  1012. [ssrDynamicImportKey]: dynamicRequest,
  1013. [ssrModuleExportsKey]: exports,
  1014. [ssrExportAllKey]: (obj) => exportAll(exports, obj),
  1015. [ssrImportMetaKey]: meta
  1016. };
  1017. return this.debug?.("[vite-runtime] executing", href), await this.runner.runViteModule(context, code, id), exports;
  1018. }
  1019. }
  1020. function exportAll(exports, sourceModule) {
  1021. if (exports !== sourceModule && !(isPrimitive(sourceModule) || Array.isArray(sourceModule) || sourceModule instanceof Promise)) {
  1022. for (const key in sourceModule)
  1023. if (key !== "default" && key !== "__esModule")
  1024. try {
  1025. Object.defineProperty(exports, key, {
  1026. enumerable: !0,
  1027. configurable: !0,
  1028. get: () => sourceModule[key]
  1029. });
  1030. } catch {
  1031. }
  1032. }
  1033. }
  1034. class ESModulesRunner {
  1035. async runViteModule(context, code) {
  1036. await new AsyncFunction(
  1037. ssrModuleExportsKey,
  1038. ssrImportMetaKey,
  1039. ssrImportKey,
  1040. ssrDynamicImportKey,
  1041. ssrExportAllKey,
  1042. // source map should already be inlined by Vite
  1043. '"use strict";' + code
  1044. )(
  1045. context[ssrModuleExportsKey],
  1046. context[ssrImportMetaKey],
  1047. context[ssrImportKey],
  1048. context[ssrDynamicImportKey],
  1049. context[ssrExportAllKey]
  1050. ), Object.seal(context[ssrModuleExportsKey]);
  1051. }
  1052. runExternalModule(filepath) {
  1053. return import(filepath);
  1054. }
  1055. }
  1056. export {
  1057. ESModulesRunner,
  1058. ModuleCacheMap,
  1059. ViteRuntime,
  1060. ssrDynamicImportKey,
  1061. ssrExportAllKey,
  1062. ssrImportKey,
  1063. ssrImportMetaKey,
  1064. ssrModuleExportsKey
  1065. };