module-runner.js 53 KB

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