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