logger.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. import { createRequire } from "node:module";
  2. import { readFileSync } from "node:fs";
  3. import path, { resolve } from "node:path";
  4. import { fileURLToPath } from "node:url";
  5. import readline from "node:readline";
  6. //#region \0rolldown/runtime.js
  7. var __create = Object.create;
  8. var __defProp = Object.defineProperty;
  9. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  10. var __getOwnPropNames = Object.getOwnPropertyNames;
  11. var __getProtoOf = Object.getPrototypeOf;
  12. var __hasOwnProp = Object.prototype.hasOwnProperty;
  13. var __esmMin = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
  14. var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
  15. var __exportAll = (all, no_symbols) => {
  16. let target = {};
  17. for (var name in all) __defProp(target, name, {
  18. get: all[name],
  19. enumerable: true
  20. });
  21. if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
  22. return target;
  23. };
  24. var __copyProps = (to, from, except, desc) => {
  25. if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
  26. key = keys[i];
  27. if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
  28. get: ((k) => from[k]).bind(null, key),
  29. enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
  30. });
  31. }
  32. return to;
  33. };
  34. var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
  35. value: mod,
  36. enumerable: true
  37. }) : target, mod));
  38. var __toCommonJS = (mod) => __hasOwnProp.call(mod, "module.exports") ? mod["module.exports"] : __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  39. var __require = /* @__PURE__ */ createRequire(import.meta.url);
  40. //#endregion
  41. //#region ../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js
  42. var require_picocolors = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  43. let p = process || {}, argv = p.argv || [], env = p.env || {};
  44. let isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI);
  45. let formatter = (open, close, replace = open) => (input) => {
  46. let string = "" + input, index = string.indexOf(close, open.length);
  47. return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
  48. };
  49. let replaceClose = (string, close, replace, index) => {
  50. let result = "", cursor = 0;
  51. do {
  52. result += string.substring(cursor, index) + replace;
  53. cursor = index + close.length;
  54. index = string.indexOf(close, cursor);
  55. } while (~index);
  56. return result + string.substring(cursor);
  57. };
  58. let createColors = (enabled = isColorSupported) => {
  59. let f = enabled ? formatter : () => String;
  60. return {
  61. isColorSupported: enabled,
  62. reset: f("\x1B[0m", "\x1B[0m"),
  63. bold: f("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"),
  64. dim: f("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"),
  65. italic: f("\x1B[3m", "\x1B[23m"),
  66. underline: f("\x1B[4m", "\x1B[24m"),
  67. inverse: f("\x1B[7m", "\x1B[27m"),
  68. hidden: f("\x1B[8m", "\x1B[28m"),
  69. strikethrough: f("\x1B[9m", "\x1B[29m"),
  70. black: f("\x1B[30m", "\x1B[39m"),
  71. red: f("\x1B[31m", "\x1B[39m"),
  72. green: f("\x1B[32m", "\x1B[39m"),
  73. yellow: f("\x1B[33m", "\x1B[39m"),
  74. blue: f("\x1B[34m", "\x1B[39m"),
  75. magenta: f("\x1B[35m", "\x1B[39m"),
  76. cyan: f("\x1B[36m", "\x1B[39m"),
  77. white: f("\x1B[37m", "\x1B[39m"),
  78. gray: f("\x1B[90m", "\x1B[39m"),
  79. bgBlack: f("\x1B[40m", "\x1B[49m"),
  80. bgRed: f("\x1B[41m", "\x1B[49m"),
  81. bgGreen: f("\x1B[42m", "\x1B[49m"),
  82. bgYellow: f("\x1B[43m", "\x1B[49m"),
  83. bgBlue: f("\x1B[44m", "\x1B[49m"),
  84. bgMagenta: f("\x1B[45m", "\x1B[49m"),
  85. bgCyan: f("\x1B[46m", "\x1B[49m"),
  86. bgWhite: f("\x1B[47m", "\x1B[49m"),
  87. blackBright: f("\x1B[90m", "\x1B[39m"),
  88. redBright: f("\x1B[91m", "\x1B[39m"),
  89. greenBright: f("\x1B[92m", "\x1B[39m"),
  90. yellowBright: f("\x1B[93m", "\x1B[39m"),
  91. blueBright: f("\x1B[94m", "\x1B[39m"),
  92. magentaBright: f("\x1B[95m", "\x1B[39m"),
  93. cyanBright: f("\x1B[96m", "\x1B[39m"),
  94. whiteBright: f("\x1B[97m", "\x1B[39m"),
  95. bgBlackBright: f("\x1B[100m", "\x1B[49m"),
  96. bgRedBright: f("\x1B[101m", "\x1B[49m"),
  97. bgGreenBright: f("\x1B[102m", "\x1B[49m"),
  98. bgYellowBright: f("\x1B[103m", "\x1B[49m"),
  99. bgBlueBright: f("\x1B[104m", "\x1B[49m"),
  100. bgMagentaBright: f("\x1B[105m", "\x1B[49m"),
  101. bgCyanBright: f("\x1B[106m", "\x1B[49m"),
  102. bgWhiteBright: f("\x1B[107m", "\x1B[49m")
  103. };
  104. };
  105. module.exports = createColors();
  106. module.exports.createColors = createColors;
  107. }));
  108. //#endregion
  109. //#region src/node/constants.ts
  110. const { version } = JSON.parse(readFileSync(new URL("../../package.json", new URL("../../../src/node/constants.ts", import.meta.url))).toString());
  111. const ROLLUP_HOOKS = [
  112. "options",
  113. "buildStart",
  114. "buildEnd",
  115. "renderStart",
  116. "renderError",
  117. "renderChunk",
  118. "writeBundle",
  119. "generateBundle",
  120. "banner",
  121. "footer",
  122. "augmentChunkHash",
  123. "outputOptions",
  124. "intro",
  125. "outro",
  126. "closeBundle",
  127. "closeWatcher",
  128. "load",
  129. "moduleParsed",
  130. "watchChange",
  131. "resolveDynamicImport",
  132. "resolveId",
  133. "transform",
  134. "onLog"
  135. ];
  136. const VERSION = version;
  137. const DEFAULT_MAIN_FIELDS = [
  138. "browser",
  139. "module",
  140. "jsnext:main",
  141. "jsnext"
  142. ];
  143. const DEFAULT_CLIENT_MAIN_FIELDS = Object.freeze(DEFAULT_MAIN_FIELDS);
  144. const DEFAULT_SERVER_MAIN_FIELDS = Object.freeze(DEFAULT_MAIN_FIELDS.filter((f) => f !== "browser"));
  145. /**
  146. * A special condition that would be replaced with production or development
  147. * depending on NODE_ENV env variable
  148. */
  149. const DEV_PROD_CONDITION = `development|production`;
  150. const DEFAULT_CONDITIONS = [
  151. "module",
  152. "browser",
  153. "node",
  154. DEV_PROD_CONDITION
  155. ];
  156. const DEFAULT_CLIENT_CONDITIONS = Object.freeze(DEFAULT_CONDITIONS.filter((c) => c !== "node"));
  157. const DEFAULT_SERVER_CONDITIONS = Object.freeze(DEFAULT_CONDITIONS.filter((c) => c !== "browser"));
  158. const DEFAULT_EXTERNAL_CONDITIONS = Object.freeze(["node", "module-sync"]);
  159. const DEFAULT_EXTENSIONS = [
  160. ".mjs",
  161. ".js",
  162. ".mts",
  163. ".ts",
  164. ".jsx",
  165. ".tsx",
  166. ".json"
  167. ];
  168. /**
  169. * The browser versions that are included in the Baseline Widely Available on 2025-05-01.
  170. *
  171. * This value would be bumped on each major release of Vite.
  172. *
  173. * The value is generated by `pnpm generate-target` script.
  174. */
  175. const ESBUILD_BASELINE_WIDELY_AVAILABLE_TARGET = [
  176. "chrome111",
  177. "edge111",
  178. "firefox114",
  179. "safari16.4",
  180. "ios16.4"
  181. ];
  182. const DEFAULT_CONFIG_FILES = [
  183. "vite.config.js",
  184. "vite.config.mjs",
  185. "vite.config.ts",
  186. "vite.config.cjs",
  187. "vite.config.mts",
  188. "vite.config.cts"
  189. ];
  190. const JS_TYPES_RE = /\.(?:j|t)sx?$|\.mjs$/;
  191. const CSS_LANGS_RE = /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/;
  192. const OPTIMIZABLE_ENTRY_RE = /\.[cm]?[jt]s$/;
  193. const SPECIAL_QUERY_RE = /[?&](?:worker|sharedworker|raw|url)\b/;
  194. /**
  195. * Prefix for resolved fs paths, since windows paths may not be valid as URLs.
  196. */
  197. const FS_PREFIX = `/@fs/`;
  198. const CLIENT_PUBLIC_PATH = `/@vite/client`;
  199. const ENV_PUBLIC_PATH = `/@vite/env`;
  200. const VITE_PACKAGE_DIR = resolve(fileURLToPath(new URL("../../../src/node/constants.ts", import.meta.url)), "../../..");
  201. const CLIENT_ENTRY = resolve(VITE_PACKAGE_DIR, "dist/client/client.mjs");
  202. const ENV_ENTRY = resolve(VITE_PACKAGE_DIR, "dist/client/env.mjs");
  203. const CLIENT_DIR = path.dirname(CLIENT_ENTRY);
  204. const KNOWN_ASSET_TYPES = [
  205. "apng",
  206. "bmp",
  207. "png",
  208. "jpe?g",
  209. "jfif",
  210. "pjpeg",
  211. "pjp",
  212. "gif",
  213. "svg",
  214. "ico",
  215. "webp",
  216. "avif",
  217. "cur",
  218. "jxl",
  219. "mp4",
  220. "webm",
  221. "ogg",
  222. "mp3",
  223. "wav",
  224. "flac",
  225. "aac",
  226. "opus",
  227. "mov",
  228. "m4a",
  229. "vtt",
  230. "woff2?",
  231. "eot",
  232. "ttf",
  233. "otf",
  234. "webmanifest",
  235. "pdf",
  236. "txt"
  237. ];
  238. const DEFAULT_ASSETS_RE = new RegExp(`\\.(` + KNOWN_ASSET_TYPES.join("|") + `)(\\?.*)?$`, "i");
  239. const DEP_VERSION_RE = /[?&](v=[\w.-]+)\b/;
  240. const loopbackHosts = new Set([
  241. "localhost",
  242. "127.0.0.1",
  243. "::1",
  244. "0000:0000:0000:0000:0000:0000:0000:0001"
  245. ]);
  246. const wildcardHosts = new Set([
  247. "0.0.0.0",
  248. "::",
  249. "0000:0000:0000:0000:0000:0000:0000:0000"
  250. ]);
  251. const DEFAULT_DEV_PORT = 5173;
  252. const DEFAULT_PREVIEW_PORT = 4173;
  253. const DEFAULT_ASSETS_INLINE_LIMIT = 4096;
  254. const defaultAllowedOrigins = /^https?:\/\/(?:(?:[^:]+\.)?localhost|127\.0\.0\.1|\[::1\])(?::\d+)?$/;
  255. const METADATA_FILENAME = "_metadata.json";
  256. const ERR_OPTIMIZE_DEPS_PROCESSING_ERROR = "ERR_OPTIMIZE_DEPS_PROCESSING_ERROR";
  257. const ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR = "ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR";
  258. //#endregion
  259. //#region src/node/logger.ts
  260. var import_picocolors = /* @__PURE__ */ __toESM(require_picocolors(), 1);
  261. const LogLevels = {
  262. silent: 0,
  263. error: 1,
  264. warn: 2,
  265. info: 3
  266. };
  267. let lastType;
  268. let lastMsg;
  269. let sameCount = 0;
  270. function clearScreen() {
  271. const repeatCount = process.stdout.rows - 2;
  272. const blank = repeatCount > 0 ? "\n".repeat(repeatCount) : "";
  273. console.log(blank);
  274. readline.cursorTo(process.stdout, 0, 0);
  275. readline.clearScreenDown(process.stdout);
  276. }
  277. let timeFormatter;
  278. function getTimeFormatter() {
  279. timeFormatter ??= new Intl.DateTimeFormat(void 0, {
  280. hour: "numeric",
  281. minute: "numeric",
  282. second: "numeric"
  283. });
  284. return timeFormatter;
  285. }
  286. function createLogger(level = "info", options = {}) {
  287. if (options.customLogger) return options.customLogger;
  288. const loggedErrors = /* @__PURE__ */ new WeakSet();
  289. const { prefix = "[vite]", allowClearScreen = true, console = globalThis.console } = options;
  290. const thresh = LogLevels[level];
  291. const canClearScreen = allowClearScreen && process.stdout.isTTY && !process.env.CI;
  292. const clear = canClearScreen ? clearScreen : () => {};
  293. function format(type, msg, options = {}) {
  294. if (options.timestamp) {
  295. let tag = "";
  296. if (type === "info") tag = import_picocolors.default.cyan(import_picocolors.default.bold(prefix));
  297. else if (type === "warn") tag = import_picocolors.default.yellow(import_picocolors.default.bold(prefix));
  298. else tag = import_picocolors.default.red(import_picocolors.default.bold(prefix));
  299. const environment = options.environment ? options.environment + " " : "";
  300. return `${import_picocolors.default.dim(getTimeFormatter().format(/* @__PURE__ */ new Date()))} ${tag} ${environment}${msg}`;
  301. } else return msg;
  302. }
  303. function output(type, msg, options = {}) {
  304. if (thresh >= LogLevels[type]) {
  305. const method = type === "info" ? "log" : type;
  306. if (options.error) loggedErrors.add(options.error);
  307. if (canClearScreen) if (type === lastType && msg === lastMsg) {
  308. sameCount++;
  309. clear();
  310. console[method](format(type, msg, options), import_picocolors.default.yellow(`(x${sameCount + 1})`));
  311. } else {
  312. sameCount = 0;
  313. lastMsg = msg;
  314. lastType = type;
  315. if (options.clear) clear();
  316. console[method](format(type, msg, options));
  317. }
  318. else console[method](format(type, msg, options));
  319. }
  320. }
  321. const warnedMessages = /* @__PURE__ */ new Set();
  322. const logger = {
  323. hasWarned: false,
  324. info(msg, opts) {
  325. output("info", msg, opts);
  326. },
  327. warn(msg, opts) {
  328. logger.hasWarned = true;
  329. output("warn", msg, opts);
  330. },
  331. warnOnce(msg, opts) {
  332. if (warnedMessages.has(msg)) return;
  333. logger.hasWarned = true;
  334. output("warn", msg, opts);
  335. warnedMessages.add(msg);
  336. },
  337. error(msg, opts) {
  338. logger.hasWarned = true;
  339. output("error", msg, opts);
  340. },
  341. clearScreen(type) {
  342. if (thresh >= LogLevels[type]) clear();
  343. },
  344. hasErrorLogged(error) {
  345. return loggedErrors.has(error);
  346. }
  347. };
  348. return logger;
  349. }
  350. function printServerUrls(urls, optionsHost, info) {
  351. const colorUrl = (url) => import_picocolors.default.cyan(url.replace(/:(\d+)\//, (_, port) => `:${import_picocolors.default.bold(port)}/`));
  352. for (const url of urls.local) info(` ${import_picocolors.default.green("➜")} ${import_picocolors.default.bold("Local")}: ${colorUrl(url)}`);
  353. for (const url of urls.network) info(` ${import_picocolors.default.green("➜")} ${import_picocolors.default.bold("Network")}: ${colorUrl(url)}`);
  354. if (urls.network.length === 0 && optionsHost === void 0) info(import_picocolors.default.dim(` ${import_picocolors.default.green("➜")} ${import_picocolors.default.bold("Network")}: use `) + import_picocolors.default.bold("--host") + import_picocolors.default.dim(" to expose"));
  355. }
  356. //#endregion
  357. export { OPTIMIZABLE_ENTRY_RE as A, __esmMin as B, ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR as C, JS_TYPES_RE as D, FS_PREFIX as E, defaultAllowedOrigins as F, __require as H, loopbackHosts as I, wildcardHosts as L, SPECIAL_QUERY_RE as M, VERSION as N, KNOWN_ASSET_TYPES as O, VITE_PACKAGE_DIR as P, require_picocolors as R, ENV_PUBLIC_PATH as S, ESBUILD_BASELINE_WIDELY_AVAILABLE_TARGET as T, __toCommonJS as U, __exportAll as V, __toESM as W, DEFAULT_SERVER_CONDITIONS as _, CLIENT_ENTRY as a, DEV_PROD_CONDITION as b, DEFAULT_ASSETS_INLINE_LIMIT as c, DEFAULT_CLIENT_MAIN_FIELDS as d, DEFAULT_CONFIG_FILES as f, DEFAULT_PREVIEW_PORT as g, DEFAULT_EXTERNAL_CONDITIONS as h, CLIENT_DIR as i, ROLLUP_HOOKS as j, METADATA_FILENAME as k, DEFAULT_ASSETS_RE as l, DEFAULT_EXTENSIONS as m, createLogger as n, CLIENT_PUBLIC_PATH as o, DEFAULT_DEV_PORT as p, printServerUrls as r, CSS_LANGS_RE as s, LogLevels as t, DEFAULT_CLIENT_CONDITIONS as u, DEFAULT_SERVER_MAIN_FIELDS as v, ERR_OPTIMIZE_DEPS_PROCESSING_ERROR as w, ENV_ENTRY as x, DEP_VERSION_RE as y, __commonJSMin as z };