module-runner.js 49 KB

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