module-runner.js 52 KB

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