import { __commonJS, __require, __toDynamicImportESM, __toESM } from "./chunk.js"; import { CLIENT_DIR, CLIENT_ENTRY, CLIENT_PUBLIC_PATH, CSS_LANGS_RE, DEFAULT_ASSETS_INLINE_LIMIT, DEFAULT_ASSETS_RE, DEFAULT_CLIENT_CONDITIONS, DEFAULT_CLIENT_MAIN_FIELDS, DEFAULT_CONFIG_FILES, DEFAULT_DEV_PORT, DEFAULT_EXTERNAL_CONDITIONS, DEFAULT_PREVIEW_PORT, DEFAULT_SERVER_CONDITIONS, DEFAULT_SERVER_MAIN_FIELDS, DEP_VERSION_RE, DEV_PROD_CONDITION, ENV_ENTRY, ENV_PUBLIC_PATH, ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR, ERR_OPTIMIZE_DEPS_PROCESSING_ERROR, ESBUILD_BASELINE_WIDELY_AVAILABLE_TARGET, FS_PREFIX, JS_TYPES_RE, KNOWN_ASSET_TYPES, LogLevels, METADATA_FILENAME, OPTIMIZABLE_ENTRY_RE, ROLLUP_HOOKS, SPECIAL_QUERY_RE, VERSION, VITE_PACKAGE_DIR, createLogger, defaultAllowedOrigins, loopbackHosts, printServerUrls, require_picocolors, wildcardHosts } from "./logger.js"; import { builtinModules, createRequire } from "node:module"; import { parseAst, parseAstAsync } from "rollup/parseAst"; import * as fs$1 from "node:fs"; import fs, { existsSync, promises, readFileSync } from "node:fs"; import path, { basename, dirname, extname, isAbsolute, join, normalize, posix, relative, resolve, sep } from "node:path"; import fsp, { constants } from "node:fs/promises"; import { URL as URL$1, fileURLToPath, pathToFileURL } from "node:url"; import { format, inspect, promisify, stripVTControlCharacters } from "node:util"; import { performance as performance$1 } from "node:perf_hooks"; import crypto from "node:crypto"; import picomatch from "picomatch"; import esbuild, { build, formatMessages, transform } from "esbuild"; import os from "node:os"; import net from "node:net"; import childProcess, { exec, execFile, execSync } from "node:child_process"; import { promises as promises$1 } from "node:dns"; import path$1, { basename as basename$1, dirname as dirname$1, extname as extname$1, isAbsolute as isAbsolute$1, join as join$1, posix as posix$1, relative as relative$1, resolve as resolve$1, sep as sep$1, win32 } from "path"; import { existsSync as existsSync$1, readFileSync as readFileSync$1, readdirSync, statSync } from "fs"; import { fdir } from "fdir"; import { gzip } from "node:zlib"; import readline from "node:readline"; import { createRequire as createRequire$1 } from "module"; import { MessageChannel, Worker } from "node:worker_threads"; import { Buffer as Buffer$1 } from "node:buffer"; import { escapePath, glob, globSync, isDynamicPattern } from "tinyglobby"; import assert from "node:assert"; import process$1 from "node:process"; import v8 from "node:v8"; import { EventEmitter } from "node:events"; import { STATUS_CODES, createServer, get } from "node:http"; import { createServer as createServer$1, get as get$1 } from "node:https"; import { ESModulesEvaluator, ModuleRunner, createNodeImportMeta } from "vite/module-runner"; import zlib from "zlib"; import * as qs from "node:querystring"; //#region src/shared/constants.ts /** * Prefix for resolved Ids that are not valid browser import specifiers */ const VALID_ID_PREFIX = `/@id/`; /** * Plugins that use 'virtual modules' (e.g. for helper functions), prefix the * module ID with `\0`, a convention from the rollup ecosystem. * This prevents other plugins from trying to process the id (like node resolution), * and core features like sourcemaps can use this info to differentiate between * virtual modules and regular files. * `\0` is not a permitted char in import URLs so we have to replace them during * import analysis. The id will be decoded back before entering the plugins pipeline. * These encoded virtual ids are also prefixed by the VALID_ID_PREFIX, so virtual * modules in the browser end up encoded as `/@id/__x00__{id}` */ const NULL_BYTE_PLACEHOLDER = `__x00__`; let SOURCEMAPPING_URL = "sourceMa"; SOURCEMAPPING_URL += "ppingURL"; const MODULE_RUNNER_SOURCEMAPPING_SOURCE = "//# sourceMappingSource=vite-generated"; const ERR_OUTDATED_OPTIMIZED_DEP = "ERR_OUTDATED_OPTIMIZED_DEP"; //#endregion //#region src/shared/utils.ts const isWindows = typeof process !== "undefined" && process.platform === "win32"; /** * Prepend `/@id/` and replace null byte so the id is URL-safe. * This is prepended to resolved ids that are not valid browser * import specifiers by the importAnalysis plugin. */ function wrapId(id) { return id.startsWith(VALID_ID_PREFIX) ? id : VALID_ID_PREFIX + id.replace("\0", NULL_BYTE_PLACEHOLDER); } /** * Undo {@link wrapId}'s `/@id/` and null byte replacements. */ function unwrapId(id) { return id.startsWith(VALID_ID_PREFIX) ? id.slice(VALID_ID_PREFIX.length).replace(NULL_BYTE_PLACEHOLDER, "\0") : id; } const windowsSlashRE = /\\/g; function slash(p) { return p.replace(windowsSlashRE, "/"); } const postfixRE = /[?#].*$/; function cleanUrl(url$3) { return url$3.replace(postfixRE, ""); } function splitFileAndPostfix(path$13) { const file = cleanUrl(path$13); return { file, postfix: path$13.slice(file.length) }; } function withTrailingSlash(path$13) { if (path$13[path$13.length - 1] !== "/") return `${path$13}/`; return path$13; } function promiseWithResolvers() { let resolve$4; let reject; return { promise: new Promise((_resolve, _reject) => { resolve$4 = _resolve; reject = _reject; }), resolve: resolve$4, reject }; } //#endregion //#region ../../node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs var comma = ",".charCodeAt(0); var semicolon = ";".charCodeAt(0); var chars$1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; var intToChar = new Uint8Array(64); var charToInt = new Uint8Array(128); for (let i$1 = 0; i$1 < chars$1.length; i$1++) { const c = chars$1.charCodeAt(i$1); intToChar[i$1] = c; charToInt[c] = i$1; } function decodeInteger(reader, relative$3) { let value$1 = 0; let shift = 0; let integer = 0; do { integer = charToInt[reader.next()]; value$1 |= (integer & 31) << shift; shift += 5; } while (integer & 32); const shouldNegate = value$1 & 1; value$1 >>>= 1; if (shouldNegate) value$1 = -2147483648 | -value$1; return relative$3 + value$1; } function encodeInteger(builder, num, relative$3) { let delta = num - relative$3; delta = delta < 0 ? -delta << 1 | 1 : delta << 1; do { let clamped = delta & 31; delta >>>= 5; if (delta > 0) clamped |= 32; builder.write(intToChar[clamped]); } while (delta > 0); return num; } function hasMoreVlq(reader, max) { if (reader.pos >= max) return false; return reader.peek() !== comma; } var bufLength = 1024 * 16; var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? { decode(buf) { return Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength).toString(); } } : { decode(buf) { let out = ""; for (let i$1 = 0; i$1 < buf.length; i$1++) out += String.fromCharCode(buf[i$1]); return out; } }; var StringWriter = class { constructor() { this.pos = 0; this.out = ""; this.buffer = new Uint8Array(bufLength); } write(v) { const { buffer } = this; buffer[this.pos++] = v; if (this.pos === bufLength) { this.out += td.decode(buffer); this.pos = 0; } } flush() { const { buffer, out, pos } = this; return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out; } }; var StringReader = class { constructor(buffer) { this.pos = 0; this.buffer = buffer; } next() { return this.buffer.charCodeAt(this.pos++); } peek() { return this.buffer.charCodeAt(this.pos); } indexOf(char) { const { buffer, pos } = this; const idx = buffer.indexOf(char, pos); return idx === -1 ? buffer.length : idx; } }; function decode(mappings) { const { length } = mappings; const reader = new StringReader(mappings); const decoded = []; let genColumn = 0; let sourcesIndex = 0; let sourceLine = 0; let sourceColumn = 0; let namesIndex = 0; do { const semi = reader.indexOf(";"); const line = []; let sorted = true; let lastCol = 0; genColumn = 0; while (reader.pos < semi) { let seg; genColumn = decodeInteger(reader, genColumn); if (genColumn < lastCol) sorted = false; lastCol = genColumn; if (hasMoreVlq(reader, semi)) { sourcesIndex = decodeInteger(reader, sourcesIndex); sourceLine = decodeInteger(reader, sourceLine); sourceColumn = decodeInteger(reader, sourceColumn); if (hasMoreVlq(reader, semi)) { namesIndex = decodeInteger(reader, namesIndex); seg = [ genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex ]; } else seg = [ genColumn, sourcesIndex, sourceLine, sourceColumn ]; } else seg = [genColumn]; line.push(seg); reader.pos++; } if (!sorted) sort(line); decoded.push(line); reader.pos = semi + 1; } while (reader.pos <= length); return decoded; } function sort(line) { line.sort(sortComparator$1); } function sortComparator$1(a, b) { return a[0] - b[0]; } function encode$1(decoded) { const writer = new StringWriter(); let sourcesIndex = 0; let sourceLine = 0; let sourceColumn = 0; let namesIndex = 0; for (let i$1 = 0; i$1 < decoded.length; i$1++) { const line = decoded[i$1]; if (i$1 > 0) writer.write(semicolon); if (line.length === 0) continue; let genColumn = 0; for (let j = 0; j < line.length; j++) { const segment = line[j]; if (j > 0) writer.write(comma); genColumn = encodeInteger(writer, segment[0], genColumn); if (segment.length === 1) continue; sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex); sourceLine = encodeInteger(writer, segment[2], sourceLine); sourceColumn = encodeInteger(writer, segment[3], sourceColumn); if (segment.length === 4) continue; namesIndex = encodeInteger(writer, segment[4], namesIndex); } } return writer.flush(); } //#endregion //#region ../../node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs const schemeRegex = /^[\w+.-]+:\/\//; /** * Matches the parts of a URL: * 1. Scheme, including ":", guaranteed. * 2. User/password, including "@", optional. * 3. Host, guaranteed. * 4. Port, including ":", optional. * 5. Path, including "/", optional. * 6. Query, including "?", optional. * 7. Hash, including "#", optional. */ const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/; /** * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive). * * 1. Host, optional. * 2. Path, which may include "/", guaranteed. * 3. Query, including "?", optional. * 4. Hash, including "#", optional. */ const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i; function isAbsoluteUrl(input) { return schemeRegex.test(input); } function isSchemeRelativeUrl(input) { return input.startsWith("//"); } function isAbsolutePath(input) { return input.startsWith("/"); } function isFileUrl(input) { return input.startsWith("file:"); } function isRelative(input) { return /^[.?#]/.test(input); } function parseAbsoluteUrl(input) { const match = urlRegex.exec(input); return makeUrl(match[1], match[2] || "", match[3], match[4] || "", match[5] || "/", match[6] || "", match[7] || ""); } function parseFileUrl(input) { const match = fileRegex.exec(input); const path$13 = match[2]; return makeUrl("file:", "", match[1] || "", "", isAbsolutePath(path$13) ? path$13 : "/" + path$13, match[3] || "", match[4] || ""); } function makeUrl(scheme, user, host, port, path$13, query, hash$1) { return { scheme, user, host, port, path: path$13, query, hash: hash$1, type: 7 }; } function parseUrl$3(input) { if (isSchemeRelativeUrl(input)) { const url$4 = parseAbsoluteUrl("http:" + input); url$4.scheme = ""; url$4.type = 6; return url$4; } if (isAbsolutePath(input)) { const url$4 = parseAbsoluteUrl("http://foo.com" + input); url$4.scheme = ""; url$4.host = ""; url$4.type = 5; return url$4; } if (isFileUrl(input)) return parseFileUrl(input); if (isAbsoluteUrl(input)) return parseAbsoluteUrl(input); const url$3 = parseAbsoluteUrl("http://foo.com/" + input); url$3.scheme = ""; url$3.host = ""; url$3.type = input ? input.startsWith("?") ? 3 : input.startsWith("#") ? 2 : 4 : 1; return url$3; } function stripPathFilename(path$13) { if (path$13.endsWith("/..")) return path$13; const index = path$13.lastIndexOf("/"); return path$13.slice(0, index + 1); } function mergePaths(url$3, base) { normalizePath$4(base, base.type); if (url$3.path === "/") url$3.path = base.path; else url$3.path = stripPathFilename(base.path) + url$3.path; } /** * The path can have empty directories "//", unneeded parents "foo/..", or current directory * "foo/.". We need to normalize to a standard representation. */ function normalizePath$4(url$3, type) { const rel = type <= 4; const pieces = url$3.path.split("/"); let pointer = 1; let positive = 0; let addTrailingSlash = false; for (let i$1 = 1; i$1 < pieces.length; i$1++) { const piece = pieces[i$1]; if (!piece) { addTrailingSlash = true; continue; } addTrailingSlash = false; if (piece === ".") continue; if (piece === "..") { if (positive) { addTrailingSlash = true; positive--; pointer--; } else if (rel) pieces[pointer++] = piece; continue; } pieces[pointer++] = piece; positive++; } let path$13 = ""; for (let i$1 = 1; i$1 < pointer; i$1++) path$13 += "/" + pieces[i$1]; if (!path$13 || addTrailingSlash && !path$13.endsWith("/..")) path$13 += "/"; url$3.path = path$13; } /** * Attempts to resolve `input` URL/path relative to `base`. */ function resolve$3(input, base) { if (!input && !base) return ""; const url$3 = parseUrl$3(input); let inputType = url$3.type; if (base && inputType !== 7) { const baseUrl = parseUrl$3(base); const baseType = baseUrl.type; switch (inputType) { case 1: url$3.hash = baseUrl.hash; case 2: url$3.query = baseUrl.query; case 3: case 4: mergePaths(url$3, baseUrl); case 5: url$3.user = baseUrl.user; url$3.host = baseUrl.host; url$3.port = baseUrl.port; case 6: url$3.scheme = baseUrl.scheme; } if (baseType > inputType) inputType = baseType; } normalizePath$4(url$3, inputType); const queryHash = url$3.query + url$3.hash; switch (inputType) { case 2: case 3: return queryHash; case 4: { const path$13 = url$3.path.slice(1); if (!path$13) return queryHash || "."; if (isRelative(base || input) && !isRelative(path$13)) return "./" + path$13 + queryHash; return path$13 + queryHash; } case 5: return url$3.path + queryHash; default: return url$3.scheme + "//" + url$3.user + url$3.host + url$3.port + url$3.path + queryHash; } } //#endregion //#region ../../node_modules/.pnpm/@jridgewell+trace-mapping@0.3.31/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs function stripFilename(path$13) { if (!path$13) return ""; const index = path$13.lastIndexOf("/"); return path$13.slice(0, index + 1); } function resolver(mapUrl, sourceRoot) { const from = stripFilename(mapUrl); const prefix = sourceRoot ? sourceRoot + "/" : ""; return (source) => resolve$3(prefix + (source || ""), from); } var COLUMN$1 = 0; var SOURCES_INDEX$1 = 1; var SOURCE_LINE$1 = 2; var SOURCE_COLUMN$1 = 3; var NAMES_INDEX$1 = 4; function maybeSort(mappings, owned) { const unsortedIndex = nextUnsortedSegmentLine(mappings, 0); if (unsortedIndex === mappings.length) return mappings; if (!owned) mappings = mappings.slice(); for (let i$1 = unsortedIndex; i$1 < mappings.length; i$1 = nextUnsortedSegmentLine(mappings, i$1 + 1)) mappings[i$1] = sortSegments(mappings[i$1], owned); return mappings; } function nextUnsortedSegmentLine(mappings, start) { for (let i$1 = start; i$1 < mappings.length; i$1++) if (!isSorted(mappings[i$1])) return i$1; return mappings.length; } function isSorted(line) { for (let j = 1; j < line.length; j++) if (line[j][COLUMN$1] < line[j - 1][COLUMN$1]) return false; return true; } function sortSegments(line, owned) { if (!owned) line = line.slice(); return line.sort(sortComparator); } function sortComparator(a, b) { return a[COLUMN$1] - b[COLUMN$1]; } var found = false; function binarySearch(haystack, needle, low, high) { while (low <= high) { const mid = low + (high - low >> 1); const cmp = haystack[mid][COLUMN$1] - needle; if (cmp === 0) { found = true; return mid; } if (cmp < 0) low = mid + 1; else high = mid - 1; } found = false; return low - 1; } function upperBound(haystack, needle, index) { for (let i$1 = index + 1; i$1 < haystack.length; index = i$1++) if (haystack[i$1][COLUMN$1] !== needle) break; return index; } function lowerBound(haystack, needle, index) { for (let i$1 = index - 1; i$1 >= 0; index = i$1--) if (haystack[i$1][COLUMN$1] !== needle) break; return index; } function memoizedState() { return { lastKey: -1, lastNeedle: -1, lastIndex: -1 }; } function memoizedBinarySearch(haystack, needle, state, key) { const { lastKey, lastNeedle, lastIndex } = state; let low = 0; let high = haystack.length - 1; if (key === lastKey) { if (needle === lastNeedle) { found = lastIndex !== -1 && haystack[lastIndex][COLUMN$1] === needle; return lastIndex; } if (needle >= lastNeedle) low = lastIndex === -1 ? 0 : lastIndex; else high = lastIndex; } state.lastKey = key; state.lastNeedle = needle; return state.lastIndex = binarySearch(haystack, needle, low, high); } function parse$16(map$1) { return typeof map$1 === "string" ? JSON.parse(map$1) : map$1; } var LINE_GTR_ZERO = "`line` must be greater than 0 (lines start at line 1)"; var COL_GTR_EQ_ZERO = "`column` must be greater than or equal to 0 (columns start at column 0)"; var LEAST_UPPER_BOUND = -1; var GREATEST_LOWER_BOUND = 1; var TraceMap = class { constructor(map$1, mapUrl) { const isString$1 = typeof map$1 === "string"; if (!isString$1 && map$1._decodedMemo) return map$1; const parsed = parse$16(map$1); const { version: version$2, file, names, sourceRoot, sources, sourcesContent } = parsed; this.version = version$2; this.file = file; this.names = names || []; this.sourceRoot = sourceRoot; this.sources = sources; this.sourcesContent = sourcesContent; this.ignoreList = parsed.ignoreList || parsed.x_google_ignoreList || void 0; const resolve$4 = resolver(mapUrl, sourceRoot); this.resolvedSources = sources.map(resolve$4); const { mappings } = parsed; if (typeof mappings === "string") { this._encoded = mappings; this._decoded = void 0; } else if (Array.isArray(mappings)) { this._encoded = void 0; this._decoded = maybeSort(mappings, isString$1); } else if (parsed.sections) throw new Error(`TraceMap passed sectioned source map, please use FlattenMap export instead`); else throw new Error(`invalid source map: ${JSON.stringify(parsed)}`); this._decodedMemo = memoizedState(); this._bySources = void 0; this._bySourceMemos = void 0; } }; function cast$1(map$1) { return map$1; } function encodedMappings(map$1) { var _a, _b; return (_b = (_a = cast$1(map$1))._encoded) != null ? _b : _a._encoded = encode$1(cast$1(map$1)._decoded); } function decodedMappings(map$1) { var _a; return (_a = cast$1(map$1))._decoded || (_a._decoded = decode(cast$1(map$1)._encoded)); } function traceSegment(map$1, line, column) { const decoded = decodedMappings(map$1); if (line >= decoded.length) return null; const segments = decoded[line]; const index = traceSegmentInternal(segments, cast$1(map$1)._decodedMemo, line, column, GREATEST_LOWER_BOUND); return index === -1 ? null : segments[index]; } function originalPositionFor(map$1, needle) { let { line, column, bias } = needle; line--; if (line < 0) throw new Error(LINE_GTR_ZERO); if (column < 0) throw new Error(COL_GTR_EQ_ZERO); const decoded = decodedMappings(map$1); if (line >= decoded.length) return OMapping(null, null, null, null); const segments = decoded[line]; const index = traceSegmentInternal(segments, cast$1(map$1)._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND); if (index === -1) return OMapping(null, null, null, null); const segment = segments[index]; if (segment.length === 1) return OMapping(null, null, null, null); const { names, resolvedSources } = map$1; return OMapping(resolvedSources[segment[SOURCES_INDEX$1]], segment[SOURCE_LINE$1] + 1, segment[SOURCE_COLUMN$1], segment.length === 5 ? names[segment[NAMES_INDEX$1]] : null); } function decodedMap(map$1) { return clone(map$1, decodedMappings(map$1)); } function encodedMap(map$1) { return clone(map$1, encodedMappings(map$1)); } function clone(map$1, mappings) { return { version: map$1.version, file: map$1.file, names: map$1.names, sourceRoot: map$1.sourceRoot, sources: map$1.sources, sourcesContent: map$1.sourcesContent, mappings, ignoreList: map$1.ignoreList || map$1.x_google_ignoreList }; } function OMapping(source, line, column, name) { return { source, line, column, name }; } function traceSegmentInternal(segments, memo, line, column, bias) { let index = memoizedBinarySearch(segments, column, memo, line); if (found) index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index); else if (bias === LEAST_UPPER_BOUND) index++; if (index === -1 || index === segments.length) return -1; return index; } //#endregion //#region ../../node_modules/.pnpm/@jridgewell+gen-mapping@0.3.12/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs var SetArray = class { constructor() { this._indexes = { __proto__: null }; this.array = []; } }; function cast(set) { return set; } function get$2(setarr, key) { return cast(setarr)._indexes[key]; } function put(setarr, key) { const index = get$2(setarr, key); if (index !== void 0) return index; const { array, _indexes: indexes } = cast(setarr); return indexes[key] = array.push(key) - 1; } function remove(setarr, key) { const index = get$2(setarr, key); if (index === void 0) return; const { array, _indexes: indexes } = cast(setarr); for (let i$1 = index + 1; i$1 < array.length; i$1++) { const k = array[i$1]; array[i$1 - 1] = k; indexes[k]--; } indexes[key] = void 0; array.pop(); } var COLUMN = 0; var SOURCES_INDEX = 1; var SOURCE_LINE = 2; var SOURCE_COLUMN = 3; var NAMES_INDEX = 4; var NO_NAME = -1; var GenMapping = class { constructor({ file, sourceRoot } = {}) { this._names = new SetArray(); this._sources = new SetArray(); this._sourcesContent = []; this._mappings = []; this.file = file; this.sourceRoot = sourceRoot; this._ignoreList = new SetArray(); } }; function cast2(map$1) { return map$1; } var maybeAddSegment = (map$1, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => { return addSegmentInternal(true, map$1, genLine, genColumn, source, sourceLine, sourceColumn, name, content); }; function setSourceContent(map$1, source, content) { const { _sources: sources, _sourcesContent: sourcesContent } = cast2(map$1); const index = put(sources, source); sourcesContent[index] = content; } function setIgnore(map$1, source, ignore = true) { const { _sources: sources, _sourcesContent: sourcesContent, _ignoreList: ignoreList } = cast2(map$1); const index = put(sources, source); if (index === sourcesContent.length) sourcesContent[index] = null; if (ignore) put(ignoreList, index); else remove(ignoreList, index); } function toDecodedMap(map$1) { const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, _ignoreList: ignoreList } = cast2(map$1); removeEmptyFinalLines(mappings); return { version: 3, file: map$1.file || void 0, names: names.array, sourceRoot: map$1.sourceRoot || void 0, sources: sources.array, sourcesContent, mappings, ignoreList: ignoreList.array }; } function toEncodedMap(map$1) { const decoded = toDecodedMap(map$1); return Object.assign({}, decoded, { mappings: encode$1(decoded.mappings) }); } function addSegmentInternal(skipable, map$1, genLine, genColumn, source, sourceLine, sourceColumn, name, content) { const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names } = cast2(map$1); const line = getIndex(mappings, genLine); const index = getColumnIndex(line, genColumn); if (!source) { if (skipable && skipSourceless(line, index)) return; return insert(line, index, [genColumn]); } assert$2(sourceLine); assert$2(sourceColumn); const sourcesIndex = put(sources, source); const namesIndex = name ? put(names, name) : NO_NAME; if (sourcesIndex === sourcesContent.length) sourcesContent[sourcesIndex] = content != null ? content : null; if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) return; return insert(line, index, name ? [ genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex ] : [ genColumn, sourcesIndex, sourceLine, sourceColumn ]); } function assert$2(_val) {} function getIndex(arr, index) { for (let i$1 = arr.length; i$1 <= index; i$1++) arr[i$1] = []; return arr[index]; } function getColumnIndex(line, genColumn) { let index = line.length; for (let i$1 = index - 1; i$1 >= 0; index = i$1--) if (genColumn >= line[i$1][COLUMN]) break; return index; } function insert(array, index, value$1) { for (let i$1 = array.length; i$1 > index; i$1--) array[i$1] = array[i$1 - 1]; array[index] = value$1; } function removeEmptyFinalLines(mappings) { const { length } = mappings; let len = length; for (let i$1 = len - 1; i$1 >= 0; len = i$1, i$1--) if (mappings[i$1].length > 0) break; if (len < length) mappings.length = len; } function skipSourceless(line, index) { if (index === 0) return true; return line[index - 1].length === 1; } function skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) { if (index === 0) return false; const prev = line[index - 1]; if (prev.length === 1) return false; return sourcesIndex === prev[SOURCES_INDEX] && sourceLine === prev[SOURCE_LINE] && sourceColumn === prev[SOURCE_COLUMN] && namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME); } //#endregion //#region ../../node_modules/.pnpm/@jridgewell+remapping@2.3.5/node_modules/@jridgewell/remapping/dist/remapping.mjs var SOURCELESS_MAPPING = /* @__PURE__ */ SegmentObject("", -1, -1, "", null, false); var EMPTY_SOURCES = []; function SegmentObject(source, line, column, name, content, ignore) { return { source, line, column, name, content, ignore }; } function Source(map$1, sources, source, content, ignore) { return { map: map$1, sources, source, content, ignore }; } function MapSource(map$1, sources) { return Source(map$1, sources, "", null, false); } function OriginalSource(source, content, ignore) { return Source(null, EMPTY_SOURCES, source, content, ignore); } function traceMappings(tree) { const gen = new GenMapping({ file: tree.map.file }); const { sources: rootSources, map: map$1 } = tree; const rootNames = map$1.names; const rootMappings = decodedMappings(map$1); for (let i$1 = 0; i$1 < rootMappings.length; i$1++) { const segments = rootMappings[i$1]; for (let j = 0; j < segments.length; j++) { const segment = segments[j]; const genCol = segment[0]; let traced = SOURCELESS_MAPPING; if (segment.length !== 1) { const source2 = rootSources[segment[1]]; traced = originalPositionFor$1(source2, segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : ""); if (traced == null) continue; } const { column, line, name, content, source, ignore } = traced; maybeAddSegment(gen, i$1, genCol, source, line, column, name); if (source && content != null) setSourceContent(gen, source, content); if (ignore) setIgnore(gen, source, true); } } return gen; } function originalPositionFor$1(source, line, column, name) { if (!source.map) return SegmentObject(source.source, line, column, name, source.content, source.ignore); const segment = traceSegment(source.map, line, column); if (segment == null) return null; if (segment.length === 1) return SOURCELESS_MAPPING; return originalPositionFor$1(source.sources[segment[1]], segment[2], segment[3], segment.length === 5 ? source.map.names[segment[4]] : name); } function asArray(value$1) { if (Array.isArray(value$1)) return value$1; return [value$1]; } function buildSourceMapTree(input, loader$1) { const maps = asArray(input).map((m$2) => new TraceMap(m$2, "")); const map$1 = maps.pop(); for (let i$1 = 0; i$1 < maps.length; i$1++) if (maps[i$1].sources.length > 1) throw new Error(`Transformation map ${i$1} must have exactly one source file. Did you specify these with the most recent transformation maps first?`); let tree = build$2(map$1, loader$1, "", 0); for (let i$1 = maps.length - 1; i$1 >= 0; i$1--) tree = MapSource(maps[i$1], [tree]); return tree; } function build$2(map$1, loader$1, importer, importerDepth) { const { resolvedSources, sourcesContent, ignoreList } = map$1; const depth = importerDepth + 1; return MapSource(map$1, resolvedSources.map((sourceFile, i$1) => { const ctx = { importer, depth, source: sourceFile || "", content: void 0, ignore: void 0 }; const sourceMap = loader$1(ctx.source, ctx); const { source, content, ignore } = ctx; if (sourceMap) return build$2(new TraceMap(sourceMap, source), loader$1, source, depth); return OriginalSource(source, content !== void 0 ? content : sourcesContent ? sourcesContent[i$1] : null, ignore !== void 0 ? ignore : ignoreList ? ignoreList.includes(i$1) : false); })); } var SourceMap$1 = class { constructor(map$1, options$1) { const out = options$1.decodedMappings ? toDecodedMap(map$1) : toEncodedMap(map$1); this.version = out.version; this.file = out.file; this.mappings = out.mappings; this.names = out.names; this.ignoreList = out.ignoreList; this.sourceRoot = out.sourceRoot; this.sources = out.sources; if (!options$1.excludeContent) this.sourcesContent = out.sourcesContent; } toString() { return JSON.stringify(this); } }; function remapping(input, loader$1, options$1) { const opts = typeof options$1 === "object" ? options$1 : { excludeContent: !!options$1, decodedMappings: false }; return new SourceMap$1(traceMappings(buildSourceMapTree(input, loader$1)), opts); } //#endregion //#region ../../node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js var require_ms$1 = /* @__PURE__ */ __commonJS({ "../../node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js": ((exports, module) => { /** * Helpers. */ var s$1 = 1e3; var m$1 = s$1 * 60; var h$1 = m$1 * 60; var d$1 = h$1 * 24; var w = d$1 * 7; var y$1 = d$1 * 365.25; /** * Parse or format the given `val`. * * Options: * * - `long` verbose formatting [false] * * @param {String|Number} val * @param {Object} [options] * @throws {Error} throw an error if val is not a non-empty string or a number * @return {String|Number} * @api public */ module.exports = function(val, options$1) { options$1 = options$1 || {}; var type = typeof val; if (type === "string" && val.length > 0) return parse$15(val); else if (type === "number" && isFinite(val)) return options$1.long ? fmtLong$1(val) : fmtShort$1(val); throw new Error("val is not a non-empty string or a valid number. val=" + JSON.stringify(val)); }; /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse$15(str) { str = String(str); if (str.length > 100) return; var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str); if (!match) return; var n$2 = parseFloat(match[1]); switch ((match[2] || "ms").toLowerCase()) { case "years": case "year": case "yrs": case "yr": case "y": return n$2 * y$1; case "weeks": case "week": case "w": return n$2 * w; case "days": case "day": case "d": return n$2 * d$1; case "hours": case "hour": case "hrs": case "hr": case "h": return n$2 * h$1; case "minutes": case "minute": case "mins": case "min": case "m": return n$2 * m$1; case "seconds": case "second": case "secs": case "sec": case "s": return n$2 * s$1; case "milliseconds": case "millisecond": case "msecs": case "msec": case "ms": return n$2; default: return; } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtShort$1(ms) { var msAbs = Math.abs(ms); if (msAbs >= d$1) return Math.round(ms / d$1) + "d"; if (msAbs >= h$1) return Math.round(ms / h$1) + "h"; if (msAbs >= m$1) return Math.round(ms / m$1) + "m"; if (msAbs >= s$1) return Math.round(ms / s$1) + "s"; return ms + "ms"; } /** * Long format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtLong$1(ms) { var msAbs = Math.abs(ms); if (msAbs >= d$1) return plural$1(ms, msAbs, d$1, "day"); if (msAbs >= h$1) return plural$1(ms, msAbs, h$1, "hour"); if (msAbs >= m$1) return plural$1(ms, msAbs, m$1, "minute"); if (msAbs >= s$1) return plural$1(ms, msAbs, s$1, "second"); return ms + " ms"; } /** * Pluralization helper. */ function plural$1(ms, msAbs, n$2, name) { var isPlural = msAbs >= n$2 * 1.5; return Math.round(ms / n$2) + " " + name + (isPlural ? "s" : ""); } }) }); //#endregion //#region ../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/common.js var require_common$1 = /* @__PURE__ */ __commonJS({ "../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/common.js": ((exports, module) => { /** * This is the common logic for both the Node.js and web browser * implementations of `debug()`. */ function setup(env$1) { createDebug$1.debug = createDebug$1; createDebug$1.default = createDebug$1; createDebug$1.coerce = coerce$1; createDebug$1.disable = disable$1; createDebug$1.enable = enable$1; createDebug$1.enabled = enabled$1; createDebug$1.humanize = require_ms$1(); createDebug$1.destroy = destroy$1; Object.keys(env$1).forEach((key) => { createDebug$1[key] = env$1[key]; }); /** * The currently active debug mode names, and names to skip. */ createDebug$1.names = []; createDebug$1.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". */ createDebug$1.formatters = {}; /** * Selects a color for a debug namespace * @param {String} namespace The namespace string for the debug instance to be colored * @return {Number|String} An ANSI color code for the given namespace * @api private */ function selectColor$1(namespace) { let hash$1 = 0; for (let i$1 = 0; i$1 < namespace.length; i$1++) { hash$1 = (hash$1 << 5) - hash$1 + namespace.charCodeAt(i$1); hash$1 |= 0; } return createDebug$1.colors[Math.abs(hash$1) % createDebug$1.colors.length]; } createDebug$1.selectColor = selectColor$1; /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function createDebug$1(namespace) { let prevTime$1; let enableOverride = null; let namespacesCache; let enabledCache; function debug$19(...args) { if (!debug$19.enabled) return; const self$1 = debug$19; const curr = Number(/* @__PURE__ */ new Date()); self$1.diff = curr - (prevTime$1 || curr); self$1.prev = prevTime$1; self$1.curr = curr; prevTime$1 = curr; args[0] = createDebug$1.coerce(args[0]); if (typeof args[0] !== "string") args.unshift("%O"); let index = 0; args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format$3) => { if (match === "%%") return "%"; index++; const formatter = createDebug$1.formatters[format$3]; if (typeof formatter === "function") { const val = args[index]; match = formatter.call(self$1, val); args.splice(index, 1); index--; } return match; }); createDebug$1.formatArgs.call(self$1, args); (self$1.log || createDebug$1.log).apply(self$1, args); } debug$19.namespace = namespace; debug$19.useColors = createDebug$1.useColors(); debug$19.color = createDebug$1.selectColor(namespace); debug$19.extend = extend; debug$19.destroy = createDebug$1.destroy; Object.defineProperty(debug$19, "enabled", { enumerable: true, configurable: false, get: () => { if (enableOverride !== null) return enableOverride; if (namespacesCache !== createDebug$1.namespaces) { namespacesCache = createDebug$1.namespaces; enabledCache = createDebug$1.enabled(namespace); } return enabledCache; }, set: (v) => { enableOverride = v; } }); if (typeof createDebug$1.init === "function") createDebug$1.init(debug$19); return debug$19; } function extend(namespace, delimiter) { const newDebug = createDebug$1(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace); newDebug.log = this.log; return newDebug; } /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. * * @param {String} namespaces * @api public */ function enable$1(namespaces) { createDebug$1.save(namespaces); createDebug$1.namespaces = namespaces; createDebug$1.names = []; createDebug$1.skips = []; const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean); for (const ns of split) if (ns[0] === "-") createDebug$1.skips.push(ns.slice(1)); else createDebug$1.names.push(ns); } /** * Checks if the given string matches a namespace template, honoring * asterisks as wildcards. * * @param {String} search * @param {String} template * @return {Boolean} */ function matchesTemplate(search, template) { let searchIndex = 0; let templateIndex = 0; let starIndex = -1; let matchIndex = 0; while (searchIndex < search.length) if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) if (template[templateIndex] === "*") { starIndex = templateIndex; matchIndex = searchIndex; templateIndex++; } else { searchIndex++; templateIndex++; } else if (starIndex !== -1) { templateIndex = starIndex + 1; matchIndex++; searchIndex = matchIndex; } else return false; while (templateIndex < template.length && template[templateIndex] === "*") templateIndex++; return templateIndex === template.length; } /** * Disable debug output. * * @return {String} namespaces * @api public */ function disable$1() { const namespaces = [...createDebug$1.names, ...createDebug$1.skips.map((namespace) => "-" + namespace)].join(","); createDebug$1.enable(""); return namespaces; } /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ function enabled$1(name) { for (const skip of createDebug$1.skips) if (matchesTemplate(name, skip)) return false; for (const ns of createDebug$1.names) if (matchesTemplate(name, ns)) return true; return false; } /** * Coerce `val`. * * @param {Mixed} val * @return {Mixed} * @api private */ function coerce$1(val) { if (val instanceof Error) return val.stack || val.message; return val; } /** * XXX DO NOT USE. This is a temporary stub function. * XXX It WILL be removed in the next major release. */ function destroy$1() { console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); } createDebug$1.enable(createDebug$1.load()); return createDebug$1; } module.exports = setup; }) }); //#endregion //#region ../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/node.js var require_node$1 = /* @__PURE__ */ __commonJS({ "../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/node.js": ((exports, module) => { /** * Module dependencies. */ const tty$1 = __require("tty"); const util$2 = __require("util"); /** * This is the Node.js implementation of `debug()`. */ exports.init = init$2; exports.log = log$3; exports.formatArgs = formatArgs$1; exports.save = save$1; exports.load = load$2; exports.useColors = useColors$1; exports.destroy = util$2.deprecate(() => {}, "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); /** * Colors. */ exports.colors = [ 6, 2, 3, 4, 5, 1 ]; try { const supportsColor = __require("supports-color"); if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) exports.colors = [ 20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63, 68, 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128, 129, 134, 135, 148, 149, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 178, 179, 184, 185, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 214, 215, 220, 221 ]; } catch (error$1) {} /** * Build up the default `inspectOpts` object from the environment variables. * * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js */ exports.inspectOpts = Object.keys(process.env).filter((key) => { return /^debug_/i.test(key); }).reduce((obj, key) => { const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_, k) => { return k.toUpperCase(); }); let val = process.env[key]; if (/^(yes|on|true|enabled)$/i.test(val)) val = true; else if (/^(no|off|false|disabled)$/i.test(val)) val = false; else if (val === "null") val = null; else val = Number(val); obj[prop] = val; return obj; }, {}); /** * Is stdout a TTY? Colored output is enabled when `true`. */ function useColors$1() { return "colors" in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty$1.isatty(process.stderr.fd); } /** * Adds ANSI color escape codes if enabled. * * @api public */ function formatArgs$1(args) { const { namespace: name, useColors: useColors$2 } = this; if (useColors$2) { const c = this.color; const colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c); const prefix = ` ${colorCode};1m${name} \u001B[0m`; args[0] = prefix + args[0].split("\n").join("\n" + prefix); args.push(colorCode + "m+" + module.exports.humanize(this.diff) + "\x1B[0m"); } else args[0] = getDate() + name + " " + args[0]; } function getDate() { if (exports.inspectOpts.hideDate) return ""; return (/* @__PURE__ */ new Date()).toISOString() + " "; } /** * Invokes `util.formatWithOptions()` with the specified arguments and writes to stderr. */ function log$3(...args) { return process.stderr.write(util$2.formatWithOptions(exports.inspectOpts, ...args) + "\n"); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save$1(namespaces) { if (namespaces) process.env.DEBUG = namespaces; else delete process.env.DEBUG; } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load$2() { return process.env.DEBUG; } /** * Init logic for `debug` instances. * * Create a new `inspectOpts` object in case `useColors` is set * differently for a particular `debug` instance. */ function init$2(debug$19) { debug$19.inspectOpts = {}; const keys = Object.keys(exports.inspectOpts); for (let i$1 = 0; i$1 < keys.length; i$1++) debug$19.inspectOpts[keys[i$1]] = exports.inspectOpts[keys[i$1]]; } module.exports = require_common$1()(exports); const { formatters } = module.exports; /** * Map %o to `util.inspect()`, all on a single line. */ formatters.o = function(v) { this.inspectOpts.colors = this.useColors; return util$2.inspect(v, this.inspectOpts).split("\n").map((str) => str.trim()).join(" "); }; /** * Map %O to `util.inspect()`, allowing multiple lines if needed. */ formatters.O = function(v) { this.inspectOpts.colors = this.useColors; return util$2.inspect(v, this.inspectOpts); }; }) }); //#endregion //#region ../../node_modules/.pnpm/estree-walker@2.0.2/node_modules/estree-walker/dist/esm/estree-walker.js /** @typedef { import('estree').BaseNode} BaseNode */ /** @typedef {{ skip: () => void; remove: () => void; replace: (node: BaseNode) => void; }} WalkerContext */ var WalkerBase$1 = class { constructor() { /** @type {boolean} */ this.should_skip = false; /** @type {boolean} */ this.should_remove = false; /** @type {BaseNode | null} */ this.replacement = null; /** @type {WalkerContext} */ this.context = { skip: () => this.should_skip = true, remove: () => this.should_remove = true, replace: (node) => this.replacement = node }; } /** * * @param {any} parent * @param {string} prop * @param {number} index * @param {BaseNode} node */ replace(parent, prop, index, node) { if (parent) if (index !== null) parent[prop][index] = node; else parent[prop] = node; } /** * * @param {any} parent * @param {string} prop * @param {number} index */ remove(parent, prop, index) { if (parent) if (index !== null) parent[prop].splice(index, 1); else delete parent[prop]; } }; /** @typedef { import('estree').BaseNode} BaseNode */ /** @typedef { import('./walker.js').WalkerContext} WalkerContext */ /** @typedef {( * this: WalkerContext, * node: BaseNode, * parent: BaseNode, * key: string, * index: number * ) => void} SyncHandler */ var SyncWalker$1 = class extends WalkerBase$1 { /** * * @param {SyncHandler} enter * @param {SyncHandler} leave */ constructor(enter, leave) { super(); /** @type {SyncHandler} */ this.enter = enter; /** @type {SyncHandler} */ this.leave = leave; } /** * * @param {BaseNode} node * @param {BaseNode} parent * @param {string} [prop] * @param {number} [index] * @returns {BaseNode} */ visit(node, parent, prop, index) { if (node) { if (this.enter) { const _should_skip = this.should_skip; const _should_remove = this.should_remove; const _replacement = this.replacement; this.should_skip = false; this.should_remove = false; this.replacement = null; this.enter.call(this.context, node, parent, prop, index); if (this.replacement) { node = this.replacement; this.replace(parent, prop, index, node); } if (this.should_remove) this.remove(parent, prop, index); const skipped = this.should_skip; const removed = this.should_remove; this.should_skip = _should_skip; this.should_remove = _should_remove; this.replacement = _replacement; if (skipped) return node; if (removed) return null; } for (const key in node) { const value$1 = node[key]; if (typeof value$1 !== "object") continue; else if (Array.isArray(value$1)) { for (let i$1 = 0; i$1 < value$1.length; i$1 += 1) if (value$1[i$1] !== null && typeof value$1[i$1].type === "string") { if (!this.visit(value$1[i$1], node, key, i$1)) i$1--; } } else if (value$1 !== null && typeof value$1.type === "string") this.visit(value$1, node, key, null); } if (this.leave) { const _replacement = this.replacement; const _should_remove = this.should_remove; this.replacement = null; this.should_remove = false; this.leave.call(this.context, node, parent, prop, index); if (this.replacement) { node = this.replacement; this.replace(parent, prop, index, node); } if (this.should_remove) this.remove(parent, prop, index); const removed = this.should_remove; this.replacement = _replacement; this.should_remove = _should_remove; if (removed) return null; } } return node; } }; /** @typedef { import('estree').BaseNode} BaseNode */ /** @typedef { import('./sync.js').SyncHandler} SyncHandler */ /** @typedef { import('./async.js').AsyncHandler} AsyncHandler */ /** * * @param {BaseNode} ast * @param {{ * enter?: SyncHandler * leave?: SyncHandler * }} walker * @returns {BaseNode} */ function walk$2(ast, { enter, leave }) { return new SyncWalker$1(enter, leave).visit(ast, null); } //#endregion //#region ../../node_modules/.pnpm/@rollup+pluginutils@5.3.0_rollup@4.43.0/node_modules/@rollup/pluginutils/dist/es/index.js const extractors = { ArrayPattern(names, param) { for (const element of param.elements) if (element) extractors[element.type](names, element); }, AssignmentPattern(names, param) { extractors[param.left.type](names, param.left); }, Identifier(names, param) { names.push(param.name); }, MemberExpression() {}, ObjectPattern(names, param) { for (const prop of param.properties) if (prop.type === "RestElement") extractors.RestElement(names, prop); else extractors[prop.value.type](names, prop.value); }, RestElement(names, param) { extractors[param.argument.type](names, param.argument); } }; const extractAssignedNames = function extractAssignedNames$1(param) { const names = []; extractors[param.type](names, param); return names; }; const blockDeclarations = { const: true, let: true }; var Scope = class { constructor(options$1 = {}) { this.parent = options$1.parent; this.isBlockScope = !!options$1.block; this.declarations = Object.create(null); if (options$1.params) options$1.params.forEach((param) => { extractAssignedNames(param).forEach((name) => { this.declarations[name] = true; }); }); } addDeclaration(node, isBlockDeclaration, isVar) { if (!isBlockDeclaration && this.isBlockScope) this.parent.addDeclaration(node, isBlockDeclaration, isVar); else if (node.id) extractAssignedNames(node.id).forEach((name) => { this.declarations[name] = true; }); } contains(name) { return this.declarations[name] || (this.parent ? this.parent.contains(name) : false); } }; const attachScopes = function attachScopes$1(ast, propertyName = "scope") { let scope = new Scope(); walk$2(ast, { enter(n$2, parent) { const node = n$2; if (/(?:Function|Class)Declaration/.test(node.type)) scope.addDeclaration(node, false, false); if (node.type === "VariableDeclaration") { const { kind } = node; const isBlockDeclaration = blockDeclarations[kind]; node.declarations.forEach((declaration) => { scope.addDeclaration(declaration, isBlockDeclaration, true); }); } let newScope; if (node.type.includes("Function")) { const func = node; newScope = new Scope({ parent: scope, block: false, params: func.params }); if (func.type === "FunctionExpression" && func.id) newScope.addDeclaration(func, false, false); } if (/For(?:In|Of)?Statement/.test(node.type)) newScope = new Scope({ parent: scope, block: true }); if (node.type === "BlockStatement" && !parent.type.includes("Function")) newScope = new Scope({ parent: scope, block: true }); if (node.type === "CatchClause") newScope = new Scope({ parent: scope, params: node.param ? [node.param] : [], block: true }); if (newScope) { Object.defineProperty(node, propertyName, { value: newScope, configurable: true }); scope = newScope; } }, leave(n$2) { if (n$2[propertyName]) scope = scope.parent; } }); return scope; }; function isArray(arg) { return Array.isArray(arg); } function ensureArray(thing) { if (isArray(thing)) return thing; if (thing == null) return []; return [thing]; } const normalizePathRegExp = new RegExp(`\\${win32.sep}`, "g"); const normalizePath$3 = function normalizePath$5(filename) { return filename.replace(normalizePathRegExp, posix$1.sep); }; function getMatcherString$1(id, resolutionBase) { if (resolutionBase === false || isAbsolute$1(id) || id.startsWith("**")) return normalizePath$3(id); const basePath = normalizePath$3(resolve$1(resolutionBase || "")).replace(/[-^$*+?.()|[\]{}]/g, "\\$&"); return posix$1.join(basePath, normalizePath$3(id)); } const createFilter$2 = function createFilter$3(include, exclude, options$1) { const resolutionBase = options$1 && options$1.resolve; const getMatcher = (id) => id instanceof RegExp ? id : { test: (what) => { return picomatch(getMatcherString$1(id, resolutionBase), { dot: true })(what); } }; const includeMatchers = ensureArray(include).map(getMatcher); const excludeMatchers = ensureArray(exclude).map(getMatcher); if (!includeMatchers.length && !excludeMatchers.length) return (id) => typeof id === "string" && !id.includes("\0"); return function result(id) { if (typeof id !== "string") return false; if (id.includes("\0")) return false; const pathId = normalizePath$3(id); for (let i$1 = 0; i$1 < excludeMatchers.length; ++i$1) { const matcher = excludeMatchers[i$1]; if (matcher instanceof RegExp) matcher.lastIndex = 0; if (matcher.test(pathId)) return false; } for (let i$1 = 0; i$1 < includeMatchers.length; ++i$1) { const matcher = includeMatchers[i$1]; if (matcher instanceof RegExp) matcher.lastIndex = 0; if (matcher.test(pathId)) return true; } return !includeMatchers.length; }; }; const forbiddenIdentifiers = new Set(`break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl`.split(" ")); forbiddenIdentifiers.add(""); const makeLegalIdentifier = function makeLegalIdentifier$1(str) { let identifier = str.replace(/-(\w)/g, (_, letter) => letter.toUpperCase()).replace(/[^$_a-zA-Z0-9]/g, "_"); if (/\d/.test(identifier[0]) || forbiddenIdentifiers.has(identifier)) identifier = `_${identifier}`; return identifier || "_"; }; function stringify$4(obj) { return (JSON.stringify(obj) || "undefined").replace(/[\u2028\u2029]/g, (char) => `\\u${`000${char.charCodeAt(0).toString(16)}`.slice(-4)}`); } function serializeArray(arr, indent, baseIndent) { let output = "["; const separator = indent ? `\n${baseIndent}${indent}` : ""; for (let i$1 = 0; i$1 < arr.length; i$1++) { const key = arr[i$1]; output += `${i$1 > 0 ? "," : ""}${separator}${serialize(key, indent, baseIndent + indent)}`; } return `${output}${indent ? `\n${baseIndent}` : ""}]`; } function serializeObject(obj, indent, baseIndent) { let output = "{"; const separator = indent ? `\n${baseIndent}${indent}` : ""; const entries = Object.entries(obj); for (let i$1 = 0; i$1 < entries.length; i$1++) { const [key, value$1] = entries[i$1]; const stringKey = makeLegalIdentifier(key) === key ? key : stringify$4(key); output += `${i$1 > 0 ? "," : ""}${separator}${stringKey}:${indent ? " " : ""}${serialize(value$1, indent, baseIndent + indent)}`; } return `${output}${indent ? `\n${baseIndent}` : ""}}`; } function serialize(obj, indent, baseIndent) { if (typeof obj === "object" && obj !== null) { if (Array.isArray(obj)) return serializeArray(obj, indent, baseIndent); if (obj instanceof Date) return `new Date(${obj.getTime()})`; if (obj instanceof RegExp) return obj.toString(); return serializeObject(obj, indent, baseIndent); } if (typeof obj === "number") { if (obj === Infinity) return "Infinity"; if (obj === -Infinity) return "-Infinity"; if (obj === 0) return 1 / obj === Infinity ? "0" : "-0"; if (obj !== obj) return "NaN"; } if (typeof obj === "symbol") { const key = Symbol.keyFor(obj); if (key !== void 0) return `Symbol.for(${stringify$4(key)})`; } if (typeof obj === "bigint") return `${obj}n`; return stringify$4(obj); } const hasStringIsWellFormed = "isWellFormed" in String.prototype; function isWellFormedString(input) { if (hasStringIsWellFormed) return input.isWellFormed(); return !/\p{Surrogate}/u.test(input); } const dataToEsm = function dataToEsm$1(data, options$1 = {}) { var _a, _b; const t$1 = options$1.compact ? "" : "indent" in options$1 ? options$1.indent : " "; const _ = options$1.compact ? "" : " "; const n$2 = options$1.compact ? "" : "\n"; const declarationType = options$1.preferConst ? "const" : "var"; if (options$1.namedExports === false || typeof data !== "object" || Array.isArray(data) || data instanceof Date || data instanceof RegExp || data === null) { const code = serialize(data, options$1.compact ? null : t$1, ""); return `export default${_ || (/^[{[\-\/]/.test(code) ? "" : " ")}${code};`; } let maxUnderbarPrefixLength = 0; for (const key of Object.keys(data)) { const underbarPrefixLength = (_b = (_a = /^(_+)/.exec(key)) === null || _a === void 0 ? void 0 : _a[0].length) !== null && _b !== void 0 ? _b : 0; if (underbarPrefixLength > maxUnderbarPrefixLength) maxUnderbarPrefixLength = underbarPrefixLength; } const arbitraryNamePrefix = `${"_".repeat(maxUnderbarPrefixLength + 1)}arbitrary`; let namedExportCode = ""; const defaultExportRows = []; const arbitraryNameExportRows = []; for (const [key, value$1] of Object.entries(data)) if (key === makeLegalIdentifier(key)) { if (options$1.objectShorthand) defaultExportRows.push(key); else defaultExportRows.push(`${key}:${_}${key}`); namedExportCode += `export ${declarationType} ${key}${_}=${_}${serialize(value$1, options$1.compact ? null : t$1, "")};${n$2}`; } else { defaultExportRows.push(`${stringify$4(key)}:${_}${serialize(value$1, options$1.compact ? null : t$1, "")}`); if (options$1.includeArbitraryNames && isWellFormedString(key)) { const variableName = `${arbitraryNamePrefix}${arbitraryNameExportRows.length}`; namedExportCode += `${declarationType} ${variableName}${_}=${_}${serialize(value$1, options$1.compact ? null : t$1, "")};${n$2}`; arbitraryNameExportRows.push(`${variableName} as ${JSON.stringify(key)}`); } } const arbitraryExportCode = arbitraryNameExportRows.length > 0 ? `export${_}{${n$2}${t$1}${arbitraryNameExportRows.join(`,${n$2}${t$1}`)}${n$2}};${n$2}` : ""; const defaultExportCode = `export default${_}{${n$2}${t$1}${defaultExportRows.join(`,${n$2}${t$1}`)}${n$2}};${n$2}`; return `${namedExportCode}${arbitraryExportCode}${defaultExportCode}`; }; //#endregion //#region src/node/packages.ts let pnp; if (process.versions.pnp) try { pnp = createRequire( /** #__KEEP__ */ import.meta.url )("pnpapi"); } catch {} function invalidatePackageData(packageCache, pkgPath) { const pkgDir = normalizePath(path.dirname(pkgPath)); packageCache.forEach((pkg, cacheKey) => { if (pkg.dir === pkgDir) packageCache.delete(cacheKey); }); } function resolvePackageData(pkgName, basedir, preserveSymlinks = false, packageCache) { if (pnp) { const cacheKey = getRpdCacheKey(pkgName, basedir, preserveSymlinks); if (packageCache?.has(cacheKey)) return packageCache.get(cacheKey); try { const pkg = pnp.resolveToUnqualified(pkgName, basedir, { considerBuiltins: false }); if (!pkg) return null; const pkgData = loadPackageData(path.join(pkg, "package.json")); packageCache?.set(cacheKey, pkgData); return pkgData; } catch { return null; } } const originalBasedir = basedir; while (basedir) { if (packageCache) { const cached = getRpdCache(packageCache, pkgName, basedir, originalBasedir, preserveSymlinks); if (cached) return cached; } const pkg = path.join(basedir, "node_modules", pkgName, "package.json"); try { if (fs.existsSync(pkg)) { const pkgData = loadPackageData(preserveSymlinks ? pkg : safeRealpathSync(pkg)); if (packageCache) setRpdCache(packageCache, pkgData, pkgName, basedir, originalBasedir, preserveSymlinks); return pkgData; } } catch {} const nextBasedir = path.dirname(basedir); if (nextBasedir === basedir) break; basedir = nextBasedir; } return null; } function findNearestPackageData(basedir, packageCache) { const originalBasedir = basedir; while (basedir) { if (packageCache) { const cached = getFnpdCache(packageCache, basedir, originalBasedir); if (cached) return cached; } const pkgPath = path.join(basedir, "package.json"); if (tryStatSync(pkgPath)?.isFile()) try { const pkgData = loadPackageData(pkgPath); if (packageCache) setFnpdCache(packageCache, pkgData, basedir, originalBasedir); return pkgData; } catch {} const nextBasedir = path.dirname(basedir); if (nextBasedir === basedir) break; basedir = nextBasedir; } return null; } function findNearestMainPackageData(basedir, packageCache) { const nearestPackage = findNearestPackageData(basedir, packageCache); return nearestPackage && (nearestPackage.data.name ? nearestPackage : findNearestMainPackageData(path.dirname(nearestPackage.dir), packageCache)); } function loadPackageData(pkgPath) { const data = JSON.parse(stripBomTag(fs.readFileSync(pkgPath, "utf-8"))); const pkgDir = normalizePath(path.dirname(pkgPath)); const { sideEffects } = data; let hasSideEffects; if (typeof sideEffects === "boolean") hasSideEffects = () => sideEffects; else if (Array.isArray(sideEffects)) if (sideEffects.length <= 0) hasSideEffects = () => false; else hasSideEffects = createFilter(sideEffects.map((sideEffect) => { if (sideEffect.includes("/")) return sideEffect; return `**/${sideEffect}`; }), null, { resolve: pkgDir }); else hasSideEffects = () => null; const resolvedCache = {}; return { dir: pkgDir, data, hasSideEffects, setResolvedCache(key, entry, options$1) { resolvedCache[getResolveCacheKey(key, options$1)] = entry; }, getResolvedCache(key, options$1) { return resolvedCache[getResolveCacheKey(key, options$1)]; } }; } function getResolveCacheKey(key, options$1) { return [ key, options$1.isRequire ? "1" : "0", options$1.conditions.join("_"), options$1.extensions.join("_"), options$1.mainFields.join("_") ].join("|"); } function findNearestNodeModules(basedir) { while (basedir) { const pkgPath = path.join(basedir, "node_modules"); if (tryStatSync(pkgPath)?.isDirectory()) return pkgPath; const nextBasedir = path.dirname(basedir); if (nextBasedir === basedir) break; basedir = nextBasedir; } return null; } function watchPackageDataPlugin(packageCache) { const watchQueue = /* @__PURE__ */ new Set(); const watchedDirs = /* @__PURE__ */ new Set(); const watchFileStub = (id) => { watchQueue.add(id); }; let watchFile = watchFileStub; const setPackageData = packageCache.set.bind(packageCache); packageCache.set = (id, pkg) => { if (!isInNodeModules(pkg.dir) && !watchedDirs.has(pkg.dir)) { watchedDirs.add(pkg.dir); watchFile(path.join(pkg.dir, "package.json")); } return setPackageData(id, pkg); }; return { name: "vite:watch-package-data", buildStart() { watchFile = this.addWatchFile.bind(this); watchQueue.forEach(watchFile); watchQueue.clear(); }, buildEnd() { watchFile = watchFileStub; }, watchChange(id) { if (id.endsWith("/package.json")) invalidatePackageData(packageCache, path.normalize(id)); } }; } /** * Get cached `resolvePackageData` value based on `basedir`. When one is found, * and we've already traversed some directories between `basedir` and `originalBasedir`, * we cache the value for those in-between directories as well. * * This makes it so the fs is only read once for a shared `basedir`. */ function getRpdCache(packageCache, pkgName, basedir, originalBasedir, preserveSymlinks) { const cacheKey = getRpdCacheKey(pkgName, basedir, preserveSymlinks); const pkgData = packageCache.get(cacheKey); if (pkgData) { traverseBetweenDirs(originalBasedir, basedir, (dir) => { packageCache.set(getRpdCacheKey(pkgName, dir, preserveSymlinks), pkgData); }); return pkgData; } } function setRpdCache(packageCache, pkgData, pkgName, basedir, originalBasedir, preserveSymlinks) { packageCache.set(getRpdCacheKey(pkgName, basedir, preserveSymlinks), pkgData); traverseBetweenDirs(originalBasedir, basedir, (dir) => { packageCache.set(getRpdCacheKey(pkgName, dir, preserveSymlinks), pkgData); }); } function getRpdCacheKey(pkgName, basedir, preserveSymlinks) { return `rpd_${pkgName}_${basedir}_${preserveSymlinks}`; } /** * Get cached `findNearestPackageData` value based on `basedir`. When one is found, * and we've already traversed some directories between `basedir` and `originalBasedir`, * we cache the value for those in-between directories as well. * * This makes it so the fs is only read once for a shared `basedir`. */ function getFnpdCache(packageCache, basedir, originalBasedir) { const cacheKey = getFnpdCacheKey(basedir); const pkgData = packageCache.get(cacheKey); if (pkgData) { traverseBetweenDirs(originalBasedir, basedir, (dir) => { packageCache.set(getFnpdCacheKey(dir), pkgData); }); return pkgData; } } function setFnpdCache(packageCache, pkgData, basedir, originalBasedir) { packageCache.set(getFnpdCacheKey(basedir), pkgData); traverseBetweenDirs(originalBasedir, basedir, (dir) => { packageCache.set(getFnpdCacheKey(dir), pkgData); }); } function getFnpdCacheKey(basedir) { return `fnpd_${basedir}`; } /** * Traverse between `longerDir` (inclusive) and `shorterDir` (exclusive) and call `cb` for each dir. * @param longerDir Longer dir path, e.g. `/User/foo/bar/baz` * @param shorterDir Shorter dir path, e.g. `/User/foo` */ function traverseBetweenDirs(longerDir, shorterDir, cb) { while (longerDir !== shorterDir) { cb(longerDir); longerDir = path.dirname(longerDir); } } //#endregion //#region src/node/utils.ts var import_picocolors$33 = /* @__PURE__ */ __toESM(require_picocolors(), 1); var import_node = /* @__PURE__ */ __toESM(require_node$1(), 1); const createFilter = createFilter$2; const replaceSlashOrColonRE = /[/:]/g; const replaceDotRE = /\./g; const replaceNestedIdRE = /\s*>\s*/g; const replaceHashRE = /#/g; const flattenId = (id) => { return limitFlattenIdLength(id.replace(replaceSlashOrColonRE, "_").replace(replaceDotRE, "__").replace(replaceNestedIdRE, "___").replace(replaceHashRE, "____")); }; const FLATTEN_ID_HASH_LENGTH = 8; const FLATTEN_ID_MAX_FILE_LENGTH = 170; const limitFlattenIdLength = (id, limit = FLATTEN_ID_MAX_FILE_LENGTH) => { if (id.length <= limit) return id; return id.slice(0, limit - (FLATTEN_ID_HASH_LENGTH + 1)) + "_" + getHash(id); }; const normalizeId = (id) => id.replace(replaceNestedIdRE, " > "); const NODE_BUILTIN_NAMESPACE = "node:"; const BUN_BUILTIN_NAMESPACE = "bun:"; const nodeBuiltins = builtinModules.filter((id) => !id.includes(":")); const isBuiltinCache = /* @__PURE__ */ new WeakMap(); function isBuiltin(builtins, id) { let isBuiltin$1 = isBuiltinCache.get(builtins); if (!isBuiltin$1) { isBuiltin$1 = createIsBuiltin(builtins); isBuiltinCache.set(builtins, isBuiltin$1); } return isBuiltin$1(id); } function createIsBuiltin(builtins) { const plainBuiltinsSet = new Set(builtins.filter((builtin) => typeof builtin === "string")); const regexBuiltins = builtins.filter((builtin) => typeof builtin !== "string"); return (id) => plainBuiltinsSet.has(id) || regexBuiltins.some((regexp) => regexp.test(id)); } const nodeLikeBuiltins = [ ...nodeBuiltins, /* @__PURE__ */ new RegExp(`^${NODE_BUILTIN_NAMESPACE}`), /* @__PURE__ */ new RegExp(`^${BUN_BUILTIN_NAMESPACE}`) ]; function isNodeLikeBuiltin(id) { return isBuiltin(nodeLikeBuiltins, id); } function isNodeBuiltin(id) { if (id.startsWith(NODE_BUILTIN_NAMESPACE)) return true; return nodeBuiltins.includes(id); } function isInNodeModules(id) { return id.includes("node_modules"); } function moduleListContains(moduleList, id) { return moduleList?.some((m$2) => m$2 === id || id.startsWith(withTrailingSlash(m$2))); } function isOptimizable(id, optimizeDeps$1) { const { extensions: extensions$1 } = optimizeDeps$1; return OPTIMIZABLE_ENTRY_RE.test(id) || (extensions$1?.some((ext) => id.endsWith(ext)) ?? false); } const bareImportRE = /^(?![a-zA-Z]:)[\w@](?!.*:\/\/)/; const deepImportRE = /^([^@][^/]*)\/|^(@[^/]+\/[^/]+)\//; const _require$1 = createRequire( /** #__KEEP__ */ import.meta.url ); const _dirname = path.dirname(fileURLToPath( /** #__KEEP__ */ import.meta.url )); const rollupVersion = resolvePackageData("rollup", _dirname, true)?.data.version ?? ""; const filter = process.env.VITE_DEBUG_FILTER; const DEBUG = process.env.DEBUG; function createDebugger(namespace, options$1 = {}) { const log$4 = (0, import_node.default)(namespace); const { onlyWhenFocused, depth } = options$1; if (depth && log$4.inspectOpts && log$4.inspectOpts.depth == null) log$4.inspectOpts.depth = options$1.depth; let enabled$1 = log$4.enabled; if (enabled$1 && onlyWhenFocused) enabled$1 = !!DEBUG?.includes(typeof onlyWhenFocused === "string" ? onlyWhenFocused : namespace); if (enabled$1) return (...args) => { if (!filter || args.some((a) => a?.includes?.(filter))) log$4(...args); }; } function testCaseInsensitiveFS() { if (!CLIENT_ENTRY.endsWith("client.mjs")) throw new Error(`cannot test case insensitive FS, CLIENT_ENTRY const doesn't contain client.mjs`); if (!fs.existsSync(CLIENT_ENTRY)) throw new Error("cannot test case insensitive FS, CLIENT_ENTRY does not point to an existing file: " + CLIENT_ENTRY); return fs.existsSync(CLIENT_ENTRY.replace("client.mjs", "cLiEnT.mjs")); } const isCaseInsensitiveFS = testCaseInsensitiveFS(); const VOLUME_RE = /^[A-Z]:/i; function normalizePath(id) { return path.posix.normalize(isWindows ? slash(id) : id); } function fsPathFromId(id) { const fsPath = normalizePath(id.startsWith(FS_PREFIX) ? id.slice(FS_PREFIX.length) : id); return fsPath[0] === "/" || VOLUME_RE.test(fsPath) ? fsPath : `/${fsPath}`; } function fsPathFromUrl(url$3) { return fsPathFromId(cleanUrl(url$3)); } /** * Check if dir is a parent of file * * Warning: parameters are not validated, only works with normalized absolute paths * * @param dir - normalized absolute path * @param file - normalized absolute path * @returns true if dir is a parent of file */ function isParentDirectory(dir, file) { dir = withTrailingSlash(dir); return file.startsWith(dir) || isCaseInsensitiveFS && file.toLowerCase().startsWith(dir.toLowerCase()); } /** * Check if 2 file name are identical * * Warning: parameters are not validated, only works with normalized absolute paths * * @param file1 - normalized absolute path * @param file2 - normalized absolute path * @returns true if both files url are identical */ function isSameFilePath(file1, file2) { return file1 === file2 || isCaseInsensitiveFS && file1.toLowerCase() === file2.toLowerCase(); } const externalRE = /^([a-z]+:)?\/\//; const isExternalUrl = (url$3) => externalRE.test(url$3); const dataUrlRE = /^\s*data:/i; const isDataUrl = (url$3) => dataUrlRE.test(url$3); const virtualModuleRE = /^virtual-module:.*/; const virtualModulePrefix = "virtual-module:"; const knownJsSrcRE = /\.(?:[jt]sx?|m[jt]s|vue|marko|svelte|astro|imba|mdx)(?:$|\?)/; const isJSRequest = (url$3) => { url$3 = cleanUrl(url$3); if (knownJsSrcRE.test(url$3)) return true; if (!path.extname(url$3) && url$3[url$3.length - 1] !== "/") return true; return false; }; const isCSSRequest = (request) => CSS_LANGS_RE.test(request); const importQueryRE = /(\?|&)import=?(?:&|$)/; const directRequestRE$1 = /(\?|&)direct=?(?:&|$)/; const internalPrefixes = [ FS_PREFIX, VALID_ID_PREFIX, CLIENT_PUBLIC_PATH, ENV_PUBLIC_PATH ]; const InternalPrefixRE = /* @__PURE__ */ new RegExp(`^(?:${internalPrefixes.join("|")})`); const trailingSeparatorRE = /[?&]$/; const isImportRequest = (url$3) => importQueryRE.test(url$3); const isInternalRequest = (url$3) => InternalPrefixRE.test(url$3); function removeImportQuery(url$3) { return url$3.replace(importQueryRE, "$1").replace(trailingSeparatorRE, ""); } function removeDirectQuery(url$3) { return url$3.replace(directRequestRE$1, "$1").replace(trailingSeparatorRE, ""); } const urlRE = /(\?|&)url(?:&|$)/; const rawRE = /(\?|&)raw(?:&|$)/; function removeUrlQuery(url$3) { return url$3.replace(urlRE, "$1").replace(trailingSeparatorRE, ""); } function injectQuery(url$3, queryToInject) { const { file, postfix } = splitFileAndPostfix(url$3); return `${isWindows ? slash(file) : file}?${queryToInject}${postfix[0] === "?" ? `&${postfix.slice(1)}` : postfix}`; } const timestampRE = /\bt=\d{13}&?\b/; function removeTimestampQuery(url$3) { return url$3.replace(timestampRE, "").replace(trailingSeparatorRE, ""); } async function asyncReplace(input, re, replacer) { let match; let remaining = input; let rewritten = ""; while (match = re.exec(remaining)) { rewritten += remaining.slice(0, match.index); rewritten += await replacer(match); remaining = remaining.slice(match.index + match[0].length); } rewritten += remaining; return rewritten; } function timeFrom(start, subtract = 0) { const time = performance$1.now() - start - subtract; const timeString = (time.toFixed(2) + `ms`).padEnd(5, " "); if (time < 10) return import_picocolors$33.default.green(timeString); else if (time < 50) return import_picocolors$33.default.yellow(timeString); else return import_picocolors$33.default.red(timeString); } /** * pretty url for logging. */ function prettifyUrl(url$3, root) { url$3 = removeTimestampQuery(url$3); const isAbsoluteFile = url$3.startsWith(root); if (isAbsoluteFile || url$3.startsWith(FS_PREFIX)) { const file = path.posix.relative(root, isAbsoluteFile ? url$3 : fsPathFromId(url$3)); return import_picocolors$33.default.dim(file); } else return import_picocolors$33.default.dim(url$3); } function isObject(value$1) { return Object.prototype.toString.call(value$1) === "[object Object]"; } function isDefined(value$1) { return value$1 != null; } function tryStatSync(file) { try { return fs.statSync(file, { throwIfNoEntry: false }); } catch {} } function lookupFile(dir, fileNames) { while (dir) { for (const fileName of fileNames) { const fullPath = path.join(dir, fileName); if (tryStatSync(fullPath)?.isFile()) return fullPath; } const parentDir$1 = path.dirname(dir); if (parentDir$1 === dir) return; dir = parentDir$1; } } function isFilePathESM(filePath, packageCache) { if (/\.m[jt]s$/.test(filePath)) return true; else if (/\.c[jt]s$/.test(filePath)) return false; else try { return findNearestPackageData(path.dirname(filePath), packageCache)?.data.type === "module"; } catch { return false; } } const splitRE = /\r?\n/g; const range = 2; function pad$1(source, n$2 = 2) { return source.split(splitRE).map((l) => ` `.repeat(n$2) + l).join(`\n`); } function posToNumber(source, pos) { if (typeof pos === "number") return pos; const lines = source.split(splitRE); const { line, column } = pos; let start = 0; for (let i$1 = 0; i$1 < line - 1 && i$1 < lines.length; i$1++) start += lines[i$1].length + 1; return start + column; } function numberToPos(source, offset$1) { if (typeof offset$1 !== "number") return offset$1; if (offset$1 > source.length) throw new Error(`offset is longer than source length! offset ${offset$1} > length ${source.length}`); const lines = source.slice(0, offset$1).split(splitRE); return { line: lines.length, column: lines[lines.length - 1].length }; } const MAX_DISPLAY_LEN = 120; const ELLIPSIS = "..."; function generateCodeFrame(source, start = 0, end) { start = Math.max(posToNumber(source, start), 0); end = Math.min(end !== void 0 ? posToNumber(source, end) : start, source.length); const lastPosLine = end !== void 0 ? numberToPos(source, end).line : numberToPos(source, start).line + range; const lineNumberWidth = Math.max(3, String(lastPosLine).length + 1); const lines = source.split(splitRE); let count = 0; const res = []; for (let i$1 = 0; i$1 < lines.length; i$1++) { count += lines[i$1].length; if (count >= start) { for (let j = i$1 - range; j <= i$1 + range || end > count; j++) { if (j < 0 || j >= lines.length) continue; const line = j + 1; const lineLength = lines[j].length; const pad$2 = Math.max(start - (count - lineLength), 0); const underlineLength = Math.max(1, end > count ? lineLength - pad$2 : end - start); let displayLine = lines[j]; let underlinePad = pad$2; if (lineLength > MAX_DISPLAY_LEN) { let startIdx = 0; if (j === i$1) { if (underlineLength > MAX_DISPLAY_LEN) startIdx = pad$2; else { const center = pad$2 + Math.floor(underlineLength / 2); startIdx = Math.max(0, center - Math.floor(MAX_DISPLAY_LEN / 2)); } underlinePad = Math.max(0, pad$2 - startIdx) + (startIdx > 0 ? 3 : 0); } const prefix = startIdx > 0 ? ELLIPSIS : ""; const suffix = lineLength - startIdx > MAX_DISPLAY_LEN ? ELLIPSIS : ""; const sliceLen = MAX_DISPLAY_LEN - prefix.length - suffix.length; displayLine = prefix + displayLine.slice(startIdx, startIdx + sliceLen) + suffix; } res.push(`${line}${" ".repeat(lineNumberWidth - String(line).length)}| ${displayLine}`); if (j === i$1) { const underline = "^".repeat(Math.min(underlineLength, MAX_DISPLAY_LEN)); res.push(`${" ".repeat(lineNumberWidth)}| ` + " ".repeat(underlinePad) + underline); } else if (j > i$1) { if (end > count) { const length = Math.max(Math.min(end - count, lineLength), 1); const underline = "^".repeat(Math.min(length, MAX_DISPLAY_LEN)); res.push(`${" ".repeat(lineNumberWidth)}| ` + underline); } count += lineLength + 1; } } break; } count++; } return res.join("\n"); } function isFileReadable(filename) { if (!tryStatSync(filename)) return false; try { fs.accessSync(filename, fs.constants.R_OK); return true; } catch { return false; } } const splitFirstDirRE = /(.+?)[\\/](.+)/; /** * Delete every file and subdirectory. **The given directory must exist.** * Pass an optional `skip` array to preserve files under the root directory. */ function emptyDir(dir, skip) { const skipInDir = []; let nested = null; if (skip?.length) for (const file of skip) if (path.dirname(file) !== ".") { const matched = splitFirstDirRE.exec(file); if (matched) { nested ??= /* @__PURE__ */ new Map(); const [, nestedDir, skipPath] = matched; let nestedSkip = nested.get(nestedDir); if (!nestedSkip) { nestedSkip = []; nested.set(nestedDir, nestedSkip); } if (!nestedSkip.includes(skipPath)) nestedSkip.push(skipPath); } } else skipInDir.push(file); for (const file of fs.readdirSync(dir)) { if (skipInDir.includes(file)) continue; if (nested?.has(file)) emptyDir(path.resolve(dir, file), nested.get(file)); else fs.rmSync(path.resolve(dir, file), { recursive: true, force: true }); } } function copyDir(srcDir, destDir) { fs.mkdirSync(destDir, { recursive: true }); for (const file of fs.readdirSync(srcDir)) { const srcFile = path.resolve(srcDir, file); if (srcFile === destDir) continue; const destFile = path.resolve(destDir, file); if (fs.statSync(srcFile).isDirectory()) copyDir(srcFile, destFile); else fs.copyFileSync(srcFile, destFile); } } const ERR_SYMLINK_IN_RECURSIVE_READDIR = "ERR_SYMLINK_IN_RECURSIVE_READDIR"; async function recursiveReaddir(dir) { if (!fs.existsSync(dir)) return []; let dirents; try { dirents = await fsp.readdir(dir, { withFileTypes: true }); } catch (e$1) { if (e$1.code === "EACCES") return []; throw e$1; } if (dirents.some((dirent) => dirent.isSymbolicLink())) { const err$2 = /* @__PURE__ */ new Error("Symbolic links are not supported in recursiveReaddir"); err$2.code = ERR_SYMLINK_IN_RECURSIVE_READDIR; throw err$2; } return (await Promise.all(dirents.map((dirent) => { const res = path.resolve(dir, dirent.name); return dirent.isDirectory() ? recursiveReaddir(res) : normalizePath(res); }))).flat(1); } let safeRealpathSync = isWindows ? windowsSafeRealPathSync : fs.realpathSync.native; const windowsNetworkMap = /* @__PURE__ */ new Map(); function windowsMappedRealpathSync(path$13) { const realPath = fs.realpathSync.native(path$13); if (realPath.startsWith("\\\\")) { for (const [network, volume] of windowsNetworkMap) if (realPath.startsWith(network)) return realPath.replace(network, volume); } return realPath; } const parseNetUseRE = /^\w* +(\w:) +([^ ]+)\s/; let firstSafeRealPathSyncRun = false; function windowsSafeRealPathSync(path$13) { if (!firstSafeRealPathSyncRun) { optimizeSafeRealPathSync(); firstSafeRealPathSyncRun = true; } return fs.realpathSync(path$13); } function optimizeSafeRealPathSync() { try { fs.realpathSync.native(path.resolve("./")); } catch (error$1) { if (error$1.message.includes("EISDIR: illegal operation on a directory")) { safeRealpathSync = fs.realpathSync; return; } } exec("net use", (error$1, stdout) => { if (error$1) return; const lines = stdout.split("\n"); for (const line of lines) { const m$2 = parseNetUseRE.exec(line); if (m$2) windowsNetworkMap.set(m$2[2], m$2[1]); } if (windowsNetworkMap.size === 0) safeRealpathSync = fs.realpathSync.native; else safeRealpathSync = windowsMappedRealpathSync; }); } function ensureWatchedFile(watcher, file, root) { if (file && !file.startsWith(withTrailingSlash(root)) && !file.includes("\0") && fs.existsSync(file)) watcher.add(path.resolve(file)); } function joinSrcset(ret) { return ret.map(({ url: url$3, descriptor }) => url$3 + (descriptor ? ` ${descriptor}` : "")).join(", "); } /** This regex represents a loose rule of an “image candidate string” and "image set options". @see https://html.spec.whatwg.org/multipage/images.html#srcset-attribute @see https://drafts.csswg.org/css-images-4/#image-set-notation The Regex has named capturing groups `url` and `descriptor`. The `url` group can be: * any CSS function * CSS string (single or double-quoted) * URL string (unquoted) The `descriptor` is anything after the space and before the comma. */ const imageCandidateRegex = /(?:^|\s|(?<=,))(?[\w-]+\([^)]*\)|"[^"]*"|'[^']*'|[^,]\S*[^,])\s*(?:\s(?\w[^,]+))?(?:,|$)/g; const escapedSpaceCharacters = /(?: |\\t|\\n|\\f|\\r)+/g; function parseSrcset(string) { const matches$2 = string.trim().replace(escapedSpaceCharacters, " ").replace(/\r?\n/, "").replace(/,\s+/, ", ").replaceAll(/\s+/g, " ").matchAll(imageCandidateRegex); return Array.from(matches$2, ({ groups: groups$1 }) => ({ url: groups$1?.url?.trim() ?? "", descriptor: groups$1?.descriptor?.trim() ?? "" })).filter(({ url: url$3 }) => !!url$3); } function processSrcSet(srcs, replacer) { return Promise.all(parseSrcset(srcs).map(async ({ url: url$3, descriptor }) => ({ url: await replacer({ url: url$3, descriptor }), descriptor }))).then(joinSrcset); } function processSrcSetSync(srcs, replacer) { return joinSrcset(parseSrcset(srcs).map(({ url: url$3, descriptor }) => ({ url: replacer({ url: url$3, descriptor }), descriptor }))); } const windowsDriveRE = /^[A-Z]:/; const replaceWindowsDriveRE = /^([A-Z]):\//; const linuxAbsolutePathRE = /^\/[^/]/; function escapeToLinuxLikePath(path$13) { if (windowsDriveRE.test(path$13)) return path$13.replace(replaceWindowsDriveRE, "/windows/$1/"); if (linuxAbsolutePathRE.test(path$13)) return `/linux${path$13}`; return path$13; } const revertWindowsDriveRE = /^\/windows\/([A-Z])\//; function unescapeToLinuxLikePath(path$13) { if (path$13.startsWith("/linux/")) return path$13.slice(6); if (path$13.startsWith("/windows/")) return path$13.replace(revertWindowsDriveRE, "$1:/"); return path$13; } const nullSourceMap = { names: [], sources: [], mappings: "", version: 3 }; /** * Combines multiple sourcemaps into a single sourcemap. * Note that the length of sourcemapList must be 2. */ function combineSourcemaps(filename, sourcemapList) { if (sourcemapList.length === 0 || sourcemapList.every((m$2) => m$2.sources.length === 0)) return { ...nullSourceMap }; sourcemapList = sourcemapList.map((sourcemap) => { const newSourcemaps = { ...sourcemap }; newSourcemaps.sources = sourcemap.sources.map((source) => source ? escapeToLinuxLikePath(source) : null); if (sourcemap.sourceRoot) newSourcemaps.sourceRoot = escapeToLinuxLikePath(sourcemap.sourceRoot); return newSourcemaps; }); const escapedFilename = escapeToLinuxLikePath(filename); let map$1; let mapIndex = 1; if (sourcemapList.slice(0, -1).find((m$2) => m$2.sources.length !== 1) === void 0) map$1 = remapping(sourcemapList, () => null); else map$1 = remapping(sourcemapList[0], function loader$1(sourcefile) { if (sourcefile === escapedFilename && sourcemapList[mapIndex]) return sourcemapList[mapIndex++]; else return null; }); if (!map$1.file) delete map$1.file; map$1.sources = map$1.sources.map((source) => source ? unescapeToLinuxLikePath(source) : source); map$1.file = filename; return map$1; } function unique(arr) { return Array.from(new Set(arr)); } /** * Returns resolved localhost address when `dns.lookup` result differs from DNS * * `dns.lookup` result is same when defaultResultOrder is `verbatim`. * Even if defaultResultOrder is `ipv4first`, `dns.lookup` result maybe same. * For example, when IPv6 is not supported on that machine/network. */ async function getLocalhostAddressIfDiffersFromDNS() { const [nodeResult, dnsResult] = await Promise.all([promises$1.lookup("localhost"), promises$1.lookup("localhost", { verbatim: true })]); return nodeResult.family === dnsResult.family && nodeResult.address === dnsResult.address ? void 0 : nodeResult.address; } function diffDnsOrderChange(oldUrls, newUrls) { return !(oldUrls === newUrls || oldUrls && newUrls && arrayEqual(oldUrls.local, newUrls.local) && arrayEqual(oldUrls.network, newUrls.network)); } async function resolveHostname(optionsHost) { let host; if (optionsHost === void 0 || optionsHost === false) host = "localhost"; else if (optionsHost === true) host = void 0; else host = optionsHost; let name = host === void 0 || wildcardHosts.has(host) ? "localhost" : host; if (host === "localhost") { const localhostAddr = await getLocalhostAddressIfDiffersFromDNS(); if (localhostAddr) name = localhostAddr; } return { host, name }; } function resolveServerUrls(server, options$1, hostname, httpsOptions, config$2) { const address = server.address(); const isAddressInfo = (x) => x?.address; if (!isAddressInfo(address)) return { local: [], network: [] }; const local = []; const network = []; const protocol = options$1.https ? "https" : "http"; const port = address.port; const base = config$2.rawBase === "./" || config$2.rawBase === "" ? "/" : config$2.rawBase; if (hostname.host !== void 0 && !wildcardHosts.has(hostname.host)) { let hostnameName = hostname.name; if (hostnameName.includes(":")) hostnameName = `[${hostnameName}]`; const address$1 = `${protocol}://${hostnameName}:${port}${base}`; if (loopbackHosts.has(hostname.host)) local.push(address$1); else network.push(address$1); } else Object.values(os.networkInterfaces()).flatMap((nInterface) => nInterface ?? []).filter((detail) => detail.address && detail.family === "IPv4").forEach((detail) => { let host = detail.address.replace("127.0.0.1", hostname.name); if (host.includes(":")) host = `[${host}]`; const url$3 = `${protocol}://${host}:${port}${base}`; if (detail.address.includes("127.0.0.1")) local.push(url$3); else network.push(url$3); }); const cert = httpsOptions?.cert && !Array.isArray(httpsOptions.cert) ? new crypto.X509Certificate(httpsOptions.cert) : void 0; const hostnameFromCert = cert?.subjectAltName ? extractHostnamesFromSubjectAltName(cert.subjectAltName) : []; if (hostnameFromCert.length > 0) { const existings = new Set([...local, ...network]); local.push(...hostnameFromCert.map((hostname$1) => `https://${hostname$1}:${port}${base}`).filter((url$3) => !existings.has(url$3))); } return { local, network }; } function extractHostnamesFromSubjectAltName(subjectAltName) { const hostnames = []; let remaining = subjectAltName; while (remaining) { const nameEndIndex = remaining.indexOf(":"); const name = remaining.slice(0, nameEndIndex); remaining = remaining.slice(nameEndIndex + 1); if (!remaining) break; const isQuoted = remaining[0] === "\""; let value$1; if (isQuoted) { const endQuoteIndex = remaining.indexOf("\"", 1); value$1 = JSON.parse(remaining.slice(0, endQuoteIndex + 1)); remaining = remaining.slice(endQuoteIndex + 1); } else { const maybeEndIndex = remaining.indexOf(","); const endIndex = maybeEndIndex === -1 ? remaining.length : maybeEndIndex; value$1 = remaining.slice(0, endIndex); remaining = remaining.slice(endIndex); } remaining = remaining.slice(1).trimStart(); if (name === "DNS" && value$1 !== "[::1]" && !(value$1.startsWith("*.") && net.isIPv4(value$1.slice(2)))) hostnames.push(value$1.replace("*", "vite")); } return hostnames; } function arraify(target) { return Array.isArray(target) ? target : [target]; } const multilineCommentsRE = /\/\*[^*]*\*+(?:[^/*][^*]*\*+)*\//g; const singlelineCommentsRE = /\/\/.*/g; const requestQuerySplitRE = /\?(?!.*[/|}])/; const requestQueryMaybeEscapedSplitRE = /\\?\?(?!.*[/|}])/; const blankReplacer = (match) => " ".repeat(match.length); function getHash(text, length = 8) { const h$2 = crypto.hash("sha256", text, "hex").substring(0, length); if (length <= 64) return h$2; return h$2.padEnd(length, "_"); } const requireResolveFromRootWithFallback = (root, id) => { if (!(resolvePackageData(id, root) || resolvePackageData(id, _dirname))) { const error$1 = /* @__PURE__ */ new Error(`${JSON.stringify(id)} not found.`); error$1.code = "MODULE_NOT_FOUND"; throw error$1; } return _require$1.resolve(id, { paths: [root, _dirname] }); }; function emptyCssComments(raw) { return raw.replace(multilineCommentsRE, blankReplacer); } function backwardCompatibleWorkerPlugins(plugins$1) { if (Array.isArray(plugins$1)) return plugins$1; if (typeof plugins$1 === "function") return plugins$1(); return []; } function deepClone(value$1) { if (Array.isArray(value$1)) return value$1.map((v) => deepClone(v)); if (isObject(value$1)) { const cloned = {}; for (const key in value$1) cloned[key] = deepClone(value$1[key]); return cloned; } if (typeof value$1 === "function") return value$1; if (value$1 instanceof RegExp) return new RegExp(value$1); if (typeof value$1 === "object" && value$1 != null) throw new Error("Cannot deep clone non-plain object"); return value$1; } function mergeWithDefaultsRecursively(defaults, values) { const merged = defaults; for (const key in values) { const value$1 = values[key]; if (value$1 === void 0) continue; const existing = merged[key]; if (existing === void 0) { merged[key] = value$1; continue; } if (isObject(existing) && isObject(value$1)) { merged[key] = mergeWithDefaultsRecursively(existing, value$1); continue; } merged[key] = value$1; } return merged; } const environmentPathRE = /^environments\.[^.]+$/; function mergeWithDefaults(defaults, values) { return mergeWithDefaultsRecursively(deepClone(defaults), values); } function mergeConfigRecursively(defaults, overrides, rootPath) { const merged = { ...defaults }; for (const key in overrides) { const value$1 = overrides[key]; if (value$1 == null) continue; const existing = merged[key]; if (existing == null) { merged[key] = value$1; continue; } if (key === "alias" && (rootPath === "resolve" || rootPath === "")) { merged[key] = mergeAlias(existing, value$1); continue; } else if (key === "assetsInclude" && rootPath === "") { merged[key] = [].concat(existing, value$1); continue; } else if ((key === "noExternal" && (rootPath === "ssr" || rootPath === "resolve") || key === "allowedHosts" && rootPath === "server") && (existing === true || value$1 === true)) { merged[key] = true; continue; } else if (key === "plugins" && rootPath === "worker") { merged[key] = () => [...backwardCompatibleWorkerPlugins(existing), ...backwardCompatibleWorkerPlugins(value$1)]; continue; } else if (key === "server" && rootPath === "server.hmr") { merged[key] = value$1; continue; } if (Array.isArray(existing) || Array.isArray(value$1)) { merged[key] = [...arraify(existing), ...arraify(value$1)]; continue; } if (isObject(existing) && isObject(value$1)) { merged[key] = mergeConfigRecursively(existing, value$1, rootPath && !environmentPathRE.test(rootPath) ? `${rootPath}.${key}` : key); continue; } merged[key] = value$1; } return merged; } function mergeConfig(defaults, overrides, isRoot = true) { if (typeof defaults === "function" || typeof overrides === "function") throw new Error(`Cannot merge config in form of callback`); return mergeConfigRecursively(defaults, overrides, isRoot ? "" : "."); } function mergeAlias(a, b) { if (!a) return b; if (!b) return a; if (isObject(a) && isObject(b)) return { ...a, ...b }; return [...normalizeAlias(b), ...normalizeAlias(a)]; } function normalizeAlias(o$1 = []) { return Array.isArray(o$1) ? o$1.map(normalizeSingleAlias) : Object.keys(o$1).map((find$1) => normalizeSingleAlias({ find: find$1, replacement: o$1[find$1] })); } function normalizeSingleAlias({ find: find$1, replacement, customResolver }) { if (typeof find$1 === "string" && find$1.endsWith("/") && replacement.endsWith("/")) { find$1 = find$1.slice(0, find$1.length - 1); replacement = replacement.slice(0, replacement.length - 1); } const alias$2 = { find: find$1, replacement }; if (customResolver) alias$2.customResolver = customResolver; return alias$2; } /** * Transforms transpiled code result where line numbers aren't altered, * so we can skip sourcemap generation during dev */ function transformStableResult(s$2, id, config$2) { return { code: s$2.toString(), map: config$2.command === "build" && config$2.build.sourcemap ? s$2.generateMap({ hires: "boundary", source: id }) : null }; } async function asyncFlatten(arr) { do arr = (await Promise.all(arr)).flat(Infinity); while (arr.some((v) => v?.then)); return arr; } function stripBomTag(content) { if (content.charCodeAt(0) === 65279) return content.slice(1); return content; } const windowsDrivePathPrefixRE = /^[A-Za-z]:[/\\]/; /** * path.isAbsolute also returns true for drive relative paths on windows (e.g. /something) * this function returns false for them but true for absolute paths (e.g. C:/something) */ const isNonDriveRelativeAbsolutePath = (p) => { if (!isWindows) return p[0] === "/"; return windowsDrivePathPrefixRE.test(p); }; /** * Determine if a file is being requested with the correct case, to ensure * consistent behavior between dev and prod and across operating systems. */ function shouldServeFile(filePath, root) { if (!isCaseInsensitiveFS) return true; return hasCorrectCase(filePath, root); } /** * Note that we can't use realpath here, because we don't want to follow * symlinks. */ function hasCorrectCase(file, assets) { if (file === assets) return true; const parent = path.dirname(file); if (fs.readdirSync(parent).includes(path.basename(file))) return hasCorrectCase(parent, assets); return false; } function joinUrlSegments(a, b) { if (!a || !b) return a || b || ""; if (a.endsWith("/")) a = a.substring(0, a.length - 1); if (b[0] !== "/") b = "/" + b; return a + b; } function removeLeadingSlash(str) { return str[0] === "/" ? str.slice(1) : str; } function stripBase(path$13, base) { if (path$13 === base) return "/"; const devBase = withTrailingSlash(base); return path$13.startsWith(devBase) ? path$13.slice(devBase.length - 1) : path$13; } function arrayEqual(a, b) { if (a === b) return true; if (a.length !== b.length) return false; for (let i$1 = 0; i$1 < a.length; i$1++) if (a[i$1] !== b[i$1]) return false; return true; } function evalValue(rawValue) { return new Function(` var console, exports, global, module, process, require return (\n${rawValue}\n) `)(); } function getNpmPackageName(importPath) { const parts = importPath.split("/"); if (parts[0][0] === "@") { if (!parts[1]) return null; return `${parts[0]}/${parts[1]}`; } else return parts[0]; } function getPkgName(name) { return name[0] === "@" ? name.split("/")[1] : name; } const escapeRegexRE$1 = /[-/\\^$*+?.()|[\]{}]/g; function escapeRegex(str) { return str.replace(escapeRegexRE$1, "\\$&"); } function getPackageManagerCommand(type = "install") { const packageManager = process.env.npm_config_user_agent?.split(" ")[0].split("/")[0] || "npm"; switch (type) { case "install": return packageManager === "npm" ? "npm install" : `${packageManager} add`; case "uninstall": return packageManager === "npm" ? "npm uninstall" : `${packageManager} remove`; case "update": return packageManager === "yarn" ? "yarn upgrade" : `${packageManager} update`; default: throw new TypeError(`Unknown command type: ${type}`); } } function isDevServer(server) { return "pluginContainer" in server; } function createSerialPromiseQueue() { let previousTask; return { async run(f$1) { const thisTask = f$1(); const depTasks = Promise.all([previousTask, thisTask]); previousTask = depTasks; const [, result] = await depTasks; if (previousTask === depTasks) previousTask = void 0; return result; } }; } function sortObjectKeys(obj) { const sorted = {}; for (const key of Object.keys(obj).sort()) sorted[key] = obj[key]; return sorted; } function displayTime(time) { if (time < 1e3) return `${time}ms`; time = time / 1e3; if (time < 60) return `${time.toFixed(2)}s`; const mins = Math.floor(time / 60); const seconds = Math.round(time % 60); if (seconds === 60) return `${mins + 1}m`; return `${mins}m${seconds < 1 ? "" : ` ${seconds}s`}`; } /** * Encodes the URI path portion (ignores part after ? or #) */ function encodeURIPath(uri) { if (uri.startsWith("data:")) return uri; const filePath = cleanUrl(uri); const postfix = filePath !== uri ? uri.slice(filePath.length) : ""; return encodeURI(filePath) + postfix; } /** * Like `encodeURIPath`, but only replacing `%` as `%25`. This is useful for environments * that can handle un-encoded URIs, where `%` is the only ambiguous character. */ function partialEncodeURIPath(uri) { if (uri.startsWith("data:")) return uri; const filePath = cleanUrl(uri); const postfix = filePath !== uri ? uri.slice(filePath.length) : ""; return filePath.replaceAll("%", "%25") + postfix; } function decodeURIIfPossible(input) { try { return decodeURI(input); } catch { return; } } const sigtermCallbacks = /* @__PURE__ */ new Set(); const parentSigtermCallback = async (signal, exitCode) => { await Promise.all([...sigtermCallbacks].map((cb) => cb(signal, exitCode))); }; const setupSIGTERMListener = (callback) => { if (sigtermCallbacks.size === 0) { process.once("SIGTERM", parentSigtermCallback); if (process.env.CI !== "true") process.stdin.on("end", parentSigtermCallback); } sigtermCallbacks.add(callback); }; const teardownSIGTERMListener = (callback) => { sigtermCallbacks.delete(callback); if (sigtermCallbacks.size === 0) { process.off("SIGTERM", parentSigtermCallback); if (process.env.CI !== "true") process.stdin.off("end", parentSigtermCallback); } }; function getServerUrlByHost(resolvedUrls, host) { if (typeof host === "string") { const matchedUrl = [...resolvedUrls?.local ?? [], ...resolvedUrls?.network ?? []].find((url$3) => url$3.includes(host)); if (matchedUrl) return matchedUrl; } return resolvedUrls?.local[0] ?? resolvedUrls?.network[0]; } let lastDateNow = 0; /** * Similar to `Date.now()`, but strictly monotonically increasing. * * This function will never return the same value. * Thus, the value may differ from the actual time. * * related: https://github.com/vitejs/vite/issues/19804 */ function monotonicDateNow() { const now = Date.now(); if (now > lastDateNow) { lastDateNow = now; return lastDateNow; } lastDateNow++; return lastDateNow; } //#endregion //#region src/node/plugin.ts async function resolveEnvironmentPlugins(environment) { const environmentPlugins = []; for (const plugin of environment.getTopLevelConfig().plugins) { if (plugin.applyToEnvironment) { const applied = await plugin.applyToEnvironment(environment); if (!applied) continue; if (applied !== true) { environmentPlugins.push(...(await asyncFlatten(arraify(applied))).filter(Boolean)); continue; } } environmentPlugins.push(plugin); } return environmentPlugins; } /** * @experimental */ function perEnvironmentPlugin(name, applyToEnvironment) { return { name, applyToEnvironment }; } //#endregion //#region ../../node_modules/.pnpm/commondir@1.0.1/node_modules/commondir/index.js var require_commondir = /* @__PURE__ */ __commonJS({ "../../node_modules/.pnpm/commondir@1.0.1/node_modules/commondir/index.js": ((exports, module) => { var path$12 = __require("path"); module.exports = function(basedir, relfiles) { if (relfiles) var files = relfiles.map(function(r$1) { return path$12.resolve(basedir, r$1); }); else var files = basedir; var res = files.slice(1).reduce(function(ps, file) { if (!file.match(/^([A-Za-z]:)?\/|\\/)) throw new Error("relative path without a basedir"); var xs = file.split(/\/+|\\+/); for (var i$1 = 0; ps[i$1] === xs[i$1] && i$1 < Math.min(ps.length, xs.length); i$1++); return ps.slice(0, i$1); }, files[0].split(/\/+|\\+/)); return res.length > 1 ? res.join("/") : "/"; }; }) }); //#endregion //#region ../../node_modules/.pnpm/magic-string@0.30.19/node_modules/magic-string/dist/magic-string.es.mjs var BitSet = class BitSet { constructor(arg) { this.bits = arg instanceof BitSet ? arg.bits.slice() : []; } add(n$2) { this.bits[n$2 >> 5] |= 1 << (n$2 & 31); } has(n$2) { return !!(this.bits[n$2 >> 5] & 1 << (n$2 & 31)); } }; var Chunk = class Chunk { constructor(start, end, content) { this.start = start; this.end = end; this.original = content; this.intro = ""; this.outro = ""; this.content = content; this.storeName = false; this.edited = false; this.previous = null; this.next = null; } appendLeft(content) { this.outro += content; } appendRight(content) { this.intro = this.intro + content; } clone() { const chunk = new Chunk(this.start, this.end, this.original); chunk.intro = this.intro; chunk.outro = this.outro; chunk.content = this.content; chunk.storeName = this.storeName; chunk.edited = this.edited; return chunk; } contains(index) { return this.start < index && index < this.end; } eachNext(fn) { let chunk = this; while (chunk) { fn(chunk); chunk = chunk.next; } } eachPrevious(fn) { let chunk = this; while (chunk) { fn(chunk); chunk = chunk.previous; } } edit(content, storeName, contentOnly) { this.content = content; if (!contentOnly) { this.intro = ""; this.outro = ""; } this.storeName = storeName; this.edited = true; return this; } prependLeft(content) { this.outro = content + this.outro; } prependRight(content) { this.intro = content + this.intro; } reset() { this.intro = ""; this.outro = ""; if (this.edited) { this.content = this.original; this.storeName = false; this.edited = false; } } split(index) { const sliceIndex = index - this.start; const originalBefore = this.original.slice(0, sliceIndex); const originalAfter = this.original.slice(sliceIndex); this.original = originalBefore; const newChunk = new Chunk(index, this.end, originalAfter); newChunk.outro = this.outro; this.outro = ""; this.end = index; if (this.edited) { newChunk.edit("", false); this.content = ""; } else this.content = originalBefore; newChunk.next = this.next; if (newChunk.next) newChunk.next.previous = newChunk; newChunk.previous = this; this.next = newChunk; return newChunk; } toString() { return this.intro + this.content + this.outro; } trimEnd(rx) { this.outro = this.outro.replace(rx, ""); if (this.outro.length) return true; const trimmed = this.content.replace(rx, ""); if (trimmed.length) { if (trimmed !== this.content) { this.split(this.start + trimmed.length).edit("", void 0, true); if (this.edited) this.edit(trimmed, this.storeName, true); } return true; } else { this.edit("", void 0, true); this.intro = this.intro.replace(rx, ""); if (this.intro.length) return true; } } trimStart(rx) { this.intro = this.intro.replace(rx, ""); if (this.intro.length) return true; const trimmed = this.content.replace(rx, ""); if (trimmed.length) { if (trimmed !== this.content) { const newChunk = this.split(this.end - trimmed.length); if (this.edited) newChunk.edit(trimmed, this.storeName, true); this.edit("", void 0, true); } return true; } else { this.edit("", void 0, true); this.outro = this.outro.replace(rx, ""); if (this.outro.length) return true; } } }; function getBtoa() { if (typeof globalThis !== "undefined" && typeof globalThis.btoa === "function") return (str) => globalThis.btoa(unescape(encodeURIComponent(str))); else if (typeof Buffer === "function") return (str) => Buffer.from(str, "utf-8").toString("base64"); else return () => { throw new Error("Unsupported environment: `window.btoa` or `Buffer` should be supported."); }; } const btoa$1 = /* @__PURE__ */ getBtoa(); var SourceMap = class { constructor(properties) { this.version = 3; this.file = properties.file; this.sources = properties.sources; this.sourcesContent = properties.sourcesContent; this.names = properties.names; this.mappings = encode$1(properties.mappings); if (typeof properties.x_google_ignoreList !== "undefined") this.x_google_ignoreList = properties.x_google_ignoreList; if (typeof properties.debugId !== "undefined") this.debugId = properties.debugId; } toString() { return JSON.stringify(this); } toUrl() { return "data:application/json;charset=utf-8;base64," + btoa$1(this.toString()); } }; function guessIndent(code) { const lines = code.split("\n"); const tabbed = lines.filter((line) => /^\t+/.test(line)); const spaced = lines.filter((line) => /^ {2,}/.test(line)); if (tabbed.length === 0 && spaced.length === 0) return null; if (tabbed.length >= spaced.length) return " "; const min$1 = spaced.reduce((previous, current) => { const numSpaces = /^ +/.exec(current)[0].length; return Math.min(numSpaces, previous); }, Infinity); return new Array(min$1 + 1).join(" "); } function getRelativePath(from, to) { const fromParts = from.split(/[/\\]/); const toParts = to.split(/[/\\]/); fromParts.pop(); while (fromParts[0] === toParts[0]) { fromParts.shift(); toParts.shift(); } if (fromParts.length) { let i$1 = fromParts.length; while (i$1--) fromParts[i$1] = ".."; } return fromParts.concat(toParts).join("/"); } const toString$1 = Object.prototype.toString; function isObject$2(thing) { return toString$1.call(thing) === "[object Object]"; } function getLocator(source) { const originalLines = source.split("\n"); const lineOffsets = []; for (let i$1 = 0, pos = 0; i$1 < originalLines.length; i$1++) { lineOffsets.push(pos); pos += originalLines[i$1].length + 1; } return function locate(index) { let i$1 = 0; let j = lineOffsets.length; while (i$1 < j) { const m$2 = i$1 + j >> 1; if (index < lineOffsets[m$2]) j = m$2; else i$1 = m$2 + 1; } const line = i$1 - 1; return { line, column: index - lineOffsets[line] }; }; } const wordRegex = /\w/; var Mappings = class { constructor(hires) { this.hires = hires; this.generatedCodeLine = 0; this.generatedCodeColumn = 0; this.raw = []; this.rawSegments = this.raw[this.generatedCodeLine] = []; this.pending = null; } addEdit(sourceIndex, content, loc, nameIndex) { if (content.length) { const contentLengthMinusOne = content.length - 1; let contentLineEnd = content.indexOf("\n", 0); let previousContentLineEnd = -1; while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) { const segment$1 = [ this.generatedCodeColumn, sourceIndex, loc.line, loc.column ]; if (nameIndex >= 0) segment$1.push(nameIndex); this.rawSegments.push(segment$1); this.generatedCodeLine += 1; this.raw[this.generatedCodeLine] = this.rawSegments = []; this.generatedCodeColumn = 0; previousContentLineEnd = contentLineEnd; contentLineEnd = content.indexOf("\n", contentLineEnd + 1); } const segment = [ this.generatedCodeColumn, sourceIndex, loc.line, loc.column ]; if (nameIndex >= 0) segment.push(nameIndex); this.rawSegments.push(segment); this.advance(content.slice(previousContentLineEnd + 1)); } else if (this.pending) { this.rawSegments.push(this.pending); this.advance(content); } this.pending = null; } addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) { let originalCharIndex = chunk.start; let first$2 = true; let charInHiresBoundary = false; while (originalCharIndex < chunk.end) { if (original[originalCharIndex] === "\n") { loc.line += 1; loc.column = 0; this.generatedCodeLine += 1; this.raw[this.generatedCodeLine] = this.rawSegments = []; this.generatedCodeColumn = 0; first$2 = true; charInHiresBoundary = false; } else { if (this.hires || first$2 || sourcemapLocations.has(originalCharIndex)) { const segment = [ this.generatedCodeColumn, sourceIndex, loc.line, loc.column ]; if (this.hires === "boundary") if (wordRegex.test(original[originalCharIndex])) { if (!charInHiresBoundary) { this.rawSegments.push(segment); charInHiresBoundary = true; } } else { this.rawSegments.push(segment); charInHiresBoundary = false; } else this.rawSegments.push(segment); } loc.column += 1; this.generatedCodeColumn += 1; first$2 = false; } originalCharIndex += 1; } this.pending = null; } advance(str) { if (!str) return; const lines = str.split("\n"); if (lines.length > 1) { for (let i$1 = 0; i$1 < lines.length - 1; i$1++) { this.generatedCodeLine++; this.raw[this.generatedCodeLine] = this.rawSegments = []; } this.generatedCodeColumn = 0; } this.generatedCodeColumn += lines[lines.length - 1].length; } }; const n$1 = "\n"; const warned = { insertLeft: false, insertRight: false, storeName: false }; var MagicString = class MagicString { constructor(string, options$1 = {}) { const chunk = new Chunk(0, string.length, string); Object.defineProperties(this, { original: { writable: true, value: string }, outro: { writable: true, value: "" }, intro: { writable: true, value: "" }, firstChunk: { writable: true, value: chunk }, lastChunk: { writable: true, value: chunk }, lastSearchedChunk: { writable: true, value: chunk }, byStart: { writable: true, value: {} }, byEnd: { writable: true, value: {} }, filename: { writable: true, value: options$1.filename }, indentExclusionRanges: { writable: true, value: options$1.indentExclusionRanges }, sourcemapLocations: { writable: true, value: new BitSet() }, storedNames: { writable: true, value: {} }, indentStr: { writable: true, value: void 0 }, ignoreList: { writable: true, value: options$1.ignoreList }, offset: { writable: true, value: options$1.offset || 0 } }); this.byStart[0] = chunk; this.byEnd[string.length] = chunk; } addSourcemapLocation(char) { this.sourcemapLocations.add(char); } append(content) { if (typeof content !== "string") throw new TypeError("outro content must be a string"); this.outro += content; return this; } appendLeft(index, content) { index = index + this.offset; if (typeof content !== "string") throw new TypeError("inserted content must be a string"); this._split(index); const chunk = this.byEnd[index]; if (chunk) chunk.appendLeft(content); else this.intro += content; return this; } appendRight(index, content) { index = index + this.offset; if (typeof content !== "string") throw new TypeError("inserted content must be a string"); this._split(index); const chunk = this.byStart[index]; if (chunk) chunk.appendRight(content); else this.outro += content; return this; } clone() { const cloned = new MagicString(this.original, { filename: this.filename, offset: this.offset }); let originalChunk = this.firstChunk; let clonedChunk = cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone(); while (originalChunk) { cloned.byStart[clonedChunk.start] = clonedChunk; cloned.byEnd[clonedChunk.end] = clonedChunk; const nextOriginalChunk = originalChunk.next; const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone(); if (nextClonedChunk) { clonedChunk.next = nextClonedChunk; nextClonedChunk.previous = clonedChunk; clonedChunk = nextClonedChunk; } originalChunk = nextOriginalChunk; } cloned.lastChunk = clonedChunk; if (this.indentExclusionRanges) cloned.indentExclusionRanges = this.indentExclusionRanges.slice(); cloned.sourcemapLocations = new BitSet(this.sourcemapLocations); cloned.intro = this.intro; cloned.outro = this.outro; return cloned; } generateDecodedMap(options$1) { options$1 = options$1 || {}; const sourceIndex = 0; const names = Object.keys(this.storedNames); const mappings = new Mappings(options$1.hires); const locate = getLocator(this.original); if (this.intro) mappings.advance(this.intro); this.firstChunk.eachNext((chunk) => { const loc = locate(chunk.start); if (chunk.intro.length) mappings.advance(chunk.intro); if (chunk.edited) mappings.addEdit(sourceIndex, chunk.content, loc, chunk.storeName ? names.indexOf(chunk.original) : -1); else mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations); if (chunk.outro.length) mappings.advance(chunk.outro); }); if (this.outro) mappings.advance(this.outro); return { file: options$1.file ? options$1.file.split(/[/\\]/).pop() : void 0, sources: [options$1.source ? getRelativePath(options$1.file || "", options$1.source) : options$1.file || ""], sourcesContent: options$1.includeContent ? [this.original] : void 0, names, mappings: mappings.raw, x_google_ignoreList: this.ignoreList ? [sourceIndex] : void 0 }; } generateMap(options$1) { return new SourceMap(this.generateDecodedMap(options$1)); } _ensureindentStr() { if (this.indentStr === void 0) this.indentStr = guessIndent(this.original); } _getRawIndentString() { this._ensureindentStr(); return this.indentStr; } getIndentString() { this._ensureindentStr(); return this.indentStr === null ? " " : this.indentStr; } indent(indentStr, options$1) { const pattern = /^[^\r\n]/gm; if (isObject$2(indentStr)) { options$1 = indentStr; indentStr = void 0; } if (indentStr === void 0) { this._ensureindentStr(); indentStr = this.indentStr || " "; } if (indentStr === "") return this; options$1 = options$1 || {}; const isExcluded = {}; if (options$1.exclude) (typeof options$1.exclude[0] === "number" ? [options$1.exclude] : options$1.exclude).forEach((exclusion) => { for (let i$1 = exclusion[0]; i$1 < exclusion[1]; i$1 += 1) isExcluded[i$1] = true; }); let shouldIndentNextCharacter = options$1.indentStart !== false; const replacer = (match) => { if (shouldIndentNextCharacter) return `${indentStr}${match}`; shouldIndentNextCharacter = true; return match; }; this.intro = this.intro.replace(pattern, replacer); let charIndex = 0; let chunk = this.firstChunk; while (chunk) { const end = chunk.end; if (chunk.edited) { if (!isExcluded[charIndex]) { chunk.content = chunk.content.replace(pattern, replacer); if (chunk.content.length) shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === "\n"; } } else { charIndex = chunk.start; while (charIndex < end) { if (!isExcluded[charIndex]) { const char = this.original[charIndex]; if (char === "\n") shouldIndentNextCharacter = true; else if (char !== "\r" && shouldIndentNextCharacter) { shouldIndentNextCharacter = false; if (charIndex === chunk.start) chunk.prependRight(indentStr); else { this._splitChunk(chunk, charIndex); chunk = chunk.next; chunk.prependRight(indentStr); } } } charIndex += 1; } } charIndex = chunk.end; chunk = chunk.next; } this.outro = this.outro.replace(pattern, replacer); return this; } insert() { throw new Error("magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)"); } insertLeft(index, content) { if (!warned.insertLeft) { console.warn("magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead"); warned.insertLeft = true; } return this.appendLeft(index, content); } insertRight(index, content) { if (!warned.insertRight) { console.warn("magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead"); warned.insertRight = true; } return this.prependRight(index, content); } move(start, end, index) { start = start + this.offset; end = end + this.offset; index = index + this.offset; if (index >= start && index <= end) throw new Error("Cannot move a selection inside itself"); this._split(start); this._split(end); this._split(index); const first$2 = this.byStart[start]; const last = this.byEnd[end]; const oldLeft = first$2.previous; const oldRight = last.next; const newRight = this.byStart[index]; if (!newRight && last === this.lastChunk) return this; const newLeft = newRight ? newRight.previous : this.lastChunk; if (oldLeft) oldLeft.next = oldRight; if (oldRight) oldRight.previous = oldLeft; if (newLeft) newLeft.next = first$2; if (newRight) newRight.previous = last; if (!first$2.previous) this.firstChunk = last.next; if (!last.next) { this.lastChunk = first$2.previous; this.lastChunk.next = null; } first$2.previous = newLeft; last.next = newRight || null; if (!newLeft) this.firstChunk = first$2; if (!newRight) this.lastChunk = last; return this; } overwrite(start, end, content, options$1) { options$1 = options$1 || {}; return this.update(start, end, content, { ...options$1, overwrite: !options$1.contentOnly }); } update(start, end, content, options$1) { start = start + this.offset; end = end + this.offset; if (typeof content !== "string") throw new TypeError("replacement content must be a string"); if (this.original.length !== 0) { while (start < 0) start += this.original.length; while (end < 0) end += this.original.length; } if (end > this.original.length) throw new Error("end is out of bounds"); if (start === end) throw new Error("Cannot overwrite a zero-length range – use appendLeft or prependRight instead"); this._split(start); this._split(end); if (options$1 === true) { if (!warned.storeName) { console.warn("The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string"); warned.storeName = true; } options$1 = { storeName: true }; } const storeName = options$1 !== void 0 ? options$1.storeName : false; const overwrite = options$1 !== void 0 ? options$1.overwrite : false; if (storeName) { const original = this.original.slice(start, end); Object.defineProperty(this.storedNames, original, { writable: true, value: true, enumerable: true }); } const first$2 = this.byStart[start]; const last = this.byEnd[end]; if (first$2) { let chunk = first$2; while (chunk !== last) { if (chunk.next !== this.byStart[chunk.end]) throw new Error("Cannot overwrite across a split point"); chunk = chunk.next; chunk.edit("", false); } first$2.edit(content, storeName, !overwrite); } else { const newChunk = new Chunk(start, end, "").edit(content, storeName); last.next = newChunk; newChunk.previous = last; } return this; } prepend(content) { if (typeof content !== "string") throw new TypeError("outro content must be a string"); this.intro = content + this.intro; return this; } prependLeft(index, content) { index = index + this.offset; if (typeof content !== "string") throw new TypeError("inserted content must be a string"); this._split(index); const chunk = this.byEnd[index]; if (chunk) chunk.prependLeft(content); else this.intro = content + this.intro; return this; } prependRight(index, content) { index = index + this.offset; if (typeof content !== "string") throw new TypeError("inserted content must be a string"); this._split(index); const chunk = this.byStart[index]; if (chunk) chunk.prependRight(content); else this.outro = content + this.outro; return this; } remove(start, end) { start = start + this.offset; end = end + this.offset; if (this.original.length !== 0) { while (start < 0) start += this.original.length; while (end < 0) end += this.original.length; } if (start === end) return this; if (start < 0 || end > this.original.length) throw new Error("Character is out of bounds"); if (start > end) throw new Error("end must be greater than start"); this._split(start); this._split(end); let chunk = this.byStart[start]; while (chunk) { chunk.intro = ""; chunk.outro = ""; chunk.edit(""); chunk = end > chunk.end ? this.byStart[chunk.end] : null; } return this; } reset(start, end) { start = start + this.offset; end = end + this.offset; if (this.original.length !== 0) { while (start < 0) start += this.original.length; while (end < 0) end += this.original.length; } if (start === end) return this; if (start < 0 || end > this.original.length) throw new Error("Character is out of bounds"); if (start > end) throw new Error("end must be greater than start"); this._split(start); this._split(end); let chunk = this.byStart[start]; while (chunk) { chunk.reset(); chunk = end > chunk.end ? this.byStart[chunk.end] : null; } return this; } lastChar() { if (this.outro.length) return this.outro[this.outro.length - 1]; let chunk = this.lastChunk; do { if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1]; if (chunk.content.length) return chunk.content[chunk.content.length - 1]; if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1]; } while (chunk = chunk.previous); if (this.intro.length) return this.intro[this.intro.length - 1]; return ""; } lastLine() { let lineIndex = this.outro.lastIndexOf(n$1); if (lineIndex !== -1) return this.outro.substr(lineIndex + 1); let lineStr = this.outro; let chunk = this.lastChunk; do { if (chunk.outro.length > 0) { lineIndex = chunk.outro.lastIndexOf(n$1); if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr; lineStr = chunk.outro + lineStr; } if (chunk.content.length > 0) { lineIndex = chunk.content.lastIndexOf(n$1); if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr; lineStr = chunk.content + lineStr; } if (chunk.intro.length > 0) { lineIndex = chunk.intro.lastIndexOf(n$1); if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr; lineStr = chunk.intro + lineStr; } } while (chunk = chunk.previous); lineIndex = this.intro.lastIndexOf(n$1); if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr; return this.intro + lineStr; } slice(start = 0, end = this.original.length - this.offset) { start = start + this.offset; end = end + this.offset; if (this.original.length !== 0) { while (start < 0) start += this.original.length; while (end < 0) end += this.original.length; } let result = ""; let chunk = this.firstChunk; while (chunk && (chunk.start > start || chunk.end <= start)) { if (chunk.start < end && chunk.end >= end) return result; chunk = chunk.next; } if (chunk && chunk.edited && chunk.start !== start) throw new Error(`Cannot use replaced character ${start} as slice start anchor.`); const startChunk = chunk; while (chunk) { if (chunk.intro && (startChunk !== chunk || chunk.start === start)) result += chunk.intro; const containsEnd = chunk.start < end && chunk.end >= end; if (containsEnd && chunk.edited && chunk.end !== end) throw new Error(`Cannot use replaced character ${end} as slice end anchor.`); const sliceStart = startChunk === chunk ? start - chunk.start : 0; const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length; result += chunk.content.slice(sliceStart, sliceEnd); if (chunk.outro && (!containsEnd || chunk.end === end)) result += chunk.outro; if (containsEnd) break; chunk = chunk.next; } return result; } snip(start, end) { const clone$1 = this.clone(); clone$1.remove(0, start); clone$1.remove(end, clone$1.original.length); return clone$1; } _split(index) { if (this.byStart[index] || this.byEnd[index]) return; let chunk = this.lastSearchedChunk; let previousChunk = chunk; const searchForward = index > chunk.end; while (chunk) { if (chunk.contains(index)) return this._splitChunk(chunk, index); chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start]; if (chunk === previousChunk) return; previousChunk = chunk; } } _splitChunk(chunk, index) { if (chunk.edited && chunk.content.length) { const loc = getLocator(this.original)(index); throw new Error(`Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`); } const newChunk = chunk.split(index); this.byEnd[index] = chunk; this.byStart[index] = newChunk; this.byEnd[newChunk.end] = newChunk; if (chunk === this.lastChunk) this.lastChunk = newChunk; this.lastSearchedChunk = chunk; return true; } toString() { let str = this.intro; let chunk = this.firstChunk; while (chunk) { str += chunk.toString(); chunk = chunk.next; } return str + this.outro; } isEmpty() { let chunk = this.firstChunk; do if (chunk.intro.length && chunk.intro.trim() || chunk.content.length && chunk.content.trim() || chunk.outro.length && chunk.outro.trim()) return false; while (chunk = chunk.next); return true; } length() { let chunk = this.firstChunk; let length = 0; do length += chunk.intro.length + chunk.content.length + chunk.outro.length; while (chunk = chunk.next); return length; } trimLines() { return this.trim("[\\r\\n]"); } trim(charType) { return this.trimStart(charType).trimEnd(charType); } trimEndAborted(charType) { const rx = /* @__PURE__ */ new RegExp((charType || "\\s") + "+$"); this.outro = this.outro.replace(rx, ""); if (this.outro.length) return true; let chunk = this.lastChunk; do { const end = chunk.end; const aborted = chunk.trimEnd(rx); if (chunk.end !== end) { if (this.lastChunk === chunk) this.lastChunk = chunk.next; this.byEnd[chunk.end] = chunk; this.byStart[chunk.next.start] = chunk.next; this.byEnd[chunk.next.end] = chunk.next; } if (aborted) return true; chunk = chunk.previous; } while (chunk); return false; } trimEnd(charType) { this.trimEndAborted(charType); return this; } trimStartAborted(charType) { const rx = /* @__PURE__ */ new RegExp("^" + (charType || "\\s") + "+"); this.intro = this.intro.replace(rx, ""); if (this.intro.length) return true; let chunk = this.firstChunk; do { const end = chunk.end; const aborted = chunk.trimStart(rx); if (chunk.end !== end) { if (chunk === this.lastChunk) this.lastChunk = chunk.next; this.byEnd[chunk.end] = chunk; this.byStart[chunk.next.start] = chunk.next; this.byEnd[chunk.next.end] = chunk.next; } if (aborted) return true; chunk = chunk.next; } while (chunk); return false; } trimStart(charType) { this.trimStartAborted(charType); return this; } hasChanged() { return this.original !== this.toString(); } _replaceRegexp(searchValue, replacement) { function getReplacement(match, str) { if (typeof replacement === "string") return replacement.replace(/\$(\$|&|\d+)/g, (_, i$1) => { if (i$1 === "$") return "$"; if (i$1 === "&") return match[0]; if (+i$1 < match.length) return match[+i$1]; return `$${i$1}`; }); else return replacement(...match, match.index, str, match.groups); } function matchAll$1(re, str) { let match; const matches$2 = []; while (match = re.exec(str)) matches$2.push(match); return matches$2; } if (searchValue.global) matchAll$1(searchValue, this.original).forEach((match) => { if (match.index != null) { const replacement$1 = getReplacement(match, this.original); if (replacement$1 !== match[0]) this.overwrite(match.index, match.index + match[0].length, replacement$1); } }); else { const match = this.original.match(searchValue); if (match && match.index != null) { const replacement$1 = getReplacement(match, this.original); if (replacement$1 !== match[0]) this.overwrite(match.index, match.index + match[0].length, replacement$1); } } return this; } _replaceString(string, replacement) { const { original } = this; const index = original.indexOf(string); if (index !== -1) { if (typeof replacement === "function") replacement = replacement(string, index, original); if (string !== replacement) this.overwrite(index, index + string.length, replacement); } return this; } replace(searchValue, replacement) { if (typeof searchValue === "string") return this._replaceString(searchValue, replacement); return this._replaceRegexp(searchValue, replacement); } _replaceAllString(string, replacement) { const { original } = this; const stringLength = string.length; for (let index = original.indexOf(string); index !== -1; index = original.indexOf(string, index + stringLength)) { const previous = original.slice(index, index + stringLength); let _replacement = replacement; if (typeof replacement === "function") _replacement = replacement(previous, index, original); if (previous !== _replacement) this.overwrite(index, index + stringLength, _replacement); } return this; } replaceAll(searchValue, replacement) { if (typeof searchValue === "string") return this._replaceAllString(searchValue, replacement); if (!searchValue.global) throw new TypeError("MagicString.prototype.replaceAll called with a non-global RegExp argument"); return this._replaceRegexp(searchValue, replacement); } }; //#endregion //#region ../../node_modules/.pnpm/is-reference@1.2.1/node_modules/is-reference/dist/is-reference.js var require_is_reference = /* @__PURE__ */ __commonJS({ "../../node_modules/.pnpm/is-reference@1.2.1/node_modules/is-reference/dist/is-reference.js": ((exports, module) => { (function(global$1, factory) { typeof exports === "object" && typeof module !== "undefined" ? module.exports = factory() : typeof define === "function" && define.amd ? define(factory) : (global$1 = global$1 || self, global$1.isReference = factory()); })(exports, (function() { function isReference$1(node, parent) { if (node.type === "MemberExpression") return !node.computed && isReference$1(node.object, node); if (node.type === "Identifier") { if (!parent) return true; switch (parent.type) { case "MemberExpression": return parent.computed || node === parent.object; case "MethodDefinition": return parent.computed; case "FieldDefinition": return parent.computed || node === parent.value; case "Property": return parent.computed || node === parent.value; case "ExportSpecifier": case "ImportSpecifier": return node === parent.local; case "LabeledStatement": case "BreakStatement": case "ContinueStatement": return false; default: return true; } } return false; } return isReference$1; })); }) }); //#endregion //#region ../../node_modules/.pnpm/@rollup+plugin-commonjs@28.0.6_rollup@4.43.0/node_modules/@rollup/plugin-commonjs/dist/es/index.js var import_commondir = /* @__PURE__ */ __toESM(require_commondir(), 1); var import_is_reference = /* @__PURE__ */ __toESM(require_is_reference(), 1); var version$1 = "28.0.6"; var peerDependencies = { rollup: "^2.68.0||^3.0.0||^4.0.0" }; function tryParse(parse$17, code, id) { try { return parse$17(code, { allowReturnOutsideFunction: true }); } catch (err$2) { err$2.message += ` in ${id}`; throw err$2; } } const firstpassGlobal = /\b(?:require|module|exports|global)\b/; const firstpassNoGlobal = /\b(?:require|module|exports)\b/; function hasCjsKeywords(code, ignoreGlobal) { return (ignoreGlobal ? firstpassNoGlobal : firstpassGlobal).test(code); } function analyzeTopLevelStatements(parse$17, code, id) { const ast = tryParse(parse$17, code, id); let isEsModule = false; let hasDefaultExport = false; let hasNamedExports = false; for (const node of ast.body) switch (node.type) { case "ExportDefaultDeclaration": isEsModule = true; hasDefaultExport = true; break; case "ExportNamedDeclaration": isEsModule = true; if (node.declaration) hasNamedExports = true; else for (const specifier of node.specifiers) if (specifier.exported.name === "default") hasDefaultExport = true; else hasNamedExports = true; break; case "ExportAllDeclaration": isEsModule = true; if (node.exported && node.exported.name === "default") hasDefaultExport = true; else hasNamedExports = true; break; case "ImportDeclaration": isEsModule = true; break; } return { isEsModule, hasDefaultExport, hasNamedExports, ast }; } function deconflict(scopes, globals, identifier) { let i$1 = 1; let deconflicted = makeLegalIdentifier(identifier); const hasConflicts = () => scopes.some((scope) => scope.contains(deconflicted)) || globals.has(deconflicted); while (hasConflicts()) { deconflicted = makeLegalIdentifier(`${identifier}_${i$1}`); i$1 += 1; } for (const scope of scopes) scope.declarations[deconflicted] = true; return deconflicted; } function getName(id) { const name = makeLegalIdentifier(basename$1(id, extname$1(id))); if (name !== "index") return name; return makeLegalIdentifier(basename$1(dirname$1(id))); } function normalizePathSlashes(path$13) { return path$13.replace(/\\/g, "/"); } const getVirtualPathForDynamicRequirePath = (path$13, commonDir) => `/${normalizePathSlashes(relative$1(commonDir, path$13))}`; function capitalize(name) { return name[0].toUpperCase() + name.slice(1); } function getStrictRequiresFilter({ strictRequires }) { switch (strictRequires) { case void 0: case true: return { strictRequiresFilter: () => true, detectCyclesAndConditional: false }; case "auto": case "debug": case null: return { strictRequiresFilter: () => false, detectCyclesAndConditional: true }; case false: return { strictRequiresFilter: () => false, detectCyclesAndConditional: false }; default: if (typeof strictRequires === "string" || Array.isArray(strictRequires)) return { strictRequiresFilter: createFilter$2(strictRequires), detectCyclesAndConditional: false }; throw new Error("Unexpected value for \"strictRequires\" option."); } } function getPackageEntryPoint(dirPath) { let entryPoint = "index.js"; try { if (existsSync$1(join$1(dirPath, "package.json"))) entryPoint = JSON.parse(readFileSync$1(join$1(dirPath, "package.json"), { encoding: "utf8" })).main || entryPoint; } catch (ignored) {} return entryPoint; } function isDirectory$1(path$13) { try { if (statSync(path$13).isDirectory()) return true; } catch (ignored) {} return false; } function getDynamicRequireModules(patterns, dynamicRequireRoot) { const dynamicRequireModules = /* @__PURE__ */ new Map(); const dirNames = /* @__PURE__ */ new Set(); for (const pattern of !patterns || Array.isArray(patterns) ? patterns || [] : [patterns]) { const isNegated = pattern.startsWith("!"); const modifyMap = (targetPath, resolvedPath) => isNegated ? dynamicRequireModules.delete(targetPath) : dynamicRequireModules.set(targetPath, resolvedPath); for (const path$13 of new fdir().withBasePath().withDirs().glob(isNegated ? pattern.substr(1) : pattern).crawl(relative$1(".", dynamicRequireRoot)).sync().sort((a, b) => a.localeCompare(b, "en"))) { const resolvedPath = resolve$1(path$13); const requirePath = normalizePathSlashes(resolvedPath); if (isDirectory$1(resolvedPath)) { dirNames.add(resolvedPath); const modulePath = resolve$1(join$1(resolvedPath, getPackageEntryPoint(path$13))); modifyMap(requirePath, modulePath); modifyMap(normalizePathSlashes(modulePath), modulePath); } else { dirNames.add(dirname$1(resolvedPath)); modifyMap(requirePath, resolvedPath); } } } return { commonDir: dirNames.size ? (0, import_commondir.default)([...dirNames, dynamicRequireRoot]) : null, dynamicRequireModules }; } const FAILED_REQUIRE_ERROR = `throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');`; const COMMONJS_REQUIRE_EXPORT = "commonjsRequire"; const CREATE_COMMONJS_REQUIRE_EXPORT = "createCommonjsRequire"; function getDynamicModuleRegistry(isDynamicRequireModulesEnabled, dynamicRequireModules, commonDir, ignoreDynamicRequires) { if (!isDynamicRequireModulesEnabled) return `export function ${COMMONJS_REQUIRE_EXPORT}(path) { ${FAILED_REQUIRE_ERROR} }`; return `${[...dynamicRequireModules.values()].map((id, index) => `import ${id.endsWith(".json") ? `json${index}` : `{ __require as require${index} }`} from ${JSON.stringify(id)};`).join("\n")} var dynamicModules; function getDynamicModules() { return dynamicModules || (dynamicModules = { ${[...dynamicRequireModules.keys()].map((id, index) => `\t\t${JSON.stringify(getVirtualPathForDynamicRequirePath(id, commonDir))}: ${id.endsWith(".json") ? `function () { return json${index}; }` : `require${index}`}`).join(",\n")} }); } export function ${CREATE_COMMONJS_REQUIRE_EXPORT}(originalModuleDir) { function handleRequire(path) { var resolvedPath = commonjsResolve(path, originalModuleDir); if (resolvedPath !== null) { return getDynamicModules()[resolvedPath](); } ${ignoreDynamicRequires ? "return require(path);" : FAILED_REQUIRE_ERROR} } handleRequire.resolve = function (path) { var resolvedPath = commonjsResolve(path, originalModuleDir); if (resolvedPath !== null) { return resolvedPath; } return require.resolve(path); } return handleRequire; } function commonjsResolve (path, originalModuleDir) { var shouldTryNodeModules = isPossibleNodeModulesPath(path); path = normalize(path); var relPath; if (path[0] === '/') { originalModuleDir = ''; } var modules = getDynamicModules(); var checkedExtensions = ['', '.js', '.json']; while (true) { if (!shouldTryNodeModules) { relPath = normalize(originalModuleDir + '/' + path); } else { relPath = normalize(originalModuleDir + '/node_modules/' + path); } if (relPath.endsWith('/..')) { break; // Travelled too far up, avoid infinite loop } for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) { var resolvedPath = relPath + checkedExtensions[extensionIndex]; if (modules[resolvedPath]) { return resolvedPath; } } if (!shouldTryNodeModules) break; var nextDir = normalize(originalModuleDir + '/..'); if (nextDir === originalModuleDir) break; originalModuleDir = nextDir; } return null; } function isPossibleNodeModulesPath (modulePath) { var c0 = modulePath[0]; if (c0 === '/' || c0 === '\\\\') return false; var c1 = modulePath[1], c2 = modulePath[2]; if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) || (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false; if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false; return true; } function normalize (path) { path = path.replace(/\\\\/g, '/'); var parts = path.split('/'); var slashed = parts[0] === ''; for (var i = 1; i < parts.length; i++) { if (parts[i] === '.' || parts[i] === '') { parts.splice(i--, 1); } } for (var i = 1; i < parts.length; i++) { if (parts[i] !== '..') continue; if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') { parts.splice(--i, 2); i--; } } path = parts.join('/'); if (slashed && path[0] !== '/') path = '/' + path; else if (path.length === 0) path = '.'; return path; }`; } const isWrappedId = (id, suffix) => id.endsWith(suffix); const wrapId$1 = (id, suffix) => `\0${id}${suffix}`; const unwrapId$1 = (wrappedId, suffix) => wrappedId.slice(1, -suffix.length); const PROXY_SUFFIX = "?commonjs-proxy"; const WRAPPED_SUFFIX = "?commonjs-wrapped"; const EXTERNAL_SUFFIX = "?commonjs-external"; const EXPORTS_SUFFIX = "?commonjs-exports"; const MODULE_SUFFIX = "?commonjs-module"; const ENTRY_SUFFIX = "?commonjs-entry"; const ES_IMPORT_SUFFIX = "?commonjs-es-import"; const DYNAMIC_MODULES_ID = "\0commonjs-dynamic-modules"; const HELPERS_ID = "\0commonjsHelpers.js"; const IS_WRAPPED_COMMONJS = "withRequireFunction"; const HELPERS = ` export var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; export function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } export function getDefaultExportFromNamespaceIfPresent (n) { return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n; } export function getDefaultExportFromNamespaceIfNotNamed (n) { return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n; } export function getAugmentedNamespace(n) { if (Object.prototype.hasOwnProperty.call(n, '__esModule')) return n; var f = n.default; if (typeof f == "function") { var a = function a () { var isInstance = false; try { isInstance = this instanceof a; } catch {} if (isInstance) { return Reflect.construct(f, arguments, this.constructor); } return f.apply(this, arguments); }; a.prototype = f.prototype; } else a = {}; Object.defineProperty(a, '__esModule', {value: true}); Object.keys(n).forEach(function (k) { var d = Object.getOwnPropertyDescriptor(n, k); Object.defineProperty(a, k, d.get ? d : { enumerable: true, get: function () { return n[k]; } }); }); return a; } `; function getHelpersModule() { return HELPERS; } function getUnknownRequireProxy(id, requireReturnsDefault) { if (requireReturnsDefault === true || id.endsWith(".json")) return `export { default } from ${JSON.stringify(id)};`; const name = getName(id); const exported = requireReturnsDefault === "auto" ? `import { getDefaultExportFromNamespaceIfNotNamed } from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfNotNamed(${name});` : requireReturnsDefault === "preferred" ? `import { getDefaultExportFromNamespaceIfPresent } from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfPresent(${name});` : !requireReturnsDefault ? `import { getAugmentedNamespace } from "${HELPERS_ID}"; export default /*@__PURE__*/getAugmentedNamespace(${name});` : `export default ${name};`; return `import * as ${name} from ${JSON.stringify(id)}; ${exported}`; } async function getStaticRequireProxy(id, requireReturnsDefault, loadModule) { const name = getName(id); const { meta: { commonjs: commonjsMeta } } = await loadModule({ id }); if (!commonjsMeta) return getUnknownRequireProxy(id, requireReturnsDefault); if (commonjsMeta.isCommonJS) return `export { __moduleExports as default } from ${JSON.stringify(id)};`; if (!requireReturnsDefault) return `import { getAugmentedNamespace } from "${HELPERS_ID}"; import * as ${name} from ${JSON.stringify(id)}; export default /*@__PURE__*/getAugmentedNamespace(${name});`; if (requireReturnsDefault !== true && (requireReturnsDefault === "namespace" || !commonjsMeta.hasDefaultExport || requireReturnsDefault === "auto" && commonjsMeta.hasNamedExports)) return `import * as ${name} from ${JSON.stringify(id)}; export default ${name};`; return `export { default } from ${JSON.stringify(id)};`; } function getEntryProxy(id, defaultIsModuleExports, getModuleInfo, shebang) { const { meta: { commonjs: commonjsMeta }, hasDefaultExport } = getModuleInfo(id); if (!commonjsMeta || commonjsMeta.isCommonJS !== IS_WRAPPED_COMMONJS) { const stringifiedId = JSON.stringify(id); let code = `export * from ${stringifiedId};`; if (hasDefaultExport) code += `export { default } from ${stringifiedId};`; return shebang + code; } const result = getEsImportProxy(id, defaultIsModuleExports, true); return { ...result, code: shebang + result.code }; } function getEsImportProxy(id, defaultIsModuleExports, moduleSideEffects) { const name = getName(id); const exportsName = `${name}Exports`; const requireModule = `require${capitalize(name)}`; let code = `import { getDefaultExportFromCjs } from "${HELPERS_ID}";\nimport { __require as ${requireModule} } from ${JSON.stringify(id)};\nvar ${exportsName} = ${moduleSideEffects ? "" : "/*@__PURE__*/ "}${requireModule}();\nexport { ${exportsName} as __moduleExports };`; if (defaultIsModuleExports === true) code += `\nexport { ${exportsName} as default };`; else if (defaultIsModuleExports === false) code += `\nexport default ${exportsName}.default;`; else code += `\nexport default /*@__PURE__*/getDefaultExportFromCjs(${exportsName});`; return { code, syntheticNamedExports: "__moduleExports" }; } function getCandidatesForExtension(resolved, extension$1) { return [resolved + extension$1, `${resolved}${sep$1}index${extension$1}`]; } function getCandidates(resolved, extensions$1) { return extensions$1.reduce((paths, extension$1) => paths.concat(getCandidatesForExtension(resolved, extension$1)), [resolved]); } function resolveExtensions(importee, importer, extensions$1) { if (importee[0] !== "." || !importer) return void 0; const candidates = getCandidates(resolve$1(dirname$1(importer), importee), extensions$1); for (let i$1 = 0; i$1 < candidates.length; i$1 += 1) try { if (statSync(candidates[i$1]).isFile()) return { id: candidates[i$1] }; } catch (err$2) {} } function getResolveId(extensions$1, isPossibleCjsId) { const currentlyResolving = /* @__PURE__ */ new Map(); return { currentlyResolving, async resolveId(importee, importer, resolveOptions) { if (resolveOptions.custom?.["node-resolve"]?.isRequire) return null; const currentlyResolvingForParent = currentlyResolving.get(importer); if (currentlyResolvingForParent && currentlyResolvingForParent.has(importee)) { this.warn({ code: "THIS_RESOLVE_WITHOUT_OPTIONS", message: "It appears a plugin has implemented a \"resolveId\" hook that uses \"this.resolve\" without forwarding the third \"options\" parameter of \"resolveId\". This is problematic as it can lead to wrong module resolutions especially for the node-resolve plugin and in certain cases cause early exit errors for the commonjs plugin.\nIn rare cases, this warning can appear if the same file is both imported and required from the same mixed ES/CommonJS module, in which case it can be ignored.", url: "https://rollupjs.org/guide/en/#resolveid" }); return null; } if (isWrappedId(importee, WRAPPED_SUFFIX)) return unwrapId$1(importee, WRAPPED_SUFFIX); if (importee.endsWith(ENTRY_SUFFIX) || isWrappedId(importee, MODULE_SUFFIX) || isWrappedId(importee, EXPORTS_SUFFIX) || isWrappedId(importee, PROXY_SUFFIX) || isWrappedId(importee, ES_IMPORT_SUFFIX) || isWrappedId(importee, EXTERNAL_SUFFIX) || importee.startsWith(HELPERS_ID) || importee === DYNAMIC_MODULES_ID) return importee; if (importer) { if (importer === DYNAMIC_MODULES_ID || isWrappedId(importer, PROXY_SUFFIX) || isWrappedId(importer, ES_IMPORT_SUFFIX) || importer.endsWith(ENTRY_SUFFIX)) return importee; if (isWrappedId(importer, EXTERNAL_SUFFIX)) { if (!await this.resolve(importee, importer, Object.assign({ skipSelf: true }, resolveOptions))) return null; return { id: importee, external: true }; } } if (importee.startsWith("\0")) return null; const resolved = await this.resolve(importee, importer, Object.assign({ skipSelf: true }, resolveOptions)) || resolveExtensions(importee, importer, extensions$1); if (!resolved || resolved.external || resolved.id.endsWith(ENTRY_SUFFIX) || isWrappedId(resolved.id, ES_IMPORT_SUFFIX) || !isPossibleCjsId(resolved.id)) return resolved; const moduleInfo = await this.load(resolved); const { meta: { commonjs: commonjsMeta } } = moduleInfo; if (commonjsMeta) { const { isCommonJS } = commonjsMeta; if (isCommonJS) { if (resolveOptions.isEntry) { moduleInfo.moduleSideEffects = true; return resolved.id + ENTRY_SUFFIX; } if (isCommonJS === IS_WRAPPED_COMMONJS) return { id: wrapId$1(resolved.id, ES_IMPORT_SUFFIX), meta: { commonjs: { resolved } } }; } } return resolved; } }; } function getRequireResolver(extensions$1, detectCyclesAndConditional, currentlyResolving) { const knownCjsModuleTypes = Object.create(null); const requiredIds = Object.create(null); const unconditionallyRequiredIds = Object.create(null); const dependencies = Object.create(null); const getDependencies = (id) => dependencies[id] || (dependencies[id] = /* @__PURE__ */ new Set()); const isCyclic = (id) => { const dependenciesToCheck = new Set(getDependencies(id)); for (const dependency of dependenciesToCheck) { if (dependency === id) return true; for (const childDependency of getDependencies(dependency)) dependenciesToCheck.add(childDependency); } return false; }; const fullyAnalyzedModules = Object.create(null); const getTypeForFullyAnalyzedModule = (id) => { const knownType = knownCjsModuleTypes[id]; if (knownType !== true || !detectCyclesAndConditional || fullyAnalyzedModules[id]) return knownType; if (isCyclic(id)) return knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS; return knownType; }; const setInitialParentType = (id, initialCommonJSType) => { if (fullyAnalyzedModules[id]) return; knownCjsModuleTypes[id] = initialCommonJSType; if (detectCyclesAndConditional && knownCjsModuleTypes[id] === true && requiredIds[id] && !unconditionallyRequiredIds[id]) knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS; }; const analyzeRequiredModule = async (parentId, resolved, isConditional, loadModule) => { const childId = resolved.id; requiredIds[childId] = true; if (!(isConditional || knownCjsModuleTypes[parentId] === IS_WRAPPED_COMMONJS)) unconditionallyRequiredIds[childId] = true; getDependencies(parentId).add(childId); if (!isCyclic(childId)) await loadModule(resolved); }; const getTypeForImportedModule = async (resolved, loadModule) => { if (resolved.id in knownCjsModuleTypes) return knownCjsModuleTypes[resolved.id]; const { meta: { commonjs: commonjs$1 } } = await loadModule(resolved); return commonjs$1 && commonjs$1.isCommonJS || false; }; return { getWrappedIds: () => Object.keys(knownCjsModuleTypes).filter((id) => knownCjsModuleTypes[id] === IS_WRAPPED_COMMONJS), isRequiredId: (id) => requiredIds[id], async shouldTransformCachedModule({ id: parentId, resolvedSources, meta: { commonjs: parentMeta } }) { if (!(parentMeta && parentMeta.isCommonJS)) knownCjsModuleTypes[parentId] = false; if (isWrappedId(parentId, ES_IMPORT_SUFFIX)) return false; const parentRequires = parentMeta && parentMeta.requires; if (parentRequires) { setInitialParentType(parentId, parentMeta.initialCommonJSType); await Promise.all(parentRequires.map(({ resolved, isConditional }) => analyzeRequiredModule(parentId, resolved, isConditional, this.load))); if (getTypeForFullyAnalyzedModule(parentId) !== parentMeta.isCommonJS) return true; for (const { resolved: { id } } of parentRequires) if (getTypeForFullyAnalyzedModule(id) !== parentMeta.isRequiredCommonJS[id]) return true; fullyAnalyzedModules[parentId] = true; for (const { resolved: { id } } of parentRequires) fullyAnalyzedModules[id] = true; } const parentRequireSet = new Set((parentRequires || []).map(({ resolved: { id } }) => id)); return (await Promise.all(Object.keys(resolvedSources).map((source) => resolvedSources[source]).filter(({ id, external }) => !(external || parentRequireSet.has(id))).map(async (resolved) => { if (isWrappedId(resolved.id, ES_IMPORT_SUFFIX)) return await getTypeForImportedModule((await this.load(resolved)).meta.commonjs.resolved, this.load) !== IS_WRAPPED_COMMONJS; return await getTypeForImportedModule(resolved, this.load) === IS_WRAPPED_COMMONJS; }))).some((shouldTransform) => shouldTransform); }, resolveRequireSourcesAndUpdateMeta: (rollupContext) => async (parentId, isParentCommonJS, parentMeta, sources) => { parentMeta.initialCommonJSType = isParentCommonJS; parentMeta.requires = []; parentMeta.isRequiredCommonJS = Object.create(null); setInitialParentType(parentId, isParentCommonJS); const currentlyResolvingForParent = currentlyResolving.get(parentId) || /* @__PURE__ */ new Set(); currentlyResolving.set(parentId, currentlyResolvingForParent); const requireTargets = await Promise.all(sources.map(async ({ source, isConditional }) => { if (source.startsWith("\0")) return { id: source, allowProxy: false }; currentlyResolvingForParent.add(source); const resolved = await rollupContext.resolve(source, parentId, { skipSelf: false, custom: { "node-resolve": { isRequire: true } } }) || resolveExtensions(source, parentId, extensions$1); currentlyResolvingForParent.delete(source); if (!resolved) return { id: wrapId$1(source, EXTERNAL_SUFFIX), allowProxy: false }; const childId = resolved.id; if (resolved.external) return { id: wrapId$1(childId, EXTERNAL_SUFFIX), allowProxy: false }; parentMeta.requires.push({ resolved, isConditional }); await analyzeRequiredModule(parentId, resolved, isConditional, rollupContext.load); return { id: childId, allowProxy: true }; })); parentMeta.isCommonJS = getTypeForFullyAnalyzedModule(parentId); fullyAnalyzedModules[parentId] = true; return requireTargets.map(({ id: dependencyId, allowProxy }, index) => { const isCommonJS = parentMeta.isRequiredCommonJS[dependencyId] = getTypeForFullyAnalyzedModule(dependencyId); const isWrappedCommonJS = isCommonJS === IS_WRAPPED_COMMONJS; fullyAnalyzedModules[dependencyId] = true; return { wrappedModuleSideEffects: isWrappedCommonJS && rollupContext.getModuleInfo(dependencyId).moduleSideEffects, source: sources[index].source, id: allowProxy ? wrapId$1(dependencyId, isWrappedCommonJS ? WRAPPED_SUFFIX : PROXY_SUFFIX) : dependencyId, isCommonJS }; }); }, isCurrentlyResolving(source, parentId) { const currentlyResolvingForParent = currentlyResolving.get(parentId); return currentlyResolvingForParent && currentlyResolvingForParent.has(source); } }; } function validateVersion(actualVersion, peerDependencyVersion, name) { const versionRegexp = /\^(\d+\.\d+\.\d+)/g; let minMajor = Infinity; let minMinor = Infinity; let minPatch = Infinity; let foundVersion; while (foundVersion = versionRegexp.exec(peerDependencyVersion)) { const [foundMajor, foundMinor, foundPatch] = foundVersion[1].split(".").map(Number); if (foundMajor < minMajor) { minMajor = foundMajor; minMinor = foundMinor; minPatch = foundPatch; } } if (!actualVersion) throw new Error(`Insufficient ${name} version: "@rollup/plugin-commonjs" requires at least ${name}@${minMajor}.${minMinor}.${minPatch}.`); const [major, minor, patch] = actualVersion.split(".").map(Number); if (major < minMajor || major === minMajor && (minor < minMinor || minor === minMinor && patch < minPatch)) throw new Error(`Insufficient ${name} version: "@rollup/plugin-commonjs" requires at least ${name}@${minMajor}.${minMinor}.${minPatch} but found ${name}@${actualVersion}.`); } const operators = { "==": (x) => equals(x.left, x.right, false), "!=": (x) => not(operators["=="](x)), "===": (x) => equals(x.left, x.right, true), "!==": (x) => not(operators["==="](x)), "!": (x) => isFalsy(x.argument), "&&": (x) => isTruthy(x.left) && isTruthy(x.right), "||": (x) => isTruthy(x.left) || isTruthy(x.right) }; function not(value$1) { return value$1 === null ? value$1 : !value$1; } function equals(a, b, strict) { if (a.type !== b.type) return null; if (a.type === "Literal") return strict ? a.value === b.value : a.value == b.value; return null; } function isTruthy(node) { if (!node) return false; if (node.type === "Literal") return !!node.value; if (node.type === "ParenthesizedExpression") return isTruthy(node.expression); if (node.operator in operators) return operators[node.operator](node); return null; } function isFalsy(node) { return not(isTruthy(node)); } function getKeypath(node) { const parts = []; while (node.type === "MemberExpression") { if (node.computed) return null; parts.unshift(node.property.name); node = node.object; } if (node.type !== "Identifier") return null; const { name } = node; parts.unshift(name); return { name, keypath: parts.join(".") }; } const KEY_COMPILED_ESM = "__esModule"; function getDefineCompiledEsmType(node) { const definedPropertyWithExports = getDefinePropertyCallName(node, "exports"); const definedProperty = definedPropertyWithExports || getDefinePropertyCallName(node, "module.exports"); if (definedProperty && definedProperty.key === KEY_COMPILED_ESM) return isTruthy(definedProperty.value) ? definedPropertyWithExports ? "exports" : "module" : false; return false; } function getDefinePropertyCallName(node, targetName) { const { callee: { object, property } } = node; if (!object || object.type !== "Identifier" || object.name !== "Object") return; if (!property || property.type !== "Identifier" || property.name !== "defineProperty") return; if (node.arguments.length !== 3) return; const targetNames = targetName.split("."); const [target, key, value$1] = node.arguments; if (targetNames.length === 1) { if (target.type !== "Identifier" || target.name !== targetNames[0]) return; } if (targetNames.length === 2) { if (target.type !== "MemberExpression" || target.object.name !== targetNames[0] || target.property.name !== targetNames[1]) return; } if (value$1.type !== "ObjectExpression" || !value$1.properties) return; const valueProperty = value$1.properties.find((p) => p.key && p.key.name === "value"); if (!valueProperty || !valueProperty.value) return; return { key: key.value, value: valueProperty.value }; } function isShorthandProperty(parent) { return parent && parent.type === "Property" && parent.shorthand; } function wrapCode(magicString, uses, moduleName, exportsName, indentExclusionRanges) { const args = []; const passedArgs = []; if (uses.module) { args.push("module"); passedArgs.push(moduleName); } if (uses.exports) { args.push("exports"); passedArgs.push(uses.module ? `${moduleName}.exports` : exportsName); } magicString.trim().indent(" ", { exclude: indentExclusionRanges }).prepend(`(function (${args.join(", ")}) {\n`).append(` \n} (${passedArgs.join(", ")}));`); } function rewriteExportsAndGetExportsBlock(magicString, moduleName, exportsName, exportedExportsName, wrapped, moduleExportsAssignments, firstTopLevelModuleExportsAssignment, exportsAssignmentsByName, topLevelAssignments, defineCompiledEsmExpressions, deconflictedExportNames, code, HELPERS_NAME, exportMode, defaultIsModuleExports, usesRequireWrapper, requireName) { const exports$1 = []; const exportDeclarations = []; if (usesRequireWrapper) getExportsWhenUsingRequireWrapper(magicString, wrapped, exportMode, exports$1, moduleExportsAssignments, exportsAssignmentsByName, moduleName, exportsName, requireName, defineCompiledEsmExpressions); else if (exportMode === "replace") getExportsForReplacedModuleExports(magicString, exports$1, exportDeclarations, moduleExportsAssignments, firstTopLevelModuleExportsAssignment, exportsName, defaultIsModuleExports, HELPERS_NAME); else { if (exportMode === "module") { exportDeclarations.push(`var ${exportedExportsName} = ${moduleName}.exports`); exports$1.push(`${exportedExportsName} as __moduleExports`); } else exports$1.push(`${exportsName} as __moduleExports`); if (wrapped) exportDeclarations.push(getDefaultExportDeclaration(exportedExportsName, defaultIsModuleExports, HELPERS_NAME)); else getExports(magicString, exports$1, exportDeclarations, moduleExportsAssignments, exportsAssignmentsByName, deconflictedExportNames, topLevelAssignments, moduleName, exportsName, exportedExportsName, defineCompiledEsmExpressions, HELPERS_NAME, defaultIsModuleExports, exportMode); } if (exports$1.length) exportDeclarations.push(`export { ${exports$1.join(", ")} }`); return `\n\n${exportDeclarations.join(";\n")};`; } function getExportsWhenUsingRequireWrapper(magicString, wrapped, exportMode, exports$1, moduleExportsAssignments, exportsAssignmentsByName, moduleName, exportsName, requireName, defineCompiledEsmExpressions) { exports$1.push(`${requireName} as __require`); if (wrapped) return; if (exportMode === "replace") rewriteModuleExportsAssignments(magicString, moduleExportsAssignments, exportsName); else { rewriteModuleExportsAssignments(magicString, moduleExportsAssignments, `${moduleName}.exports`); for (const [exportName, { nodes }] of exportsAssignmentsByName) for (const { node, type } of nodes) magicString.overwrite(node.start, node.left.end, `${exportMode === "module" && type === "module" ? `${moduleName}.exports` : exportsName}.${exportName}`); replaceDefineCompiledEsmExpressionsAndGetIfRestorable(defineCompiledEsmExpressions, magicString, exportMode, moduleName, exportsName); } } function getExportsForReplacedModuleExports(magicString, exports$1, exportDeclarations, moduleExportsAssignments, firstTopLevelModuleExportsAssignment, exportsName, defaultIsModuleExports, HELPERS_NAME) { for (const { left } of moduleExportsAssignments) magicString.overwrite(left.start, left.end, exportsName); magicString.prependRight(firstTopLevelModuleExportsAssignment.left.start, "var "); exports$1.push(`${exportsName} as __moduleExports`); exportDeclarations.push(getDefaultExportDeclaration(exportsName, defaultIsModuleExports, HELPERS_NAME)); } function getDefaultExportDeclaration(exportedExportsName, defaultIsModuleExports, HELPERS_NAME) { return `export default ${defaultIsModuleExports === true ? exportedExportsName : defaultIsModuleExports === false ? `${exportedExportsName}.default` : `/*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${exportedExportsName})`}`; } function getExports(magicString, exports$1, exportDeclarations, moduleExportsAssignments, exportsAssignmentsByName, deconflictedExportNames, topLevelAssignments, moduleName, exportsName, exportedExportsName, defineCompiledEsmExpressions, HELPERS_NAME, defaultIsModuleExports, exportMode) { let deconflictedDefaultExportName; for (const { left } of moduleExportsAssignments) magicString.overwrite(left.start, left.end, `${moduleName}.exports`); for (const [exportName, { nodes }] of exportsAssignmentsByName) { const deconflicted = deconflictedExportNames[exportName]; let needsDeclaration = true; for (const { node, type } of nodes) { let replacement = `${deconflicted} = ${exportMode === "module" && type === "module" ? `${moduleName}.exports` : exportsName}.${exportName}`; if (needsDeclaration && topLevelAssignments.has(node)) { replacement = `var ${replacement}`; needsDeclaration = false; } magicString.overwrite(node.start, node.left.end, replacement); } if (needsDeclaration) magicString.prepend(`var ${deconflicted};\n`); if (exportName === "default") deconflictedDefaultExportName = deconflicted; else exports$1.push(exportName === deconflicted ? exportName : `${deconflicted} as ${exportName}`); } const isRestorableCompiledEsm = replaceDefineCompiledEsmExpressionsAndGetIfRestorable(defineCompiledEsmExpressions, magicString, exportMode, moduleName, exportsName); if (defaultIsModuleExports === false || defaultIsModuleExports === "auto" && isRestorableCompiledEsm && moduleExportsAssignments.length === 0) exports$1.push(`${deconflictedDefaultExportName || exportedExportsName} as default`); else if (defaultIsModuleExports === true || !isRestorableCompiledEsm && moduleExportsAssignments.length === 0) exports$1.push(`${exportedExportsName} as default`); else exportDeclarations.push(getDefaultExportDeclaration(exportedExportsName, defaultIsModuleExports, HELPERS_NAME)); } function rewriteModuleExportsAssignments(magicString, moduleExportsAssignments, exportsName) { for (const { left } of moduleExportsAssignments) magicString.overwrite(left.start, left.end, exportsName); } function replaceDefineCompiledEsmExpressionsAndGetIfRestorable(defineCompiledEsmExpressions, magicString, exportMode, moduleName, exportsName) { let isRestorableCompiledEsm = false; for (const { node, type } of defineCompiledEsmExpressions) { isRestorableCompiledEsm = true; const moduleExportsExpression = node.type === "CallExpression" ? node.arguments[0] : node.left.object; magicString.overwrite(moduleExportsExpression.start, moduleExportsExpression.end, exportMode === "module" && type === "module" ? `${moduleName}.exports` : exportsName); } return isRestorableCompiledEsm; } function isRequireExpression(node, scope) { if (!node) return false; if (node.type !== "CallExpression") return false; if (node.arguments.length === 0) return false; return isRequire(node.callee, scope); } function isRequire(node, scope) { return node.type === "Identifier" && node.name === "require" && !scope.contains("require") || node.type === "MemberExpression" && isModuleRequire(node, scope); } function isModuleRequire({ object, property }, scope) { return object.type === "Identifier" && object.name === "module" && property.type === "Identifier" && property.name === "require" && !scope.contains("module"); } function hasDynamicArguments(node) { return node.arguments.length > 1 || node.arguments[0].type !== "Literal" && (node.arguments[0].type !== "TemplateLiteral" || node.arguments[0].expressions.length > 0); } const reservedMethod = { resolve: true, cache: true, main: true }; function isNodeRequirePropertyAccess(parent) { return parent && parent.property && reservedMethod[parent.property.name]; } function getRequireStringArg(node) { return node.arguments[0].type === "Literal" ? node.arguments[0].value : node.arguments[0].quasis[0].value.cooked; } function getRequireHandlers() { const requireExpressions = []; function addRequireExpression(sourceId, node, scope, usesReturnValue, isInsideTryBlock, isInsideConditional, toBeRemoved) { requireExpressions.push({ sourceId, node, scope, usesReturnValue, isInsideTryBlock, isInsideConditional, toBeRemoved }); } async function rewriteRequireExpressionsAndGetImportBlock(magicString, topLevelDeclarations, reassignedNames, helpersName, dynamicRequireName, moduleName, exportsName, id, exportMode, resolveRequireSourcesAndUpdateMeta, needsRequireWrapper, isEsModule, isDynamicRequireModulesEnabled, getIgnoreTryCatchRequireStatementMode, commonjsMeta) { const imports = []; imports.push(`import * as ${helpersName} from "${HELPERS_ID}"`); if (dynamicRequireName) imports.push(`import { ${isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT} as ${dynamicRequireName} } from "${DYNAMIC_MODULES_ID}"`); if (exportMode === "module") imports.push(`import { __module as ${moduleName} } from ${JSON.stringify(wrapId$1(id, MODULE_SUFFIX))}`, `var ${exportsName} = ${moduleName}.exports`); else if (exportMode === "exports") imports.push(`import { __exports as ${exportsName} } from ${JSON.stringify(wrapId$1(id, EXPORTS_SUFFIX))}`); const requiresBySource = collectSources(requireExpressions); processRequireExpressions(imports, await resolveRequireSourcesAndUpdateMeta(id, needsRequireWrapper ? IS_WRAPPED_COMMONJS : !isEsModule, commonjsMeta, Object.keys(requiresBySource).map((source) => { return { source, isConditional: requiresBySource[source].every((require$1) => require$1.isInsideConditional) }; })), requiresBySource, getIgnoreTryCatchRequireStatementMode, magicString); return imports.length ? `${imports.join(";\n")};\n\n` : ""; } return { addRequireExpression, rewriteRequireExpressionsAndGetImportBlock }; } function collectSources(requireExpressions) { const requiresBySource = Object.create(null); for (const requireExpression of requireExpressions) { const { sourceId } = requireExpression; if (!requiresBySource[sourceId]) requiresBySource[sourceId] = []; requiresBySource[sourceId].push(requireExpression); } return requiresBySource; } function processRequireExpressions(imports, requireTargets, requiresBySource, getIgnoreTryCatchRequireStatementMode, magicString) { const generateRequireName = getGenerateRequireName(); for (const { source, id: resolvedId, isCommonJS, wrappedModuleSideEffects } of requireTargets) { const requires = requiresBySource[source]; const name = generateRequireName(requires); let usesRequired = false; let needsImport = false; for (const { node, usesReturnValue, toBeRemoved, isInsideTryBlock } of requires) { const { canConvertRequire, shouldRemoveRequire } = isInsideTryBlock && isWrappedId(resolvedId, EXTERNAL_SUFFIX) ? getIgnoreTryCatchRequireStatementMode(source) : { canConvertRequire: true, shouldRemoveRequire: false }; if (shouldRemoveRequire) if (usesReturnValue) magicString.overwrite(node.start, node.end, "undefined"); else magicString.remove(toBeRemoved.start, toBeRemoved.end); else if (canConvertRequire) { needsImport = true; if (isCommonJS === IS_WRAPPED_COMMONJS) magicString.overwrite(node.start, node.end, `${wrappedModuleSideEffects ? "" : "/*@__PURE__*/ "}${name}()`); else if (usesReturnValue) { usesRequired = true; magicString.overwrite(node.start, node.end, name); } else magicString.remove(toBeRemoved.start, toBeRemoved.end); } } if (needsImport) if (isCommonJS === IS_WRAPPED_COMMONJS) imports.push(`import { __require as ${name} } from ${JSON.stringify(resolvedId)}`); else imports.push(`import ${usesRequired ? `${name} from ` : ""}${JSON.stringify(resolvedId)}`); } } function getGenerateRequireName() { let uid = 0; return (requires) => { let name; const hasNameConflict = ({ scope }) => scope.contains(name); do { name = `require$$${uid}`; uid += 1; } while (requires.some(hasNameConflict)); return name; }; } const exportsPattern = /^(?:module\.)?exports(?:\.([a-zA-Z_$][a-zA-Z_$0-9]*))?$/; const functionType = /^(?:FunctionDeclaration|FunctionExpression|ArrowFunctionExpression)$/; async function transformCommonjs(parse$17, code, id, isEsModule, ignoreGlobal, ignoreRequire, ignoreDynamicRequires, getIgnoreTryCatchRequireStatementMode, sourceMap, isDynamicRequireModulesEnabled, dynamicRequireModules, commonDir, astCache, defaultIsModuleExports, needsRequireWrapper, resolveRequireSourcesAndUpdateMeta, isRequired, checkDynamicRequire, commonjsMeta) { const ast = astCache || tryParse(parse$17, code, id); const magicString = new MagicString(code); const uses = { module: false, exports: false, global: false, require: false }; const virtualDynamicRequirePath = isDynamicRequireModulesEnabled && getVirtualPathForDynamicRequirePath(dirname$1(id), commonDir); let scope = attachScopes(ast, "scope"); let lexicalDepth = 0; let programDepth = 0; let classBodyDepth = 0; let currentTryBlockEnd = null; let shouldWrap = false; const globals = /* @__PURE__ */ new Set(); let currentConditionalNodeEnd = null; const conditionalNodes = /* @__PURE__ */ new Set(); const { addRequireExpression, rewriteRequireExpressionsAndGetImportBlock } = getRequireHandlers(); const reassignedNames = /* @__PURE__ */ new Set(); const topLevelDeclarations = []; const skippedNodes = /* @__PURE__ */ new Set(); const moduleAccessScopes = new Set([scope]); const exportsAccessScopes = new Set([scope]); const moduleExportsAssignments = []; let firstTopLevelModuleExportsAssignment = null; const exportsAssignmentsByName = /* @__PURE__ */ new Map(); const topLevelAssignments = /* @__PURE__ */ new Set(); const topLevelDefineCompiledEsmExpressions = []; const replacedGlobal = []; const replacedThis = []; const replacedDynamicRequires = []; const importedVariables = /* @__PURE__ */ new Set(); const indentExclusionRanges = []; walk$2(ast, { enter(node, parent) { if (skippedNodes.has(node)) { this.skip(); return; } if (currentTryBlockEnd !== null && node.start > currentTryBlockEnd) currentTryBlockEnd = null; if (currentConditionalNodeEnd !== null && node.start > currentConditionalNodeEnd) currentConditionalNodeEnd = null; if (currentConditionalNodeEnd === null && conditionalNodes.has(node)) currentConditionalNodeEnd = node.end; programDepth += 1; if (node.scope) ({scope} = node); if (functionType.test(node.type)) lexicalDepth += 1; if (sourceMap) { magicString.addSourcemapLocation(node.start); magicString.addSourcemapLocation(node.end); } switch (node.type) { case "AssignmentExpression": if (node.left.type === "MemberExpression") { const flattened = getKeypath(node.left); if (!flattened || scope.contains(flattened.name)) return; const exportsPatternMatch = exportsPattern.exec(flattened.keypath); if (!exportsPatternMatch || flattened.keypath === "exports") return; const [, exportName] = exportsPatternMatch; uses[flattened.name] = true; if (flattened.keypath === "module.exports") { moduleExportsAssignments.push(node); if (programDepth > 3) moduleAccessScopes.add(scope); else if (!firstTopLevelModuleExportsAssignment) firstTopLevelModuleExportsAssignment = node; } else if (exportName === KEY_COMPILED_ESM) if (programDepth > 3) shouldWrap = true; else topLevelDefineCompiledEsmExpressions.push({ node, type: flattened.name }); else { const exportsAssignments = exportsAssignmentsByName.get(exportName) || { nodes: [], scopes: /* @__PURE__ */ new Set() }; exportsAssignments.nodes.push({ node, type: flattened.name }); exportsAssignments.scopes.add(scope); exportsAccessScopes.add(scope); exportsAssignmentsByName.set(exportName, exportsAssignments); if (programDepth <= 3) topLevelAssignments.add(node); } skippedNodes.add(node.left); } else for (const name of extractAssignedNames(node.left)) reassignedNames.add(name); return; case "CallExpression": { const defineCompiledEsmType = getDefineCompiledEsmType(node); if (defineCompiledEsmType) { if (programDepth === 3 && parent.type === "ExpressionStatement") { skippedNodes.add(node.arguments[0]); topLevelDefineCompiledEsmExpressions.push({ node, type: defineCompiledEsmType }); } else shouldWrap = true; return; } if (isDynamicRequireModulesEnabled && node.callee.object && isRequire(node.callee.object, scope) && node.callee.property.name === "resolve") { checkDynamicRequire(node.start); uses.require = true; replacedDynamicRequires.push(node.callee.object); skippedNodes.add(node.callee); return; } if (!isRequireExpression(node, scope)) { const keypath = getKeypath(node.callee); if (keypath && importedVariables.has(keypath.name)) currentConditionalNodeEnd = Infinity; return; } skippedNodes.add(node.callee); uses.require = true; if (hasDynamicArguments(node)) { if (isDynamicRequireModulesEnabled) checkDynamicRequire(node.start); if (!ignoreDynamicRequires) replacedDynamicRequires.push(node.callee); return; } const requireStringArg = getRequireStringArg(node); if (!ignoreRequire(requireStringArg)) { addRequireExpression(requireStringArg, node, scope, parent.type !== "ExpressionStatement", currentTryBlockEnd !== null, currentConditionalNodeEnd !== null, parent.type === "ExpressionStatement" && (!currentConditionalNodeEnd || currentTryBlockEnd !== null && currentTryBlockEnd < currentConditionalNodeEnd) ? parent : node); if (parent.type === "VariableDeclarator" && parent.id.type === "Identifier") for (const name of extractAssignedNames(parent.id)) importedVariables.add(name); } return; } case "ClassBody": classBodyDepth += 1; return; case "ConditionalExpression": case "IfStatement": if (isFalsy(node.test)) skippedNodes.add(node.consequent); else if (isTruthy(node.test)) { if (node.alternate) skippedNodes.add(node.alternate); } else { conditionalNodes.add(node.consequent); if (node.alternate) conditionalNodes.add(node.alternate); } return; case "ArrowFunctionExpression": case "FunctionDeclaration": case "FunctionExpression": if (currentConditionalNodeEnd === null && !(parent.type === "CallExpression" && parent.callee === node)) currentConditionalNodeEnd = node.end; return; case "Identifier": { const { name } = node; if (!(0, import_is_reference.default)(node, parent) || scope.contains(name) || parent.type === "PropertyDefinition" && parent.key === node) return; switch (name) { case "require": uses.require = true; if (isNodeRequirePropertyAccess(parent)) return; if (!ignoreDynamicRequires) { if (isShorthandProperty(parent)) { skippedNodes.add(parent.value); magicString.prependRight(node.start, "require: "); } replacedDynamicRequires.push(node); } return; case "module": case "exports": shouldWrap = true; uses[name] = true; return; case "global": uses.global = true; if (!ignoreGlobal) replacedGlobal.push(node); return; case "define": magicString.overwrite(node.start, node.end, "undefined", { storeName: true }); return; default: globals.add(name); return; } } case "LogicalExpression": if (node.operator === "&&") { if (isFalsy(node.left)) skippedNodes.add(node.right); else if (!isTruthy(node.left)) conditionalNodes.add(node.right); } else if (node.operator === "||") { if (isTruthy(node.left)) skippedNodes.add(node.right); else if (!isFalsy(node.left)) conditionalNodes.add(node.right); } return; case "MemberExpression": if (!isDynamicRequireModulesEnabled && isModuleRequire(node, scope)) { uses.require = true; replacedDynamicRequires.push(node); skippedNodes.add(node.object); skippedNodes.add(node.property); } return; case "ReturnStatement": if (lexicalDepth === 0) shouldWrap = true; return; case "ThisExpression": if (lexicalDepth === 0 && !classBodyDepth) { uses.global = true; if (!ignoreGlobal) replacedThis.push(node); } return; case "TryStatement": if (currentTryBlockEnd === null) currentTryBlockEnd = node.block.end; if (currentConditionalNodeEnd === null) currentConditionalNodeEnd = node.end; return; case "UnaryExpression": if (node.operator === "typeof") { const flattened = getKeypath(node.argument); if (!flattened) return; if (scope.contains(flattened.name)) return; if (!isEsModule && (flattened.keypath === "module.exports" || flattened.keypath === "module" || flattened.keypath === "exports")) magicString.overwrite(node.start, node.end, `'object'`, { storeName: false }); } return; case "VariableDeclaration": if (!scope.parent) topLevelDeclarations.push(node); return; case "TemplateElement": if (node.value.raw.includes("\n")) indentExclusionRanges.push([node.start, node.end]); } }, leave(node) { programDepth -= 1; if (node.scope) scope = scope.parent; if (functionType.test(node.type)) lexicalDepth -= 1; if (node.type === "ClassBody") classBodyDepth -= 1; } }); const nameBase = getName(id); const exportsName = deconflict([...exportsAccessScopes], globals, nameBase); const moduleName = deconflict([...moduleAccessScopes], globals, `${nameBase}Module`); const requireName = deconflict([scope], globals, `require${capitalize(nameBase)}`); const isRequiredName = deconflict([scope], globals, `hasRequired${capitalize(nameBase)}`); const helpersName = deconflict([scope], globals, "commonjsHelpers"); const dynamicRequireName = replacedDynamicRequires.length > 0 && deconflict([scope], globals, isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT); const deconflictedExportNames = Object.create(null); for (const [exportName, { scopes }] of exportsAssignmentsByName) deconflictedExportNames[exportName] = deconflict([...scopes], globals, exportName); for (const node of replacedGlobal) magicString.overwrite(node.start, node.end, `${helpersName}.commonjsGlobal`, { storeName: true }); for (const node of replacedThis) magicString.overwrite(node.start, node.end, exportsName, { storeName: true }); for (const node of replacedDynamicRequires) magicString.overwrite(node.start, node.end, isDynamicRequireModulesEnabled ? `${dynamicRequireName}(${JSON.stringify(virtualDynamicRequirePath)})` : dynamicRequireName, { contentOnly: true, storeName: true }); shouldWrap = !isEsModule && (shouldWrap || uses.exports && moduleExportsAssignments.length > 0); if (!(shouldWrap || isRequired || needsRequireWrapper || uses.module || uses.exports || uses.require || topLevelDefineCompiledEsmExpressions.length > 0) && (ignoreGlobal || !uses.global)) return { meta: { commonjs: { isCommonJS: false } } }; let leadingComment = ""; if (code.startsWith("/*")) { const commentEnd = code.indexOf("*/", 2) + 2; leadingComment = `${code.slice(0, commentEnd)}\n`; magicString.remove(0, commentEnd).trim(); } let shebang = ""; if (code.startsWith("#!")) { const shebangEndPosition = code.indexOf("\n") + 1; shebang = code.slice(0, shebangEndPosition); magicString.remove(0, shebangEndPosition).trim(); } const exportMode = isEsModule ? "none" : shouldWrap ? uses.module ? "module" : "exports" : firstTopLevelModuleExportsAssignment ? exportsAssignmentsByName.size === 0 && topLevelDefineCompiledEsmExpressions.length === 0 ? "replace" : "module" : moduleExportsAssignments.length === 0 ? "exports" : "module"; const exportedExportsName = exportMode === "module" ? deconflict([], globals, `${nameBase}Exports`) : exportsName; const importBlock = await rewriteRequireExpressionsAndGetImportBlock(magicString, topLevelDeclarations, reassignedNames, helpersName, dynamicRequireName, moduleName, exportsName, id, exportMode, resolveRequireSourcesAndUpdateMeta, needsRequireWrapper, isEsModule, isDynamicRequireModulesEnabled, getIgnoreTryCatchRequireStatementMode, commonjsMeta); const usesRequireWrapper = commonjsMeta.isCommonJS === IS_WRAPPED_COMMONJS; const exportBlock = isEsModule ? "" : rewriteExportsAndGetExportsBlock(magicString, moduleName, exportsName, exportedExportsName, shouldWrap, moduleExportsAssignments, firstTopLevelModuleExportsAssignment, exportsAssignmentsByName, topLevelAssignments, topLevelDefineCompiledEsmExpressions, deconflictedExportNames, code, helpersName, exportMode, defaultIsModuleExports, usesRequireWrapper, requireName); if (shouldWrap) wrapCode(magicString, uses, moduleName, exportsName, indentExclusionRanges); if (usesRequireWrapper) { magicString.trim().indent(" ", { exclude: indentExclusionRanges }); const exported = exportMode === "module" ? `${moduleName}.exports` : exportsName; magicString.prepend(`var ${isRequiredName}; function ${requireName} () { \tif (${isRequiredName}) return ${exported}; \t${isRequiredName} = 1; `).append(` \treturn ${exported}; }`); if (exportMode === "replace") magicString.prepend(`var ${exportsName};\n`); } magicString.trim().prepend(shebang + leadingComment + importBlock).append(exportBlock); return { code: magicString.toString(), map: sourceMap ? magicString.generateMap() : null, syntheticNamedExports: isEsModule || usesRequireWrapper ? false : "__moduleExports", meta: { commonjs: { ...commonjsMeta, shebang } } }; } const PLUGIN_NAME = "commonjs"; function commonjs(options$1 = {}) { const { ignoreGlobal, ignoreDynamicRequires, requireReturnsDefault: requireReturnsDefaultOption, defaultIsModuleExports: defaultIsModuleExportsOption, esmExternals } = options$1; const extensions$1 = options$1.extensions || [".js"]; const filter$1 = createFilter$2(options$1.include, options$1.exclude); const isPossibleCjsId = (id) => { const extName = extname$1(id); return extName === ".cjs" || extensions$1.includes(extName) && filter$1(id); }; const { strictRequiresFilter, detectCyclesAndConditional } = getStrictRequiresFilter(options$1); const getRequireReturnsDefault = typeof requireReturnsDefaultOption === "function" ? requireReturnsDefaultOption : () => requireReturnsDefaultOption; let esmExternalIds; const isEsmExternal = typeof esmExternals === "function" ? esmExternals : Array.isArray(esmExternals) ? (esmExternalIds = new Set(esmExternals), (id) => esmExternalIds.has(id)) : () => esmExternals; const getDefaultIsModuleExports = typeof defaultIsModuleExportsOption === "function" ? defaultIsModuleExportsOption : () => typeof defaultIsModuleExportsOption === "boolean" ? defaultIsModuleExportsOption : "auto"; const dynamicRequireRoot = typeof options$1.dynamicRequireRoot === "string" ? resolve$1(options$1.dynamicRequireRoot) : process.cwd(); const { commonDir, dynamicRequireModules } = getDynamicRequireModules(options$1.dynamicRequireTargets, dynamicRequireRoot); const isDynamicRequireModulesEnabled = dynamicRequireModules.size > 0; const ignoreRequire = typeof options$1.ignore === "function" ? options$1.ignore : Array.isArray(options$1.ignore) ? (id) => options$1.ignore.includes(id) : () => false; const getIgnoreTryCatchRequireStatementMode = (id) => { const mode = typeof options$1.ignoreTryCatch === "function" ? options$1.ignoreTryCatch(id) : Array.isArray(options$1.ignoreTryCatch) ? options$1.ignoreTryCatch.includes(id) : typeof options$1.ignoreTryCatch !== "undefined" ? options$1.ignoreTryCatch : true; return { canConvertRequire: mode !== "remove" && mode !== true, shouldRemoveRequire: mode === "remove" }; }; const { currentlyResolving, resolveId } = getResolveId(extensions$1, isPossibleCjsId); const sourceMap = options$1.sourceMap !== false; let requireResolver; function transformAndCheckExports(code, id) { const normalizedId = normalizePathSlashes(id); const { isEsModule, hasDefaultExport, hasNamedExports, ast } = analyzeTopLevelStatements(this.parse, code, id); const commonjsMeta = this.getModuleInfo(id).meta.commonjs || {}; if (hasDefaultExport) commonjsMeta.hasDefaultExport = true; if (hasNamedExports) commonjsMeta.hasNamedExports = true; if (!dynamicRequireModules.has(normalizedId) && (!(hasCjsKeywords(code, ignoreGlobal) || requireResolver.isRequiredId(id)) || isEsModule && !options$1.transformMixedEsModules)) { commonjsMeta.isCommonJS = false; return { meta: { commonjs: commonjsMeta } }; } const needsRequireWrapper = !isEsModule && (dynamicRequireModules.has(normalizedId) || strictRequiresFilter(id)); const checkDynamicRequire = (position) => { const normalizedDynamicRequireRoot = normalizePathSlashes(dynamicRequireRoot); if (normalizedId.indexOf(normalizedDynamicRequireRoot) !== 0) this.error({ code: "DYNAMIC_REQUIRE_OUTSIDE_ROOT", normalizedId, normalizedDynamicRequireRoot, message: `"${normalizedId}" contains dynamic require statements but it is not within the current dynamicRequireRoot "${normalizedDynamicRequireRoot}". You should set dynamicRequireRoot to "${dirname$1(normalizedId)}" or one of its parent directories.` }, position); }; return transformCommonjs(this.parse, code, id, isEsModule, ignoreGlobal || isEsModule, ignoreRequire, ignoreDynamicRequires && !isDynamicRequireModulesEnabled, getIgnoreTryCatchRequireStatementMode, sourceMap, isDynamicRequireModulesEnabled, dynamicRequireModules, commonDir, ast, getDefaultIsModuleExports(id), needsRequireWrapper, requireResolver.resolveRequireSourcesAndUpdateMeta(this), requireResolver.isRequiredId(id), checkDynamicRequire, commonjsMeta); } return { name: PLUGIN_NAME, version: version$1, options(rawOptions) { const plugins$1 = Array.isArray(rawOptions.plugins) ? [...rawOptions.plugins] : rawOptions.plugins ? [rawOptions.plugins] : []; plugins$1.unshift({ name: "commonjs--resolver", resolveId }); return { ...rawOptions, plugins: plugins$1 }; }, buildStart({ plugins: plugins$1 }) { validateVersion(this.meta.rollupVersion, peerDependencies.rollup, "rollup"); const nodeResolve = plugins$1.find(({ name }) => name === "node-resolve"); if (nodeResolve) validateVersion(nodeResolve.version, "^13.0.6", "@rollup/plugin-node-resolve"); if (options$1.namedExports != null) this.warn("The namedExports option from \"@rollup/plugin-commonjs\" is deprecated. Named exports are now handled automatically."); requireResolver = getRequireResolver(extensions$1, detectCyclesAndConditional, currentlyResolving); }, buildEnd() { if (options$1.strictRequires === "debug") { const wrappedIds = requireResolver.getWrappedIds(); if (wrappedIds.length) this.warn({ code: "WRAPPED_IDS", ids: wrappedIds, message: `The commonjs plugin automatically wrapped the following files:\n[\n${wrappedIds.map((id) => `\t${JSON.stringify(relative$1(process.cwd(), id))}`).join(",\n")}\n]` }); else this.warn({ code: "WRAPPED_IDS", ids: wrappedIds, message: "The commonjs plugin did not wrap any files." }); } }, async load(id) { if (id === HELPERS_ID) return getHelpersModule(); if (isWrappedId(id, MODULE_SUFFIX)) { const name = getName(unwrapId$1(id, MODULE_SUFFIX)); return { code: `var ${name} = {exports: {}}; export {${name} as __module}`, meta: { commonjs: { isCommonJS: false } } }; } if (isWrappedId(id, EXPORTS_SUFFIX)) { const name = getName(unwrapId$1(id, EXPORTS_SUFFIX)); return { code: `var ${name} = {}; export {${name} as __exports}`, meta: { commonjs: { isCommonJS: false } } }; } if (isWrappedId(id, EXTERNAL_SUFFIX)) { const actualId = unwrapId$1(id, EXTERNAL_SUFFIX); return getUnknownRequireProxy(actualId, isEsmExternal(actualId) ? getRequireReturnsDefault(actualId) : true); } if (id.endsWith(ENTRY_SUFFIX)) { const acutalId = id.slice(0, -15); const { meta: { commonjs: commonjsMeta } } = this.getModuleInfo(acutalId); const shebang = commonjsMeta?.shebang ?? ""; return getEntryProxy(acutalId, getDefaultIsModuleExports(acutalId), this.getModuleInfo, shebang); } if (isWrappedId(id, ES_IMPORT_SUFFIX)) { const actualId = unwrapId$1(id, ES_IMPORT_SUFFIX); return getEsImportProxy(actualId, getDefaultIsModuleExports(actualId), (await this.load({ id: actualId })).moduleSideEffects); } if (id === DYNAMIC_MODULES_ID) return getDynamicModuleRegistry(isDynamicRequireModulesEnabled, dynamicRequireModules, commonDir, ignoreDynamicRequires); if (isWrappedId(id, PROXY_SUFFIX)) { const actualId = unwrapId$1(id, PROXY_SUFFIX); return getStaticRequireProxy(actualId, getRequireReturnsDefault(actualId), this.load); } return null; }, shouldTransformCachedModule(...args) { return requireResolver.shouldTransformCachedModule.call(this, ...args); }, transform(code, id) { if (!isPossibleCjsId(id)) return null; try { return transformAndCheckExports.call(this, code, id); } catch (err$2) { return this.error(err$2, err$2.pos); } } }; } //#endregion //#region src/node/environment.ts /** * Creates a function that hides the complexities of a WeakMap with an initial value * to implement object metadata. Used by plugins to implement cross hooks per * environment metadata * * @experimental */ function perEnvironmentState(initial) { const stateMap = /* @__PURE__ */ new WeakMap(); return function(context) { const { environment } = context; let state = stateMap.get(environment); if (!state) { state = initial(environment); stateMap.set(environment, state); } return state; }; } //#endregion //#region src/node/plugins/reporter.ts var import_picocolors$32 = /* @__PURE__ */ __toESM(require_picocolors(), 1); const groups = [ { name: "Assets", color: import_picocolors$32.default.green }, { name: "CSS", color: import_picocolors$32.default.magenta }, { name: "JS", color: import_picocolors$32.default.cyan } ]; const COMPRESSIBLE_ASSETS_RE = /\.(?:html|json|svg|txt|xml|xhtml|wasm)$/; function buildReporterPlugin(config$2) { const compress = promisify(gzip); const numberFormatter = new Intl.NumberFormat("en", { maximumFractionDigits: 2, minimumFractionDigits: 2 }); const displaySize = (bytes) => { return `${numberFormatter.format(bytes / 1e3)} kB`; }; const tty$2 = process.stdout.isTTY && !process.env.CI; const shouldLogInfo = LogLevels[config$2.logLevel || "info"] >= LogLevels.info; const modulesReporter = shouldLogInfo ? perEnvironmentState((environment) => { let hasTransformed = false; let transformedCount = 0; const logTransform = throttle((id) => { writeLine(`transforming (${transformedCount}) ${import_picocolors$32.default.dim(path.relative(config$2.root, id))}`); }); return { reset() { transformedCount = 0; }, register(id) { transformedCount++; if (!tty$2) { if (!hasTransformed) config$2.logger.info(`transforming...`); } else { if (id.includes(`?`)) return; logTransform(id); } hasTransformed = true; }, log() { if (tty$2) clearLine$1(); environment.logger.info(`${import_picocolors$32.default.green(`✓`)} ${transformedCount} modules transformed.`); } }; }) : void 0; const chunksReporter = perEnvironmentState((environment) => { let hasRenderedChunk = false; let hasCompressChunk = false; let chunkCount = 0; let compressedCount = 0; async function getCompressedSize(code) { if (environment.config.consumer !== "client" || !environment.config.build.reportCompressedSize) return null; if (shouldLogInfo && !hasCompressChunk) { if (!tty$2) config$2.logger.info("computing gzip size..."); else writeLine("computing gzip size (0)..."); hasCompressChunk = true; } const compressed = await compress(typeof code === "string" ? code : Buffer.from(code)); compressedCount++; if (shouldLogInfo && tty$2) writeLine(`computing gzip size (${compressedCount})...`); return compressed.length; } return { reset() { chunkCount = 0; compressedCount = 0; }, register() { chunkCount++; if (shouldLogInfo) { if (!tty$2) { if (!hasRenderedChunk) environment.logger.info("rendering chunks..."); } else writeLine(`rendering chunks (${chunkCount})...`); hasRenderedChunk = true; } }, async log(output, outDir) { const chunkLimit = environment.config.build.chunkSizeWarningLimit; let hasLargeChunks = false; if (shouldLogInfo) { const entries = (await Promise.all(Object.values(output).map(async (chunk) => { if (chunk.type === "chunk") return { name: chunk.fileName, group: "JS", size: Buffer.byteLength(chunk.code), compressedSize: await getCompressedSize(chunk.code), mapSize: chunk.map ? Buffer.byteLength(chunk.map.toString()) : null }; else { if (chunk.fileName.endsWith(".map")) return null; const isCSS = chunk.fileName.endsWith(".css"); const isCompressible = isCSS || COMPRESSIBLE_ASSETS_RE.test(chunk.fileName); return { name: chunk.fileName, group: isCSS ? "CSS" : "Assets", size: Buffer.byteLength(chunk.source), mapSize: null, compressedSize: isCompressible ? await getCompressedSize(chunk.source) : null }; } }))).filter(isDefined); if (tty$2) clearLine$1(); let longest = 0; let biggestSize = 0; let biggestMap = 0; let biggestCompressSize = 0; for (const entry of entries) { if (entry.name.length > longest) longest = entry.name.length; if (entry.size > biggestSize) biggestSize = entry.size; if (entry.mapSize && entry.mapSize > biggestMap) biggestMap = entry.mapSize; if (entry.compressedSize && entry.compressedSize > biggestCompressSize) biggestCompressSize = entry.compressedSize; } const sizePad = displaySize(biggestSize).length; const mapPad = displaySize(biggestMap).length; const compressPad = displaySize(biggestCompressSize).length; const relativeOutDir = normalizePath(path.relative(config$2.root, path.resolve(config$2.root, outDir ?? environment.config.build.outDir))); const assetsDir = path.join(environment.config.build.assetsDir, "/"); for (const group of groups) { const filtered = entries.filter((e$1) => e$1.group === group.name); if (!filtered.length) continue; for (const entry of filtered.sort((a, z) => a.size - z.size)) { const isLarge = group.name === "JS" && entry.size / 1e3 > chunkLimit; if (isLarge) hasLargeChunks = true; const sizeColor = isLarge ? import_picocolors$32.default.yellow : import_picocolors$32.default.dim; let log$4 = import_picocolors$32.default.dim(withTrailingSlash(relativeOutDir)); log$4 += !config$2.build.lib && entry.name.startsWith(withTrailingSlash(assetsDir)) ? import_picocolors$32.default.dim(assetsDir) + group.color(entry.name.slice(assetsDir.length).padEnd(longest + 2 - assetsDir.length)) : group.color(entry.name.padEnd(longest + 2)); log$4 += import_picocolors$32.default.bold(sizeColor(displaySize(entry.size).padStart(sizePad))); if (entry.compressedSize) log$4 += import_picocolors$32.default.dim(` │ gzip: ${displaySize(entry.compressedSize).padStart(compressPad)}`); if (entry.mapSize) log$4 += import_picocolors$32.default.dim(` │ map: ${displaySize(entry.mapSize).padStart(mapPad)}`); config$2.logger.info(log$4); } } } else hasLargeChunks = Object.values(output).some((chunk) => { return chunk.type === "chunk" && chunk.code.length / 1e3 > chunkLimit; }); if (hasLargeChunks && environment.config.build.minify && !config$2.build.lib && environment.config.consumer === "client") environment.logger.warn(import_picocolors$32.default.yellow(`\n(!) Some chunks are larger than ${chunkLimit} kB after minification. Consider:\n- Using dynamic import() to code-split the application\n- Use build.rollupOptions.output.manualChunks to improve chunking: https://rollupjs.org/configuration-options/#output-manualchunks\n- Adjust chunk size limit for this warning via build.chunkSizeWarningLimit.`)); } }; }); return { name: "vite:reporter", sharedDuringBuild: true, perEnvironmentStartEndDuringDev: true, ...modulesReporter ? { transform(_, id) { modulesReporter(this).register(id); }, buildStart() { modulesReporter(this).reset(); }, buildEnd() { modulesReporter(this).log(); } } : {}, renderStart() { chunksReporter(this).reset(); }, renderChunk(_, chunk, options$1) { if (!options$1.inlineDynamicImports) for (const id of chunk.moduleIds) { const module$1 = this.getModuleInfo(id); if (!module$1) continue; if (module$1.importers.length && module$1.dynamicImporters.length) { if (module$1.dynamicImporters.some((id$1) => !isInNodeModules(id$1) && chunk.moduleIds.includes(id$1))) this.warn(`\n(!) ${module$1.id} is dynamically imported by ${module$1.dynamicImporters.join(", ")} but also statically imported by ${module$1.importers.join(", ")}, dynamic import will not move module into another chunk.\n`); } } chunksReporter(this).register(); }, generateBundle() { if (shouldLogInfo && tty$2) clearLine$1(); }, async writeBundle({ dir }, output) { await chunksReporter(this).log(output, dir); } }; } function writeLine(output) { clearLine$1(); if (output.length < process.stdout.columns) process.stdout.write(output); else process.stdout.write(output.substring(0, process.stdout.columns - 1)); } function clearLine$1() { process.stdout.clearLine(0); process.stdout.cursorTo(0); } function throttle(fn) { let timerHandle = null; return (...args) => { if (timerHandle) return; fn(...args); timerHandle = setTimeout(() => { timerHandle = null; }, 100); }; } //#endregion //#region ../../node_modules/.pnpm/tsconfck@3.1.6_typescript@5.9.2/node_modules/tsconfck/src/util.js const POSIX_SEP_RE = new RegExp("\\" + path.posix.sep, "g"); const NATIVE_SEP_RE = new RegExp("\\" + path.sep, "g"); /** @type {Map}*/ const PATTERN_REGEX_CACHE = /* @__PURE__ */ new Map(); const GLOB_ALL_PATTERN = `**/*`; const TS_EXTENSIONS = [ ".ts", ".tsx", ".mts", ".cts" ]; const TSJS_EXTENSIONS = TS_EXTENSIONS.concat([ ".js", ".jsx", ".mjs", ".cjs" ]); const TS_EXTENSIONS_RE_GROUP = `\\.(?:${TS_EXTENSIONS.map((ext) => ext.substring(1)).join("|")})`; const TSJS_EXTENSIONS_RE_GROUP = `\\.(?:${TSJS_EXTENSIONS.map((ext) => ext.substring(1)).join("|")})`; const IS_POSIX = path.posix.sep === path.sep; /** * @template T * @returns {{resolve:(result:T)=>void, reject:(error:any)=>void, promise: Promise}} */ function makePromise() { let resolve$4, reject; return { promise: new Promise((res, rej) => { resolve$4 = res; reject = rej; }), resolve: resolve$4, reject }; } /** * @param {string} filename * @param {import('./cache.js').TSConfckCache} [cache] * @returns {Promise} */ async function resolveTSConfigJson(filename, cache$1) { if (path.extname(filename) !== ".json") return; const tsconfig = path.resolve(filename); if (cache$1 && (cache$1.hasParseResult(tsconfig) || cache$1.hasParseResult(filename))) return tsconfig; return promises.stat(tsconfig).then((stat$4) => { if (stat$4.isFile() || stat$4.isFIFO()) return tsconfig; else throw new Error(`${filename} exists but is not a regular file.`); }); } /** * * @param {string} dir an absolute directory path * @returns {boolean} if dir path includes a node_modules segment */ const isInNodeModules$1 = IS_POSIX ? (dir) => dir.includes("/node_modules/") : (dir) => dir.match(/[/\\]node_modules[/\\]/); /** * convert posix separator to native separator * * eg. * windows: C:/foo/bar -> c:\foo\bar * linux: /foo/bar -> /foo/bar * * @param {string} filename with posix separators * @returns {string} filename with native separators */ const posix2native = IS_POSIX ? (filename) => filename : (filename) => filename.replace(POSIX_SEP_RE, path.sep); /** * convert native separator to posix separator * * eg. * windows: C:\foo\bar -> c:/foo/bar * linux: /foo/bar -> /foo/bar * * @param {string} filename - filename with native separators * @returns {string} filename with posix separators */ const native2posix = IS_POSIX ? (filename) => filename : (filename) => filename.replace(NATIVE_SEP_RE, path.posix.sep); /** * converts params to native separator, resolves path and converts native back to posix * * needed on windows to handle posix paths in tsconfig * * @param dir {string|null} directory to resolve from * @param filename {string} filename or pattern to resolve * @returns string */ const resolve2posix = IS_POSIX ? (dir, filename) => dir ? path.resolve(dir, filename) : path.resolve(filename) : (dir, filename) => native2posix(dir ? path.resolve(posix2native(dir), posix2native(filename)) : path.resolve(posix2native(filename))); /** * * @param {import('./public.d.ts').TSConfckParseResult} result * @param {import('./public.d.ts').TSConfckParseOptions} [options] * @returns {string[]} */ function resolveReferencedTSConfigFiles(result, options$1) { const dir = path.dirname(result.tsconfigFile); return result.tsconfig.references.map((ref) => { return resolve2posix(dir, ref.path.endsWith(".json") ? ref.path : path.join(ref.path, options$1?.configName ?? "tsconfig.json")); }); } /** * @param {string} filename * @param {import('./public.d.ts').TSConfckParseResult} result * @returns {import('./public.d.ts').TSConfckParseResult} */ function resolveSolutionTSConfig(filename, result) { if (result.referenced && (result.tsconfig.compilerOptions?.allowJs ? TSJS_EXTENSIONS : TS_EXTENSIONS).some((ext) => filename.endsWith(ext)) && !isIncluded(filename, result)) { const solutionTSConfig = result.referenced.find((referenced) => isIncluded(filename, referenced)); if (solutionTSConfig) return solutionTSConfig; } return result; } /** * * @param {string} filename * @param {import('./public.d.ts').TSConfckParseResult} result * @returns {boolean} */ function isIncluded(filename, result) { const dir = native2posix(path.dirname(result.tsconfigFile)); const files = (result.tsconfig.files || []).map((file) => resolve2posix(dir, file)); const absoluteFilename = resolve2posix(null, filename); if (files.includes(filename)) return true; const allowJs = result.tsconfig.compilerOptions?.allowJs; if (isGlobMatch(absoluteFilename, dir, result.tsconfig.include || (result.tsconfig.files ? [] : [GLOB_ALL_PATTERN]), allowJs)) return !isGlobMatch(absoluteFilename, dir, result.tsconfig.exclude || [], allowJs); return false; } /** * test filenames agains glob patterns in tsconfig * * @param filename {string} posix style abolute path to filename to test * @param dir {string} posix style absolute path to directory of tsconfig containing patterns * @param patterns {string[]} glob patterns to match against * @param allowJs {boolean} allowJs setting in tsconfig to include js extensions in checks * @returns {boolean} true when at least one pattern matches filename */ function isGlobMatch(filename, dir, patterns, allowJs) { const extensions$1 = allowJs ? TSJS_EXTENSIONS : TS_EXTENSIONS; return patterns.some((pattern) => { let lastWildcardIndex = pattern.length; let hasWildcard = false; let hasExtension = false; let hasSlash = false; let lastSlashIndex = -1; for (let i$1 = pattern.length - 1; i$1 > -1; i$1--) { const c = pattern[i$1]; if (!hasWildcard) { if (c === "*" || c === "?") { lastWildcardIndex = i$1; hasWildcard = true; } } if (!hasSlash) { if (c === ".") hasExtension = true; else if (c === "/") { lastSlashIndex = i$1; hasSlash = true; } } if (hasWildcard && hasSlash) break; } if (!hasExtension && (!hasWildcard || lastWildcardIndex < lastSlashIndex)) { pattern += `${pattern.endsWith("/") ? "" : "/"}${GLOB_ALL_PATTERN}`; lastWildcardIndex = pattern.length - 1; hasWildcard = true; } if (lastWildcardIndex < pattern.length - 1 && !filename.endsWith(pattern.slice(lastWildcardIndex + 1))) return false; if (pattern.endsWith("*") && !extensions$1.some((ext) => filename.endsWith(ext))) return false; if (pattern === GLOB_ALL_PATTERN) return filename.startsWith(`${dir}/`); const resolvedPattern = resolve2posix(dir, pattern); let firstWildcardIndex = -1; for (let i$1 = 0; i$1 < resolvedPattern.length; i$1++) if (resolvedPattern[i$1] === "*" || resolvedPattern[i$1] === "?") { firstWildcardIndex = i$1; hasWildcard = true; break; } if (firstWildcardIndex > 1 && !filename.startsWith(resolvedPattern.slice(0, firstWildcardIndex - 1))) return false; if (!hasWildcard) return filename === resolvedPattern; else if (firstWildcardIndex + GLOB_ALL_PATTERN.length === resolvedPattern.length - (pattern.length - 1 - lastWildcardIndex) && resolvedPattern.slice(firstWildcardIndex, firstWildcardIndex + GLOB_ALL_PATTERN.length) === GLOB_ALL_PATTERN) return true; if (PATTERN_REGEX_CACHE.has(resolvedPattern)) return PATTERN_REGEX_CACHE.get(resolvedPattern).test(filename); const regex = pattern2regex(resolvedPattern, allowJs); PATTERN_REGEX_CACHE.set(resolvedPattern, regex); return regex.test(filename); }); } /** * @param {string} resolvedPattern * @param {boolean} allowJs * @returns {RegExp} */ function pattern2regex(resolvedPattern, allowJs) { let regexStr = "^"; for (let i$1 = 0; i$1 < resolvedPattern.length; i$1++) { const char = resolvedPattern[i$1]; if (char === "?") { regexStr += "[^\\/]"; continue; } if (char === "*") { if (resolvedPattern[i$1 + 1] === "*" && resolvedPattern[i$1 + 2] === "/") { i$1 += 2; regexStr += "(?:[^\\/]*\\/)*"; continue; } regexStr += "[^\\/]*"; continue; } if ("/.+^${}()|[]\\".includes(char)) regexStr += `\\`; regexStr += char; } if (resolvedPattern.endsWith("*")) regexStr += allowJs ? TSJS_EXTENSIONS_RE_GROUP : TS_EXTENSIONS_RE_GROUP; regexStr += "$"; return new RegExp(regexStr); } /** * replace tokens like ${configDir} * @param {import('./public.d.ts').TSConfckParseResult} result */ function replaceTokens(result) { if (result.tsconfig) result.tsconfig = JSON.parse(JSON.stringify(result.tsconfig).replaceAll(/"\${configDir}/g, `"${native2posix(path.dirname(result.tsconfigFile))}`)); } //#endregion //#region ../../node_modules/.pnpm/tsconfck@3.1.6_typescript@5.9.2/node_modules/tsconfck/src/find.js /** * find the closest tsconfig.json file * * @param {string} filename - path to file to find tsconfig for (absolute or relative to cwd) * @param {import('./public.d.ts').TSConfckFindOptions} [options] - options * @returns {Promise} absolute path to closest tsconfig.json or null if not found */ async function find(filename, options$1) { let dir = path.dirname(path.resolve(filename)); if (options$1?.ignoreNodeModules && isInNodeModules$1(dir)) return null; const cache$1 = options$1?.cache; const configName = options$1?.configName ?? "tsconfig.json"; if (cache$1?.hasConfigPath(dir, configName)) return cache$1.getConfigPath(dir, configName); const { promise, resolve: resolve$4, reject } = makePromise(); if (options$1?.root && !path.isAbsolute(options$1.root)) options$1.root = path.resolve(options$1.root); findUp(dir, { promise, resolve: resolve$4, reject }, options$1); return promise; } /** * * @param {string} dir * @param {{promise:Promise,resolve:(result:string|null)=>void,reject:(err:any)=>void}} madePromise * @param {import('./public.d.ts').TSConfckFindOptions} [options] - options */ function findUp(dir, { resolve: resolve$4, reject, promise }, options$1) { const { cache: cache$1, root, configName } = options$1 ?? {}; if (cache$1) if (cache$1.hasConfigPath(dir, configName)) { let cached; try { cached = cache$1.getConfigPath(dir, configName); } catch (e$1) { reject(e$1); return; } if (cached?.then) cached.then(resolve$4).catch(reject); else resolve$4(cached); } else cache$1.setConfigPath(dir, promise, configName); const tsconfig = path.join(dir, options$1?.configName ?? "tsconfig.json"); fs.stat(tsconfig, (err$2, stats) => { if (stats && (stats.isFile() || stats.isFIFO())) resolve$4(tsconfig); else if (err$2?.code !== "ENOENT") reject(err$2); else { let parent; if (root === dir || (parent = path.dirname(dir)) === dir) resolve$4(null); else findUp(parent, { promise, resolve: resolve$4, reject }, options$1); } }); } //#endregion //#region ../../node_modules/.pnpm/tsconfck@3.1.6_typescript@5.9.2/node_modules/tsconfck/src/to-json.js /** * convert content of tsconfig.json to regular json * * @param {string} tsconfigJson - content of tsconfig.json * @returns {string} content as regular json, comments and dangling commas have been replaced with whitespace */ function toJson(tsconfigJson) { const stripped = stripDanglingComma(stripJsonComments(stripBom(tsconfigJson))); if (stripped.trim() === "") return "{}"; else return stripped; } /** * replace dangling commas from pseudo-json string with single space * implementation heavily inspired by strip-json-comments * * @param {string} pseudoJson * @returns {string} */ function stripDanglingComma(pseudoJson) { let insideString = false; let offset$1 = 0; let result = ""; let danglingCommaPos = null; for (let i$1 = 0; i$1 < pseudoJson.length; i$1++) { const currentCharacter = pseudoJson[i$1]; if (currentCharacter === "\"") { if (!isEscaped(pseudoJson, i$1)) insideString = !insideString; } if (insideString) { danglingCommaPos = null; continue; } if (currentCharacter === ",") { danglingCommaPos = i$1; continue; } if (danglingCommaPos) { if (currentCharacter === "}" || currentCharacter === "]") { result += pseudoJson.slice(offset$1, danglingCommaPos) + " "; offset$1 = danglingCommaPos + 1; danglingCommaPos = null; } else if (!currentCharacter.match(/\s/)) danglingCommaPos = null; } } return result + pseudoJson.substring(offset$1); } /** * * @param {string} jsonString * @param {number} quotePosition * @returns {boolean} */ function isEscaped(jsonString, quotePosition) { let index = quotePosition - 1; let backslashCount = 0; while (jsonString[index] === "\\") { index -= 1; backslashCount += 1; } return Boolean(backslashCount % 2); } /** * * @param {string} string * @param {number?} start * @param {number?} end */ function strip(string, start, end) { return string.slice(start, end).replace(/\S/g, " "); } const singleComment = Symbol("singleComment"); const multiComment = Symbol("multiComment"); /** * @param {string} jsonString * @returns {string} */ function stripJsonComments(jsonString) { let isInsideString = false; /** @type {false | symbol} */ let isInsideComment = false; let offset$1 = 0; let result = ""; for (let index = 0; index < jsonString.length; index++) { const currentCharacter = jsonString[index]; const nextCharacter = jsonString[index + 1]; if (!isInsideComment && currentCharacter === "\"") { if (!isEscaped(jsonString, index)) isInsideString = !isInsideString; } if (isInsideString) continue; if (!isInsideComment && currentCharacter + nextCharacter === "//") { result += jsonString.slice(offset$1, index); offset$1 = index; isInsideComment = singleComment; index++; } else if (isInsideComment === singleComment && currentCharacter + nextCharacter === "\r\n") { index++; isInsideComment = false; result += strip(jsonString, offset$1, index); offset$1 = index; } else if (isInsideComment === singleComment && currentCharacter === "\n") { isInsideComment = false; result += strip(jsonString, offset$1, index); offset$1 = index; } else if (!isInsideComment && currentCharacter + nextCharacter === "/*") { result += jsonString.slice(offset$1, index); offset$1 = index; isInsideComment = multiComment; index++; } else if (isInsideComment === multiComment && currentCharacter + nextCharacter === "*/") { index++; isInsideComment = false; result += strip(jsonString, offset$1, index + 1); offset$1 = index + 1; } } return result + (isInsideComment ? strip(jsonString.slice(offset$1)) : jsonString.slice(offset$1)); } /** * @param {string} string * @returns {string} */ function stripBom(string) { if (string.charCodeAt(0) === 65279) return string.slice(1); return string; } //#endregion //#region ../../node_modules/.pnpm/tsconfck@3.1.6_typescript@5.9.2/node_modules/tsconfck/src/parse.js const not_found_result = { tsconfigFile: null, tsconfig: {} }; /** * parse the closest tsconfig.json file * * @param {string} filename - path to a tsconfig .json or a source file or directory (absolute or relative to cwd) * @param {import('./public.d.ts').TSConfckParseOptions} [options] - options * @returns {Promise} * @throws {TSConfckParseError} */ async function parse$14(filename, options$1) { /** @type {import('./cache.js').TSConfckCache} */ const cache$1 = options$1?.cache; if (cache$1?.hasParseResult(filename)) return getParsedDeep(filename, cache$1, options$1); const { resolve: resolve$4, reject, promise } = makePromise(); cache$1?.setParseResult(filename, promise, true); try { let tsconfigFile = await resolveTSConfigJson(filename, cache$1) || await find(filename, options$1); if (!tsconfigFile) { resolve$4(not_found_result); return promise; } let result; if (filename !== tsconfigFile && cache$1?.hasParseResult(tsconfigFile)) result = await getParsedDeep(tsconfigFile, cache$1, options$1); else { result = await parseFile$1(tsconfigFile, cache$1, filename === tsconfigFile); await Promise.all([parseExtends(result, cache$1), parseReferences(result, options$1)]); } replaceTokens(result); resolve$4(resolveSolutionTSConfig(filename, result)); } catch (e$1) { reject(e$1); } return promise; } /** * ensure extends and references are parsed * * @param {string} filename - cached file * @param {import('./cache.js').TSConfckCache} cache - cache * @param {import('./public.d.ts').TSConfckParseOptions} options - options */ async function getParsedDeep(filename, cache$1, options$1) { const result = await cache$1.getParseResult(filename); if (result.tsconfig.extends && !result.extended || result.tsconfig.references && !result.referenced) { const promise = Promise.all([parseExtends(result, cache$1), parseReferences(result, options$1)]).then(() => result); cache$1.setParseResult(filename, promise, true); return promise; } return result; } /** * * @param {string} tsconfigFile - path to tsconfig file * @param {import('./cache.js').TSConfckCache} [cache] - cache * @param {boolean} [skipCache] - skip cache * @returns {Promise} */ async function parseFile$1(tsconfigFile, cache$1, skipCache) { if (!skipCache && cache$1?.hasParseResult(tsconfigFile) && !cache$1.getParseResult(tsconfigFile)._isRootFile_) return cache$1.getParseResult(tsconfigFile); const promise = promises.readFile(tsconfigFile, "utf-8").then(toJson).then((json) => { const parsed = JSON.parse(json); applyDefaults(parsed, tsconfigFile); return { tsconfigFile, tsconfig: normalizeTSConfig(parsed, path.dirname(tsconfigFile)) }; }).catch((e$1) => { throw new TSConfckParseError(`parsing ${tsconfigFile} failed: ${e$1}`, "PARSE_FILE", tsconfigFile, e$1); }); if (!skipCache && (!cache$1?.hasParseResult(tsconfigFile) || !cache$1.getParseResult(tsconfigFile)._isRootFile_)) cache$1?.setParseResult(tsconfigFile, promise); return promise; } /** * normalize to match the output of ts.parseJsonConfigFileContent * * @param {any} tsconfig - typescript tsconfig output * @param {string} dir - directory */ function normalizeTSConfig(tsconfig, dir) { const baseUrl = tsconfig.compilerOptions?.baseUrl; if (baseUrl && !baseUrl.startsWith("${") && !path.isAbsolute(baseUrl)) tsconfig.compilerOptions.baseUrl = resolve2posix(dir, baseUrl); return tsconfig; } /** * * @param {import('./public.d.ts').TSConfckParseResult} result * @param {import('./public.d.ts').TSConfckParseOptions} [options] * @returns {Promise} */ async function parseReferences(result, options$1) { if (!result.tsconfig.references) return; const referencedFiles = resolveReferencedTSConfigFiles(result, options$1); const referenced = await Promise.all(referencedFiles.map((file) => parseFile$1(file, options$1?.cache))); await Promise.all(referenced.map((ref) => parseExtends(ref, options$1?.cache))); referenced.forEach((ref) => { ref.solution = result; replaceTokens(ref); }); result.referenced = referenced; } /** * @param {import('./public.d.ts').TSConfckParseResult} result * @param {import('./cache.js').TSConfckCache}[cache] * @returns {Promise} */ async function parseExtends(result, cache$1) { if (!result.tsconfig.extends) return; /** @type {import('./public.d.ts').TSConfckParseResult[]} */ const extended = [{ tsconfigFile: result.tsconfigFile, tsconfig: JSON.parse(JSON.stringify(result.tsconfig)) }]; let pos = 0; /** @type {string[]} */ const extendsPath = []; let currentBranchDepth = 0; while (pos < extended.length) { const extending = extended[pos]; extendsPath.push(extending.tsconfigFile); if (extending.tsconfig.extends) { currentBranchDepth += 1; /** @type {string[]} */ let resolvedExtends; if (!Array.isArray(extending.tsconfig.extends)) resolvedExtends = [resolveExtends(extending.tsconfig.extends, extending.tsconfigFile)]; else resolvedExtends = extending.tsconfig.extends.reverse().map((ex) => resolveExtends(ex, extending.tsconfigFile)); const circularExtends = resolvedExtends.find((tsconfigFile) => extendsPath.includes(tsconfigFile)); if (circularExtends) throw new TSConfckParseError(`Circular dependency in "extends": ${extendsPath.concat([circularExtends]).join(" -> ")}`, "EXTENDS_CIRCULAR", result.tsconfigFile); extended.splice(pos + 1, 0, ...await Promise.all(resolvedExtends.map((file) => parseFile$1(file, cache$1)))); } else { extendsPath.splice(-currentBranchDepth); currentBranchDepth = 0; } pos = pos + 1; } result.extended = extended; for (const ext of result.extended.slice(1)) extendTSConfig(result, ext); } /** * * @param {string} extended * @param {string} from * @returns {string} */ function resolveExtends(extended, from) { if ([".", ".."].includes(extended)) extended = extended + "/tsconfig.json"; const req$4 = createRequire$1(from); let error$1; try { return req$4.resolve(extended); } catch (e$1) { error$1 = e$1; } if (extended[0] !== "." && !path.isAbsolute(extended)) try { return req$4.resolve(`${extended}/tsconfig.json`); } catch (e$1) { error$1 = e$1; } throw new TSConfckParseError(`failed to resolve "extends":"${extended}" in ${from}`, "EXTENDS_RESOLVE", from, error$1); } const EXTENDABLE_KEYS = [ "compilerOptions", "files", "include", "exclude", "watchOptions", "compileOnSave", "typeAcquisition", "buildOptions" ]; /** * * @param {import('./public.d.ts').TSConfckParseResult} extending * @param {import('./public.d.ts').TSConfckParseResult} extended * @returns void */ function extendTSConfig(extending, extended) { const extendingConfig = extending.tsconfig; const extendedConfig = extended.tsconfig; const relativePath = native2posix(path.relative(path.dirname(extending.tsconfigFile), path.dirname(extended.tsconfigFile))); for (const key of Object.keys(extendedConfig).filter((key$1) => EXTENDABLE_KEYS.includes(key$1))) if (key === "compilerOptions") { if (!extendingConfig.compilerOptions) extendingConfig.compilerOptions = {}; for (const option of Object.keys(extendedConfig.compilerOptions)) { if (Object.prototype.hasOwnProperty.call(extendingConfig.compilerOptions, option)) continue; extendingConfig.compilerOptions[option] = rebaseRelative(option, extendedConfig.compilerOptions[option], relativePath); } } else if (extendingConfig[key] === void 0) if (key === "watchOptions") { extendingConfig.watchOptions = {}; for (const option of Object.keys(extendedConfig.watchOptions)) extendingConfig.watchOptions[option] = rebaseRelative(option, extendedConfig.watchOptions[option], relativePath); } else extendingConfig[key] = rebaseRelative(key, extendedConfig[key], relativePath); } const REBASE_KEYS = [ "files", "include", "exclude", "baseUrl", "rootDir", "rootDirs", "typeRoots", "outDir", "outFile", "declarationDir", "excludeDirectories", "excludeFiles" ]; /** @typedef {string | string[]} PathValue */ /** * * @param {string} key * @param {PathValue} value * @param {string} prependPath * @returns {PathValue} */ function rebaseRelative(key, value$1, prependPath) { if (!REBASE_KEYS.includes(key)) return value$1; if (Array.isArray(value$1)) return value$1.map((x) => rebasePath(x, prependPath)); else return rebasePath(value$1, prependPath); } /** * * @param {string} value * @param {string} prependPath * @returns {string} */ function rebasePath(value$1, prependPath) { if (path.isAbsolute(value$1) || value$1.startsWith("${configDir}")) return value$1; else return path.posix.normalize(path.posix.join(prependPath, value$1)); } var TSConfckParseError = class TSConfckParseError extends Error { /** * error code * @type {string} */ code; /** * error cause * @type { Error | undefined} */ cause; /** * absolute path of tsconfig file where the error happened * @type {string} */ tsconfigFile; /** * * @param {string} message - error message * @param {string} code - error code * @param {string} tsconfigFile - path to tsconfig file * @param {Error?} cause - cause of this error */ constructor(message, code, tsconfigFile, cause) { super(message); Object.setPrototypeOf(this, TSConfckParseError.prototype); this.name = TSConfckParseError.name; this.code = code; this.cause = cause; this.tsconfigFile = tsconfigFile; } }; /** * * @param {any} tsconfig * @param {string} tsconfigFile */ function applyDefaults(tsconfig, tsconfigFile) { if (isJSConfig(tsconfigFile)) tsconfig.compilerOptions = { ...DEFAULT_JSCONFIG_COMPILER_OPTIONS, ...tsconfig.compilerOptions }; } const DEFAULT_JSCONFIG_COMPILER_OPTIONS = { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true }; /** * @param {string} configFileName */ function isJSConfig(configFileName) { return path.basename(configFileName) === "jsconfig.json"; } //#endregion //#region ../../node_modules/.pnpm/tsconfck@3.1.6_typescript@5.9.2/node_modules/tsconfck/src/parse-native.js /** @typedef TSDiagnosticError { code: number; category: number; messageText: string; start?: number; } TSDiagnosticError */ //#endregion //#region ../../node_modules/.pnpm/tsconfck@3.1.6_typescript@5.9.2/node_modules/tsconfck/src/cache.js /** @template T */ var TSConfckCache = class { /** * clear cache, use this if you have a long running process and tsconfig files have been added,changed or deleted */ clear() { this.#configPaths.clear(); this.#parsed.clear(); } /** * has cached closest config for files in dir * @param {string} dir * @param {string} [configName=tsconfig.json] * @returns {boolean} */ hasConfigPath(dir, configName = "tsconfig.json") { return this.#configPaths.has(`${dir}/${configName}`); } /** * get cached closest tsconfig for files in dir * @param {string} dir * @param {string} [configName=tsconfig.json] * @returns {Promise|string|null} * @throws {unknown} if cached value is an error */ getConfigPath(dir, configName = "tsconfig.json") { const key = `${dir}/${configName}`; const value$1 = this.#configPaths.get(key); if (value$1 == null || value$1.length || value$1.then) return value$1; else throw value$1; } /** * has parsed tsconfig for file * @param {string} file * @returns {boolean} */ hasParseResult(file) { return this.#parsed.has(file); } /** * get parsed tsconfig for file * @param {string} file * @returns {Promise|T} * @throws {unknown} if cached value is an error */ getParseResult(file) { const value$1 = this.#parsed.get(file); if (value$1.then || value$1.tsconfig) return value$1; else throw value$1; } /** * @internal * @private * @param file * @param {boolean} isRootFile a flag to check if current file which involking the parse() api, used to distinguish the normal cache which only parsed by parseFile() * @param {Promise} result */ setParseResult(file, result, isRootFile = false) { Object.defineProperty(result, "_isRootFile_", { value: isRootFile, writable: false, enumerable: false, configurable: false }); this.#parsed.set(file, result); result.then((parsed) => { if (this.#parsed.get(file) === result) this.#parsed.set(file, parsed); }).catch((e$1) => { if (this.#parsed.get(file) === result) this.#parsed.set(file, e$1); }); } /** * @internal * @private * @param {string} dir * @param {Promise} configPath * @param {string} [configName=tsconfig.json] */ setConfigPath(dir, configPath, configName = "tsconfig.json") { const key = `${dir}/${configName}`; this.#configPaths.set(key, configPath); configPath.then((path$13) => { if (this.#configPaths.get(key) === configPath) this.#configPaths.set(key, path$13); }).catch((e$1) => { if (this.#configPaths.get(key) === configPath) this.#configPaths.set(key, e$1); }); } /** * map directories to their closest tsconfig.json * @internal * @private * @type{Map|string|null)>} */ #configPaths = /* @__PURE__ */ new Map(); /** * map files to their parsed tsconfig result * @internal * @private * @type {Map|T)> } */ #parsed = /* @__PURE__ */ new Map(); }; //#endregion //#region src/node/plugins/esbuild.ts var import_picocolors$31 = /* @__PURE__ */ __toESM(require_picocolors(), 1); const debug$17 = createDebugger("vite:esbuild"); const IIFE_BEGIN_RE = /(?:const|var)\s+\S+\s*=\s*\(?function\([^()]*\)\s*\{\s*"use strict";/; const validExtensionRE = /\.\w+$/; const jsxExtensionsRE = /\.(?:j|t)sx\b/; const defaultEsbuildSupported = { "dynamic-import": true, "import-meta": true }; async function transformWithEsbuild(code, filename, options$1, inMap, config$2, watcher) { let loader$1 = options$1?.loader; if (!loader$1) { const ext = path.extname(validExtensionRE.test(filename) ? filename : cleanUrl(filename)).slice(1); if (ext === "cjs" || ext === "mjs") loader$1 = "js"; else if (ext === "cts" || ext === "mts") loader$1 = "ts"; else loader$1 = ext; } let tsconfigRaw = options$1?.tsconfigRaw; if (typeof tsconfigRaw !== "string") { const meaningfulFields = [ "alwaysStrict", "experimentalDecorators", "importsNotUsedAsValues", "jsx", "jsxFactory", "jsxFragmentFactory", "jsxImportSource", "preserveValueImports", "target", "useDefineForClassFields", "verbatimModuleSyntax" ]; const compilerOptionsForFile = {}; if (loader$1 === "ts" || loader$1 === "tsx") try { const { tsconfig: loadedTsconfig, tsconfigFile } = await loadTsconfigJsonForFile(filename, config$2); if (watcher && tsconfigFile && config$2) ensureWatchedFile(watcher, tsconfigFile, config$2.root); const loadedCompilerOptions = loadedTsconfig.compilerOptions ?? {}; for (const field of meaningfulFields) if (field in loadedCompilerOptions) compilerOptionsForFile[field] = loadedCompilerOptions[field]; } catch (e$1) { if (e$1 instanceof TSConfckParseError) { if (watcher && e$1.tsconfigFile && config$2) ensureWatchedFile(watcher, e$1.tsconfigFile, config$2.root); } throw e$1; } const compilerOptions = { ...compilerOptionsForFile, ...tsconfigRaw?.compilerOptions }; if (compilerOptions.useDefineForClassFields === void 0 && compilerOptions.target === void 0) compilerOptions.useDefineForClassFields = false; if (options$1) { if (options$1.jsx) compilerOptions.jsx = void 0; if (options$1.jsxFactory) compilerOptions.jsxFactory = void 0; if (options$1.jsxFragment) compilerOptions.jsxFragmentFactory = void 0; if (options$1.jsxImportSource) compilerOptions.jsxImportSource = void 0; } tsconfigRaw = { ...tsconfigRaw, compilerOptions }; } const resolvedOptions = { sourcemap: true, sourcefile: filename, ...options$1, loader: loader$1, tsconfigRaw }; delete resolvedOptions.include; delete resolvedOptions.exclude; delete resolvedOptions.jsxInject; try { const result = await transform(code, resolvedOptions); let map$1; if (inMap && resolvedOptions.sourcemap) { const nextMap = JSON.parse(result.map); nextMap.sourcesContent = []; map$1 = combineSourcemaps(filename, [nextMap, inMap]); } else map$1 = resolvedOptions.sourcemap && resolvedOptions.sourcemap !== "inline" ? JSON.parse(result.map) : { mappings: "" }; return { ...result, map: map$1 }; } catch (e$1) { debug$17?.(`esbuild error with options used: `, resolvedOptions); if (e$1.errors) { e$1.frame = ""; e$1.errors.forEach((m$2) => { if (m$2.text === "Experimental decorators are not currently enabled" || m$2.text === "Parameter decorators only work when experimental decorators are enabled") m$2.text += ". Vite 5 now uses esbuild 0.18 and you need to enable them by adding \"experimentalDecorators\": true in your \"tsconfig.json\" file."; e$1.frame += `\n` + prettifyMessage(m$2, code); }); e$1.loc = e$1.errors[0].location; } throw e$1; } } function esbuildPlugin(config$2) { const { jsxInject, include, exclude,...esbuildTransformOptions } = config$2.esbuild; const filter$1 = createFilter(include || /\.(m?ts|[jt]sx)$/, exclude || /\.js$/); const transformOptions = { target: "esnext", charset: "utf8", ...esbuildTransformOptions, minify: false, minifyIdentifiers: false, minifySyntax: false, minifyWhitespace: false, treeShaking: false, keepNames: false, supported: { ...defaultEsbuildSupported, ...esbuildTransformOptions.supported } }; let server; return { name: "vite:esbuild", configureServer(_server) { server = _server; }, async transform(code, id) { if (filter$1(id) || filter$1(cleanUrl(id))) { const result = await transformWithEsbuild(code, id, transformOptions, void 0, config$2, server?.watcher); if (result.warnings.length) result.warnings.forEach((m$2) => { this.warn(prettifyMessage(m$2, code)); }); if (jsxInject && jsxExtensionsRE.test(id)) result.code = jsxInject + ";" + result.code; return { code: result.code, map: result.map }; } } }; } const rollupToEsbuildFormatMap = { es: "esm", cjs: "cjs", iife: void 0 }; const injectEsbuildHelpers = (esbuildCode, format$3) => { const contentIndex = format$3 === "iife" ? Math.max(esbuildCode.search(IIFE_BEGIN_RE), 0) : format$3 === "umd" ? esbuildCode.indexOf(`(function(`) : 0; if (contentIndex > 0) { const esbuildHelpers = esbuildCode.slice(0, contentIndex); return esbuildCode.slice(contentIndex).replace("\"use strict\";", (m$2) => m$2 + esbuildHelpers); } return esbuildCode; }; const buildEsbuildPlugin = () => { return { name: "vite:esbuild-transpile", applyToEnvironment(environment) { return environment.config.esbuild !== false; }, async renderChunk(code, chunk, opts) { if (opts.__vite_skip_esbuild__) return null; const config$2 = this.environment.config; const options$1 = resolveEsbuildTranspileOptions(config$2, opts.format); if (!options$1) return null; const res = await transformWithEsbuild(code, chunk.fileName, options$1, void 0, config$2); if (config$2.build.lib) res.code = injectEsbuildHelpers(res.code, opts.format); return res; } }; }; function resolveEsbuildTranspileOptions(config$2, format$3) { const target = config$2.build.target; const minify = config$2.build.minify === "esbuild"; if ((!target || target === "esnext") && !minify) return null; const isEsLibBuild = config$2.build.lib && format$3 === "es"; const esbuildOptions = config$2.esbuild || {}; const options$1 = { charset: "utf8", ...esbuildOptions, loader: "js", target: target || void 0, format: rollupToEsbuildFormatMap[format$3], supported: { ...defaultEsbuildSupported, ...esbuildOptions.supported } }; if (!minify) return { ...options$1, minify: false, minifyIdentifiers: false, minifySyntax: false, minifyWhitespace: false, treeShaking: false }; if (options$1.minifyIdentifiers != null || options$1.minifySyntax != null || options$1.minifyWhitespace != null) if (isEsLibBuild) return { ...options$1, minify: false, minifyIdentifiers: options$1.minifyIdentifiers ?? true, minifySyntax: options$1.minifySyntax ?? true, minifyWhitespace: false, treeShaking: true }; else return { ...options$1, minify: false, minifyIdentifiers: options$1.minifyIdentifiers ?? true, minifySyntax: options$1.minifySyntax ?? true, minifyWhitespace: options$1.minifyWhitespace ?? true, treeShaking: true }; if (isEsLibBuild) return { ...options$1, minify: false, minifyIdentifiers: true, minifySyntax: true, minifyWhitespace: false, treeShaking: true }; else return { ...options$1, minify: true, treeShaking: true }; } function prettifyMessage(m$2, code) { let res = import_picocolors$31.default.yellow(m$2.text); if (m$2.location) res += `\n` + generateCodeFrame(code, m$2.location); return res + `\n`; } let globalTSConfckCache; const tsconfckCacheMap = /* @__PURE__ */ new WeakMap(); function getTSConfckCache(config$2) { if (!config$2) return globalTSConfckCache ??= new TSConfckCache(); let cache$1 = tsconfckCacheMap.get(config$2); if (!cache$1) { cache$1 = new TSConfckCache(); tsconfckCacheMap.set(config$2, cache$1); } return cache$1; } async function loadTsconfigJsonForFile(filename, config$2) { const { tsconfig, tsconfigFile } = await parse$14(filename, { cache: getTSConfckCache(config$2), ignoreNodeModules: true }); return { tsconfigFile, tsconfig }; } async function reloadOnTsconfigChange(server, changedFile) { if (changedFile.endsWith(".json")) { const cache$1 = getTSConfckCache(server.config); if (changedFile.endsWith("/tsconfig.json") || cache$1.hasParseResult(changedFile)) { server.config.logger.info(`changed tsconfig file detected: ${changedFile} - Clearing cache and forcing full-reload to ensure TypeScript is compiled with updated config values.`, { clear: server.config.clearScreen, timestamp: true }); for (const environment of Object.values(server.environments)) environment.moduleGraph.invalidateAll(); cache$1.clear(); for (const environment of Object.values(server.environments)) environment.hot.send({ type: "full-reload", path: "*" }); } } } //#endregion //#region ../../node_modules/.pnpm/artichokie@0.4.2/node_modules/artichokie/dist/index.js const AsyncFunction = async function() {}.constructor; const codeToDataUrl = (code) => `data:application/javascript,${encodeURIComponent(code + "\n//# sourceURL=[worker-eval(artichokie)]")}`; const viteSsrDynamicImport = "__vite_ssr_dynamic_import__"; const stackBlitzImport = "𝐢𝐦𝐩𝐨𝐫𝐭"; var Worker$1 = class { /** @internal */ _isModule; /** @internal */ _code; /** @internal */ _parentFunctions; /** @internal */ _max; /** @internal */ _pool; /** @internal */ _idlePool; /** @internal */ _queue; constructor(fn, options$1 = {}) { this._isModule = options$1.type === "module"; this._code = genWorkerCode(fn, this._isModule, 5 * 1e3, options$1.parentFunctions ?? {}); this._parentFunctions = options$1.parentFunctions ?? {}; const defaultMax = Math.max(1, (os.availableParallelism?.() ?? os.cpus().length) - 1); this._max = options$1.max || defaultMax; this._pool = []; this._idlePool = []; this._queue = []; } async run(...args) { const worker = await this._getAvailableWorker(); return new Promise((resolve$4, reject) => { worker.currentResolve = resolve$4; worker.currentReject = reject; worker.postMessage({ args }); }); } stop() { this._pool.forEach((w$1) => w$1.unref()); this._queue.forEach(([, reject]) => reject(/* @__PURE__ */ new Error("Main worker pool stopped before a worker was available."))); this._pool = []; this._idlePool = []; this._queue = []; } /** @internal */ _createWorker(parentFunctionSyncMessagePort, parentFunctionAsyncMessagePort, lockState) { const options$1 = { workerData: [ parentFunctionSyncMessagePort, parentFunctionAsyncMessagePort, lockState ], transferList: [parentFunctionSyncMessagePort, parentFunctionAsyncMessagePort] }; if (this._isModule) return new Worker(new URL(codeToDataUrl(this._code)), options$1); return new Worker(this._code, { ...options$1, eval: true }); } /** @internal */ async _getAvailableWorker() { if (this._idlePool.length) return this._idlePool.shift(); if (this._pool.length < this._max) { const parentFunctionResponder = createParentFunctionResponder(this._parentFunctions); const worker = this._createWorker(parentFunctionResponder.workerPorts.sync, parentFunctionResponder.workerPorts.async, parentFunctionResponder.lockState); worker.on("message", async (args) => { if ("result" in args) { worker.currentResolve?.(args.result); worker.currentResolve = null; } else { if (args.error instanceof ReferenceError) args.error.message += ". Maybe you forgot to pass the function to parentFunction?"; worker.currentReject?.(args.error); worker.currentReject = null; } this._assignDoneWorker(worker); }); worker.on("error", (err$2) => { worker.currentReject?.(err$2); worker.currentReject = null; parentFunctionResponder.close(); }); worker.on("exit", (code) => { const i$1 = this._pool.indexOf(worker); if (i$1 > -1) this._pool.splice(i$1, 1); if (code !== 0 && worker.currentReject) { worker.currentReject(/* @__PURE__ */ new Error(`Worker stopped with non-0 exit code ${code}`)); worker.currentReject = null; parentFunctionResponder.close(); } }); this._pool.push(worker); return worker; } let resolve$4; let reject; const onWorkerAvailablePromise = new Promise((r$1, rj) => { resolve$4 = r$1; reject = rj; }); this._queue.push([resolve$4, reject]); return onWorkerAvailablePromise; } /** @internal */ _assignDoneWorker(worker) { if (this._queue.length) { const [resolve$4] = this._queue.shift(); resolve$4(worker); return; } this._idlePool.push(worker); } }; function createParentFunctionResponder(parentFunctions) { const lockState = new Int32Array(new SharedArrayBuffer(4)); const unlock = () => { Atomics.store(lockState, 0, 0); Atomics.notify(lockState, 0); }; const parentFunctionSyncMessageChannel = new MessageChannel(); const parentFunctionAsyncMessageChannel = new MessageChannel(); const parentFunctionSyncMessagePort = parentFunctionSyncMessageChannel.port1; const parentFunctionAsyncMessagePort = parentFunctionAsyncMessageChannel.port1; const syncResponse = (data) => { parentFunctionSyncMessagePort.postMessage(data); unlock(); }; parentFunctionSyncMessagePort.on("message", async (args) => { let syncResult; try { syncResult = parentFunctions[args.name](...args.args); } catch (error$1) { syncResponse({ id: args.id, error: error$1 }); return; } if (!(typeof syncResult === "object" && syncResult !== null && "then" in syncResult && typeof syncResult.then === "function")) { syncResponse({ id: args.id, result: syncResult }); return; } syncResponse({ id: args.id, isAsync: true }); try { const result = await syncResult; parentFunctionAsyncMessagePort.postMessage({ id: args.id, result }); } catch (error$1) { parentFunctionAsyncMessagePort.postMessage({ id: args.id, error: error$1 }); } }); parentFunctionSyncMessagePort.unref(); return { close: () => { parentFunctionSyncMessagePort.close(); parentFunctionAsyncMessagePort.close(); }, lockState, workerPorts: { sync: parentFunctionSyncMessageChannel.port2, async: parentFunctionAsyncMessageChannel.port2 } }; } function genWorkerCode(fn, isModule, waitTimeout, parentFunctions) { const createLock = (performance$2, lockState) => { return { lock: () => { Atomics.store(lockState, 0, 1); }, waitUnlock: () => { let utilizationBefore; while (true) { const status$1 = Atomics.wait(lockState, 0, 1, waitTimeout); if (status$1 === "timed-out") { if (utilizationBefore === void 0) { utilizationBefore = performance$2.eventLoopUtilization(); continue; } utilizationBefore = performance$2.eventLoopUtilization(utilizationBefore); if (utilizationBefore.utilization > .9) continue; throw new Error(status$1); } break; } } }; }; const createParentFunctionRequester = (syncPort, asyncPort, receive, lock) => { let id = 0; const resolvers = /* @__PURE__ */ new Map(); const call$1 = (key) => (...args) => { id++; lock.lock(); syncPort.postMessage({ id, name: key, args }); lock.waitUnlock(); const resArgs = receive(syncPort).message; if (resArgs.isAsync) { let resolve$4, reject; const promise = new Promise((res, rej) => { resolve$4 = res; reject = rej; }); resolvers.set(id, { resolve: resolve$4, reject }); return promise; } if ("error" in resArgs) throw resArgs.error; else return resArgs.result; }; asyncPort.on("message", (args) => { const id$1 = args.id; if (resolvers.has(id$1)) { const { resolve: resolve$4, reject } = resolvers.get(id$1); resolvers.delete(id$1); if ("result" in args) resolve$4(args.result); else reject(args.error); } }); return { call: call$1 }; }; const fnString = fn.toString().replaceAll(stackBlitzImport, "import").replaceAll(viteSsrDynamicImport, "import"); return ` ${isModule ? "import { parentPort, receiveMessageOnPort, workerData } from 'worker_threads'" : "const { parentPort, receiveMessageOnPort, workerData } = require('worker_threads')"} ${isModule ? "import { performance } from 'node:perf_hooks'" : "const { performance } = require('node:perf_hooks')"} const [parentFunctionSyncMessagePort, parentFunctionAsyncMessagePort, lockState] = workerData const waitTimeout = ${waitTimeout} const createLock = ${createLock.toString()} const parentFunctionRequester = (${createParentFunctionRequester.toString()})( parentFunctionSyncMessagePort, parentFunctionAsyncMessagePort, receiveMessageOnPort, createLock(performance, lockState) ) const doWorkPromise = (async () => { ${Object.keys(parentFunctions).map((key) => `const ${key} = parentFunctionRequester.call(${JSON.stringify(key)});`).join("\n")} return await (${fnString})() })() let doWork parentPort.on('message', async (args) => { doWork ||= await doWorkPromise try { const res = await doWork(...args.args) parentPort.postMessage({ result: res }) } catch (e) { parentPort.postMessage({ error: e }) } }) `; } const importRe = /\bimport\s*\(/g; const internalImportName = "__artichokie_local_import__"; var FakeWorker = class { /** @internal */ _fn; constructor(fn, options$1 = {}) { const declareRequire = options$1.type !== "module"; const argsAndCode = genFakeWorkerArgsAndCode(fn, declareRequire, options$1.parentFunctions ?? {}); const localImport = (specifier) => import(specifier); const args = [ ...declareRequire ? [createRequire(import.meta.url)] : [], localImport, options$1.parentFunctions ]; this._fn = new AsyncFunction(...argsAndCode)(...args); } async run(...args) { try { return await (await this._fn)(...args); } catch (err$2) { if (err$2 instanceof ReferenceError) err$2.message += ". Maybe you forgot to pass the function to parentFunction?"; throw err$2; } } stop() {} }; function genFakeWorkerArgsAndCode(fn, declareRequire, parentFunctions) { const fnString = fn.toString().replace(importRe, `${internalImportName}(`).replaceAll(stackBlitzImport, internalImportName).replaceAll(viteSsrDynamicImport, internalImportName); return [ ...declareRequire ? ["require"] : [], internalImportName, "parentFunctions", ` ${Object.keys(parentFunctions).map((key) => `const ${key} = parentFunctions[${JSON.stringify(key)}];`).join("\n")} return await (${fnString})() ` ]; } var WorkerWithFallback = class { /** @internal */ _disableReal; /** @internal */ _realWorker; /** @internal */ _fakeWorker; /** @internal */ _shouldUseFake; constructor(fn, options$1) { this._disableReal = options$1.max !== void 0 && options$1.max <= 0; this._realWorker = new Worker$1(fn, options$1); this._fakeWorker = new FakeWorker(fn, options$1); this._shouldUseFake = options$1.shouldUseFake; } async run(...args) { const useFake = this._disableReal || this._shouldUseFake(...args); return this[useFake ? "_fakeWorker" : "_realWorker"].run(...args); } stop() { this._realWorker.stop(); this._fakeWorker.stop(); } }; //#endregion //#region src/node/plugins/terser.ts let terserPath; const loadTerserPath = (root) => { if (terserPath) return terserPath; try { terserPath = requireResolveFromRootWithFallback(root, "terser"); } catch (e$1) { if (e$1.code === "MODULE_NOT_FOUND") throw new Error("terser not found. Since Vite v3, terser has become an optional dependency. You need to install it."); else { const message = /* @__PURE__ */ new Error(`terser failed to load:\n${e$1.message}`); message.stack = e$1.stack + "\n" + message.stack; throw message; } } return terserPath; }; function terserPlugin(config$2) { const { maxWorkers,...terserOptions } = config$2.build.terserOptions; const makeWorker = () => new WorkerWithFallback(() => async (terserPath$1, code, options$1) => { const terser = (await import(terserPath$1)).default; try { return await terser.minify(code, options$1); } catch (e$1) { throw { stack: e$1.stack, ...e$1 }; } }, { shouldUseFake(_terserPath, _code, options$1) { return !!(typeof options$1.mangle === "object" && (options$1.mangle.nth_identifier?.get || typeof options$1.mangle.properties === "object" && options$1.mangle.properties.nth_identifier?.get) || typeof options$1.format?.comments === "function" || typeof options$1.output?.comments === "function" || options$1.nameCache); }, max: maxWorkers }); let worker; return { name: "vite:terser", applyToEnvironment(environment) { return !!environment.config.build.minify; }, async renderChunk(code, chunk, outputOptions) { if (config$2.build.minify !== "terser" && !outputOptions.__vite_force_terser__) return null; if (config$2.build.lib && outputOptions.format === "es") return null; worker ||= makeWorker(); const terserPath$1 = pathToFileURL(loadTerserPath(config$2.root)).href; try { const res = await worker.run(terserPath$1, code, { safari10: true, ...terserOptions, sourceMap: !!outputOptions.sourcemap, module: outputOptions.format.startsWith("es"), toplevel: outputOptions.format === "cjs" }); return { code: res.code, map: res.map }; } catch (e$1) { if (e$1.line !== void 0 && e$1.col !== void 0) e$1.loc = { file: chunk.fileName, line: e$1.line, column: e$1.col }; if (e$1.pos !== void 0) e$1.frame = generateCodeFrame(code, e$1.pos); throw e$1; } }, closeBundle() { worker?.stop(); } }; } //#endregion //#region ../../node_modules/.pnpm/mrmime@2.0.1/node_modules/mrmime/index.mjs const mimes = { "3g2": "video/3gpp2", "3gp": "video/3gpp", "3gpp": "video/3gpp", "3mf": "model/3mf", "aac": "audio/aac", "ac": "application/pkix-attr-cert", "adp": "audio/adpcm", "adts": "audio/aac", "ai": "application/postscript", "aml": "application/automationml-aml+xml", "amlx": "application/automationml-amlx+zip", "amr": "audio/amr", "apng": "image/apng", "appcache": "text/cache-manifest", "appinstaller": "application/appinstaller", "appx": "application/appx", "appxbundle": "application/appxbundle", "asc": "application/pgp-keys", "atom": "application/atom+xml", "atomcat": "application/atomcat+xml", "atomdeleted": "application/atomdeleted+xml", "atomsvc": "application/atomsvc+xml", "au": "audio/basic", "avci": "image/avci", "avcs": "image/avcs", "avif": "image/avif", "aw": "application/applixware", "bdoc": "application/bdoc", "bin": "application/octet-stream", "bmp": "image/bmp", "bpk": "application/octet-stream", "btf": "image/prs.btif", "btif": "image/prs.btif", "buffer": "application/octet-stream", "ccxml": "application/ccxml+xml", "cdfx": "application/cdfx+xml", "cdmia": "application/cdmi-capability", "cdmic": "application/cdmi-container", "cdmid": "application/cdmi-domain", "cdmio": "application/cdmi-object", "cdmiq": "application/cdmi-queue", "cer": "application/pkix-cert", "cgm": "image/cgm", "cjs": "application/node", "class": "application/java-vm", "coffee": "text/coffeescript", "conf": "text/plain", "cpl": "application/cpl+xml", "cpt": "application/mac-compactpro", "crl": "application/pkix-crl", "css": "text/css", "csv": "text/csv", "cu": "application/cu-seeme", "cwl": "application/cwl", "cww": "application/prs.cww", "davmount": "application/davmount+xml", "dbk": "application/docbook+xml", "deb": "application/octet-stream", "def": "text/plain", "deploy": "application/octet-stream", "dib": "image/bmp", "disposition-notification": "message/disposition-notification", "dist": "application/octet-stream", "distz": "application/octet-stream", "dll": "application/octet-stream", "dmg": "application/octet-stream", "dms": "application/octet-stream", "doc": "application/msword", "dot": "application/msword", "dpx": "image/dpx", "drle": "image/dicom-rle", "dsc": "text/prs.lines.tag", "dssc": "application/dssc+der", "dtd": "application/xml-dtd", "dump": "application/octet-stream", "dwd": "application/atsc-dwd+xml", "ear": "application/java-archive", "ecma": "application/ecmascript", "elc": "application/octet-stream", "emf": "image/emf", "eml": "message/rfc822", "emma": "application/emma+xml", "emotionml": "application/emotionml+xml", "eps": "application/postscript", "epub": "application/epub+zip", "exe": "application/octet-stream", "exi": "application/exi", "exp": "application/express", "exr": "image/aces", "ez": "application/andrew-inset", "fdf": "application/fdf", "fdt": "application/fdt+xml", "fits": "image/fits", "g3": "image/g3fax", "gbr": "application/rpki-ghostbusters", "geojson": "application/geo+json", "gif": "image/gif", "glb": "model/gltf-binary", "gltf": "model/gltf+json", "gml": "application/gml+xml", "gpx": "application/gpx+xml", "gram": "application/srgs", "grxml": "application/srgs+xml", "gxf": "application/gxf", "gz": "application/gzip", "h261": "video/h261", "h263": "video/h263", "h264": "video/h264", "heic": "image/heic", "heics": "image/heic-sequence", "heif": "image/heif", "heifs": "image/heif-sequence", "hej2": "image/hej2k", "held": "application/atsc-held+xml", "hjson": "application/hjson", "hlp": "application/winhlp", "hqx": "application/mac-binhex40", "hsj2": "image/hsj2", "htm": "text/html", "html": "text/html", "ics": "text/calendar", "ief": "image/ief", "ifb": "text/calendar", "iges": "model/iges", "igs": "model/iges", "img": "application/octet-stream", "in": "text/plain", "ini": "text/plain", "ink": "application/inkml+xml", "inkml": "application/inkml+xml", "ipfix": "application/ipfix", "iso": "application/octet-stream", "its": "application/its+xml", "jade": "text/jade", "jar": "application/java-archive", "jhc": "image/jphc", "jls": "image/jls", "jp2": "image/jp2", "jpe": "image/jpeg", "jpeg": "image/jpeg", "jpf": "image/jpx", "jpg": "image/jpeg", "jpg2": "image/jp2", "jpgm": "image/jpm", "jpgv": "video/jpeg", "jph": "image/jph", "jpm": "image/jpm", "jpx": "image/jpx", "js": "text/javascript", "json": "application/json", "json5": "application/json5", "jsonld": "application/ld+json", "jsonml": "application/jsonml+json", "jsx": "text/jsx", "jt": "model/jt", "jxl": "image/jxl", "jxr": "image/jxr", "jxra": "image/jxra", "jxrs": "image/jxrs", "jxs": "image/jxs", "jxsc": "image/jxsc", "jxsi": "image/jxsi", "jxss": "image/jxss", "kar": "audio/midi", "ktx": "image/ktx", "ktx2": "image/ktx2", "less": "text/less", "lgr": "application/lgr+xml", "list": "text/plain", "litcoffee": "text/coffeescript", "log": "text/plain", "lostxml": "application/lost+xml", "lrf": "application/octet-stream", "m1v": "video/mpeg", "m21": "application/mp21", "m2a": "audio/mpeg", "m2t": "video/mp2t", "m2ts": "video/mp2t", "m2v": "video/mpeg", "m3a": "audio/mpeg", "m4a": "audio/mp4", "m4p": "application/mp4", "m4s": "video/iso.segment", "ma": "application/mathematica", "mads": "application/mads+xml", "maei": "application/mmt-aei+xml", "man": "text/troff", "manifest": "text/cache-manifest", "map": "application/json", "mar": "application/octet-stream", "markdown": "text/markdown", "mathml": "application/mathml+xml", "mb": "application/mathematica", "mbox": "application/mbox", "md": "text/markdown", "mdx": "text/mdx", "me": "text/troff", "mesh": "model/mesh", "meta4": "application/metalink4+xml", "metalink": "application/metalink+xml", "mets": "application/mets+xml", "mft": "application/rpki-manifest", "mid": "audio/midi", "midi": "audio/midi", "mime": "message/rfc822", "mj2": "video/mj2", "mjp2": "video/mj2", "mjs": "text/javascript", "mml": "text/mathml", "mods": "application/mods+xml", "mov": "video/quicktime", "mp2": "audio/mpeg", "mp21": "application/mp21", "mp2a": "audio/mpeg", "mp3": "audio/mpeg", "mp4": "video/mp4", "mp4a": "audio/mp4", "mp4s": "application/mp4", "mp4v": "video/mp4", "mpd": "application/dash+xml", "mpe": "video/mpeg", "mpeg": "video/mpeg", "mpf": "application/media-policy-dataset+xml", "mpg": "video/mpeg", "mpg4": "video/mp4", "mpga": "audio/mpeg", "mpp": "application/dash-patch+xml", "mrc": "application/marc", "mrcx": "application/marcxml+xml", "ms": "text/troff", "mscml": "application/mediaservercontrol+xml", "msh": "model/mesh", "msi": "application/octet-stream", "msix": "application/msix", "msixbundle": "application/msixbundle", "msm": "application/octet-stream", "msp": "application/octet-stream", "mtl": "model/mtl", "mts": "video/mp2t", "musd": "application/mmt-usd+xml", "mxf": "application/mxf", "mxmf": "audio/mobile-xmf", "mxml": "application/xv+xml", "n3": "text/n3", "nb": "application/mathematica", "nq": "application/n-quads", "nt": "application/n-triples", "obj": "model/obj", "oda": "application/oda", "oga": "audio/ogg", "ogg": "audio/ogg", "ogv": "video/ogg", "ogx": "application/ogg", "omdoc": "application/omdoc+xml", "onepkg": "application/onenote", "onetmp": "application/onenote", "onetoc": "application/onenote", "onetoc2": "application/onenote", "opf": "application/oebps-package+xml", "opus": "audio/ogg", "otf": "font/otf", "owl": "application/rdf+xml", "oxps": "application/oxps", "p10": "application/pkcs10", "p7c": "application/pkcs7-mime", "p7m": "application/pkcs7-mime", "p7s": "application/pkcs7-signature", "p8": "application/pkcs8", "pdf": "application/pdf", "pfr": "application/font-tdpfr", "pgp": "application/pgp-encrypted", "pkg": "application/octet-stream", "pki": "application/pkixcmp", "pkipath": "application/pkix-pkipath", "pls": "application/pls+xml", "png": "image/png", "prc": "model/prc", "prf": "application/pics-rules", "provx": "application/provenance+xml", "ps": "application/postscript", "pskcxml": "application/pskc+xml", "pti": "image/prs.pti", "qt": "video/quicktime", "raml": "application/raml+yaml", "rapd": "application/route-apd+xml", "rdf": "application/rdf+xml", "relo": "application/p2p-overlay+xml", "rif": "application/reginfo+xml", "rl": "application/resource-lists+xml", "rld": "application/resource-lists-diff+xml", "rmi": "audio/midi", "rnc": "application/relax-ng-compact-syntax", "rng": "application/xml", "roa": "application/rpki-roa", "roff": "text/troff", "rq": "application/sparql-query", "rs": "application/rls-services+xml", "rsat": "application/atsc-rsat+xml", "rsd": "application/rsd+xml", "rsheet": "application/urc-ressheet+xml", "rss": "application/rss+xml", "rtf": "text/rtf", "rtx": "text/richtext", "rusd": "application/route-usd+xml", "s3m": "audio/s3m", "sbml": "application/sbml+xml", "scq": "application/scvp-cv-request", "scs": "application/scvp-cv-response", "sdp": "application/sdp", "senmlx": "application/senml+xml", "sensmlx": "application/sensml+xml", "ser": "application/java-serialized-object", "setpay": "application/set-payment-initiation", "setreg": "application/set-registration-initiation", "sgi": "image/sgi", "sgm": "text/sgml", "sgml": "text/sgml", "shex": "text/shex", "shf": "application/shf+xml", "shtml": "text/html", "sieve": "application/sieve", "sig": "application/pgp-signature", "sil": "audio/silk", "silo": "model/mesh", "siv": "application/sieve", "slim": "text/slim", "slm": "text/slim", "sls": "application/route-s-tsid+xml", "smi": "application/smil+xml", "smil": "application/smil+xml", "snd": "audio/basic", "so": "application/octet-stream", "spdx": "text/spdx", "spp": "application/scvp-vp-response", "spq": "application/scvp-vp-request", "spx": "audio/ogg", "sql": "application/sql", "sru": "application/sru+xml", "srx": "application/sparql-results+xml", "ssdl": "application/ssdl+xml", "ssml": "application/ssml+xml", "stk": "application/hyperstudio", "stl": "model/stl", "stpx": "model/step+xml", "stpxz": "model/step-xml+zip", "stpz": "model/step+zip", "styl": "text/stylus", "stylus": "text/stylus", "svg": "image/svg+xml", "svgz": "image/svg+xml", "swidtag": "application/swid+xml", "t": "text/troff", "t38": "image/t38", "td": "application/urc-targetdesc+xml", "tei": "application/tei+xml", "teicorpus": "application/tei+xml", "text": "text/plain", "tfi": "application/thraud+xml", "tfx": "image/tiff-fx", "tif": "image/tiff", "tiff": "image/tiff", "toml": "application/toml", "tr": "text/troff", "trig": "application/trig", "ts": "video/mp2t", "tsd": "application/timestamped-data", "tsv": "text/tab-separated-values", "ttc": "font/collection", "ttf": "font/ttf", "ttl": "text/turtle", "ttml": "application/ttml+xml", "txt": "text/plain", "u3d": "model/u3d", "u8dsn": "message/global-delivery-status", "u8hdr": "message/global-headers", "u8mdn": "message/global-disposition-notification", "u8msg": "message/global", "ubj": "application/ubjson", "uri": "text/uri-list", "uris": "text/uri-list", "urls": "text/uri-list", "vcard": "text/vcard", "vrml": "model/vrml", "vtt": "text/vtt", "vxml": "application/voicexml+xml", "war": "application/java-archive", "wasm": "application/wasm", "wav": "audio/wav", "weba": "audio/webm", "webm": "video/webm", "webmanifest": "application/manifest+json", "webp": "image/webp", "wgsl": "text/wgsl", "wgt": "application/widget", "wif": "application/watcherinfo+xml", "wmf": "image/wmf", "woff": "font/woff", "woff2": "font/woff2", "wrl": "model/vrml", "wsdl": "application/wsdl+xml", "wspolicy": "application/wspolicy+xml", "x3d": "model/x3d+xml", "x3db": "model/x3d+fastinfoset", "x3dbz": "model/x3d+binary", "x3dv": "model/x3d-vrml", "x3dvz": "model/x3d+vrml", "x3dz": "model/x3d+xml", "xaml": "application/xaml+xml", "xav": "application/xcap-att+xml", "xca": "application/xcap-caps+xml", "xcs": "application/calendar+xml", "xdf": "application/xcap-diff+xml", "xdssc": "application/dssc+xml", "xel": "application/xcap-el+xml", "xenc": "application/xenc+xml", "xer": "application/patch-ops-error+xml", "xfdf": "application/xfdf", "xht": "application/xhtml+xml", "xhtml": "application/xhtml+xml", "xhvml": "application/xv+xml", "xlf": "application/xliff+xml", "xm": "audio/xm", "xml": "text/xml", "xns": "application/xcap-ns+xml", "xop": "application/xop+xml", "xpl": "application/xproc+xml", "xsd": "application/xml", "xsf": "application/prs.xsf+xml", "xsl": "application/xml", "xslt": "application/xml", "xspf": "application/xspf+xml", "xvm": "application/xv+xml", "xvml": "application/xv+xml", "yaml": "text/yaml", "yang": "application/yang", "yin": "application/yin+xml", "yml": "text/yaml", "zip": "application/zip" }; function lookup(extn) { let tmp = ("" + extn).trim().toLowerCase(); let idx = tmp.lastIndexOf("."); return mimes[!~idx ? tmp : tmp.substring(++idx)]; } //#endregion //#region src/node/publicDir.ts const publicFilesMap = /* @__PURE__ */ new WeakMap(); async function initPublicFiles(config$2) { let fileNames; try { fileNames = await recursiveReaddir(config$2.publicDir); } catch (e$1) { if (e$1.code === ERR_SYMLINK_IN_RECURSIVE_READDIR) return; throw e$1; } const publicFiles = new Set(fileNames.map((fileName) => fileName.slice(config$2.publicDir.length))); publicFilesMap.set(config$2, publicFiles); return publicFiles; } function getPublicFiles(config$2) { return publicFilesMap.get(config$2); } function checkPublicFile(url$3, config$2) { const { publicDir } = config$2; if (!publicDir || url$3[0] !== "/") return; const fileName = cleanUrl(url$3); const publicFiles = getPublicFiles(config$2); if (publicFiles) return publicFiles.has(fileName) ? normalizePath(path.join(publicDir, fileName)) : void 0; const publicFile = normalizePath(path.join(publicDir, fileName)); if (!publicFile.startsWith(withTrailingSlash(publicDir))) return; return tryStatSync(publicFile)?.isFile() ? publicFile : void 0; } //#endregion //#region src/node/plugins/asset.ts var import_picocolors$30 = /* @__PURE__ */ __toESM(require_picocolors(), 1); const assetUrlRE = /__VITE_ASSET__([\w$]+)__(?:\$_(.*?)__)?/g; const jsSourceMapRE = /\.[cm]?js\.map$/; const noInlineRE = /[?&]no-inline\b/; const inlineRE$3 = /[?&]inline\b/; const assetCache = /* @__PURE__ */ new WeakMap(); /** a set of referenceId for entry CSS assets for each environment */ const cssEntriesMap = /* @__PURE__ */ new WeakMap(); function registerCustomMime() { mimes.ico = "image/x-icon"; mimes.cur = "image/x-icon"; mimes.flac = "audio/flac"; mimes.eot = "application/vnd.ms-fontobject"; } function renderAssetUrlInJS(pluginContext, chunk, opts, code) { const { environment } = pluginContext; const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime(opts.format, environment.config.isWorker); let match; let s$2; assetUrlRE.lastIndex = 0; while (match = assetUrlRE.exec(code)) { s$2 ||= new MagicString(code); const [full, referenceId, postfix = ""] = match; const file = pluginContext.getFileName(referenceId); chunk.viteMetadata.importedAssets.add(cleanUrl(file)); const replacement = toOutputFilePathInJS(environment, file + postfix, "asset", chunk.fileName, "js", toRelativeRuntime); const replacementString = typeof replacement === "string" ? JSON.stringify(encodeURIPath(replacement)).slice(1, -1) : `"+${replacement.runtime}+"`; s$2.update(match.index, match.index + full.length, replacementString); } const publicAssetUrlMap = publicAssetUrlCache.get(environment.getTopLevelConfig()); publicAssetUrlRE.lastIndex = 0; while (match = publicAssetUrlRE.exec(code)) { s$2 ||= new MagicString(code); const [full, hash$1] = match; const replacement = toOutputFilePathInJS(environment, publicAssetUrlMap.get(hash$1).slice(1), "public", chunk.fileName, "js", toRelativeRuntime); const replacementString = typeof replacement === "string" ? JSON.stringify(encodeURIPath(replacement)).slice(1, -1) : `"+${replacement.runtime}+"`; s$2.update(match.index, match.index + full.length, replacementString); } return s$2; } /** * Also supports loading plain strings with import text from './foo.txt?raw' */ function assetPlugin(config$2) { registerCustomMime(); return { name: "vite:asset", perEnvironmentStartEndDuringDev: true, buildStart() { assetCache.set(this.environment, /* @__PURE__ */ new Map()); cssEntriesMap.set(this.environment, /* @__PURE__ */ new Set()); }, resolveId: { handler(id) { if (!config$2.assetsInclude(cleanUrl(id)) && !urlRE.test(id)) return; if (checkPublicFile(id, config$2)) return id; } }, load: { filter: { id: { exclude: /^\0/ } }, async handler(id) { if (rawRE.test(id)) { const file = checkPublicFile(id, config$2) || cleanUrl(id); this.addWatchFile(file); return `export default ${JSON.stringify(await fsp.readFile(file, "utf-8"))}`; } if (!urlRE.test(id) && !config$2.assetsInclude(cleanUrl(id))) return; id = removeUrlQuery(id); let url$3 = await fileToUrl$1(this, id); if (!url$3.startsWith("data:") && this.environment.mode === "dev") { const mod = this.environment.moduleGraph.getModuleById(id); if (mod && mod.lastHMRTimestamp > 0) url$3 = injectQuery(url$3, `t=${mod.lastHMRTimestamp}`); } return { code: `export default ${JSON.stringify(encodeURIPath(url$3))}`, moduleSideEffects: config$2.command === "build" && this.getModuleInfo(id)?.isEntry ? "no-treeshake" : false, meta: config$2.command === "build" ? { "vite:asset": true } : void 0 }; } }, renderChunk(code, chunk, opts) { const s$2 = renderAssetUrlInJS(this, chunk, opts, code); if (s$2) return { code: s$2.toString(), map: this.environment.config.build.sourcemap ? s$2.generateMap({ hires: "boundary" }) : null }; else return null; }, generateBundle(_, bundle) { let importedFiles; for (const file in bundle) { const chunk = bundle[file]; if (chunk.type === "chunk" && chunk.isEntry && chunk.moduleIds.length === 1 && config$2.assetsInclude(chunk.moduleIds[0]) && this.getModuleInfo(chunk.moduleIds[0])?.meta["vite:asset"]) { if (!importedFiles) { importedFiles = /* @__PURE__ */ new Set(); for (const file$1 in bundle) { const chunk$1 = bundle[file$1]; if (chunk$1.type === "chunk") { for (const importedFile of chunk$1.imports) importedFiles.add(importedFile); for (const importedFile of chunk$1.dynamicImports) importedFiles.add(importedFile); } } } if (!importedFiles.has(file)) delete bundle[file]; } } if (config$2.command === "build" && !this.environment.config.build.emitAssets) { for (const file in bundle) if (bundle[file].type === "asset" && !file.endsWith("ssr-manifest.json") && !jsSourceMapRE.test(file)) delete bundle[file]; } } }; } async function fileToUrl$1(pluginContext, id) { const { environment } = pluginContext; if (environment.config.command === "serve") return fileToDevUrl(environment, id); else return fileToBuiltUrl(pluginContext, id); } async function fileToDevUrl(environment, id, skipBase = false) { const config$2 = environment.getTopLevelConfig(); const publicFile = checkPublicFile(id, config$2); if (inlineRE$3.test(id)) { const file = publicFile || cleanUrl(id); return assetToDataURL(environment, file, await fsp.readFile(file)); } const cleanedId = cleanUrl(id); if (cleanedId.endsWith(".svg")) { const file = publicFile || cleanedId; const content = await fsp.readFile(file); if (shouldInline(environment, file, id, content, void 0, void 0)) return assetToDataURL(environment, file, content); } let rtn; if (publicFile) rtn = id; else if (id.startsWith(withTrailingSlash(config$2.root))) rtn = "/" + path.posix.relative(config$2.root, id); else rtn = path.posix.join(FS_PREFIX, id); if (skipBase) return rtn; return joinUrlSegments(joinUrlSegments(config$2.server.origin ?? "", config$2.decodedBase), removeLeadingSlash(rtn)); } function getPublicAssetFilename(hash$1, config$2) { return publicAssetUrlCache.get(config$2)?.get(hash$1); } const publicAssetUrlCache = /* @__PURE__ */ new WeakMap(); const publicAssetUrlRE = /__VITE_PUBLIC_ASSET__([a-z\d]{8})__/g; function publicFileToBuiltUrl(url$3, config$2) { if (config$2.command !== "build") return joinUrlSegments(config$2.decodedBase, url$3); const hash$1 = getHash(url$3); let cache$1 = publicAssetUrlCache.get(config$2); if (!cache$1) { cache$1 = /* @__PURE__ */ new Map(); publicAssetUrlCache.set(config$2, cache$1); } if (!cache$1.get(hash$1)) cache$1.set(hash$1, url$3); return `__VITE_PUBLIC_ASSET__${hash$1}__`; } const GIT_LFS_PREFIX = Buffer$1.from("version https://git-lfs.github.com"); function isGitLfsPlaceholder(content) { if (content.length < GIT_LFS_PREFIX.length) return false; return GIT_LFS_PREFIX.compare(content, 0, GIT_LFS_PREFIX.length) === 0; } /** * Register an asset to be emitted as part of the bundle (if necessary) * and returns the resolved public URL */ async function fileToBuiltUrl(pluginContext, id, skipPublicCheck = false, forceInline) { const environment = pluginContext.environment; const topLevelConfig = environment.getTopLevelConfig(); if (!skipPublicCheck) { const publicFile = checkPublicFile(id, topLevelConfig); if (publicFile) if (inlineRE$3.test(id)) id = publicFile; else return publicFileToBuiltUrl(id, topLevelConfig); } const cache$1 = assetCache.get(environment); const cached = cache$1.get(id); if (cached) return cached; let { file, postfix } = splitFileAndPostfix(id); const content = await fsp.readFile(file); let url$3; if (shouldInline(environment, file, id, content, pluginContext, forceInline)) url$3 = assetToDataURL(environment, file, content); else { const originalFileName = normalizePath(path.relative(environment.config.root, file)); const referenceId = pluginContext.emitFile({ type: "asset", name: path.basename(file), originalFileName, source: content }); if (environment.config.command === "build" && noInlineRE.test(postfix)) postfix = postfix.replace(noInlineRE, "").replace(/^&/, "?"); url$3 = `__VITE_ASSET__${referenceId}__${postfix ? `$_${postfix}__` : ``}`; } cache$1.set(id, url$3); return url$3; } async function urlToBuiltUrl(pluginContext, url$3, importer, forceInline) { const topLevelConfig = pluginContext.environment.getTopLevelConfig(); if (checkPublicFile(url$3, topLevelConfig)) return publicFileToBuiltUrl(url$3, topLevelConfig); return fileToBuiltUrl(pluginContext, normalizePath(url$3[0] === "/" ? path.join(topLevelConfig.root, url$3) : path.join(path.dirname(importer), url$3)), true, forceInline); } function shouldInline(environment, file, id, content, buildPluginContext, forceInline) { if (noInlineRE.test(id)) return false; if (inlineRE$3.test(id)) return true; if (buildPluginContext) { if (environment.config.build.lib) return true; if (buildPluginContext.getModuleInfo(id)?.isEntry) return false; } if (forceInline !== void 0) return forceInline; if (file.endsWith(".html")) return false; if (file.endsWith(".svg") && id.includes("#")) return false; let limit; const { assetsInlineLimit } = environment.config.build; if (typeof assetsInlineLimit === "function") { const userShouldInline = assetsInlineLimit(file, content); if (userShouldInline != null) return userShouldInline; limit = DEFAULT_ASSETS_INLINE_LIMIT; } else limit = Number(assetsInlineLimit); return content.length < limit && !isGitLfsPlaceholder(content); } function assetToDataURL(environment, file, content) { if (environment.config.build.lib && isGitLfsPlaceholder(content)) environment.logger.warn(import_picocolors$30.default.yellow(`Inlined file ${file} was not downloaded via Git LFS`)); if (file.endsWith(".svg")) return svgToDataURL(content); else return `data:${lookup(file) ?? "application/octet-stream"};base64,${content.toString("base64")}`; } const nestedQuotesRE = /"[^"']*'[^"]*"|'[^'"]*"[^']*'/; function svgToDataURL(content) { const stringContent = content.toString(); if (stringContent.includes("\s+<").replaceAll("\"", "'").replaceAll("%", "%25").replaceAll("#", "%23").replaceAll("<", "%3c").replaceAll(">", "%3e").replaceAll(/\s+/g, "%20"); } //#endregion //#region src/node/plugins/manifest.ts const endsWithJSRE = /\.[cm]?js$/; function manifestPlugin() { const getState = perEnvironmentState(() => { return { manifest: {}, outputCount: 0, reset() { this.manifest = {}; this.outputCount = 0; } }; }); return { name: "vite:manifest", perEnvironmentStartEndDuringDev: true, applyToEnvironment(environment) { return !!environment.config.build.manifest; }, buildStart() { getState(this).reset(); }, generateBundle({ format: format$3 }, bundle) { const state = getState(this); const { manifest } = state; const { root } = this.environment.config; const buildOptions = this.environment.config.build; function getChunkName(chunk) { return getChunkOriginalFileName(chunk, root, format$3) ?? `_${path.basename(chunk.fileName)}`; } function getInternalImports(imports) { const filteredImports = []; for (const file of imports) { if (bundle[file] === void 0) continue; filteredImports.push(getChunkName(bundle[file])); } return filteredImports; } function createChunk(chunk) { const manifestChunk = { file: chunk.fileName, name: chunk.name }; if (chunk.facadeModuleId) manifestChunk.src = getChunkName(chunk); if (chunk.isEntry) manifestChunk.isEntry = true; if (chunk.isDynamicEntry) manifestChunk.isDynamicEntry = true; if (chunk.imports.length) { const internalImports = getInternalImports(chunk.imports); if (internalImports.length > 0) manifestChunk.imports = internalImports; } if (chunk.dynamicImports.length) { const internalImports = getInternalImports(chunk.dynamicImports); if (internalImports.length > 0) manifestChunk.dynamicImports = internalImports; } if (chunk.viteMetadata?.importedCss.size) manifestChunk.css = [...chunk.viteMetadata.importedCss]; if (chunk.viteMetadata?.importedAssets.size) manifestChunk.assets = [...chunk.viteMetadata.importedAssets]; return manifestChunk; } function createAsset(asset, src, isEntry) { const manifestChunk = { file: asset.fileName, src }; if (isEntry) { manifestChunk.isEntry = true; manifestChunk.names = asset.names; } return manifestChunk; } const entryCssReferenceIds = cssEntriesMap.get(this.environment); const entryCssAssetFileNames = /* @__PURE__ */ new Set(); for (const id of entryCssReferenceIds) try { const fileName = this.getFileName(id); entryCssAssetFileNames.add(fileName); } catch {} for (const file in bundle) { const chunk = bundle[file]; if (chunk.type === "chunk") manifest[getChunkName(chunk)] = createChunk(chunk); else if (chunk.type === "asset" && chunk.names.length > 0) { const src = chunk.originalFileNames.length > 0 ? chunk.originalFileNames[0] : `_${path.basename(chunk.fileName)}`; const asset = createAsset(chunk, src, entryCssAssetFileNames.has(chunk.fileName)); const file$1 = manifest[src]?.file; if (!(file$1 && endsWithJSRE.test(file$1))) manifest[src] = asset; for (const originalFileName of chunk.originalFileNames.slice(1)) { const file$2 = manifest[originalFileName]?.file; if (!(file$2 && endsWithJSRE.test(file$2))) manifest[originalFileName] = asset; } } } state.outputCount++; const output = buildOptions.rollupOptions.output; if (state.outputCount >= (Array.isArray(output) ? output.length : 1)) this.emitFile({ fileName: typeof buildOptions.manifest === "string" ? buildOptions.manifest : ".vite/manifest.json", type: "asset", source: JSON.stringify(sortObjectKeys(manifest), void 0, 2) }); } }; } function getChunkOriginalFileName(chunk, root, format$3) { if (chunk.facadeModuleId) { let name = normalizePath(path.relative(root, chunk.facadeModuleId)); if (format$3 === "system" && !chunk.name.includes("-legacy")) { const ext = path.extname(name); const endPos = ext.length !== 0 ? -ext.length : void 0; name = `${name.slice(0, endPos)}-legacy${ext}`; } return name.replace(/\0/g, ""); } } //#endregion //#region src/node/plugins/dataUri.ts const dataUriRE = /^([^/]+\/[^;,]+)(;base64)?,([\s\S]*)$/; const base64RE = /base64/i; const dataUriPrefix = `\0/@data-uri/`; /** * Build only, since importing from a data URI works natively. */ function dataURIPlugin() { let resolved; return { name: "vite:data-uri", buildStart() { resolved = /* @__PURE__ */ new Map(); }, resolveId(id) { if (!id.trimStart().startsWith("data:")) return; const uri = new URL$1(id); if (uri.protocol !== "data:") return; const match = dataUriRE.exec(uri.pathname); if (!match) return; const [, mime, format$3, data] = match; if (mime !== "text/javascript") throw new Error(`data URI with non-JavaScript mime type is not supported. If you're using legacy JavaScript MIME types (such as 'application/javascript'), please use 'text/javascript' instead.`); const content = format$3 && base64RE.test(format$3.substring(1)) ? Buffer.from(data, "base64").toString("utf-8") : data; resolved.set(id, content); return dataUriPrefix + id; }, load(id) { if (id.startsWith(dataUriPrefix)) return resolved.get(id.slice(dataUriPrefix.length)); } }; } //#endregion //#region ../../node_modules/.pnpm/es-module-lexer@1.7.0/node_modules/es-module-lexer/dist/lexer.js var ImportType; (function(A$1) { A$1[A$1.Static = 1] = "Static", A$1[A$1.Dynamic = 2] = "Dynamic", A$1[A$1.ImportMeta = 3] = "ImportMeta", A$1[A$1.StaticSourcePhase = 4] = "StaticSourcePhase", A$1[A$1.DynamicSourcePhase = 5] = "DynamicSourcePhase", A$1[A$1.StaticDeferPhase = 6] = "StaticDeferPhase", A$1[A$1.DynamicDeferPhase = 7] = "DynamicDeferPhase"; })(ImportType || (ImportType = {})); const A = 1 === new Uint8Array(new Uint16Array([1]).buffer)[0]; function parse(E$1, g = "@") { if (!C) return init.then((() => parse(E$1))); const I = E$1.length + 1, w$1 = (C.__heap_base.value || C.__heap_base) + 4 * I - C.memory.buffer.byteLength; w$1 > 0 && C.memory.grow(Math.ceil(w$1 / 65536)); const K = C.sa(I - 1); if ((A ? B : Q)(E$1, new Uint16Array(C.memory.buffer, K, I)), !C.parse()) throw Object.assign(/* @__PURE__ */ new Error(`Parse error ${g}:${E$1.slice(0, C.e()).split("\n").length}:${C.e() - E$1.lastIndexOf("\n", C.e() - 1)}`), { idx: C.e() }); const o$1 = [], D = []; for (; C.ri();) { const A$1 = C.is(), Q$1 = C.ie(), B$1 = C.it(), g$1 = C.ai(), I$1 = C.id(), w$2 = C.ss(), K$1 = C.se(); let D$1; C.ip() && (D$1 = k(E$1.slice(-1 === I$1 ? A$1 - 1 : A$1, -1 === I$1 ? Q$1 + 1 : Q$1))), o$1.push({ n: D$1, t: B$1, s: A$1, e: Q$1, ss: w$2, se: K$1, d: I$1, a: g$1 }); } for (; C.re();) { const A$1 = C.es(), Q$1 = C.ee(), B$1 = C.els(), g$1 = C.ele(), I$1 = E$1.slice(A$1, Q$1), w$2 = I$1[0], K$1 = B$1 < 0 ? void 0 : E$1.slice(B$1, g$1), o$2 = K$1 ? K$1[0] : ""; D.push({ s: A$1, e: Q$1, ls: B$1, le: g$1, n: "\"" === w$2 || "'" === w$2 ? k(I$1) : I$1, ln: "\"" === o$2 || "'" === o$2 ? k(K$1) : K$1 }); } function k(A$1) { try { return (0, eval)(A$1); } catch (A$2) {} } return [ o$1, D, !!C.f(), !!C.ms() ]; } function Q(A$1, Q$1) { const B$1 = A$1.length; let C$1 = 0; for (; C$1 < B$1;) { const B$2 = A$1.charCodeAt(C$1); Q$1[C$1++] = (255 & B$2) << 8 | B$2 >>> 8; } } function B(A$1, Q$1) { const B$1 = A$1.length; let C$1 = 0; for (; C$1 < B$1;) Q$1[C$1] = A$1.charCodeAt(C$1++); } let C; const E = () => { return A$1 = "AGFzbQEAAAABKwhgAX8Bf2AEf39/fwBgAAF/YAAAYAF/AGADf39/AX9gAn9/AX9gA39/fwADMTAAAQECAgICAgICAgICAgICAgICAgIAAwMDBAQAAAUAAAAAAAMDAwAGAAAABwAGAgUEBQFwAQEBBQMBAAEGDwJ/AUHA8gALfwBBwPIACwd6FQZtZW1vcnkCAAJzYQAAAWUAAwJpcwAEAmllAAUCc3MABgJzZQAHAml0AAgCYWkACQJpZAAKAmlwAAsCZXMADAJlZQANA2VscwAOA2VsZQAPAnJpABACcmUAEQFmABICbXMAEwVwYXJzZQAUC19faGVhcF9iYXNlAwEKzkQwaAEBf0EAIAA2AoAKQQAoAtwJIgEgAEEBdGoiAEEAOwEAQQAgAEECaiIANgKECkEAIAA2AogKQQBBADYC4AlBAEEANgLwCUEAQQA2AugJQQBBADYC5AlBAEEANgL4CUEAQQA2AuwJIAEL0wEBA39BACgC8AkhBEEAQQAoAogKIgU2AvAJQQAgBDYC9AlBACAFQSRqNgKICiAEQSBqQeAJIAQbIAU2AgBBACgC1AkhBEEAKALQCSEGIAUgATYCACAFIAA2AgggBSACIAJBAmpBACAGIANGIgAbIAQgA0YiBBs2AgwgBSADNgIUIAVBADYCECAFIAI2AgQgBUEANgIgIAVBA0EBQQIgABsgBBs2AhwgBUEAKALQCSADRiICOgAYAkACQCACDQBBACgC1AkgA0cNAQtBAEEBOgCMCgsLXgEBf0EAKAL4CSIEQRBqQeQJIAQbQQAoAogKIgQ2AgBBACAENgL4CUEAIARBFGo2AogKQQBBAToAjAogBEEANgIQIAQgAzYCDCAEIAI2AgggBCABNgIEIAQgADYCAAsIAEEAKAKQCgsVAEEAKALoCSgCAEEAKALcCWtBAXULHgEBf0EAKALoCSgCBCIAQQAoAtwJa0EBdUF/IAAbCxUAQQAoAugJKAIIQQAoAtwJa0EBdQseAQF/QQAoAugJKAIMIgBBACgC3AlrQQF1QX8gABsLCwBBACgC6AkoAhwLHgEBf0EAKALoCSgCECIAQQAoAtwJa0EBdUF/IAAbCzsBAX8CQEEAKALoCSgCFCIAQQAoAtAJRw0AQX8PCwJAIABBACgC1AlHDQBBfg8LIABBACgC3AlrQQF1CwsAQQAoAugJLQAYCxUAQQAoAuwJKAIAQQAoAtwJa0EBdQsVAEEAKALsCSgCBEEAKALcCWtBAXULHgEBf0EAKALsCSgCCCIAQQAoAtwJa0EBdUF/IAAbCx4BAX9BACgC7AkoAgwiAEEAKALcCWtBAXVBfyAAGwslAQF/QQBBACgC6AkiAEEgakHgCSAAGygCACIANgLoCSAAQQBHCyUBAX9BAEEAKALsCSIAQRBqQeQJIAAbKAIAIgA2AuwJIABBAEcLCABBAC0AlAoLCABBAC0AjAoL3Q0BBX8jAEGA0ABrIgAkAEEAQQE6AJQKQQBBACgC2Ak2ApwKQQBBACgC3AlBfmoiATYCsApBACABQQAoAoAKQQF0aiICNgK0CkEAQQA6AIwKQQBBADsBlgpBAEEAOwGYCkEAQQA6AKAKQQBBADYCkApBAEEAOgD8CUEAIABBgBBqNgKkCkEAIAA2AqgKQQBBADoArAoCQAJAAkACQANAQQAgAUECaiIDNgKwCiABIAJPDQECQCADLwEAIgJBd2pBBUkNAAJAAkACQAJAAkAgAkGbf2oOBQEICAgCAAsgAkEgRg0EIAJBL0YNAyACQTtGDQIMBwtBAC8BmAoNASADEBVFDQEgAUEEakGCCEEKEC8NARAWQQAtAJQKDQFBAEEAKAKwCiIBNgKcCgwHCyADEBVFDQAgAUEEakGMCEEKEC8NABAXC0EAQQAoArAKNgKcCgwBCwJAIAEvAQQiA0EqRg0AIANBL0cNBBAYDAELQQEQGQtBACgCtAohAkEAKAKwCiEBDAALC0EAIQIgAyEBQQAtAPwJDQIMAQtBACABNgKwCkEAQQA6AJQKCwNAQQAgAUECaiIDNgKwCgJAAkACQAJAAkACQAJAIAFBACgCtApPDQAgAy8BACICQXdqQQVJDQYCQAJAAkACQAJAAkACQAJAAkACQCACQWBqDgoQDwYPDw8PBQECAAsCQAJAAkACQCACQaB/ag4KCxISAxIBEhISAgALIAJBhX9qDgMFEQYJC0EALwGYCg0QIAMQFUUNECABQQRqQYIIQQoQLw0QEBYMEAsgAxAVRQ0PIAFBBGpBjAhBChAvDQ8QFwwPCyADEBVFDQ4gASkABELsgISDsI7AOVINDiABLwEMIgNBd2oiAUEXSw0MQQEgAXRBn4CABHFFDQwMDQtBAEEALwGYCiIBQQFqOwGYCkEAKAKkCiABQQN0aiIBQQE2AgAgAUEAKAKcCjYCBAwNC0EALwGYCiIDRQ0JQQAgA0F/aiIDOwGYCkEALwGWCiICRQ0MQQAoAqQKIANB//8DcUEDdGooAgBBBUcNDAJAIAJBAnRBACgCqApqQXxqKAIAIgMoAgQNACADQQAoApwKQQJqNgIEC0EAIAJBf2o7AZYKIAMgAUEEajYCDAwMCwJAQQAoApwKIgEvAQBBKUcNAEEAKALwCSIDRQ0AIAMoAgQgAUcNAEEAQQAoAvQJIgM2AvAJAkAgA0UNACADQQA2AiAMAQtBAEEANgLgCQtBAEEALwGYCiIDQQFqOwGYCkEAKAKkCiADQQN0aiIDQQZBAkEALQCsChs2AgAgAyABNgIEQQBBADoArAoMCwtBAC8BmAoiAUUNB0EAIAFBf2oiATsBmApBACgCpAogAUH//wNxQQN0aigCAEEERg0EDAoLQScQGgwJC0EiEBoMCAsgAkEvRw0HAkACQCABLwEEIgFBKkYNACABQS9HDQEQGAwKC0EBEBkMCQsCQAJAAkACQEEAKAKcCiIBLwEAIgMQG0UNAAJAAkAgA0FVag4EAAkBAwkLIAFBfmovAQBBK0YNAwwICyABQX5qLwEAQS1GDQIMBwsgA0EpRw0BQQAoAqQKQQAvAZgKIgJBA3RqKAIEEBxFDQIMBgsgAUF+ai8BAEFQakH//wNxQQpPDQULQQAvAZgKIQILAkACQCACQf//A3EiAkUNACADQeYARw0AQQAoAqQKIAJBf2pBA3RqIgQoAgBBAUcNACABQX5qLwEAQe8ARw0BIAQoAgRBlghBAxAdRQ0BDAULIANB/QBHDQBBACgCpAogAkEDdGoiAigCBBAeDQQgAigCAEEGRg0ECyABEB8NAyADRQ0DIANBL0ZBAC0AoApBAEdxDQMCQEEAKAL4CSICRQ0AIAEgAigCAEkNACABIAIoAgRNDQQLIAFBfmohAUEAKALcCSECAkADQCABQQJqIgQgAk0NAUEAIAE2ApwKIAEvAQAhAyABQX5qIgQhASADECBFDQALIARBAmohBAsCQCADQf//A3EQIUUNACAEQX5qIQECQANAIAFBAmoiAyACTQ0BQQAgATYCnAogAS8BACEDIAFBfmoiBCEBIAMQIQ0ACyAEQQJqIQMLIAMQIg0EC0EAQQE6AKAKDAcLQQAoAqQKQQAvAZgKIgFBA3QiA2pBACgCnAo2AgRBACABQQFqOwGYCkEAKAKkCiADakEDNgIACxAjDAULQQAtAPwJQQAvAZYKQQAvAZgKcnJFIQIMBwsQJEEAQQA6AKAKDAMLECVBACECDAULIANBoAFHDQELQQBBAToArAoLQQBBACgCsAo2ApwKC0EAKAKwCiEBDAALCyAAQYDQAGokACACCxoAAkBBACgC3AkgAEcNAEEBDwsgAEF+ahAmC/4KAQZ/QQBBACgCsAoiAEEMaiIBNgKwCkEAKAL4CSECQQEQKSEDAkACQAJAAkACQAJAAkACQAJAQQAoArAKIgQgAUcNACADEChFDQELAkACQAJAAkACQAJAAkAgA0EqRg0AIANB+wBHDQFBACAEQQJqNgKwCkEBECkhA0EAKAKwCiEEA0ACQAJAIANB//8DcSIDQSJGDQAgA0EnRg0AIAMQLBpBACgCsAohAwwBCyADEBpBAEEAKAKwCkECaiIDNgKwCgtBARApGgJAIAQgAxAtIgNBLEcNAEEAQQAoArAKQQJqNgKwCkEBECkhAwsgA0H9AEYNA0EAKAKwCiIFIARGDQ8gBSEEIAVBACgCtApNDQAMDwsLQQAgBEECajYCsApBARApGkEAKAKwCiIDIAMQLRoMAgtBAEEAOgCUCgJAAkACQAJAAkACQCADQZ9/ag4MAgsEAQsDCwsLCwsFAAsgA0H2AEYNBAwKC0EAIARBDmoiAzYCsAoCQAJAAkBBARApQZ9/ag4GABICEhIBEgtBACgCsAoiBSkAAkLzgOSD4I3AMVINESAFLwEKECFFDRFBACAFQQpqNgKwCkEAECkaC0EAKAKwCiIFQQJqQbIIQQ4QLw0QIAUvARAiAkF3aiIBQRdLDQ1BASABdEGfgIAEcUUNDQwOC0EAKAKwCiIFKQACQuyAhIOwjsA5Ug0PIAUvAQoiAkF3aiIBQRdNDQYMCgtBACAEQQpqNgKwCkEAECkaQQAoArAKIQQLQQAgBEEQajYCsAoCQEEBECkiBEEqRw0AQQBBACgCsApBAmo2ArAKQQEQKSEEC0EAKAKwCiEDIAQQLBogA0EAKAKwCiIEIAMgBBACQQBBACgCsApBfmo2ArAKDwsCQCAEKQACQuyAhIOwjsA5Ug0AIAQvAQoQIEUNAEEAIARBCmo2ArAKQQEQKSEEQQAoArAKIQMgBBAsGiADQQAoArAKIgQgAyAEEAJBAEEAKAKwCkF+ajYCsAoPC0EAIARBBGoiBDYCsAoLQQAgBEEGajYCsApBAEEAOgCUCkEBECkhBEEAKAKwCiEDIAQQLCEEQQAoArAKIQIgBEHf/wNxIgFB2wBHDQNBACACQQJqNgKwCkEBECkhBUEAKAKwCiEDQQAhBAwEC0EAQQE6AIwKQQBBACgCsApBAmo2ArAKC0EBECkhBEEAKAKwCiEDAkAgBEHmAEcNACADQQJqQawIQQYQLw0AQQAgA0EIajYCsAogAEEBEClBABArIAJBEGpB5AkgAhshAwNAIAMoAgAiA0UNBSADQgA3AgggA0EQaiEDDAALC0EAIANBfmo2ArAKDAMLQQEgAXRBn4CABHFFDQMMBAtBASEECwNAAkACQCAEDgIAAQELIAVB//8DcRAsGkEBIQQMAQsCQAJAQQAoArAKIgQgA0YNACADIAQgAyAEEAJBARApIQQCQCABQdsARw0AIARBIHJB/QBGDQQLQQAoArAKIQMCQCAEQSxHDQBBACADQQJqNgKwCkEBECkhBUEAKAKwCiEDIAVBIHJB+wBHDQILQQAgA0F+ajYCsAoLIAFB2wBHDQJBACACQX5qNgKwCg8LQQAhBAwACwsPCyACQaABRg0AIAJB+wBHDQQLQQAgBUEKajYCsApBARApIgVB+wBGDQMMAgsCQCACQVhqDgMBAwEACyACQaABRw0CC0EAIAVBEGo2ArAKAkBBARApIgVBKkcNAEEAQQAoArAKQQJqNgKwCkEBECkhBQsgBUEoRg0BC0EAKAKwCiEBIAUQLBpBACgCsAoiBSABTQ0AIAQgAyABIAUQAkEAQQAoArAKQX5qNgKwCg8LIAQgA0EAQQAQAkEAIARBDGo2ArAKDwsQJQuFDAEKf0EAQQAoArAKIgBBDGoiATYCsApBARApIQJBACgCsAohAwJAAkACQAJAAkACQAJAAkAgAkEuRw0AQQAgA0ECajYCsAoCQEEBECkiAkHkAEYNAAJAIAJB8wBGDQAgAkHtAEcNB0EAKAKwCiICQQJqQZwIQQYQLw0HAkBBACgCnAoiAxAqDQAgAy8BAEEuRg0ICyAAIAAgAkEIakEAKALUCRABDwtBACgCsAoiAkECakGiCEEKEC8NBgJAQQAoApwKIgMQKg0AIAMvAQBBLkYNBwtBACEEQQAgAkEMajYCsApBASEFQQUhBkEBECkhAkEAIQdBASEIDAILQQAoArAKIgIpAAJC5YCYg9CMgDlSDQUCQEEAKAKcCiIDECoNACADLwEAQS5GDQYLQQAhBEEAIAJBCmo2ArAKQQIhCEEHIQZBASEHQQEQKSECQQEhBQwBCwJAAkACQAJAIAJB8wBHDQAgAyABTQ0AIANBAmpBoghBChAvDQACQCADLwEMIgRBd2oiB0EXSw0AQQEgB3RBn4CABHENAgsgBEGgAUYNAQtBACEHQQchBkEBIQQgAkHkAEYNAQwCC0EAIQRBACADQQxqIgI2ArAKQQEhBUEBECkhCQJAQQAoArAKIgYgAkYNAEHmACECAkAgCUHmAEYNAEEFIQZBACEHQQEhCCAJIQIMBAtBACEHQQEhCCAGQQJqQawIQQYQLw0EIAYvAQgQIEUNBAtBACEHQQAgAzYCsApBByEGQQEhBEEAIQVBACEIIAkhAgwCCyADIABBCmpNDQBBACEIQeQAIQICQCADKQACQuWAmIPQjIA5Ug0AAkACQCADLwEKIgRBd2oiB0EXSw0AQQEgB3RBn4CABHENAQtBACEIIARBoAFHDQELQQAhBUEAIANBCmo2ArAKQSohAkEBIQdBAiEIQQEQKSIJQSpGDQRBACADNgKwCkEBIQRBACEHQQAhCCAJIQIMAgsgAyEGQQAhBwwCC0EAIQVBACEICwJAIAJBKEcNAEEAKAKkCkEALwGYCiICQQN0aiIDQQAoArAKNgIEQQAgAkEBajsBmAogA0EFNgIAQQAoApwKLwEAQS5GDQRBAEEAKAKwCiIDQQJqNgKwCkEBECkhAiAAQQAoArAKQQAgAxABAkACQCAFDQBBACgC8AkhAQwBC0EAKALwCSIBIAY2AhwLQQBBAC8BlgoiA0EBajsBlgpBACgCqAogA0ECdGogATYCAAJAIAJBIkYNACACQSdGDQBBAEEAKAKwCkF+ajYCsAoPCyACEBpBAEEAKAKwCkECaiICNgKwCgJAAkACQEEBEClBV2oOBAECAgACC0EAQQAoArAKQQJqNgKwCkEBECkaQQAoAvAJIgMgAjYCBCADQQE6ABggA0EAKAKwCiICNgIQQQAgAkF+ajYCsAoPC0EAKALwCSIDIAI2AgQgA0EBOgAYQQBBAC8BmApBf2o7AZgKIANBACgCsApBAmo2AgxBAEEALwGWCkF/ajsBlgoPC0EAQQAoArAKQX5qNgKwCg8LAkAgBEEBcyACQfsAR3INAEEAKAKwCiECQQAvAZgKDQUDQAJAAkACQCACQQAoArQKTw0AQQEQKSICQSJGDQEgAkEnRg0BIAJB/QBHDQJBAEEAKAKwCkECajYCsAoLQQEQKSEDQQAoArAKIQICQCADQeYARw0AIAJBAmpBrAhBBhAvDQcLQQAgAkEIajYCsAoCQEEBECkiAkEiRg0AIAJBJ0cNBwsgACACQQAQKw8LIAIQGgtBAEEAKAKwCkECaiICNgKwCgwACwsCQAJAIAJBWWoOBAMBAQMACyACQSJGDQILQQAoArAKIQYLIAYgAUcNAEEAIABBCmo2ArAKDwsgAkEqRyAHcQ0DQQAvAZgKQf//A3ENA0EAKAKwCiECQQAoArQKIQEDQCACIAFPDQECQAJAIAIvAQAiA0EnRg0AIANBIkcNAQsgACADIAgQKw8LQQAgAkECaiICNgKwCgwACwsQJQsPC0EAIAJBfmo2ArAKDwtBAEEAKAKwCkF+ajYCsAoLRwEDf0EAKAKwCkECaiEAQQAoArQKIQECQANAIAAiAkF+aiABTw0BIAJBAmohACACLwEAQXZqDgQBAAABAAsLQQAgAjYCsAoLmAEBA39BAEEAKAKwCiIBQQJqNgKwCiABQQZqIQFBACgCtAohAgNAAkACQAJAIAFBfGogAk8NACABQX5qLwEAIQMCQAJAIAANACADQSpGDQEgA0F2ag4EAgQEAgQLIANBKkcNAwsgAS8BAEEvRw0CQQAgAUF+ajYCsAoMAQsgAUF+aiEBC0EAIAE2ArAKDwsgAUECaiEBDAALC4gBAQR/QQAoArAKIQFBACgCtAohAgJAAkADQCABIgNBAmohASADIAJPDQEgAS8BACIEIABGDQICQCAEQdwARg0AIARBdmoOBAIBAQIBCyADQQRqIQEgAy8BBEENRw0AIANBBmogASADLwEGQQpGGyEBDAALC0EAIAE2ArAKECUPC0EAIAE2ArAKC2wBAX8CQAJAIABBX2oiAUEFSw0AQQEgAXRBMXENAQsgAEFGakH//wNxQQZJDQAgAEEpRyAAQVhqQf//A3FBB0lxDQACQCAAQaV/ag4EAQAAAQALIABB/QBHIABBhX9qQf//A3FBBElxDwtBAQsuAQF/QQEhAQJAIABBpglBBRAdDQAgAEGWCEEDEB0NACAAQbAJQQIQHSEBCyABC0YBA39BACEDAkAgACACQQF0IgJrIgRBAmoiAEEAKALcCSIFSQ0AIAAgASACEC8NAAJAIAAgBUcNAEEBDwsgBBAmIQMLIAMLgwEBAn9BASEBAkACQAJAAkACQAJAIAAvAQAiAkFFag4EBQQEAQALAkAgAkGbf2oOBAMEBAIACyACQSlGDQQgAkH5AEcNAyAAQX5qQbwJQQYQHQ8LIABBfmovAQBBPUYPCyAAQX5qQbQJQQQQHQ8LIABBfmpByAlBAxAdDwtBACEBCyABC7QDAQJ/QQAhAQJAAkACQAJAAkACQAJAAkACQAJAIAAvAQBBnH9qDhQAAQIJCQkJAwkJBAUJCQYJBwkJCAkLAkACQCAAQX5qLwEAQZd/ag4EAAoKAQoLIABBfGpByghBAhAdDwsgAEF8akHOCEEDEB0PCwJAAkACQCAAQX5qLwEAQY1/ag4DAAECCgsCQCAAQXxqLwEAIgJB4QBGDQAgAkHsAEcNCiAAQXpqQeUAECcPCyAAQXpqQeMAECcPCyAAQXxqQdQIQQQQHQ8LIABBfGpB3AhBBhAdDwsgAEF+ai8BAEHvAEcNBiAAQXxqLwEAQeUARw0GAkAgAEF6ai8BACICQfAARg0AIAJB4wBHDQcgAEF4akHoCEEGEB0PCyAAQXhqQfQIQQIQHQ8LIABBfmpB+AhBBBAdDwtBASEBIABBfmoiAEHpABAnDQQgAEGACUEFEB0PCyAAQX5qQeQAECcPCyAAQX5qQYoJQQcQHQ8LIABBfmpBmAlBBBAdDwsCQCAAQX5qLwEAIgJB7wBGDQAgAkHlAEcNASAAQXxqQe4AECcPCyAAQXxqQaAJQQMQHSEBCyABCzQBAX9BASEBAkAgAEF3akH//wNxQQVJDQAgAEGAAXJBoAFGDQAgAEEuRyAAEChxIQELIAELMAEBfwJAAkAgAEF3aiIBQRdLDQBBASABdEGNgIAEcQ0BCyAAQaABRg0AQQAPC0EBC04BAn9BACEBAkACQCAALwEAIgJB5QBGDQAgAkHrAEcNASAAQX5qQfgIQQQQHQ8LIABBfmovAQBB9QBHDQAgAEF8akHcCEEGEB0hAQsgAQveAQEEf0EAKAKwCiEAQQAoArQKIQECQAJAAkADQCAAIgJBAmohACACIAFPDQECQAJAAkAgAC8BACIDQaR/ag4FAgMDAwEACyADQSRHDQIgAi8BBEH7AEcNAkEAIAJBBGoiADYCsApBAEEALwGYCiICQQFqOwGYCkEAKAKkCiACQQN0aiICQQQ2AgAgAiAANgIEDwtBACAANgKwCkEAQQAvAZgKQX9qIgA7AZgKQQAoAqQKIABB//8DcUEDdGooAgBBA0cNAwwECyACQQRqIQAMAAsLQQAgADYCsAoLECULC3ABAn8CQAJAA0BBAEEAKAKwCiIAQQJqIgE2ArAKIABBACgCtApPDQECQAJAAkAgAS8BACIBQaV/ag4CAQIACwJAIAFBdmoOBAQDAwQACyABQS9HDQIMBAsQLhoMAQtBACAAQQRqNgKwCgwACwsQJQsLNQEBf0EAQQE6APwJQQAoArAKIQBBAEEAKAK0CkECajYCsApBACAAQQAoAtwJa0EBdTYCkAoLQwECf0EBIQECQCAALwEAIgJBd2pB//8DcUEFSQ0AIAJBgAFyQaABRg0AQQAhASACEChFDQAgAkEuRyAAECpyDwsgAQs9AQJ/QQAhAgJAQQAoAtwJIgMgAEsNACAALwEAIAFHDQACQCADIABHDQBBAQ8LIABBfmovAQAQICECCyACC2gBAn9BASEBAkACQCAAQV9qIgJBBUsNAEEBIAJ0QTFxDQELIABB+P8DcUEoRg0AIABBRmpB//8DcUEGSQ0AAkAgAEGlf2oiAkEDSw0AIAJBAUcNAQsgAEGFf2pB//8DcUEESSEBCyABC5wBAQN/QQAoArAKIQECQANAAkACQCABLwEAIgJBL0cNAAJAIAEvAQIiAUEqRg0AIAFBL0cNBBAYDAILIAAQGQwBCwJAAkAgAEUNACACQXdqIgFBF0sNAUEBIAF0QZ+AgARxRQ0BDAILIAIQIUUNAwwBCyACQaABRw0CC0EAQQAoArAKIgNBAmoiATYCsAogA0EAKAK0CkkNAAsLIAILMQEBf0EAIQECQCAALwEAQS5HDQAgAEF+ai8BAEEuRw0AIABBfGovAQBBLkYhAQsgAQumBAEBfwJAIAFBIkYNACABQSdGDQAQJQ8LQQAoArAKIQMgARAaIAAgA0ECakEAKAKwCkEAKALQCRABAkAgAkEBSA0AQQAoAvAJQQRBBiACQQFGGzYCHAtBAEEAKAKwCkECajYCsAoCQAJAAkACQEEAECkiAUHhAEYNACABQfcARg0BQQAoArAKIQEMAgtBACgCsAoiAUECakHACEEKEC8NAUEGIQIMAgtBACgCsAoiAS8BAkHpAEcNACABLwEEQfQARw0AQQQhAiABLwEGQegARg0BC0EAIAFBfmo2ArAKDwtBACABIAJBAXRqNgKwCgJAQQEQKUH7AEYNAEEAIAE2ArAKDwtBACgCsAoiACECA0BBACACQQJqNgKwCgJAAkACQEEBECkiAkEiRg0AIAJBJ0cNAUEnEBpBAEEAKAKwCkECajYCsApBARApIQIMAgtBIhAaQQBBACgCsApBAmo2ArAKQQEQKSECDAELIAIQLCECCwJAIAJBOkYNAEEAIAE2ArAKDwtBAEEAKAKwCkECajYCsAoCQEEBECkiAkEiRg0AIAJBJ0YNAEEAIAE2ArAKDwsgAhAaQQBBACgCsApBAmo2ArAKAkACQEEBECkiAkEsRg0AIAJB/QBGDQFBACABNgKwCg8LQQBBACgCsApBAmo2ArAKQQEQKUH9AEYNAEEAKAKwCiECDAELC0EAKALwCSIBIAA2AhAgAUEAKAKwCkECajYCDAttAQJ/AkACQANAAkAgAEH//wNxIgFBd2oiAkEXSw0AQQEgAnRBn4CABHENAgsgAUGgAUYNASAAIQIgARAoDQJBACECQQBBACgCsAoiAEECajYCsAogAC8BAiIADQAMAgsLIAAhAgsgAkH//wNxC6sBAQR/AkACQEEAKAKwCiICLwEAIgNB4QBGDQAgASEEIAAhBQwBC0EAIAJBBGo2ArAKQQEQKSECQQAoArAKIQUCQAJAIAJBIkYNACACQSdGDQAgAhAsGkEAKAKwCiEEDAELIAIQGkEAQQAoArAKQQJqIgQ2ArAKC0EBECkhA0EAKAKwCiECCwJAIAIgBUYNACAFIARBACAAIAAgAUYiAhtBACABIAIbEAILIAMLcgEEf0EAKAKwCiEAQQAoArQKIQECQAJAA0AgAEECaiECIAAgAU8NAQJAAkAgAi8BACIDQaR/ag4CAQQACyACIQAgA0F2ag4EAgEBAgELIABBBGohAAwACwtBACACNgKwChAlQQAPC0EAIAI2ArAKQd0AC0kBA39BACEDAkAgAkUNAAJAA0AgAC0AACIEIAEtAAAiBUcNASABQQFqIQEgAEEBaiEAIAJBf2oiAg0ADAILCyAEIAVrIQMLIAMLC+wBAgBBgAgLzgEAAHgAcABvAHIAdABtAHAAbwByAHQAZgBvAHIAZQB0AGEAbwB1AHIAYwBlAHIAbwBtAHUAbgBjAHQAaQBvAG4AcwBzAGUAcgB0AHYAbwB5AGkAZQBkAGUAbABlAGMAbwBuAHQAaQBuAGkAbgBzAHQAYQBuAHQAeQBiAHIAZQBhAHIAZQB0AHUAcgBkAGUAYgB1AGcAZwBlAGEAdwBhAGkAdABoAHIAdwBoAGkAbABlAGkAZgBjAGEAdABjAGYAaQBuAGEAbABsAGUAbABzAABB0AkLEAEAAAACAAAAAAQAAEA5AAA=", "undefined" != typeof Buffer ? Buffer.from(A$1, "base64") : Uint8Array.from(atob(A$1), ((A$2) => A$2.charCodeAt(0))); var A$1; }; const init = WebAssembly.compile(E()).then(WebAssembly.instantiate).then((({ exports: A$1 }) => { C = A$1; })); //#endregion //#region ../../node_modules/.pnpm/convert-source-map@2.0.0/node_modules/convert-source-map/index.js var require_convert_source_map = /* @__PURE__ */ __commonJS({ "../../node_modules/.pnpm/convert-source-map@2.0.0/node_modules/convert-source-map/index.js": ((exports) => { Object.defineProperty(exports, "commentRegex", { get: function getCommentRegex() { return /^\s*?\/[\/\*][@#]\s+?sourceMappingURL=data:(((?:application|text)\/json)(?:;charset=([^;,]+?)?)?)?(?:;(base64))?,(.*?)$/gm; } }); Object.defineProperty(exports, "mapFileCommentRegex", { get: function getMapFileCommentRegex() { return /(?:\/\/[@#][ \t]+?sourceMappingURL=([^\s'"`]+?)[ \t]*?$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^*]+?)[ \t]*?(?:\*\/){1}[ \t]*?$)/gm; } }); var decodeBase64; if (typeof Buffer !== "undefined") if (typeof Buffer.from === "function") decodeBase64 = decodeBase64WithBufferFrom; else decodeBase64 = decodeBase64WithNewBuffer; else decodeBase64 = decodeBase64WithAtob; function decodeBase64WithBufferFrom(base64) { return Buffer.from(base64, "base64").toString(); } function decodeBase64WithNewBuffer(base64) { if (typeof value === "number") throw new TypeError("The value to decode must not be of type number."); return new Buffer(base64, "base64").toString(); } function decodeBase64WithAtob(base64) { return decodeURIComponent(escape(atob(base64))); } function stripComment(sm) { return sm.split(",").pop(); } function readFromFileMap(sm, read) { var r$1 = exports.mapFileCommentRegex.exec(sm); var filename = r$1[1] || r$1[2]; try { var sm = read(filename); if (sm != null && typeof sm.catch === "function") return sm.catch(throwError); else return sm; } catch (e$1) { throwError(e$1); } function throwError(e$1) { throw new Error("An error occurred while trying to read the map file at " + filename + "\n" + e$1.stack); } } function Converter(sm, opts) { opts = opts || {}; if (opts.hasComment) sm = stripComment(sm); if (opts.encoding === "base64") sm = decodeBase64(sm); else if (opts.encoding === "uri") sm = decodeURIComponent(sm); if (opts.isJSON || opts.encoding) sm = JSON.parse(sm); this.sourcemap = sm; } Converter.prototype.toJSON = function(space) { return JSON.stringify(this.sourcemap, null, space); }; if (typeof Buffer !== "undefined") if (typeof Buffer.from === "function") Converter.prototype.toBase64 = encodeBase64WithBufferFrom; else Converter.prototype.toBase64 = encodeBase64WithNewBuffer; else Converter.prototype.toBase64 = encodeBase64WithBtoa; function encodeBase64WithBufferFrom() { var json = this.toJSON(); return Buffer.from(json, "utf8").toString("base64"); } function encodeBase64WithNewBuffer() { var json = this.toJSON(); if (typeof json === "number") throw new TypeError("The json to encode must not be of type number."); return new Buffer(json, "utf8").toString("base64"); } function encodeBase64WithBtoa() { var json = this.toJSON(); return btoa(unescape(encodeURIComponent(json))); } Converter.prototype.toURI = function() { var json = this.toJSON(); return encodeURIComponent(json); }; Converter.prototype.toComment = function(options$1) { var encoding, content, data; if (options$1 != null && options$1.encoding === "uri") { encoding = ""; content = this.toURI(); } else { encoding = ";base64"; content = this.toBase64(); } data = "sourceMappingURL=data:application/json;charset=utf-8" + encoding + "," + content; return options$1 != null && options$1.multiline ? "/*# " + data + " */" : "//# " + data; }; Converter.prototype.toObject = function() { return JSON.parse(this.toJSON()); }; Converter.prototype.addProperty = function(key, value$1) { if (this.sourcemap.hasOwnProperty(key)) throw new Error("property \"" + key + "\" already exists on the sourcemap, use set property instead"); return this.setProperty(key, value$1); }; Converter.prototype.setProperty = function(key, value$1) { this.sourcemap[key] = value$1; return this; }; Converter.prototype.getProperty = function(key) { return this.sourcemap[key]; }; exports.fromObject = function(obj) { return new Converter(obj); }; exports.fromJSON = function(json) { return new Converter(json, { isJSON: true }); }; exports.fromURI = function(uri) { return new Converter(uri, { encoding: "uri" }); }; exports.fromBase64 = function(base64) { return new Converter(base64, { encoding: "base64" }); }; exports.fromComment = function(comment) { var m$2, encoding; comment = comment.replace(/^\/\*/g, "//").replace(/\*\/$/g, ""); m$2 = exports.commentRegex.exec(comment); encoding = m$2 && m$2[4] || "uri"; return new Converter(comment, { encoding, hasComment: true }); }; function makeConverter(sm) { return new Converter(sm, { isJSON: true }); } exports.fromMapFileComment = function(comment, read) { if (typeof read === "string") throw new Error("String directory paths are no longer supported with `fromMapFileComment`\nPlease review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading"); var sm = readFromFileMap(comment, read); if (sm != null && typeof sm.then === "function") return sm.then(makeConverter); else return makeConverter(sm); }; exports.fromSource = function(content) { var m$2 = content.match(exports.commentRegex); return m$2 ? exports.fromComment(m$2.pop()) : null; }; exports.fromMapFileSource = function(content, read) { if (typeof read === "string") throw new Error("String directory paths are no longer supported with `fromMapFileSource`\nPlease review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading"); var m$2 = content.match(exports.mapFileCommentRegex); return m$2 ? exports.fromMapFileComment(m$2.pop(), read) : null; }; exports.removeComments = function(src) { return src.replace(exports.commentRegex, ""); }; exports.removeMapFileComments = function(src) { return src.replace(exports.mapFileCommentRegex, ""); }; exports.generateMapFileComment = function(file, options$1) { var data = "sourceMappingURL=" + file; return options$1 && options$1.multiline ? "/*# " + data + " */" : "//# " + data; }; }) }); //#endregion //#region ../../node_modules/.pnpm/@rolldown+pluginutils@1.0.0-beta.43/node_modules/@rolldown/pluginutils/dist/index.mjs /** * Constructs a RegExp that matches the exact string specified. * * This is useful for plugin hook filters. * * @param str the string to match. * @param flags flags for the RegExp. * * @example * ```ts * import { exactRegex } from '@rolldown/pluginutils'; * const plugin = { * name: 'plugin', * resolveId: { * filter: { id: exactRegex('foo') }, * handler(id) {} // will only be called for `foo` * } * } * ``` */ function exactRegex(str, flags) { return new RegExp(`^${escapeRegex$1(str)}$`, flags); } /** * Constructs a RegExp that matches a value that has the specified prefix. * * This is useful for plugin hook filters. * * @param str the string to match. * @param flags flags for the RegExp. * * @example * ```ts * import { prefixRegex } from '@rolldown/pluginutils'; * const plugin = { * name: 'plugin', * resolveId: { * filter: { id: prefixRegex('foo') }, * handler(id) {} // will only be called for IDs starting with `foo` * } * } * ``` */ function prefixRegex(str, flags) { return new RegExp(`^${escapeRegex$1(str)}`, flags); } const escapeRegexRE = /[-/\\^$*+?.()|[\]{}]/g; function escapeRegex$1(str) { return str.replace(escapeRegexRE, "\\$&"); } //#endregion //#region src/node/server/sourcemap.ts var import_convert_source_map$2 = /* @__PURE__ */ __toESM(require_convert_source_map(), 1); const debug$16 = createDebugger("vite:sourcemap", { onlyWhenFocused: true }); const virtualSourceRE = /^(?:dep:|browser-external:|virtual:)|\0/; async function computeSourceRoute(map$1, file) { let sourceRoot; try { sourceRoot = await fsp.realpath(path.resolve(path.dirname(file), map$1.sourceRoot || "")); } catch {} return sourceRoot; } async function injectSourcesContent(map$1, file, logger) { let sourceRootPromise; const missingSources = []; const sourcesContent = map$1.sourcesContent || []; const sourcesContentPromises = []; for (let index = 0; index < map$1.sources.length; index++) { const sourcePath = map$1.sources[index]; if (sourcesContent[index] == null && sourcePath && !virtualSourceRE.test(sourcePath)) sourcesContentPromises.push((async () => { sourceRootPromise ??= computeSourceRoute(map$1, file); const sourceRoot = await sourceRootPromise; let resolvedSourcePath = cleanUrl(decodeURI(sourcePath)); if (sourceRoot) resolvedSourcePath = path.resolve(sourceRoot, resolvedSourcePath); sourcesContent[index] = await fsp.readFile(resolvedSourcePath, "utf-8").catch(() => { missingSources.push(resolvedSourcePath); return null; }); })()); } await Promise.all(sourcesContentPromises); map$1.sourcesContent = sourcesContent; if (missingSources.length) { logger.warnOnce(`Sourcemap for "${file}" points to missing source files`); debug$16?.(`Missing sources:\n ` + missingSources.join(`\n `)); } } function genSourceMapUrl(map$1) { if (typeof map$1 !== "string") map$1 = JSON.stringify(map$1); return `data:application/json;base64,${Buffer.from(map$1).toString("base64")}`; } function getCodeWithSourcemap(type, code, map$1) { if (debug$16) code += `\n/*${JSON.stringify(map$1, null, 2).replace(/\*\//g, "*\\/")}*/\n`; if (type === "js") code += `\n//# sourceMappingURL=${genSourceMapUrl(map$1)}`; else if (type === "css") code += `\n/*# sourceMappingURL=${genSourceMapUrl(map$1)} */`; return code; } function applySourcemapIgnoreList(map$1, sourcemapPath, sourcemapIgnoreList, logger) { let { x_google_ignoreList } = map$1; if (x_google_ignoreList === void 0) x_google_ignoreList = []; for (let sourcesIndex = 0; sourcesIndex < map$1.sources.length; ++sourcesIndex) { const sourcePath = map$1.sources[sourcesIndex]; if (!sourcePath) continue; const ignoreList = sourcemapIgnoreList(path.isAbsolute(sourcePath) ? sourcePath : path.resolve(path.dirname(sourcemapPath), sourcePath), sourcemapPath); if (logger && typeof ignoreList !== "boolean") logger.warn("sourcemapIgnoreList function must return a boolean."); if (ignoreList && !x_google_ignoreList.includes(sourcesIndex)) x_google_ignoreList.push(sourcesIndex); } if (x_google_ignoreList.length > 0) { if (!map$1.x_google_ignoreList) map$1.x_google_ignoreList = x_google_ignoreList; } } async function extractSourcemapFromFile(code, filePath) { const map$1 = (import_convert_source_map$2.fromSource(code) || await import_convert_source_map$2.fromMapFileSource(code, createConvertSourceMapReadMap(filePath)))?.toObject(); if (map$1) return { code: code.replace(import_convert_source_map$2.default.mapFileCommentRegex, blankReplacer), map: map$1 }; } function createConvertSourceMapReadMap(originalFileName) { return (filename) => { return fsp.readFile(path.resolve(path.dirname(originalFileName), filename), "utf-8"); }; } //#endregion //#region ../../node_modules/.pnpm/lilconfig@3.1.3/node_modules/lilconfig/src/index.js var require_src$1 = /* @__PURE__ */ __commonJS({ "../../node_modules/.pnpm/lilconfig@3.1.3/node_modules/lilconfig/src/index.js": ((exports, module) => { const path$11 = __require("path"); const fs$11 = __require("fs"); const os$4 = __require("os"); const url$2 = __require("url"); const fsReadFileAsync = fs$11.promises.readFile; /** @type {(name: string, sync: boolean) => string[]} */ function getDefaultSearchPlaces(name, sync$3) { return [ "package.json", `.${name}rc.json`, `.${name}rc.js`, `.${name}rc.cjs`, ...sync$3 ? [] : [`.${name}rc.mjs`], `.config/${name}rc`, `.config/${name}rc.json`, `.config/${name}rc.js`, `.config/${name}rc.cjs`, ...sync$3 ? [] : [`.config/${name}rc.mjs`], `${name}.config.js`, `${name}.config.cjs`, ...sync$3 ? [] : [`${name}.config.mjs`] ]; } /** * @type {(p: string) => string} * * see #17 * On *nix, if cwd is not under homedir, * the last path will be '', ('/build' -> '') * but it should be '/' actually. * And on Windows, this will never happen. ('C:\build' -> 'C:') */ function parentDir(p) { return path$11.dirname(p) || path$11.sep; } /** @type {import('./index').LoaderSync} */ const jsonLoader = (_, content) => JSON.parse(content); const requireFunc = typeof __webpack_require__ === "function" ? __non_webpack_require__ : __require; /** @type {import('./index').LoadersSync} */ const defaultLoadersSync = Object.freeze({ ".js": requireFunc, ".json": requireFunc, ".cjs": requireFunc, noExt: jsonLoader }); module.exports.defaultLoadersSync = defaultLoadersSync; /** @type {import('./index').Loader} */ const dynamicImport = async (id) => { try { return (await import(url$2.pathToFileURL(id).href)).default; } catch (e$1) { try { return requireFunc(id); } catch (requireE) { if (requireE.code === "ERR_REQUIRE_ESM" || requireE instanceof SyntaxError && requireE.toString().includes("Cannot use import statement outside a module")) throw e$1; throw requireE; } } }; /** @type {import('./index').Loaders} */ const defaultLoaders = Object.freeze({ ".js": dynamicImport, ".mjs": dynamicImport, ".cjs": dynamicImport, ".json": jsonLoader, noExt: jsonLoader }); module.exports.defaultLoaders = defaultLoaders; /** * @param {string} name * @param {import('./index').Options | import('./index').OptionsSync} options * @param {boolean} sync * @returns {Required} */ function getOptions(name, options$1, sync$3) { /** @type {Required} */ const conf = { stopDir: os$4.homedir(), searchPlaces: getDefaultSearchPlaces(name, sync$3), ignoreEmptySearchPlaces: true, cache: true, transform: (x) => x, packageProp: [name], ...options$1, loaders: { ...sync$3 ? defaultLoadersSync : defaultLoaders, ...options$1.loaders } }; conf.searchPlaces.forEach((place) => { const key = path$11.extname(place) || "noExt"; const loader$1 = conf.loaders[key]; if (!loader$1) throw new Error(`Missing loader for extension "${place}"`); if (typeof loader$1 !== "function") throw new Error(`Loader for extension "${place}" is not a function: Received ${typeof loader$1}.`); }); return conf; } /** @type {(props: string | string[], obj: Record) => unknown} */ function getPackageProp(props, obj) { if (typeof props === "string" && props in obj) return obj[props]; return (Array.isArray(props) ? props : props.split(".")).reduce((acc, prop) => acc === void 0 ? acc : acc[prop], obj) || null; } /** @param {string} filepath */ function validateFilePath(filepath) { if (!filepath) throw new Error("load must pass a non-empty string"); } /** @type {(loader: import('./index').Loader, ext: string) => void} */ function validateLoader(loader$1, ext) { if (!loader$1) throw new Error(`No loader specified for extension "${ext}"`); if (typeof loader$1 !== "function") throw new Error("loader is not a function"); } /** @type {(enableCache: boolean) => (c: Map, filepath: string, res: T) => T} */ const makeEmplace = (enableCache) => (c, filepath, res) => { if (enableCache) c.set(filepath, res); return res; }; /** @type {import('./index').lilconfig} */ module.exports.lilconfig = function lilconfig(name, options$1) { const { ignoreEmptySearchPlaces, loaders, packageProp, searchPlaces, stopDir, transform: transform$2, cache: cache$1 } = getOptions(name, options$1 ?? {}, false); const searchCache = /* @__PURE__ */ new Map(); const loadCache = /* @__PURE__ */ new Map(); const emplace = makeEmplace(cache$1); return { async search(searchFrom = process.cwd()) { /** @type {import('./index').LilconfigResult} */ const result = { config: null, filepath: "" }; /** @type {Set} */ const visited = /* @__PURE__ */ new Set(); let dir = searchFrom; dirLoop: while (true) { if (cache$1) { const r$1 = searchCache.get(dir); if (r$1 !== void 0) { for (const p of visited) searchCache.set(p, r$1); return r$1; } visited.add(dir); } for (const searchPlace of searchPlaces) { const filepath = path$11.join(dir, searchPlace); try { await fs$11.promises.access(filepath); } catch { continue; } const content = String(await fsReadFileAsync(filepath)); const loaderKey = path$11.extname(searchPlace) || "noExt"; const loader$1 = loaders[loaderKey]; if (searchPlace === "package.json") { const maybeConfig = getPackageProp(packageProp, await loader$1(filepath, content)); if (maybeConfig != null) { result.config = maybeConfig; result.filepath = filepath; break dirLoop; } continue; } const isEmpty = content.trim() === ""; if (isEmpty && ignoreEmptySearchPlaces) continue; if (isEmpty) { result.isEmpty = true; result.config = void 0; } else { validateLoader(loader$1, loaderKey); result.config = await loader$1(filepath, content); } result.filepath = filepath; break dirLoop; } if (dir === stopDir || dir === parentDir(dir)) break dirLoop; dir = parentDir(dir); } const transformed = result.filepath === "" && result.config === null ? transform$2(null) : transform$2(result); if (cache$1) for (const p of visited) searchCache.set(p, transformed); return transformed; }, async load(filepath) { validateFilePath(filepath); const absPath = path$11.resolve(process.cwd(), filepath); if (cache$1 && loadCache.has(absPath)) return loadCache.get(absPath); const { base, ext } = path$11.parse(absPath); const loaderKey = ext || "noExt"; const loader$1 = loaders[loaderKey]; validateLoader(loader$1, loaderKey); const content = String(await fsReadFileAsync(absPath)); if (base === "package.json") return emplace(loadCache, absPath, transform$2({ config: getPackageProp(packageProp, await loader$1(absPath, content)), filepath: absPath })); /** @type {import('./index').LilconfigResult} */ const result = { config: null, filepath: absPath }; const isEmpty = content.trim() === ""; if (isEmpty && ignoreEmptySearchPlaces) return emplace(loadCache, absPath, transform$2({ config: void 0, filepath: absPath, isEmpty: true })); result.config = isEmpty ? void 0 : await loader$1(absPath, content); return emplace(loadCache, absPath, transform$2(isEmpty ? { ...result, isEmpty, config: void 0 } : result)); }, clearLoadCache() { if (cache$1) loadCache.clear(); }, clearSearchCache() { if (cache$1) searchCache.clear(); }, clearCaches() { if (cache$1) { loadCache.clear(); searchCache.clear(); } } }; }; /** @type {import('./index').lilconfigSync} */ module.exports.lilconfigSync = function lilconfigSync(name, options$1) { const { ignoreEmptySearchPlaces, loaders, packageProp, searchPlaces, stopDir, transform: transform$2, cache: cache$1 } = getOptions(name, options$1 ?? {}, true); const searchCache = /* @__PURE__ */ new Map(); const loadCache = /* @__PURE__ */ new Map(); const emplace = makeEmplace(cache$1); return { search(searchFrom = process.cwd()) { /** @type {import('./index').LilconfigResult} */ const result = { config: null, filepath: "" }; /** @type {Set} */ const visited = /* @__PURE__ */ new Set(); let dir = searchFrom; dirLoop: while (true) { if (cache$1) { const r$1 = searchCache.get(dir); if (r$1 !== void 0) { for (const p of visited) searchCache.set(p, r$1); return r$1; } visited.add(dir); } for (const searchPlace of searchPlaces) { const filepath = path$11.join(dir, searchPlace); try { fs$11.accessSync(filepath); } catch { continue; } const loaderKey = path$11.extname(searchPlace) || "noExt"; const loader$1 = loaders[loaderKey]; const content = String(fs$11.readFileSync(filepath)); if (searchPlace === "package.json") { const maybeConfig = getPackageProp(packageProp, loader$1(filepath, content)); if (maybeConfig != null) { result.config = maybeConfig; result.filepath = filepath; break dirLoop; } continue; } const isEmpty = content.trim() === ""; if (isEmpty && ignoreEmptySearchPlaces) continue; if (isEmpty) { result.isEmpty = true; result.config = void 0; } else { validateLoader(loader$1, loaderKey); result.config = loader$1(filepath, content); } result.filepath = filepath; break dirLoop; } if (dir === stopDir || dir === parentDir(dir)) break dirLoop; dir = parentDir(dir); } const transformed = result.filepath === "" && result.config === null ? transform$2(null) : transform$2(result); if (cache$1) for (const p of visited) searchCache.set(p, transformed); return transformed; }, load(filepath) { validateFilePath(filepath); const absPath = path$11.resolve(process.cwd(), filepath); if (cache$1 && loadCache.has(absPath)) return loadCache.get(absPath); const { base, ext } = path$11.parse(absPath); const loaderKey = ext || "noExt"; const loader$1 = loaders[loaderKey]; validateLoader(loader$1, loaderKey); const content = String(fs$11.readFileSync(absPath)); if (base === "package.json") return transform$2({ config: getPackageProp(packageProp, loader$1(absPath, content)), filepath: absPath }); const result = { config: null, filepath: absPath }; const isEmpty = content.trim() === ""; if (isEmpty && ignoreEmptySearchPlaces) return emplace(loadCache, absPath, transform$2({ filepath: absPath, config: void 0, isEmpty: true })); result.config = isEmpty ? void 0 : loader$1(absPath, content); return emplace(loadCache, absPath, transform$2(isEmpty ? { ...result, isEmpty, config: void 0 } : result)); }, clearLoadCache() { if (cache$1) loadCache.clear(); }, clearSearchCache() { if (cache$1) searchCache.clear(); }, clearCaches() { if (cache$1) { loadCache.clear(); searchCache.clear(); } } }; }; }) }); //#endregion //#region ../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.6_tsx@4.20.6_yaml@2.8.1/node_modules/postcss-load-config/src/req.js var require_req = /* @__PURE__ */ __commonJS({ "../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.6_tsx@4.20.6_yaml@2.8.1/node_modules/postcss-load-config/src/req.js": ((exports, module) => { const { createRequire: createRequire$2 } = __require("node:module"); const { fileURLToPath: fileURLToPath$1, pathToFileURL: pathToFileURL$1 } = __require("node:url"); const TS_EXT_RE = /\.[mc]?ts$/; let tsx; let jiti; let importError = []; /** * @param {string} name * @param {string} rootFile * @returns {Promise} */ async function req$3(name, rootFile = fileURLToPath$1(import.meta.url)) { let url$3 = createRequire$2(rootFile).resolve(name); try { return (await import(`${pathToFileURL$1(url$3)}?t=${Date.now()}`)).default; } catch (err$2) { if (!TS_EXT_RE.test(url$3)) /* c8 ignore start */ throw err$2; } if (tsx === void 0) try { tsx = await import("tsx/cjs/api"); } catch (error$1) { importError.push(error$1); } if (tsx) { let loaded = tsx.require(name, rootFile); return loaded && "__esModule" in loaded ? loaded.default : loaded; } if (jiti === void 0) try { jiti = (await import("jiti")).default; } catch (error$1) { importError.push(error$1); } if (jiti) return jiti(rootFile, { interopDefault: true })(name); throw new Error(`'tsx' or 'jiti' is required for the TypeScript configuration files. Make sure it is installed\nError: ${importError.map((error$1) => error$1.message).join("\n")}`); } module.exports = req$3; }) }); //#endregion //#region ../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.6_tsx@4.20.6_yaml@2.8.1/node_modules/postcss-load-config/src/options.js var require_options = /* @__PURE__ */ __commonJS({ "../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.6_tsx@4.20.6_yaml@2.8.1/node_modules/postcss-load-config/src/options.js": ((exports, module) => { const req$2 = require_req(); /** * Load Options * * @private * @method options * * @param {Object} config PostCSS Config * * @return {Promise} options PostCSS Options */ async function options(config$2, file) { if (config$2.parser && typeof config$2.parser === "string") try { config$2.parser = await req$2(config$2.parser, file); } catch (err$2) { throw new Error(`Loading PostCSS Parser failed: ${err$2.message}\n\n(@${file})`); } if (config$2.syntax && typeof config$2.syntax === "string") try { config$2.syntax = await req$2(config$2.syntax, file); } catch (err$2) { throw new Error(`Loading PostCSS Syntax failed: ${err$2.message}\n\n(@${file})`); } if (config$2.stringifier && typeof config$2.stringifier === "string") try { config$2.stringifier = await req$2(config$2.stringifier, file); } catch (err$2) { throw new Error(`Loading PostCSS Stringifier failed: ${err$2.message}\n\n(@${file})`); } return config$2; } module.exports = options; }) }); //#endregion //#region ../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.6_tsx@4.20.6_yaml@2.8.1/node_modules/postcss-load-config/src/plugins.js var require_plugins = /* @__PURE__ */ __commonJS({ "../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.6_tsx@4.20.6_yaml@2.8.1/node_modules/postcss-load-config/src/plugins.js": ((exports, module) => { const req$1 = require_req(); /** * Plugin Loader * * @private * @method load * * @param {String} plugin PostCSS Plugin Name * @param {Object} options PostCSS Plugin Options * * @return {Promise} PostCSS Plugin */ async function load$1(plugin, options$1, file) { try { if (options$1 === null || options$1 === void 0 || Object.keys(options$1).length === 0) return await req$1(plugin, file); else return (await req$1(plugin, file))(options$1); } catch (err$2) { throw new Error(`Loading PostCSS Plugin failed: ${err$2.message}\n\n(@${file})`); } } /** * Load Plugins * * @private * @method plugins * * @param {Object} config PostCSS Config Plugins * * @return {Promise} plugins PostCSS Plugins */ async function plugins(config$2, file) { let list = []; if (Array.isArray(config$2.plugins)) list = config$2.plugins.filter(Boolean); else { list = Object.entries(config$2.plugins).filter(([, options$1]) => { return options$1 !== false; }).map(([plugin, options$1]) => { return load$1(plugin, options$1, file); }); list = await Promise.all(list); } if (list.length && list.length > 0) list.forEach((plugin, i$1) => { if (plugin.default) plugin = plugin.default; if (plugin.postcss === true) plugin = plugin(); else if (plugin.postcss) plugin = plugin.postcss; if (!(typeof plugin === "object" && Array.isArray(plugin.plugins) || typeof plugin === "object" && plugin.postcssPlugin || typeof plugin === "function")) throw new TypeError(`Invalid PostCSS Plugin found at: plugins[${i$1}]\n\n(@${file})`); }); return list; } module.exports = plugins; }) }); //#endregion //#region ../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.6_tsx@4.20.6_yaml@2.8.1/node_modules/postcss-load-config/src/index.js var require_src = /* @__PURE__ */ __commonJS({ "../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.6_tsx@4.20.6_yaml@2.8.1/node_modules/postcss-load-config/src/index.js": ((exports, module) => { const { resolve: resolve$2 } = __require("node:path"); const config$1 = require_src$1(); const loadOptions = require_options(); const loadPlugins = require_plugins(); const req = require_req(); const interopRequireDefault = (obj) => obj && obj.__esModule ? obj : { default: obj }; /** * Process the result from cosmiconfig * * @param {Object} ctx Config Context * @param {Object} result Cosmiconfig result * * @return {Promise} PostCSS Config */ async function processResult(ctx, result) { let file = result.filepath || ""; let projectConfig = interopRequireDefault(result.config).default || {}; if (typeof projectConfig === "function") projectConfig = projectConfig(ctx); else projectConfig = Object.assign({}, projectConfig, ctx); if (!projectConfig.plugins) projectConfig.plugins = []; let res = { file, options: await loadOptions(projectConfig, file), plugins: await loadPlugins(projectConfig, file) }; delete projectConfig.plugins; return res; } /** * Builds the Config Context * * @param {Object} ctx Config Context * * @return {Object} Config Context */ function createContext(ctx) { /** * @type {Object} * * @prop {String} cwd=process.cwd() Config search start location * @prop {String} env=process.env.NODE_ENV Config Enviroment, will be set to `development` by `postcss-load-config` if `process.env.NODE_ENV` is `undefined` */ ctx = Object.assign({ cwd: process.cwd(), env: process.env.NODE_ENV }, ctx); if (!ctx.env) process.env.NODE_ENV = "development"; return ctx; } async function loader(filepath) { return req(filepath); } let yaml; async function yamlLoader(_, content) { if (!yaml) try { yaml = await import("yaml"); } catch (e$1) { /* c8 ignore start */ throw new Error(`'yaml' is required for the YAML configuration files. Make sure it is installed\nError: ${e$1.message}`); } return yaml.parse(content); } /** @return {import('lilconfig').Options} */ const withLoaders = (options$1 = {}) => { let moduleName = "postcss"; return { ...options$1, loaders: { ...options$1.loaders, ".cjs": loader, ".cts": loader, ".js": loader, ".mjs": loader, ".mts": loader, ".ts": loader, ".yaml": yamlLoader, ".yml": yamlLoader }, searchPlaces: [ ...options$1.searchPlaces || [], "package.json", `.${moduleName}rc`, `.${moduleName}rc.json`, `.${moduleName}rc.yaml`, `.${moduleName}rc.yml`, `.${moduleName}rc.ts`, `.${moduleName}rc.cts`, `.${moduleName}rc.mts`, `.${moduleName}rc.js`, `.${moduleName}rc.cjs`, `.${moduleName}rc.mjs`, `${moduleName}.config.ts`, `${moduleName}.config.cts`, `${moduleName}.config.mts`, `${moduleName}.config.js`, `${moduleName}.config.cjs`, `${moduleName}.config.mjs` ] }; }; /** * Load Config * * @method rc * * @param {Object} ctx Config Context * @param {String} path Config Path * @param {Object} options Config Options * * @return {Promise} config PostCSS Config */ function rc(ctx, path$13, options$1) { /** * @type {Object} The full Config Context */ ctx = createContext(ctx); /** * @type {String} `process.cwd()` */ path$13 = path$13 ? resolve$2(path$13) : process.cwd(); return config$1.lilconfig("postcss", withLoaders(options$1)).search(path$13).then((result) => { if (!result) throw new Error(`No PostCSS Config found in: ${path$13}`); return processResult(ctx, result); }); } /** * Autoload Config for PostCSS * * @author Michael Ciniawsky @michael-ciniawsky * @license MIT * * @module postcss-load-config * @version 2.1.0 * * @requires comsiconfig * @requires ./options * @requires ./plugins */ module.exports = rc; }) }); //#endregion //#region ../../node_modules/.pnpm/@rollup+plugin-alias@5.1.1_rollup@4.43.0/node_modules/@rollup/plugin-alias/dist/es/index.js function matches$1(pattern, importee) { if (pattern instanceof RegExp) return pattern.test(importee); if (importee.length < pattern.length) return false; if (importee === pattern) return true; return importee.startsWith(pattern + "/"); } function getEntries({ entries, customResolver }) { if (!entries) return []; const resolverFunctionFromOptions = resolveCustomResolver(customResolver); if (Array.isArray(entries)) return entries.map((entry) => { return { find: entry.find, replacement: entry.replacement, resolverFunction: resolveCustomResolver(entry.customResolver) || resolverFunctionFromOptions }; }); return Object.entries(entries).map(([key, value$1]) => { return { find: key, replacement: value$1, resolverFunction: resolverFunctionFromOptions }; }); } function getHookFunction(hook) { if (typeof hook === "function") return hook; if (hook && "handler" in hook && typeof hook.handler === "function") return hook.handler; return null; } function resolveCustomResolver(customResolver) { if (typeof customResolver === "function") return customResolver; if (customResolver) return getHookFunction(customResolver.resolveId); return null; } function alias(options$1 = {}) { const entries = getEntries(options$1); if (entries.length === 0) return { name: "alias", resolveId: () => null }; return { name: "alias", async buildStart(inputOptions) { await Promise.all([...Array.isArray(options$1.entries) ? options$1.entries : [], options$1].map(({ customResolver }) => { var _a; return customResolver && ((_a = getHookFunction(customResolver.buildStart)) === null || _a === void 0 ? void 0 : _a.call(this, inputOptions)); })); }, resolveId(importee, importer, resolveOptions) { const matchedEntry = entries.find((entry) => matches$1(entry.find, importee)); if (!matchedEntry) return null; const updatedId = importee.replace(matchedEntry.find, matchedEntry.replacement); if (matchedEntry.resolverFunction) return matchedEntry.resolverFunction.call(this, updatedId, importer, resolveOptions); return this.resolve(updatedId, importer, Object.assign({ skipSelf: true }, resolveOptions)).then((resolved) => { if (resolved) return resolved; if (!path$1.isAbsolute(updatedId)) this.warn(`rewrote ${importee} to ${updatedId} but was not an abolute path and was not handled by other plugins. This will lead to duplicated modules for the same path. To avoid duplicating modules, you should resolve to an absolute path.`); return { id: updatedId }; }); } }; } //#endregion //#region src/node/plugins/json.ts const jsonExtRE = /\.json(?:$|\?)(?!commonjs-(?:proxy|external))/; const jsonObjRE = /^\s*\{/; const jsonLangRE = new RegExp(`\\.(?:json|json5)(?:$|\\?)`); const isJSONRequest = (request) => jsonLangRE.test(request); function jsonPlugin(options$1, isBuild) { return { name: "vite:json", transform: { filter: { id: { include: jsonExtRE, exclude: SPECIAL_QUERY_RE } }, handler(json, id) { if (inlineRE$3.test(id) || noInlineRE.test(id)) this.warn("\nUsing ?inline or ?no-inline for JSON imports will have no effect.\nPlease use ?url&inline or ?url&no-inline to control JSON file inlining behavior.\n"); json = stripBomTag(json); try { if (options$1.stringify !== false) { if (options$1.namedExports && jsonObjRE.test(json)) { const parsed = JSON.parse(json); const keys = Object.keys(parsed); let code = ""; let defaultObjectCode = "{\n"; for (const key of keys) if (key === makeLegalIdentifier(key)) { code += `export const ${key} = ${serializeValue(parsed[key])};\n`; defaultObjectCode += ` ${key},\n`; } else defaultObjectCode += ` ${JSON.stringify(key)}: ${serializeValue(parsed[key])},\n`; defaultObjectCode += "}"; code += `export default ${defaultObjectCode};\n`; return { code, map: { mappings: "" } }; } if (options$1.stringify === true || json.length > 10 * 1e3) { if (isBuild) json = JSON.stringify(JSON.parse(json)); return { code: `export default /* #__PURE__ */ JSON.parse(${JSON.stringify(json)})`, map: { mappings: "" } }; } } return { code: dataToEsm(JSON.parse(json), { preferConst: true, namedExports: options$1.namedExports }), map: { mappings: "" } }; } catch (e$1) { const position = extractJsonErrorPosition(e$1.message, json.length); const msg = position ? `, invalid JSON syntax found at position ${position}` : `.`; this.error(`Failed to parse JSON file` + msg, position); } } } }; } function serializeValue(value$1) { const valueAsString = JSON.stringify(value$1); if (typeof value$1 === "object" && value$1 != null && valueAsString.length > 10 * 1e3) return `/* #__PURE__ */ JSON.parse(${JSON.stringify(valueAsString)})`; return valueAsString; } function extractJsonErrorPosition(errorMessage, inputLength) { if (errorMessage.startsWith("Unexpected end of JSON input")) return inputLength - 1; const errorMessageList = /at position (\d+)/.exec(errorMessage); return errorMessageList ? Math.max(parseInt(errorMessageList[1], 10) - 1, 0) : void 0; } //#endregion //#region ../../node_modules/.pnpm/resolve.exports@2.0.3/node_modules/resolve.exports/dist/index.mjs function e(e$1, n$2, r$1) { throw new Error(r$1 ? `No known conditions for "${n$2}" specifier in "${e$1}" package` : `Missing "${n$2}" specifier in "${e$1}" package`); } function n(n$2, i$1, o$1, f$1) { let s$2, u, l = r(n$2, o$1), c = function(e$1) { let n$3 = new Set(["default", ...e$1.conditions || []]); return e$1.unsafe || n$3.add(e$1.require ? "require" : "import"), e$1.unsafe || n$3.add(e$1.browser ? "browser" : "node"), n$3; }(f$1 || {}), a = i$1[l]; if (void 0 === a) { let e$1, n$3, r$1, t$1; for (t$1 in i$1) n$3 && t$1.length < n$3.length || ("/" === t$1[t$1.length - 1] && l.startsWith(t$1) ? (u = l.substring(t$1.length), n$3 = t$1) : t$1.length > 1 && (r$1 = t$1.indexOf("*", 1), ~r$1 && (e$1 = RegExp("^" + t$1.substring(0, r$1) + "(.*)" + t$1.substring(1 + r$1) + "$").exec(l), e$1 && e$1[1] && (u = e$1[1], n$3 = t$1)))); a = i$1[n$3]; } return a || e(n$2, l), s$2 = t(a, c), s$2 || e(n$2, l, 1), u && function(e$1, n$3) { let r$1, t$1 = 0, i$2 = e$1.length, o$2 = /[*]/g, f$2 = /[/]$/; for (; t$1 < i$2; t$1++) e$1[t$1] = o$2.test(r$1 = e$1[t$1]) ? r$1.replace(o$2, n$3) : f$2.test(r$1) ? r$1 + n$3 : r$1; }(s$2, u), s$2; } function r(e$1, n$2, r$1) { if (e$1 === n$2 || "." === n$2) return "."; let t$1 = e$1 + "/", i$1 = t$1.length, o$1 = n$2.slice(0, i$1) === t$1, f$1 = o$1 ? n$2.slice(i$1) : n$2; return "#" === f$1[0] ? f$1 : o$1 || !r$1 ? "./" === f$1.slice(0, 2) ? f$1 : "./" + f$1 : f$1; } function t(e$1, n$2, r$1) { if (e$1) { if ("string" == typeof e$1) return r$1 && r$1.add(e$1), [e$1]; let i$1, o$1; if (Array.isArray(e$1)) { for (o$1 = r$1 || /* @__PURE__ */ new Set(), i$1 = 0; i$1 < e$1.length; i$1++) t(e$1[i$1], n$2, o$1); if (!r$1 && o$1.size) return [...o$1]; } else for (i$1 in e$1) if (n$2.has(i$1)) return t(e$1[i$1], n$2, r$1); } } function o(e$1, r$1, t$1) { let i$1, o$1 = e$1.exports; if (o$1) { if ("string" == typeof o$1) o$1 = { ".": o$1 }; else for (i$1 in o$1) { "." !== i$1[0] && (o$1 = { ".": o$1 }); break; } return n(e$1.name, o$1, r$1 || ".", t$1); } } function f(e$1, r$1, t$1) { if (e$1.imports) return n(e$1.name, e$1.imports, r$1, t$1); } //#endregion //#region ../../node_modules/.pnpm/ufo@1.6.1/node_modules/ufo/dist/index.mjs const HASH_RE = /#/g; const AMPERSAND_RE = /&/g; const SLASH_RE = /\//g; const EQUAL_RE = /=/g; const PLUS_RE = /\+/g; const ENC_CARET_RE = /%5e/gi; const ENC_BACKTICK_RE = /%60/gi; const ENC_PIPE_RE = /%7c/gi; const ENC_SPACE_RE = /%20/gi; function encode(text) { return encodeURI("" + text).replace(ENC_PIPE_RE, "|"); } function encodeQueryValue(input) { return encode(typeof input === "string" ? input : JSON.stringify(input)).replace(PLUS_RE, "%2B").replace(ENC_SPACE_RE, "+").replace(HASH_RE, "%23").replace(AMPERSAND_RE, "%26").replace(ENC_BACKTICK_RE, "`").replace(ENC_CARET_RE, "^").replace(SLASH_RE, "%2F"); } function encodeQueryKey(text) { return encodeQueryValue(text).replace(EQUAL_RE, "%3D"); } function encodeQueryItem(key, value$1) { if (typeof value$1 === "number" || typeof value$1 === "boolean") value$1 = String(value$1); if (!value$1) return encodeQueryKey(key); if (Array.isArray(value$1)) return value$1.map((_value) => `${encodeQueryKey(key)}=${encodeQueryValue(_value)}`).join("&"); return `${encodeQueryKey(key)}=${encodeQueryValue(value$1)}`; } function stringifyQuery(query) { return Object.keys(query).filter((k) => query[k] !== void 0).map((k) => encodeQueryItem(k, query[k])).filter(Boolean).join("&"); } const protocolRelative = Symbol.for("ufo:protocolRelative"); //#endregion //#region ../../node_modules/.pnpm/mlly@1.8.0/node_modules/mlly/dist/index.mjs const BUILTIN_MODULES = new Set(builtinModules); function clearImports(imports) { return (imports || "").replace(/\/\/[^\n]*\n|\/\*.*\*\//g, "").replace(/\s+/g, " "); } function getImportNames(cleanedImports) { const topLevelImports = cleanedImports.replace(/{[^}]*}/, ""); return { namespacedImport: topLevelImports.match(/\* as \s*(\S*)/)?.[1], defaultImport: topLevelImports.split(",").find((index) => !/[*{}]/.test(index))?.trim() || void 0 }; } /** * @typedef ErrnoExceptionFields * @property {number | undefined} [errnode] * @property {string | undefined} [code] * @property {string | undefined} [path] * @property {string | undefined} [syscall] * @property {string | undefined} [url] * * @typedef {Error & ErrnoExceptionFields} ErrnoException */ const own$1 = {}.hasOwnProperty; const classRegExp = /^([A-Z][a-z\d]*)+$/; const kTypes = new Set([ "string", "function", "number", "object", "Function", "Object", "boolean", "bigint", "symbol" ]); const codes$1 = {}; /** * Create a list string in the form like 'A and B' or 'A, B, ..., and Z'. * We cannot use Intl.ListFormat because it's not available in * --without-intl builds. * * @param {Array} array * An array of strings. * @param {string} [type] * The list type to be inserted before the last element. * @returns {string} */ function formatList(array, type = "and") { return array.length < 3 ? array.join(` ${type} `) : `${array.slice(0, -1).join(", ")}, ${type} ${array[array.length - 1]}`; } /** @type {Map} */ const messages = /* @__PURE__ */ new Map(); const nodeInternalPrefix = "__node_internal_"; /** @type {number} */ let userStackTraceLimit; codes$1.ERR_INVALID_ARG_TYPE = createError( "ERR_INVALID_ARG_TYPE", /** * @param {string} name * @param {Array | string} expected * @param {unknown} actual */ (name, expected, actual) => { assert(typeof name === "string", "'name' must be a string"); if (!Array.isArray(expected)) expected = [expected]; let message = "The "; if (name.endsWith(" argument")) message += `${name} `; else { const type = name.includes(".") ? "property" : "argument"; message += `"${name}" ${type} `; } message += "must be "; /** @type {Array} */ const types = []; /** @type {Array} */ const instances = []; /** @type {Array} */ const other = []; for (const value$1 of expected) { assert(typeof value$1 === "string", "All expected entries have to be of type string"); if (kTypes.has(value$1)) types.push(value$1.toLowerCase()); else if (classRegExp.exec(value$1) === null) { assert(value$1 !== "object", "The value \"object\" should be written as \"Object\""); other.push(value$1); } else instances.push(value$1); } if (instances.length > 0) { const pos = types.indexOf("object"); if (pos !== -1) { types.slice(pos, 1); instances.push("Object"); } } if (types.length > 0) { message += `${types.length > 1 ? "one of type" : "of type"} ${formatList(types, "or")}`; if (instances.length > 0 || other.length > 0) message += " or "; } if (instances.length > 0) { message += `an instance of ${formatList(instances, "or")}`; if (other.length > 0) message += " or "; } if (other.length > 0) if (other.length > 1) message += `one of ${formatList(other, "or")}`; else { if (other[0].toLowerCase() !== other[0]) message += "an "; message += `${other[0]}`; } message += `. Received ${determineSpecificType(actual)}`; return message; }, TypeError ); codes$1.ERR_INVALID_MODULE_SPECIFIER = createError( "ERR_INVALID_MODULE_SPECIFIER", /** * @param {string} request * @param {string} reason * @param {string} [base] */ (request, reason, base = void 0) => { return `Invalid module "${request}" ${reason}${base ? ` imported from ${base}` : ""}`; }, TypeError ); codes$1.ERR_INVALID_PACKAGE_CONFIG = createError( "ERR_INVALID_PACKAGE_CONFIG", /** * @param {string} path * @param {string} [base] * @param {string} [message] */ (path$13, base, message) => { return `Invalid package config ${path$13}${base ? ` while importing ${base}` : ""}${message ? `. ${message}` : ""}`; }, Error ); codes$1.ERR_INVALID_PACKAGE_TARGET = createError( "ERR_INVALID_PACKAGE_TARGET", /** * @param {string} packagePath * @param {string} key * @param {unknown} target * @param {boolean} [isImport=false] * @param {string} [base] */ (packagePath, key, target, isImport = false, base = void 0) => { const relatedError = typeof target === "string" && !isImport && target.length > 0 && !target.startsWith("./"); if (key === ".") { assert(isImport === false); return `Invalid "exports" main target ${JSON.stringify(target)} defined in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? "; targets must start with \"./\"" : ""}`; } return `Invalid "${isImport ? "imports" : "exports"}" target ${JSON.stringify(target)} defined for '${key}' in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? "; targets must start with \"./\"" : ""}`; }, Error ); codes$1.ERR_MODULE_NOT_FOUND = createError( "ERR_MODULE_NOT_FOUND", /** * @param {string} path * @param {string} base * @param {boolean} [exactUrl] */ (path$13, base, exactUrl = false) => { return `Cannot find ${exactUrl ? "module" : "package"} '${path$13}' imported from ${base}`; }, Error ); codes$1.ERR_NETWORK_IMPORT_DISALLOWED = createError("ERR_NETWORK_IMPORT_DISALLOWED", "import of '%s' by %s is not supported: %s", Error); codes$1.ERR_PACKAGE_IMPORT_NOT_DEFINED = createError( "ERR_PACKAGE_IMPORT_NOT_DEFINED", /** * @param {string} specifier * @param {string} packagePath * @param {string} base */ (specifier, packagePath, base) => { return `Package import specifier "${specifier}" is not defined${packagePath ? ` in package ${packagePath}package.json` : ""} imported from ${base}`; }, TypeError ); codes$1.ERR_PACKAGE_PATH_NOT_EXPORTED = createError( "ERR_PACKAGE_PATH_NOT_EXPORTED", /** * @param {string} packagePath * @param {string} subpath * @param {string} [base] */ (packagePath, subpath, base = void 0) => { if (subpath === ".") return `No "exports" main defined in ${packagePath}package.json${base ? ` imported from ${base}` : ""}`; return `Package subpath '${subpath}' is not defined by "exports" in ${packagePath}package.json${base ? ` imported from ${base}` : ""}`; }, Error ); codes$1.ERR_UNSUPPORTED_DIR_IMPORT = createError("ERR_UNSUPPORTED_DIR_IMPORT", "Directory import '%s' is not supported resolving ES modules imported from %s", Error); codes$1.ERR_UNSUPPORTED_RESOLVE_REQUEST = createError("ERR_UNSUPPORTED_RESOLVE_REQUEST", "Failed to resolve module specifier \"%s\" from \"%s\": Invalid relative URL or base scheme is not hierarchical.", TypeError); codes$1.ERR_UNKNOWN_FILE_EXTENSION = createError( "ERR_UNKNOWN_FILE_EXTENSION", /** * @param {string} extension * @param {string} path */ (extension$1, path$13) => { return `Unknown file extension "${extension$1}" for ${path$13}`; }, TypeError ); codes$1.ERR_INVALID_ARG_VALUE = createError( "ERR_INVALID_ARG_VALUE", /** * @param {string} name * @param {unknown} value * @param {string} [reason='is invalid'] */ (name, value$1, reason = "is invalid") => { let inspected = inspect(value$1); if (inspected.length > 128) inspected = `${inspected.slice(0, 128)}...`; return `The ${name.includes(".") ? "property" : "argument"} '${name}' ${reason}. Received ${inspected}`; }, TypeError ); /** * Utility function for registering the error codes. Only used here. Exported * *only* to allow for testing. * @param {string} sym * @param {MessageFunction | string} value * @param {ErrorConstructor} constructor * @returns {new (...parameters: Array) => Error} */ function createError(sym, value$1, constructor) { messages.set(sym, value$1); return makeNodeErrorWithCode(constructor, sym); } /** * @param {ErrorConstructor} Base * @param {string} key * @returns {ErrorConstructor} */ function makeNodeErrorWithCode(Base, key) { return NodeError; /** * @param {Array} parameters */ function NodeError(...parameters) { const limit = Error.stackTraceLimit; if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0; const error$1 = new Base(); if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = limit; const message = getMessage(key, parameters, error$1); Object.defineProperties(error$1, { message: { value: message, enumerable: false, writable: true, configurable: true }, toString: { value() { return `${this.name} [${key}]: ${this.message}`; }, enumerable: false, writable: true, configurable: true } }); captureLargerStackTrace(error$1); error$1.code = key; return error$1; } } /** * @returns {boolean} */ function isErrorStackTraceLimitWritable() { try { if (v8.startupSnapshot.isBuildingSnapshot()) return false; } catch {} const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); if (desc === void 0) return Object.isExtensible(Error); return own$1.call(desc, "writable") && desc.writable !== void 0 ? desc.writable : desc.set !== void 0; } /** * This function removes unnecessary frames from Node.js core errors. * @template {(...parameters: unknown[]) => unknown} T * @param {T} wrappedFunction * @returns {T} */ function hideStackFrames(wrappedFunction) { const hidden = nodeInternalPrefix + wrappedFunction.name; Object.defineProperty(wrappedFunction, "name", { value: hidden }); return wrappedFunction; } const captureLargerStackTrace = hideStackFrames( /** * @param {Error} error * @returns {Error} */ function(error$1) { const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable(); if (stackTraceLimitIsWritable) { userStackTraceLimit = Error.stackTraceLimit; Error.stackTraceLimit = Number.POSITIVE_INFINITY; } Error.captureStackTrace(error$1); if (stackTraceLimitIsWritable) Error.stackTraceLimit = userStackTraceLimit; return error$1; } ); /** * @param {string} key * @param {Array} parameters * @param {Error} self * @returns {string} */ function getMessage(key, parameters, self$1) { const message = messages.get(key); assert(message !== void 0, "expected `message` to be found"); if (typeof message === "function") { assert(message.length <= parameters.length, `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${message.length}).`); return Reflect.apply(message, self$1, parameters); } const regex = /%[dfijoOs]/g; let expectedLength = 0; while (regex.exec(message) !== null) expectedLength++; assert(expectedLength === parameters.length, `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${expectedLength}).`); if (parameters.length === 0) return message; parameters.unshift(message); return Reflect.apply(format, null, parameters); } /** * Determine the specific type of a value for type-mismatch errors. * @param {unknown} value * @returns {string} */ function determineSpecificType(value$1) { if (value$1 === null || value$1 === void 0) return String(value$1); if (typeof value$1 === "function" && value$1.name) return `function ${value$1.name}`; if (typeof value$1 === "object") { if (value$1.constructor && value$1.constructor.name) return `an instance of ${value$1.constructor.name}`; return `${inspect(value$1, { depth: -1 })}`; } let inspected = inspect(value$1, { colors: false }); if (inspected.length > 28) inspected = `${inspected.slice(0, 25)}...`; return `type ${typeof value$1} (${inspected})`; } const ESM_STATIC_IMPORT_RE = /(?<=\s|^|;|\})import\s*(?:[\s"']*(?[\p{L}\p{M}\w\t\n\r $*,/{}@.]+)from\s*)?["']\s*(?(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][\s;]*/gmu; const TYPE_RE = /^\s*?type\s/; function parseStaticImport(matched) { const cleanedImports = clearImports(matched.imports); const namedImports = {}; const _matches = cleanedImports.match(/{([^}]*)}/)?.[1]?.split(",") || []; for (const namedImport of _matches) { const _match = namedImport.match(/^\s*(\S*) as (\S*)\s*$/); const source = _match?.[1] || namedImport.trim(); const importName = _match?.[2] || source; if (source && !TYPE_RE.test(source)) namedImports[source] = importName; } const { namespacedImport, defaultImport } = getImportNames(cleanedImports); return { ...matched, defaultImport, namespacedImport, namedImports }; } const ESM_RE = /(?:[\s;]|^)(?:import[\s\w*,{}]*from|import\s*["'*{]|export\b\s*(?:[*{]|default|class|type|function|const|var|let|async function)|import\.meta\b)/m; const COMMENT_RE = /\/\*.+?\*\/|\/\/.*(?=[nr])/g; function hasESMSyntax(code, opts = {}) { if (opts.stripComments) code = code.replace(COMMENT_RE, ""); return ESM_RE.test(code); } //#endregion //#region src/node/optimizer/esbuildDepPlugin.ts const externalWithConversionNamespace = "vite:dep-pre-bundle:external-conversion"; const convertedExternalPrefix = "vite-dep-pre-bundle-external:"; const cjsExternalFacadeNamespace = "vite:cjs-external-facade"; const nonFacadePrefix = "vite-cjs-external-facade:"; const externalTypes = [ "css", "less", "sass", "scss", "styl", "stylus", "pcss", "postcss", "wasm", "vue", "svelte", "marko", "astro", "imba", "jsx", "tsx", ...KNOWN_ASSET_TYPES ]; function esbuildDepPlugin(environment, qualified, external) { const { isProduction } = environment.config; const { extensions: extensions$1 } = environment.config.optimizeDeps; const allExternalTypes = extensions$1 ? externalTypes.filter((type) => !extensions$1.includes("." + type)) : externalTypes; const esmPackageCache = /* @__PURE__ */ new Map(); const cjsPackageCache = /* @__PURE__ */ new Map(); const _resolve = createBackCompatIdResolver(environment.getTopLevelConfig(), { asSrc: false, scan: true, packageCache: esmPackageCache }); const _resolveRequire = createBackCompatIdResolver(environment.getTopLevelConfig(), { asSrc: false, isRequire: true, scan: true, packageCache: cjsPackageCache }); const resolve$4 = (id, importer, kind, resolveDir) => { let _importer; if (resolveDir) _importer = normalizePath(path.join(resolveDir, "*")); else _importer = importer in qualified ? qualified[importer] : importer; return (kind.startsWith("require") ? _resolveRequire : _resolve)(environment, id, _importer); }; const resolveResult = (id, resolved) => { if (resolved.startsWith(browserExternalId)) return { path: id, namespace: "browser-external" }; if (resolved.startsWith(optionalPeerDepId)) return { path: resolved, namespace: "optional-peer-dep" }; if (isBuiltin(environment.config.resolve.builtins, resolved)) return; if (isExternalUrl(resolved)) return { path: resolved, external: true }; return { path: path.resolve(resolved) }; }; return { name: "vite:dep-pre-bundle", setup(build$3) { build$3.onEnd(() => { esmPackageCache.clear(); cjsPackageCache.clear(); }); build$3.onResolve({ filter: /* @__PURE__ */ new RegExp(`\\.(` + allExternalTypes.join("|") + `)(\\?.*)?$`) }, async ({ path: id, importer, kind }) => { if (id.startsWith(convertedExternalPrefix)) return { path: id.slice(29), external: true }; const resolved = await resolve$4(id, importer, kind); if (resolved) { if (JS_TYPES_RE.test(resolved)) return { path: resolved, external: false }; if (kind === "require-call") return { path: resolved, namespace: externalWithConversionNamespace }; return { path: resolved, external: true }; } }); build$3.onLoad({ filter: /./, namespace: externalWithConversionNamespace }, (args) => { const modulePath = `"${convertedExternalPrefix}${args.path}"`; return { contents: isCSSRequest(args.path) && !isModuleCSSRequest(args.path) ? `import ${modulePath};` : `export { default } from ${modulePath};export * from ${modulePath};`, loader: "js" }; }); function resolveEntry(id) { const flatId = flattenId(id); if (flatId in qualified) return { path: qualified[flatId] }; } build$3.onResolve({ filter: /^[\w@][^:]/ }, async ({ path: id, importer, kind }) => { if (moduleListContains(external, id)) return { path: id, external: true }; let entry; if (!importer) { if (entry = resolveEntry(id)) return entry; const aliased = await _resolve(environment, id, void 0, true); if (aliased && (entry = resolveEntry(aliased))) return entry; } const resolved = await resolve$4(id, importer, kind); if (resolved) return resolveResult(id, resolved); }); build$3.onLoad({ filter: /.*/, namespace: "browser-external" }, ({ path: path$13 }) => { if (isProduction) return { contents: "module.exports = {}" }; else return { contents: `\ module.exports = Object.create(new Proxy({}, { get(_, key) { if ( key !== '__esModule' && key !== '__proto__' && key !== 'constructor' && key !== 'splice' ) { console.warn(\`Module "${path$13}" has been externalized for browser compatibility. Cannot access "${path$13}.\${key}" in client code. See https://vite.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.\`) } } }))` }; }); build$3.onLoad({ filter: /.*/, namespace: "optional-peer-dep" }, ({ path: path$13 }) => { const [, peerDep, parentDep] = path$13.split(":"); return { contents: `module.exports = {};throw new Error(\`Could not resolve "${peerDep}" imported by "${parentDep}".${isProduction ? "" : " Is it installed?"}\`)` }; }); } }; } const matchesEntireLine = (text) => `^${escapeRegex(text)}$`; function esbuildCjsExternalPlugin(externals, platform$2) { return { name: "cjs-external", setup(build$3) { const filter$1 = new RegExp(externals.map(matchesEntireLine).join("|")); build$3.onResolve({ filter: /* @__PURE__ */ new RegExp(`^${nonFacadePrefix}`) }, (args) => { return { path: args.path.slice(25), external: true }; }); build$3.onResolve({ filter: filter$1 }, (args) => { if (args.kind === "require-call" && platform$2 !== "node") return { path: args.path, namespace: cjsExternalFacadeNamespace }; return { path: args.path, external: true }; }); build$3.onLoad({ filter: /.*/, namespace: cjsExternalFacadeNamespace }, (args) => ({ contents: `\ import * as m from ${JSON.stringify(nonFacadePrefix + args.path)}; module.exports = ${isNodeBuiltin(args.path) ? "m.default" : "{ ...m }"}; ` })); } }; } //#endregion //#region src/node/baseEnvironment.ts var import_picocolors$29 = /* @__PURE__ */ __toESM(require_picocolors(), 1); const environmentColors = [ import_picocolors$29.default.blue, import_picocolors$29.default.magenta, import_picocolors$29.default.green, import_picocolors$29.default.gray ]; var PartialEnvironment = class { name; getTopLevelConfig() { return this._topLevelConfig; } config; logger; /** * @internal */ _options; /** * @internal */ _topLevelConfig; constructor(name, topLevelConfig, options$1 = topLevelConfig.environments[name]) { if (!/^[\w$]+$/.test(name)) throw new Error(`Invalid environment name "${name}". Environment names must only contain alphanumeric characters and "$", "_".`); this.name = name; this._topLevelConfig = topLevelConfig; this._options = options$1; this.config = new Proxy(options$1, { get: (target, prop) => { if (prop === "logger") return this.logger; if (prop in target) return this._options[prop]; return this._topLevelConfig[prop]; } }); const environment = import_picocolors$29.default.dim(`(${this.name})`); const infoColor = environmentColors[[...this.name].reduce((acc, c) => acc + c.charCodeAt(0), 0) % environmentColors.length || 0]; this.logger = { get hasWarned() { return topLevelConfig.logger.hasWarned; }, info(msg, opts) { return topLevelConfig.logger.info(msg, { ...opts, environment: infoColor(environment) }); }, warn(msg, opts) { return topLevelConfig.logger.warn(msg, { ...opts, environment: import_picocolors$29.default.yellow(environment) }); }, warnOnce(msg, opts) { return topLevelConfig.logger.warnOnce(msg, { ...opts, environment: import_picocolors$29.default.yellow(environment) }); }, error(msg, opts) { return topLevelConfig.logger.error(msg, { ...opts, environment: import_picocolors$29.default.red(environment) }); }, clearScreen(type) { return topLevelConfig.logger.clearScreen(type); }, hasErrorLogged(error$1) { return topLevelConfig.logger.hasErrorLogged(error$1); } }; } }; var BaseEnvironment = class extends PartialEnvironment { get plugins() { return this.config.plugins; } /** * @internal */ _initiated = false; constructor(name, config$2, options$1 = config$2.environments[name]) { super(name, config$2, options$1); } }; //#endregion //#region ../../node_modules/.pnpm/js-tokens@9.0.1/node_modules/js-tokens/index.js var require_js_tokens = /* @__PURE__ */ __commonJS({ "../../node_modules/.pnpm/js-tokens@9.0.1/node_modules/js-tokens/index.js": ((exports, module) => { var HashbangComment, Identifier, JSXIdentifier, JSXPunctuator, JSXString, JSXText, KeywordsWithExpressionAfter, KeywordsWithNoLineTerminatorAfter, LineTerminatorSequence, MultiLineComment, Newline, NumericLiteral, Punctuator, RegularExpressionLiteral = /\/(?![*\/])(?:\[(?:[^\]\\\n\r\u2028\u2029]+|\\.)*\]?|[^\/[\\\n\r\u2028\u2029]+|\\.)*(\/[$_\u200C\u200D\p{ID_Continue}]*|\\)?/uy, SingleLineComment, StringLiteral, Template, TokensNotPrecedingObjectLiteral, TokensPrecedingExpression, WhiteSpace; Punctuator = /--|\+\+|=>|\.{3}|\??\.(?!\d)|(?:&&|\|\||\?\?|[+\-%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2}|\/(?![\/*]))=?|[?~,:;[\](){}]/y; Identifier = /(\x23?)(?=[$_\p{ID_Start}\\])(?:[$_\u200C\u200D\p{ID_Continue}]+|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+/uy; StringLiteral = /(['"])(?:[^'"\\\n\r]+|(?!\1)['"]|\\(?:\r\n|[^]))*(\1)?/y; NumericLiteral = /(?:0[xX][\da-fA-F](?:_?[\da-fA-F])*|0[oO][0-7](?:_?[0-7])*|0[bB][01](?:_?[01])*)n?|0n|[1-9](?:_?\d)*n|(?:(?:0(?!\d)|0\d*[89]\d*|[1-9](?:_?\d)*)(?:\.(?:\d(?:_?\d)*)?)?|\.\d(?:_?\d)*)(?:[eE][+-]?\d(?:_?\d)*)?|0[0-7]+/y; Template = /[`}](?:[^`\\$]+|\\[^]|\$(?!\{))*(`|\$\{)?/y; WhiteSpace = /[\t\v\f\ufeff\p{Zs}]+/uy; LineTerminatorSequence = /\r?\n|[\r\u2028\u2029]/y; MultiLineComment = /\/\*(?:[^*]+|\*(?!\/))*(\*\/)?/y; SingleLineComment = /\/\/.*/y; HashbangComment = /^#!.*/; JSXPunctuator = /[<>.:={}]|\/(?![\/*])/y; JSXIdentifier = /[$_\p{ID_Start}][$_\u200C\u200D\p{ID_Continue}-]*/uy; JSXString = /(['"])(?:[^'"]+|(?!\1)['"])*(\1)?/y; JSXText = /[^<>{}]+/y; TokensPrecedingExpression = /^(?:[\/+-]|\.{3}|\?(?:InterpolationIn(?:JSX|Template)|NoLineTerminatorHere|NonExpressionParenEnd|UnaryIncDec))?$|[{}([,;<>=*%&|^!~?:]$/; TokensNotPrecedingObjectLiteral = /^(?:=>|[;\]){}]|else|\?(?:NoLineTerminatorHere|NonExpressionParenEnd))?$/; KeywordsWithExpressionAfter = /^(?:await|case|default|delete|do|else|instanceof|new|return|throw|typeof|void|yield)$/; KeywordsWithNoLineTerminatorAfter = /^(?:return|throw|yield)$/; Newline = RegExp(LineTerminatorSequence.source); module.exports = function* (input, { jsx = false } = {}) { var braces$2, firstCodePoint, isExpression, lastIndex, lastSignificantToken, length, match, mode, nextLastIndex, nextLastSignificantToken, parenNesting, postfixIncDec, punctuator, stack; ({length} = input); lastIndex = 0; lastSignificantToken = ""; stack = [{ tag: "JS" }]; braces$2 = []; parenNesting = 0; postfixIncDec = false; if (match = HashbangComment.exec(input)) { yield { type: "HashbangComment", value: match[0] }; lastIndex = match[0].length; } while (lastIndex < length) { mode = stack[stack.length - 1]; switch (mode.tag) { case "JS": case "JSNonExpressionParen": case "InterpolationInTemplate": case "InterpolationInJSX": if (input[lastIndex] === "/" && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) { RegularExpressionLiteral.lastIndex = lastIndex; if (match = RegularExpressionLiteral.exec(input)) { lastIndex = RegularExpressionLiteral.lastIndex; lastSignificantToken = match[0]; postfixIncDec = true; yield { type: "RegularExpressionLiteral", value: match[0], closed: match[1] !== void 0 && match[1] !== "\\" }; continue; } } Punctuator.lastIndex = lastIndex; if (match = Punctuator.exec(input)) { punctuator = match[0]; nextLastIndex = Punctuator.lastIndex; nextLastSignificantToken = punctuator; switch (punctuator) { case "(": if (lastSignificantToken === "?NonExpressionParenKeyword") stack.push({ tag: "JSNonExpressionParen", nesting: parenNesting }); parenNesting++; postfixIncDec = false; break; case ")": parenNesting--; postfixIncDec = true; if (mode.tag === "JSNonExpressionParen" && parenNesting === mode.nesting) { stack.pop(); nextLastSignificantToken = "?NonExpressionParenEnd"; postfixIncDec = false; } break; case "{": Punctuator.lastIndex = 0; isExpression = !TokensNotPrecedingObjectLiteral.test(lastSignificantToken) && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken)); braces$2.push(isExpression); postfixIncDec = false; break; case "}": switch (mode.tag) { case "InterpolationInTemplate": if (braces$2.length === mode.nesting) { Template.lastIndex = lastIndex; match = Template.exec(input); lastIndex = Template.lastIndex; lastSignificantToken = match[0]; if (match[1] === "${") { lastSignificantToken = "?InterpolationInTemplate"; postfixIncDec = false; yield { type: "TemplateMiddle", value: match[0] }; } else { stack.pop(); postfixIncDec = true; yield { type: "TemplateTail", value: match[0], closed: match[1] === "`" }; } continue; } break; case "InterpolationInJSX": if (braces$2.length === mode.nesting) { stack.pop(); lastIndex += 1; lastSignificantToken = "}"; yield { type: "JSXPunctuator", value: "}" }; continue; } } postfixIncDec = braces$2.pop(); nextLastSignificantToken = postfixIncDec ? "?ExpressionBraceEnd" : "}"; break; case "]": postfixIncDec = true; break; case "++": case "--": nextLastSignificantToken = postfixIncDec ? "?PostfixIncDec" : "?UnaryIncDec"; break; case "<": if (jsx && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) { stack.push({ tag: "JSXTag" }); lastIndex += 1; lastSignificantToken = "<"; yield { type: "JSXPunctuator", value: punctuator }; continue; } postfixIncDec = false; break; default: postfixIncDec = false; } lastIndex = nextLastIndex; lastSignificantToken = nextLastSignificantToken; yield { type: "Punctuator", value: punctuator }; continue; } Identifier.lastIndex = lastIndex; if (match = Identifier.exec(input)) { lastIndex = Identifier.lastIndex; nextLastSignificantToken = match[0]; switch (match[0]) { case "for": case "if": case "while": case "with": if (lastSignificantToken !== "." && lastSignificantToken !== "?.") nextLastSignificantToken = "?NonExpressionParenKeyword"; } lastSignificantToken = nextLastSignificantToken; postfixIncDec = !KeywordsWithExpressionAfter.test(match[0]); yield { type: match[1] === "#" ? "PrivateIdentifier" : "IdentifierName", value: match[0] }; continue; } StringLiteral.lastIndex = lastIndex; if (match = StringLiteral.exec(input)) { lastIndex = StringLiteral.lastIndex; lastSignificantToken = match[0]; postfixIncDec = true; yield { type: "StringLiteral", value: match[0], closed: match[2] !== void 0 }; continue; } NumericLiteral.lastIndex = lastIndex; if (match = NumericLiteral.exec(input)) { lastIndex = NumericLiteral.lastIndex; lastSignificantToken = match[0]; postfixIncDec = true; yield { type: "NumericLiteral", value: match[0] }; continue; } Template.lastIndex = lastIndex; if (match = Template.exec(input)) { lastIndex = Template.lastIndex; lastSignificantToken = match[0]; if (match[1] === "${") { lastSignificantToken = "?InterpolationInTemplate"; stack.push({ tag: "InterpolationInTemplate", nesting: braces$2.length }); postfixIncDec = false; yield { type: "TemplateHead", value: match[0] }; } else { postfixIncDec = true; yield { type: "NoSubstitutionTemplate", value: match[0], closed: match[1] === "`" }; } continue; } break; case "JSXTag": case "JSXTagEnd": JSXPunctuator.lastIndex = lastIndex; if (match = JSXPunctuator.exec(input)) { lastIndex = JSXPunctuator.lastIndex; nextLastSignificantToken = match[0]; switch (match[0]) { case "<": stack.push({ tag: "JSXTag" }); break; case ">": stack.pop(); if (lastSignificantToken === "/" || mode.tag === "JSXTagEnd") { nextLastSignificantToken = "?JSX"; postfixIncDec = true; } else stack.push({ tag: "JSXChildren" }); break; case "{": stack.push({ tag: "InterpolationInJSX", nesting: braces$2.length }); nextLastSignificantToken = "?InterpolationInJSX"; postfixIncDec = false; break; case "/": if (lastSignificantToken === "<") { stack.pop(); if (stack[stack.length - 1].tag === "JSXChildren") stack.pop(); stack.push({ tag: "JSXTagEnd" }); } } lastSignificantToken = nextLastSignificantToken; yield { type: "JSXPunctuator", value: match[0] }; continue; } JSXIdentifier.lastIndex = lastIndex; if (match = JSXIdentifier.exec(input)) { lastIndex = JSXIdentifier.lastIndex; lastSignificantToken = match[0]; yield { type: "JSXIdentifier", value: match[0] }; continue; } JSXString.lastIndex = lastIndex; if (match = JSXString.exec(input)) { lastIndex = JSXString.lastIndex; lastSignificantToken = match[0]; yield { type: "JSXString", value: match[0], closed: match[2] !== void 0 }; continue; } break; case "JSXChildren": JSXText.lastIndex = lastIndex; if (match = JSXText.exec(input)) { lastIndex = JSXText.lastIndex; lastSignificantToken = match[0]; yield { type: "JSXText", value: match[0] }; continue; } switch (input[lastIndex]) { case "<": stack.push({ tag: "JSXTag" }); lastIndex++; lastSignificantToken = "<"; yield { type: "JSXPunctuator", value: "<" }; continue; case "{": stack.push({ tag: "InterpolationInJSX", nesting: braces$2.length }); lastIndex++; lastSignificantToken = "?InterpolationInJSX"; postfixIncDec = false; yield { type: "JSXPunctuator", value: "{" }; continue; } } WhiteSpace.lastIndex = lastIndex; if (match = WhiteSpace.exec(input)) { lastIndex = WhiteSpace.lastIndex; yield { type: "WhiteSpace", value: match[0] }; continue; } LineTerminatorSequence.lastIndex = lastIndex; if (match = LineTerminatorSequence.exec(input)) { lastIndex = LineTerminatorSequence.lastIndex; postfixIncDec = false; if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) lastSignificantToken = "?NoLineTerminatorHere"; yield { type: "LineTerminatorSequence", value: match[0] }; continue; } MultiLineComment.lastIndex = lastIndex; if (match = MultiLineComment.exec(input)) { lastIndex = MultiLineComment.lastIndex; if (Newline.test(match[0])) { postfixIncDec = false; if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) lastSignificantToken = "?NoLineTerminatorHere"; } yield { type: "MultiLineComment", value: match[0], closed: match[1] !== void 0 }; continue; } SingleLineComment.lastIndex = lastIndex; if (match = SingleLineComment.exec(input)) { lastIndex = SingleLineComment.lastIndex; postfixIncDec = false; yield { type: "SingleLineComment", value: match[0] }; continue; } firstCodePoint = String.fromCodePoint(input.codePointAt(lastIndex)); lastIndex += firstCodePoint.length; lastSignificantToken = firstCodePoint; postfixIncDec = false; yield { type: mode.tag.startsWith("JSX") ? "JSXInvalid" : "Invalid", value: firstCodePoint }; } }; }) }); //#endregion //#region ../../node_modules/.pnpm/strip-literal@3.1.0/node_modules/strip-literal/dist/index.mjs var import_js_tokens = /* @__PURE__ */ __toESM(require_js_tokens(), 1); const FILL_COMMENT = " "; function stripLiteralFromToken(token, fillChar, filter$1) { if (token.type === "SingleLineComment") return FILL_COMMENT.repeat(token.value.length); if (token.type === "MultiLineComment") return token.value.replace(/[^\n]/g, FILL_COMMENT); if (token.type === "StringLiteral") { if (!token.closed) return token.value; const body = token.value.slice(1, -1); if (filter$1(body)) return token.value[0] + fillChar.repeat(body.length) + token.value[token.value.length - 1]; } if (token.type === "NoSubstitutionTemplate") { const body = token.value.slice(1, -1); if (filter$1(body)) return `\`${body.replace(/[^\n]/g, fillChar)}\``; } if (token.type === "RegularExpressionLiteral") { const body = token.value; if (filter$1(body)) return body.replace(/\/(.*)\/(\w?)$/g, (_, $1, $2) => `/${fillChar.repeat($1.length)}/${$2}`); } if (token.type === "TemplateHead") { const body = token.value.slice(1, -2); if (filter$1(body)) return `\`${body.replace(/[^\n]/g, fillChar)}\${`; } if (token.type === "TemplateTail") { const body = token.value.slice(0, -2); if (filter$1(body)) return `}${body.replace(/[^\n]/g, fillChar)}\``; } if (token.type === "TemplateMiddle") { const body = token.value.slice(1, -2); if (filter$1(body)) return `}${body.replace(/[^\n]/g, fillChar)}\${`; } return token.value; } function optionsWithDefaults(options$1) { return { fillChar: options$1?.fillChar ?? " ", filter: options$1?.filter ?? (() => true) }; } function stripLiteral(code, options$1) { let result = ""; const _options = optionsWithDefaults(options$1); for (const token of (0, import_js_tokens.default)(code, { jsx: false })) result += stripLiteralFromToken(token, _options.fillChar, _options.filter); return result; } //#endregion //#region src/node/plugins/importMetaGlob.ts var import_picocolors$28 = /* @__PURE__ */ __toESM(require_picocolors(), 1); function importGlobPlugin(config$2) { const importGlobMaps = /* @__PURE__ */ new Map(); return { name: "vite:import-glob", buildStart() { importGlobMaps.clear(); }, transform: { filter: { code: "import.meta.glob" }, async handler(code, id) { const result = await transformGlobImport(code, id, config$2.root, (im, _, options$1) => this.resolve(im, id, options$1).then((i$1) => i$1?.id || im), config$2.experimental.importGlobRestoreExtension, config$2.logger); if (result) { const allGlobs = result.matches.map((i$1) => i$1.globsResolved); if (!importGlobMaps.has(this.environment)) importGlobMaps.set(this.environment, /* @__PURE__ */ new Map()); const globMatchers = allGlobs.map((globs) => { const affirmed = []; const negated = []; for (const glob$1 of globs) if (glob$1[0] === "!") negated.push(glob$1.slice(1)); else affirmed.push(glob$1); const affirmedMatcher = picomatch(affirmed); const negatedMatcher = picomatch(negated); return (file) => { return (affirmed.length === 0 || affirmedMatcher(file)) && !(negated.length > 0 && negatedMatcher(file)); }; }); importGlobMaps.get(this.environment).set(id, globMatchers); return transformStableResult(result.s, id, config$2); } } }, hotUpdate({ type, file, modules: oldModules }) { if (type === "update") return; const importGlobMap = importGlobMaps.get(this.environment); if (!importGlobMap) return; const modules = []; for (const [id, globMatchers] of importGlobMap) if (globMatchers.some((matcher) => matcher(file))) { const mod = this.environment.moduleGraph.getModuleById(id); if (mod) modules.push(mod); } return modules.length > 0 ? [...oldModules, ...modules] : void 0; } }; } const importGlobRE = /\bimport\.meta\.glob(?:<\w+>)?\s*\(/g; const objectKeysRE = /\bObject\.keys\(\s*$/; const objectValuesRE = /\bObject\.values\(\s*$/; const knownOptions = { as: ["string"], eager: ["boolean"], import: ["string"], exhaustive: ["boolean"], query: ["object", "string"], base: ["string"] }; const forceDefaultAs = ["raw", "url"]; function err$1(e$1, pos) { const error$1 = new Error(e$1); error$1.pos = pos; return error$1; } function parseGlobOptions(rawOpts, optsStartIndex, logger) { let opts = {}; try { opts = evalValue(rawOpts); } catch { throw err$1("Vite is unable to parse the glob options as the value is not static", optsStartIndex); } if (opts == null) return {}; for (const key in opts) { if (!(key in knownOptions)) throw err$1(`Unknown glob option "${key}"`, optsStartIndex); const allowedTypes = knownOptions[key]; const valueType = typeof opts[key]; if (!allowedTypes.includes(valueType)) throw err$1(`Expected glob option "${key}" to be of type ${allowedTypes.join(" or ")}, but got ${valueType}`, optsStartIndex); } if (opts.base) { if (opts.base[0] === "!") throw err$1("Option \"base\" cannot start with \"!\"", optsStartIndex); else if (opts.base[0] !== "/" && !opts.base.startsWith("./") && !opts.base.startsWith("../")) throw err$1(`Option "base" must start with '/', './' or '../', but got "${opts.base}"`, optsStartIndex); } if (typeof opts.query === "object") { for (const key in opts.query) { const value$1 = opts.query[key]; if (![ "string", "number", "boolean" ].includes(typeof value$1)) throw err$1(`Expected glob option "query.${key}" to be of type string, number, or boolean, but got ${typeof value$1}`, optsStartIndex); } opts.query = stringifyQuery(opts.query); } if (opts.as && logger) { const importSuggestion = forceDefaultAs.includes(opts.as) ? `, import: 'default'` : ""; logger.warn(import_picocolors$28.default.yellow(`The glob option "as" has been deprecated in favour of "query". Please update \`as: '${opts.as}'\` to \`query: '?${opts.as}'${importSuggestion}\`.`)); } if (opts.as && forceDefaultAs.includes(opts.as)) { if (opts.import && opts.import !== "default" && opts.import !== "*") throw err$1(`Option "import" can only be "default" or "*" when "as" is "${opts.as}", but got "${opts.import}"`, optsStartIndex); opts.import = opts.import || "default"; } if (opts.as && opts.query) throw err$1("Options \"as\" and \"query\" cannot be used together", optsStartIndex); if (opts.as) opts.query = opts.as; if (opts.query && opts.query[0] !== "?") opts.query = `?${opts.query}`; return opts; } async function parseImportGlob(code, importer, root, resolveId, logger) { let cleanCode; try { cleanCode = stripLiteral(code); } catch { return []; } const tasks = Array.from(cleanCode.matchAll(importGlobRE)).map(async (match, index) => { const start = match.index; const err$2 = (msg) => { const e$1 = /* @__PURE__ */ new Error(`Invalid glob import syntax: ${msg}`); e$1.pos = start; return e$1; }; const end = findCorrespondingCloseParenthesisPosition(cleanCode, start + match[0].length) + 1; if (end <= 0) throw err$2("Close parenthesis not found"); const rootAst = (await parseAstAsync(code.slice(start, end))).body[0]; if (rootAst.type !== "ExpressionStatement") throw err$2(`Expect CallExpression, got ${rootAst.type}`); const ast = rootAst.expression; if (ast.type !== "CallExpression") throw err$2(`Expect CallExpression, got ${ast.type}`); if (ast.arguments.length < 1 || ast.arguments.length > 2) throw err$2(`Expected 1-2 arguments, but got ${ast.arguments.length}`); const arg1 = ast.arguments[0]; const arg2 = ast.arguments[1]; const globs = []; const validateLiteral = (element) => { if (!element) return; if (element.type === "Literal") { if (typeof element.value !== "string") throw err$2(`Expected glob to be a string, but got "${typeof element.value}"`); globs.push(element.value); } else if (element.type === "TemplateLiteral") { if (element.expressions.length !== 0) throw err$2(`Expected glob to be a string, but got dynamic template literal`); globs.push(element.quasis[0].value.raw); } else throw err$2("Could only use literals"); }; if (arg1.type === "ArrayExpression") for (const element of arg1.elements) validateLiteral(element); else validateLiteral(arg1); let options$1 = {}; if (arg2) { if (arg2.type !== "ObjectExpression") throw err$2(`Expected the second argument to be an object literal, but got "${arg2.type}"`); options$1 = parseGlobOptions(code.slice(start + arg2.start, start + arg2.end), start + arg2.start, logger); } const globsResolved = await Promise.all(globs.map((glob$1) => toAbsoluteGlob(glob$1, root, importer, resolveId, options$1.base))); const isRelative$1 = globs.every((i$1) => ".!".includes(i$1[0])); const sliceCode = cleanCode.slice(0, start); const onlyKeys = objectKeysRE.test(sliceCode); let onlyValues = false; if (!onlyKeys) onlyValues = objectValuesRE.test(sliceCode); return { index, globs, globsResolved, isRelative: isRelative$1, options: options$1, start, end, onlyKeys, onlyValues }; }); return (await Promise.all(tasks)).filter(Boolean); } function findCorrespondingCloseParenthesisPosition(cleanCode, openPos) { const closePos = cleanCode.indexOf(")", openPos); if (closePos < 0) return -1; if (!cleanCode.slice(openPos, closePos).includes("(")) return closePos; let remainingParenthesisCount = 0; const cleanCodeLen = cleanCode.length; for (let pos = openPos; pos < cleanCodeLen; pos++) switch (cleanCode[pos]) { case "(": remainingParenthesisCount++; break; case ")": remainingParenthesisCount--; if (remainingParenthesisCount <= 0) return pos; } return -1; } const importPrefix = "__vite_glob_"; const { basename: basename$2, dirname: dirname$2, relative: relative$2 } = posix; /** * @param optimizeExport for dynamicImportVar plugin don't need to optimize export. */ async function transformGlobImport(code, id, root, resolveId, restoreQueryExtension = false, logger) { id = slash(id); root = slash(root); const isVirtual = isVirtualModule(id); const dir = isVirtual ? void 0 : dirname$2(id); const matches$2 = await parseImportGlob(code, isVirtual ? void 0 : id, root, resolveId, logger); const matchedFiles = /* @__PURE__ */ new Set(); if (!matches$2.length) return null; const s$2 = new MagicString(code); const staticImports = (await Promise.all(matches$2.map(async ({ globsResolved, isRelative: isRelative$1, options: options$1, index, start, end, onlyKeys, onlyValues }) => { const files = (await glob(globsResolved, { absolute: true, cwd: getCommonBase(globsResolved) ?? root, dot: !!options$1.exhaustive, expandDirectories: false, ignore: options$1.exhaustive ? [] : ["**/node_modules/**"] })).filter((file) => file !== id).sort(); const objectProps = []; const staticImports$1 = []; const resolvePaths = (file) => { if (!dir) { if (!options$1.base && isRelative$1) throw new Error("In virtual modules, all globs must start with '/'"); const importPath$1 = `/${relative$2(root, file)}`; let filePath$1 = options$1.base ? `${relative$2(posix.join(root, options$1.base), file)}` : importPath$1; if (options$1.base && !filePath$1.startsWith("./") && !filePath$1.startsWith("../")) filePath$1 = `./${filePath$1}`; return { filePath: filePath$1, importPath: importPath$1 }; } let importPath = relative$2(dir, file); if (!importPath.startsWith("./") && !importPath.startsWith("../")) importPath = `./${importPath}`; let filePath; if (options$1.base) { filePath = relative$2(posix.join(options$1.base[0] === "/" ? root : dir, options$1.base), file); if (!filePath.startsWith("./") && !filePath.startsWith("../")) filePath = `./${filePath}`; if (options$1.base[0] === "/") importPath = `/${relative$2(root, file)}`; } else if (isRelative$1) filePath = importPath; else { filePath = relative$2(root, file); if (!filePath.startsWith("./") && !filePath.startsWith("../")) filePath = `/${filePath}`; } return { filePath, importPath }; }; files.forEach((file, i$1) => { const paths = resolvePaths(file); const filePath = paths.filePath; let importPath = paths.importPath; let importQuery = options$1.query ?? ""; if (onlyKeys) { objectProps.push(`${JSON.stringify(filePath)}: 0`); return; } if (importQuery && importQuery !== "?raw") { const fileExtension = basename$2(file).split(".").slice(-1)[0]; if (fileExtension && restoreQueryExtension) importQuery = `${importQuery}&lang.${fileExtension}`; } importPath = `${importPath}${importQuery}`; const importKey = options$1.import && options$1.import !== "*" ? options$1.import : void 0; if (options$1.eager) { const variableName = `${importPrefix}${index}_${i$1}`; const expression = importKey ? `{ ${importKey} as ${variableName} }` : `* as ${variableName}`; staticImports$1.push(`import ${expression} from ${JSON.stringify(importPath)}`); objectProps.push(onlyValues ? `${variableName}` : `${JSON.stringify(filePath)}: ${variableName}`); } else { let importStatement = `import(${JSON.stringify(importPath)})`; if (importKey) importStatement += `.then(m => m[${JSON.stringify(importKey)}])`; objectProps.push(onlyValues ? `() => ${importStatement}` : `${JSON.stringify(filePath)}: () => ${importStatement}`); } }); files.forEach((i$1) => matchedFiles.add(i$1)); const originalLineBreakCount = code.slice(start, end).match(/\n/g)?.length ?? 0; const lineBreaks = originalLineBreakCount > 0 ? "\n".repeat(originalLineBreakCount) : ""; let replacement = ""; if (onlyKeys) replacement = `{${objectProps.join(",")}${lineBreaks}}`; else if (onlyValues) replacement = `[${objectProps.join(",")}${lineBreaks}]`; else replacement = `/* #__PURE__ */ Object.assign({${objectProps.join(",")}${lineBreaks}})`; s$2.overwrite(start, end, replacement); return staticImports$1; }))).flat(); if (staticImports.length) s$2.prepend(`${staticImports.join(";")};`); return { s: s$2, matches: matches$2, files: matchedFiles }; } function globSafePath(path$13) { return escapePath(normalizePath(path$13)); } function lastNthChar(str, n$2) { return str.charAt(str.length - 1 - n$2); } function globSafeResolvedPath(resolved, glob$1) { let numEqual = 0; const maxEqual = Math.min(resolved.length, glob$1.length); while (numEqual < maxEqual && lastNthChar(resolved, numEqual) === lastNthChar(glob$1, numEqual)) numEqual += 1; const staticPartEnd = resolved.length - numEqual; const staticPart = resolved.slice(0, staticPartEnd); const dynamicPart = resolved.slice(staticPartEnd); return globSafePath(staticPart) + dynamicPart; } async function toAbsoluteGlob(glob$1, root, importer, resolveId, base) { let pre = ""; if (glob$1[0] === "!") { pre = "!"; glob$1 = glob$1.slice(1); } root = globSafePath(root); let dir; if (base) if (base[0] === "/") dir = posix.join(root, base); else dir = posix.resolve(importer ? globSafePath(dirname$2(importer)) : root, base); else dir = importer ? globSafePath(dirname$2(importer)) : root; if (glob$1[0] === "/") return pre + posix.join(root, glob$1.slice(1)); if (glob$1.startsWith("./")) return pre + posix.join(dir, glob$1.slice(2)); if (glob$1.startsWith("../")) return pre + posix.join(dir, glob$1); if (glob$1.startsWith("**")) return pre + glob$1; const isSubImportsPattern = glob$1[0] === "#" && glob$1.includes("*"); const resolved = normalizePath(await resolveId(glob$1, importer, { custom: { "vite:import-glob": { isSubImportsPattern } } }) || glob$1); if (isAbsolute(resolved)) return pre + globSafeResolvedPath(resolved, glob$1); throw new Error(`Invalid glob: "${glob$1}" (resolved: "${resolved}"). It must start with '/' or './'`); } function getCommonBase(globsResolved) { const bases = globsResolved.filter((g) => g[0] !== "!").map((glob$1) => { let { base } = picomatch.scan(glob$1); if (posix.basename(base).includes(".")) base = posix.dirname(base); return base; }); if (!bases.length) return null; let commonAncestor = ""; const dirS = bases[0].split("/"); for (let i$1 = 0; i$1 < dirS.length; i$1++) { const candidate = dirS.slice(0, i$1 + 1).join("/"); if (bases.every((base) => base.startsWith(candidate))) commonAncestor = candidate; else break; } if (!commonAncestor) commonAncestor = "/"; return commonAncestor; } function isVirtualModule(id) { return id.startsWith("virtual:") || id[0] === "\0" || !id.includes("/"); } //#endregion //#region src/node/optimizer/scan.ts var import_picocolors$27 = /* @__PURE__ */ __toESM(require_picocolors(), 1); var ScanEnvironment = class extends BaseEnvironment { mode = "scan"; get pluginContainer() { if (!this._pluginContainer) throw new Error(`${this.name} environment.pluginContainer called before initialized`); return this._pluginContainer; } /** * @internal */ _pluginContainer; async init() { if (this._initiated) return; this._initiated = true; this._pluginContainer = await createEnvironmentPluginContainer(this, this.plugins, void 0, false); } }; function devToScanEnvironment(environment) { return { mode: "scan", get name() { return environment.name; }, getTopLevelConfig() { return environment.getTopLevelConfig(); }, get config() { return environment.config; }, get logger() { return environment.logger; }, get pluginContainer() { return environment.pluginContainer; }, get plugins() { return environment.plugins; } }; } const debug$15 = createDebugger("vite:deps"); const htmlTypesRE = /\.(html|vue|svelte|astro|imba)$/; const importsRE = /(? context?.cancel()); } async function scan() { const entries = await computeEntries(environment); if (!entries.length) { if (!config$2.optimizeDeps.entries && !config$2.optimizeDeps.include) environment.logger.warn(import_picocolors$27.default.yellow("(!) Could not auto-determine entry point from rollupOptions or html files and there are no explicit optimizeDeps.include patterns. Skipping dependency pre-bundling.")); return; } if (scanContext.cancelled) return; debug$15?.(`Crawling dependencies using entries: ${entries.map((entry) => `\n ${import_picocolors$27.default.dim(entry)}`).join("")}`); const deps = {}; const missing = {}; let context; try { esbuildContext = prepareEsbuildScanner(environment, entries, deps, missing); context = await esbuildContext; if (scanContext.cancelled) return; try { await context.rebuild(); return { deps: orderedDependencies(deps), missing }; } catch (e$1) { if (e$1.errors && e$1.message.includes("The build was canceled")) return; const prependMessage = import_picocolors$27.default.red(`\ Failed to scan for dependencies from entries: ${entries.join("\n")} `); if (e$1.errors) e$1.message = prependMessage + (await formatMessages(e$1.errors, { kind: "error", color: true })).join("\n"); else e$1.message = prependMessage + e$1.message; throw e$1; } finally { if (debug$15) debug$15(`Scan completed in ${(performance$1.now() - start).toFixed(2)}ms: ${Object.keys(orderedDependencies(deps)).sort().map((id) => `\n ${import_picocolors$27.default.cyan(id)} -> ${import_picocolors$27.default.dim(deps[id])}`).join("") || import_picocolors$27.default.dim("no dependencies found")}`); } } finally { context?.dispose().catch((e$1) => { environment.logger.error("Failed to dispose esbuild context", { error: e$1 }); }); } } return { cancel, result: scan().then((res) => res ?? { deps: {}, missing: {} }) }; } async function computeEntries(environment) { let entries = []; const explicitEntryPatterns = environment.config.optimizeDeps.entries; const buildInput = environment.config.build.rollupOptions.input; if (explicitEntryPatterns) entries = await globEntries(explicitEntryPatterns, environment); else if (buildInput) { const resolvePath = async (p) => { const id = (await environment.pluginContainer.resolveId(p, path.join(process.cwd(), "*"), { isEntry: true, scan: true }))?.id; if (id === void 0) throw new Error(`failed to resolve rollupOptions.input value: ${JSON.stringify(p)}.`); return id; }; if (typeof buildInput === "string") entries = [await resolvePath(buildInput)]; else if (Array.isArray(buildInput)) entries = await Promise.all(buildInput.map(resolvePath)); else if (isObject(buildInput)) entries = await Promise.all(Object.values(buildInput).map(resolvePath)); else throw new Error("invalid rollupOptions.input value."); } else entries = await globEntries("**/*.html", environment); entries = entries.filter((entry) => isScannable(entry, environment.config.optimizeDeps.extensions) && fs.existsSync(entry)); return entries; } async function prepareEsbuildScanner(environment, entries, deps, missing) { const plugin = esbuildScanPlugin(environment, deps, missing, entries); const { plugins: plugins$1 = [],...esbuildOptions } = environment.config.optimizeDeps.esbuildOptions ?? {}; let tsconfigRaw = esbuildOptions.tsconfigRaw; if (!tsconfigRaw && !esbuildOptions.tsconfig) { const { tsconfig } = await loadTsconfigJsonForFile(path.join(environment.config.root, "_dummy.js")); if (tsconfig.compilerOptions?.experimentalDecorators || tsconfig.compilerOptions?.jsx || tsconfig.compilerOptions?.jsxFactory || tsconfig.compilerOptions?.jsxFragmentFactory || tsconfig.compilerOptions?.jsxImportSource) tsconfigRaw = { compilerOptions: { experimentalDecorators: tsconfig.compilerOptions?.experimentalDecorators, jsx: esbuildOptions.jsx ? void 0 : tsconfig.compilerOptions?.jsx, jsxFactory: esbuildOptions.jsxFactory ? void 0 : tsconfig.compilerOptions?.jsxFactory, jsxFragmentFactory: esbuildOptions.jsxFragment ? void 0 : tsconfig.compilerOptions?.jsxFragmentFactory, jsxImportSource: esbuildOptions.jsxImportSource ? void 0 : tsconfig.compilerOptions?.jsxImportSource } }; } return await esbuild.context({ absWorkingDir: process.cwd(), write: false, stdin: { contents: entries.map((e$1) => `import ${JSON.stringify(e$1)}`).join("\n"), loader: "js" }, bundle: true, format: "esm", logLevel: "silent", plugins: [...plugins$1, plugin], jsxDev: !environment.config.isProduction, ...esbuildOptions, tsconfigRaw }); } function orderedDependencies(deps) { const depsList = Object.entries(deps); depsList.sort((a, b) => a[0].localeCompare(b[0])); return Object.fromEntries(depsList); } async function globEntries(patterns, environment) { const nodeModulesPatterns = []; const regularPatterns = []; for (const pattern of arraify(patterns)) if (pattern.includes("node_modules")) nodeModulesPatterns.push(pattern); else regularPatterns.push(pattern); const sharedOptions = { absolute: true, cwd: environment.config.root, ignore: [`**/${environment.config.build.outDir}/**`, ...environment.config.optimizeDeps.entries ? [] : [`**/__tests__/**`, `**/coverage/**`]] }; return (await Promise.all([glob(nodeModulesPatterns, sharedOptions), glob(regularPatterns, { ...sharedOptions, ignore: [...sharedOptions.ignore, "**/node_modules/**"] })])).flat(); } const scriptRE = /(=\s]+))?)*\s*>)(.*?)<\/script>/gis; const commentRE$1 = //gs; const srcRE = /\bsrc\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i; const typeRE = /\btype\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i; const langRE = /\blang\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i; const svelteScriptModuleRE = /\bcontext\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i; const svelteModuleRE = /\smodule\b/i; function esbuildScanPlugin(environment, depImports, missing, entries) { const seen$1 = /* @__PURE__ */ new Map(); async function resolveId(id, importer) { return environment.pluginContainer.resolveId(id, importer && normalizePath(importer), { scan: true }); } const resolve$4 = async (id, importer) => { const key = id + (importer && path.dirname(importer)); if (seen$1.has(key)) return seen$1.get(key); const res = (await resolveId(id, importer))?.id; seen$1.set(key, res); return res; }; const optimizeDepsOptions = environment.config.optimizeDeps; const include = optimizeDepsOptions.include; const exclude = [ ...optimizeDepsOptions.exclude ?? [], "@vite/client", "@vite/env" ]; const isUnlessEntry = (path$13) => !entries.includes(path$13); const externalUnlessEntry = ({ path: path$13 }) => ({ path: path$13, external: isUnlessEntry(path$13) }); const doTransformGlobImport = async (contents, id, loader$1) => { let transpiledContents; if (loader$1 !== "js") transpiledContents = (await transform(contents, { loader: loader$1 })).code; else transpiledContents = contents; return (await transformGlobImport(transpiledContents, id, environment.config.root, resolve$4))?.s.toString() || transpiledContents; }; return { name: "vite:dep-scan", setup(build$3) { const scripts = {}; build$3.onResolve({ filter: externalRE }, ({ path: path$13 }) => ({ path: path$13, external: true })); build$3.onResolve({ filter: dataUrlRE }, ({ path: path$13 }) => ({ path: path$13, external: true })); build$3.onResolve({ filter: virtualModuleRE }, ({ path: path$13 }) => { return { path: path$13.replace(virtualModulePrefix, ""), namespace: "script" }; }); build$3.onLoad({ filter: /.*/, namespace: "script" }, ({ path: path$13 }) => { return scripts[path$13]; }); build$3.onResolve({ filter: htmlTypesRE }, async ({ path: path$13, importer }) => { const resolved = await resolve$4(path$13, importer); if (!resolved) return; if (isInNodeModules(resolved) && isOptimizable(resolved, optimizeDepsOptions)) return; return { path: resolved, namespace: "html" }; }); const htmlTypeOnLoadCallback = async ({ path: p }) => { let raw = await fsp.readFile(p, "utf-8"); raw = raw.replace(commentRE$1, ""); const isHtml = p.endsWith(".html"); let js = ""; let scriptId = 0; const matches$2 = raw.matchAll(scriptRE); for (const [, openTag, content] of matches$2) { const typeMatch = typeRE.exec(openTag); const type = typeMatch && (typeMatch[1] || typeMatch[2] || typeMatch[3]); const langMatch = langRE.exec(openTag); const lang = langMatch && (langMatch[1] || langMatch[2] || langMatch[3]); if (isHtml && type !== "module") continue; if (type && !(type.includes("javascript") || type.includes("ecmascript") || type === "module")) continue; let loader$1 = "js"; if (lang === "ts" || lang === "tsx" || lang === "jsx") loader$1 = lang; else if (p.endsWith(".astro")) loader$1 = "ts"; const srcMatch = srcRE.exec(openTag); if (srcMatch) { const src = srcMatch[1] || srcMatch[2] || srcMatch[3]; js += `import ${JSON.stringify(src)}\n`; } else if (content.trim()) { const contents = content + (loader$1.startsWith("ts") ? extractImportPaths(content) : ""); const key = `${p}?id=${scriptId++}`; if (contents.includes("import.meta.glob")) scripts[key] = { loader: "js", contents: await doTransformGlobImport(contents, p, loader$1), resolveDir: normalizePath(path.dirname(p)), pluginData: { htmlType: { loader: loader$1 } } }; else scripts[key] = { loader: loader$1, contents, resolveDir: normalizePath(path.dirname(p)), pluginData: { htmlType: { loader: loader$1 } } }; const virtualModulePath = JSON.stringify(virtualModulePrefix + key); let addedImport = false; if (p.endsWith(".svelte")) { let isModule = svelteModuleRE.test(openTag); if (!isModule) { const contextMatch = svelteScriptModuleRE.exec(openTag); isModule = (contextMatch && (contextMatch[1] || contextMatch[2] || contextMatch[3])) === "module"; } if (!isModule) { addedImport = true; js += `import ${virtualModulePath}\n`; } } if (!addedImport) js += `export * from ${virtualModulePath}\n`; } } if (!p.endsWith(".vue") || !js.includes("export default")) js += "\nexport default {}"; return { loader: "js", contents: js }; }; build$3.onLoad({ filter: htmlTypesRE, namespace: "html" }, htmlTypeOnLoadCallback); build$3.onLoad({ filter: htmlTypesRE, namespace: "file" }, htmlTypeOnLoadCallback); build$3.onResolve({ filter: /^[\w@][^:]/ }, async ({ path: id, importer }) => { if (moduleListContains(exclude, id)) return externalUnlessEntry({ path: id }); if (depImports[id]) return externalUnlessEntry({ path: id }); const resolved = await resolve$4(id, importer); if (resolved) { if (shouldExternalizeDep(resolved, id)) return externalUnlessEntry({ path: id }); if (isInNodeModules(resolved) || include?.includes(id)) { if (isOptimizable(resolved, optimizeDepsOptions)) depImports[id] = resolved; return externalUnlessEntry({ path: id }); } else if (isScannable(resolved, optimizeDepsOptions.extensions)) { const namespace = htmlTypesRE.test(resolved) ? "html" : void 0; return { path: path.resolve(resolved), namespace }; } else return externalUnlessEntry({ path: id }); } else missing[id] = normalizePath(importer); }); const setupExternalize = (filter$1, doExternalize) => { build$3.onResolve({ filter: filter$1 }, ({ path: path$13 }) => { return { path: path$13, external: doExternalize(path$13) }; }); }; setupExternalize(CSS_LANGS_RE, isUnlessEntry); setupExternalize(/\.(json|json5|wasm)$/, isUnlessEntry); setupExternalize(/* @__PURE__ */ new RegExp(`\\.(${KNOWN_ASSET_TYPES.join("|")})$`), isUnlessEntry); setupExternalize(SPECIAL_QUERY_RE, () => true); build$3.onResolve({ filter: /.*/ }, async ({ path: id, importer }) => { const resolved = await resolve$4(id, importer); if (resolved) { if (shouldExternalizeDep(resolved, id) || !isScannable(resolved, optimizeDepsOptions.extensions)) return externalUnlessEntry({ path: id }); const namespace = htmlTypesRE.test(resolved) ? "html" : void 0; return { path: path.resolve(cleanUrl(resolved)), namespace }; } else return externalUnlessEntry({ path: id }); }); build$3.onLoad({ filter: JS_TYPES_RE }, async ({ path: id }) => { let ext = path.extname(id).slice(1); if (ext === "mjs") ext = "js"; const esbuildConfig = environment.config.esbuild; let contents = await fsp.readFile(id, "utf-8"); if (ext.endsWith("x") && esbuildConfig && esbuildConfig.jsxInject) contents = esbuildConfig.jsxInject + `\n` + contents; const loader$1 = optimizeDepsOptions.esbuildOptions?.loader?.[`.${ext}`] ?? ext; if (contents.includes("import.meta.glob")) return { loader: "js", contents: await doTransformGlobImport(contents, id, loader$1) }; return { loader: loader$1, contents }; }); build$3.onLoad({ filter: /.*/, namespace: "file" }, () => { return { loader: "js", contents: "export default {}" }; }); } }; } /** * when using TS + (Vue + `