runtime.js 44 KB

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