市场夺宝奇兵
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

700 lines
26 KiB

  1. import { __toESM } from "./chunks/dep-lCKrEJQm.js";
  2. import { VERSION, createLogger, require_picocolors } from "./chunks/dep-SmwnYDP9.js";
  3. import fs from "node:fs";
  4. import path from "node:path";
  5. import { performance } from "node:perf_hooks";
  6. import { EventEmitter } from "events";
  7. //#region ../../node_modules/.pnpm/cac@6.7.14/node_modules/cac/dist/index.mjs
  8. function toArr(any) {
  9. return any == null ? [] : Array.isArray(any) ? any : [any];
  10. }
  11. function toVal(out, key, val, opts) {
  12. var x, old = out[key], nxt = !!~opts.string.indexOf(key) ? val == null || val === true ? "" : String(val) : typeof val === "boolean" ? val : !!~opts.boolean.indexOf(key) ? val === "false" ? false : val === "true" || (out._.push((x = +val, x * 0 === 0) ? x : val), !!val) : (x = +val, x * 0 === 0) ? x : val;
  13. out[key] = old == null ? nxt : Array.isArray(old) ? old.concat(nxt) : [old, nxt];
  14. }
  15. function mri2(args, opts) {
  16. args = args || [];
  17. opts = opts || {};
  18. var k, arr, arg, name, val, out = { _: [] };
  19. var i = 0, j = 0, idx = 0, len = args.length;
  20. const alibi = opts.alias !== void 0;
  21. const strict = opts.unknown !== void 0;
  22. const defaults = opts.default !== void 0;
  23. opts.alias = opts.alias || {};
  24. opts.string = toArr(opts.string);
  25. opts.boolean = toArr(opts.boolean);
  26. if (alibi) for (k in opts.alias) {
  27. arr = opts.alias[k] = toArr(opts.alias[k]);
  28. for (i = 0; i < arr.length; i++) (opts.alias[arr[i]] = arr.concat(k)).splice(i, 1);
  29. }
  30. for (i = opts.boolean.length; i-- > 0;) {
  31. arr = opts.alias[opts.boolean[i]] || [];
  32. for (j = arr.length; j-- > 0;) opts.boolean.push(arr[j]);
  33. }
  34. for (i = opts.string.length; i-- > 0;) {
  35. arr = opts.alias[opts.string[i]] || [];
  36. for (j = arr.length; j-- > 0;) opts.string.push(arr[j]);
  37. }
  38. if (defaults) for (k in opts.default) {
  39. name = typeof opts.default[k];
  40. arr = opts.alias[k] = opts.alias[k] || [];
  41. if (opts[name] !== void 0) {
  42. opts[name].push(k);
  43. for (i = 0; i < arr.length; i++) opts[name].push(arr[i]);
  44. }
  45. }
  46. const keys = strict ? Object.keys(opts.alias) : [];
  47. for (i = 0; i < len; i++) {
  48. arg = args[i];
  49. if (arg === "--") {
  50. out._ = out._.concat(args.slice(++i));
  51. break;
  52. }
  53. for (j = 0; j < arg.length; j++) if (arg.charCodeAt(j) !== 45) break;
  54. if (j === 0) out._.push(arg);
  55. else if (arg.substring(j, j + 3) === "no-") {
  56. name = arg.substring(j + 3);
  57. if (strict && !~keys.indexOf(name)) return opts.unknown(arg);
  58. out[name] = false;
  59. } else {
  60. for (idx = j + 1; idx < arg.length; idx++) if (arg.charCodeAt(idx) === 61) break;
  61. name = arg.substring(j, idx);
  62. val = arg.substring(++idx) || i + 1 === len || ("" + args[i + 1]).charCodeAt(0) === 45 || args[++i];
  63. arr = j === 2 ? [name] : name;
  64. for (idx = 0; idx < arr.length; idx++) {
  65. name = arr[idx];
  66. if (strict && !~keys.indexOf(name)) return opts.unknown("-".repeat(j) + name);
  67. toVal(out, name, idx + 1 < arr.length || val, opts);
  68. }
  69. }
  70. }
  71. if (defaults) {
  72. for (k in opts.default) if (out[k] === void 0) out[k] = opts.default[k];
  73. }
  74. if (alibi) for (k in out) {
  75. arr = opts.alias[k] || [];
  76. while (arr.length > 0) out[arr.shift()] = out[k];
  77. }
  78. return out;
  79. }
  80. const removeBrackets = (v) => v.replace(/[<[].+/, "").trim();
  81. const findAllBrackets = (v) => {
  82. const ANGLED_BRACKET_RE_GLOBAL = /<([^>]+)>/g;
  83. const SQUARE_BRACKET_RE_GLOBAL = /\[([^\]]+)\]/g;
  84. const res = [];
  85. const parse = (match) => {
  86. let variadic = false;
  87. let value = match[1];
  88. if (value.startsWith("...")) {
  89. value = value.slice(3);
  90. variadic = true;
  91. }
  92. return {
  93. required: match[0].startsWith("<"),
  94. value,
  95. variadic
  96. };
  97. };
  98. let angledMatch;
  99. while (angledMatch = ANGLED_BRACKET_RE_GLOBAL.exec(v)) res.push(parse(angledMatch));
  100. let squareMatch;
  101. while (squareMatch = SQUARE_BRACKET_RE_GLOBAL.exec(v)) res.push(parse(squareMatch));
  102. return res;
  103. };
  104. const getMriOptions = (options) => {
  105. const result = {
  106. alias: {},
  107. boolean: []
  108. };
  109. for (const [index, option] of options.entries()) {
  110. if (option.names.length > 1) result.alias[option.names[0]] = option.names.slice(1);
  111. if (option.isBoolean) if (option.negated) {
  112. if (!options.some((o, i) => {
  113. return i !== index && o.names.some((name) => option.names.includes(name)) && typeof o.required === "boolean";
  114. })) result.boolean.push(option.names[0]);
  115. } else result.boolean.push(option.names[0]);
  116. }
  117. return result;
  118. };
  119. const findLongest = (arr) => {
  120. return arr.sort((a, b) => {
  121. return a.length > b.length ? -1 : 1;
  122. })[0];
  123. };
  124. const padRight = (str, length) => {
  125. return str.length >= length ? str : `${str}${" ".repeat(length - str.length)}`;
  126. };
  127. const camelcase = (input) => {
  128. return input.replace(/([a-z])-([a-z])/g, (_, p1, p2) => {
  129. return p1 + p2.toUpperCase();
  130. });
  131. };
  132. const setDotProp = (obj, keys, val) => {
  133. let i = 0;
  134. let length = keys.length;
  135. let t = obj;
  136. let x;
  137. for (; i < length; ++i) {
  138. x = t[keys[i]];
  139. t = t[keys[i]] = i === length - 1 ? val : x != null ? x : !!~keys[i + 1].indexOf(".") || !(+keys[i + 1] > -1) ? {} : [];
  140. }
  141. };
  142. const setByType = (obj, transforms) => {
  143. for (const key of Object.keys(transforms)) {
  144. const transform = transforms[key];
  145. if (transform.shouldTransform) {
  146. obj[key] = Array.prototype.concat.call([], obj[key]);
  147. if (typeof transform.transformFunction === "function") obj[key] = obj[key].map(transform.transformFunction);
  148. }
  149. }
  150. };
  151. const getFileName = (input) => {
  152. const m = /([^\\\/]+)$/.exec(input);
  153. return m ? m[1] : "";
  154. };
  155. const camelcaseOptionName = (name) => {
  156. return name.split(".").map((v, i) => {
  157. return i === 0 ? camelcase(v) : v;
  158. }).join(".");
  159. };
  160. var CACError = class extends Error {
  161. constructor(message) {
  162. super(message);
  163. this.name = this.constructor.name;
  164. if (typeof Error.captureStackTrace === "function") Error.captureStackTrace(this, this.constructor);
  165. else this.stack = new Error(message).stack;
  166. }
  167. };
  168. var Option = class {
  169. constructor(rawName, description, config) {
  170. this.rawName = rawName;
  171. this.description = description;
  172. this.config = Object.assign({}, config);
  173. rawName = rawName.replace(/\.\*/g, "");
  174. this.negated = false;
  175. this.names = removeBrackets(rawName).split(",").map((v) => {
  176. let name = v.trim().replace(/^-{1,2}/, "");
  177. if (name.startsWith("no-")) {
  178. this.negated = true;
  179. name = name.replace(/^no-/, "");
  180. }
  181. return camelcaseOptionName(name);
  182. }).sort((a, b) => a.length > b.length ? 1 : -1);
  183. this.name = this.names[this.names.length - 1];
  184. if (this.negated && this.config.default == null) this.config.default = true;
  185. if (rawName.includes("<")) this.required = true;
  186. else if (rawName.includes("[")) this.required = false;
  187. else this.isBoolean = true;
  188. }
  189. };
  190. const processArgs = process.argv;
  191. const platformInfo = `${process.platform}-${process.arch} node-${process.version}`;
  192. var Command = class {
  193. constructor(rawName, description, config = {}, cli$1) {
  194. this.rawName = rawName;
  195. this.description = description;
  196. this.config = config;
  197. this.cli = cli$1;
  198. this.options = [];
  199. this.aliasNames = [];
  200. this.name = removeBrackets(rawName);
  201. this.args = findAllBrackets(rawName);
  202. this.examples = [];
  203. }
  204. usage(text) {
  205. this.usageText = text;
  206. return this;
  207. }
  208. allowUnknownOptions() {
  209. this.config.allowUnknownOptions = true;
  210. return this;
  211. }
  212. ignoreOptionDefaultValue() {
  213. this.config.ignoreOptionDefaultValue = true;
  214. return this;
  215. }
  216. version(version, customFlags = "-v, --version") {
  217. this.versionNumber = version;
  218. this.option(customFlags, "Display version number");
  219. return this;
  220. }
  221. example(example) {
  222. this.examples.push(example);
  223. return this;
  224. }
  225. option(rawName, description, config) {
  226. const option = new Option(rawName, description, config);
  227. this.options.push(option);
  228. return this;
  229. }
  230. alias(name) {
  231. this.aliasNames.push(name);
  232. return this;
  233. }
  234. action(callback) {
  235. this.commandAction = callback;
  236. return this;
  237. }
  238. isMatched(name) {
  239. return this.name === name || this.aliasNames.includes(name);
  240. }
  241. get isDefaultCommand() {
  242. return this.name === "" || this.aliasNames.includes("!");
  243. }
  244. get isGlobalCommand() {
  245. return this instanceof GlobalCommand;
  246. }
  247. hasOption(name) {
  248. name = name.split(".")[0];
  249. return this.options.find((option) => {
  250. return option.names.includes(name);
  251. });
  252. }
  253. outputHelp() {
  254. const { name, commands } = this.cli;
  255. const { versionNumber, options: globalOptions, helpCallback } = this.cli.globalCommand;
  256. let sections = [{ body: `${name}${versionNumber ? `/${versionNumber}` : ""}` }];
  257. sections.push({
  258. title: "Usage",
  259. body: ` $ ${name} ${this.usageText || this.rawName}`
  260. });
  261. if ((this.isGlobalCommand || this.isDefaultCommand) && commands.length > 0) {
  262. const longestCommandName = findLongest(commands.map((command) => command.rawName));
  263. sections.push({
  264. title: "Commands",
  265. body: commands.map((command) => {
  266. return ` ${padRight(command.rawName, longestCommandName.length)} ${command.description}`;
  267. }).join("\n")
  268. });
  269. sections.push({
  270. title: `For more info, run any command with the \`--help\` flag`,
  271. body: commands.map((command) => ` $ ${name}${command.name === "" ? "" : ` ${command.name}`} --help`).join("\n")
  272. });
  273. }
  274. let options = this.isGlobalCommand ? globalOptions : [...this.options, ...globalOptions || []];
  275. if (!this.isGlobalCommand && !this.isDefaultCommand) options = options.filter((option) => option.name !== "version");
  276. if (options.length > 0) {
  277. const longestOptionName = findLongest(options.map((option) => option.rawName));
  278. sections.push({
  279. title: "Options",
  280. body: options.map((option) => {
  281. return ` ${padRight(option.rawName, longestOptionName.length)} ${option.description} ${option.config.default === void 0 ? "" : `(default: ${option.config.default})`}`;
  282. }).join("\n")
  283. });
  284. }
  285. if (this.examples.length > 0) sections.push({
  286. title: "Examples",
  287. body: this.examples.map((example) => {
  288. if (typeof example === "function") return example(name);
  289. return example;
  290. }).join("\n")
  291. });
  292. if (helpCallback) sections = helpCallback(sections) || sections;
  293. console.log(sections.map((section) => {
  294. return section.title ? `${section.title}:
  295. ${section.body}` : section.body;
  296. }).join("\n\n"));
  297. }
  298. outputVersion() {
  299. const { name } = this.cli;
  300. const { versionNumber } = this.cli.globalCommand;
  301. if (versionNumber) console.log(`${name}/${versionNumber} ${platformInfo}`);
  302. }
  303. checkRequiredArgs() {
  304. const minimalArgsCount = this.args.filter((arg) => arg.required).length;
  305. if (this.cli.args.length < minimalArgsCount) throw new CACError(`missing required args for command \`${this.rawName}\``);
  306. }
  307. checkUnknownOptions() {
  308. const { options, globalCommand } = this.cli;
  309. if (!this.config.allowUnknownOptions) {
  310. for (const name of Object.keys(options)) if (name !== "--" && !this.hasOption(name) && !globalCommand.hasOption(name)) throw new CACError(`Unknown option \`${name.length > 1 ? `--${name}` : `-${name}`}\``);
  311. }
  312. }
  313. checkOptionValue() {
  314. const { options: parsedOptions, globalCommand } = this.cli;
  315. const options = [...globalCommand.options, ...this.options];
  316. for (const option of options) {
  317. const value = parsedOptions[option.name.split(".")[0]];
  318. if (option.required) {
  319. const hasNegated = options.some((o) => o.negated && o.names.includes(option.name));
  320. if (value === true || value === false && !hasNegated) throw new CACError(`option \`${option.rawName}\` value is missing`);
  321. }
  322. }
  323. }
  324. };
  325. var GlobalCommand = class extends Command {
  326. constructor(cli$1) {
  327. super("@@global@@", "", {}, cli$1);
  328. }
  329. };
  330. var __assign = Object.assign;
  331. var CAC = class extends EventEmitter {
  332. constructor(name = "") {
  333. super();
  334. this.name = name;
  335. this.commands = [];
  336. this.rawArgs = [];
  337. this.args = [];
  338. this.options = {};
  339. this.globalCommand = new GlobalCommand(this);
  340. this.globalCommand.usage("<command> [options]");
  341. }
  342. usage(text) {
  343. this.globalCommand.usage(text);
  344. return this;
  345. }
  346. command(rawName, description, config) {
  347. const command = new Command(rawName, description || "", config, this);
  348. command.globalCommand = this.globalCommand;
  349. this.commands.push(command);
  350. return command;
  351. }
  352. option(rawName, description, config) {
  353. this.globalCommand.option(rawName, description, config);
  354. return this;
  355. }
  356. help(callback) {
  357. this.globalCommand.option("-h, --help", "Display this message");
  358. this.globalCommand.helpCallback = callback;
  359. this.showHelpOnExit = true;
  360. return this;
  361. }
  362. version(version, customFlags = "-v, --version") {
  363. this.globalCommand.version(version, customFlags);
  364. this.showVersionOnExit = true;
  365. return this;
  366. }
  367. example(example) {
  368. this.globalCommand.example(example);
  369. return this;
  370. }
  371. outputHelp() {
  372. if (this.matchedCommand) this.matchedCommand.outputHelp();
  373. else this.globalCommand.outputHelp();
  374. }
  375. outputVersion() {
  376. this.globalCommand.outputVersion();
  377. }
  378. setParsedInfo({ args, options }, matchedCommand, matchedCommandName) {
  379. this.args = args;
  380. this.options = options;
  381. if (matchedCommand) this.matchedCommand = matchedCommand;
  382. if (matchedCommandName) this.matchedCommandName = matchedCommandName;
  383. return this;
  384. }
  385. unsetMatchedCommand() {
  386. this.matchedCommand = void 0;
  387. this.matchedCommandName = void 0;
  388. }
  389. parse(argv = processArgs, { run = true } = {}) {
  390. this.rawArgs = argv;
  391. if (!this.name) this.name = argv[1] ? getFileName(argv[1]) : "cli";
  392. let shouldParse = true;
  393. for (const command of this.commands) {
  394. const parsed = this.mri(argv.slice(2), command);
  395. const commandName = parsed.args[0];
  396. if (command.isMatched(commandName)) {
  397. shouldParse = false;
  398. const parsedInfo = __assign(__assign({}, parsed), { args: parsed.args.slice(1) });
  399. this.setParsedInfo(parsedInfo, command, commandName);
  400. this.emit(`command:${commandName}`, command);
  401. }
  402. }
  403. if (shouldParse) {
  404. for (const command of this.commands) if (command.name === "") {
  405. shouldParse = false;
  406. const parsed = this.mri(argv.slice(2), command);
  407. this.setParsedInfo(parsed, command);
  408. this.emit(`command:!`, command);
  409. }
  410. }
  411. if (shouldParse) {
  412. const parsed = this.mri(argv.slice(2));
  413. this.setParsedInfo(parsed);
  414. }
  415. if (this.options.help && this.showHelpOnExit) {
  416. this.outputHelp();
  417. run = false;
  418. this.unsetMatchedCommand();
  419. }
  420. if (this.options.version && this.showVersionOnExit && this.matchedCommandName == null) {
  421. this.outputVersion();
  422. run = false;
  423. this.unsetMatchedCommand();
  424. }
  425. const parsedArgv = {
  426. args: this.args,
  427. options: this.options
  428. };
  429. if (run) this.runMatchedCommand();
  430. if (!this.matchedCommand && this.args[0]) this.emit("command:*");
  431. return parsedArgv;
  432. }
  433. mri(argv, command) {
  434. const cliOptions = [...this.globalCommand.options, ...command ? command.options : []];
  435. const mriOptions = getMriOptions(cliOptions);
  436. let argsAfterDoubleDashes = [];
  437. const doubleDashesIndex = argv.indexOf("--");
  438. if (doubleDashesIndex > -1) {
  439. argsAfterDoubleDashes = argv.slice(doubleDashesIndex + 1);
  440. argv = argv.slice(0, doubleDashesIndex);
  441. }
  442. let parsed = mri2(argv, mriOptions);
  443. parsed = Object.keys(parsed).reduce((res, name) => {
  444. return __assign(__assign({}, res), { [camelcaseOptionName(name)]: parsed[name] });
  445. }, { _: [] });
  446. const args = parsed._;
  447. const options = { "--": argsAfterDoubleDashes };
  448. const ignoreDefault = command && command.config.ignoreOptionDefaultValue ? command.config.ignoreOptionDefaultValue : this.globalCommand.config.ignoreOptionDefaultValue;
  449. let transforms = Object.create(null);
  450. for (const cliOption of cliOptions) {
  451. if (!ignoreDefault && cliOption.config.default !== void 0) for (const name of cliOption.names) options[name] = cliOption.config.default;
  452. if (Array.isArray(cliOption.config.type)) {
  453. if (transforms[cliOption.name] === void 0) {
  454. transforms[cliOption.name] = Object.create(null);
  455. transforms[cliOption.name]["shouldTransform"] = true;
  456. transforms[cliOption.name]["transformFunction"] = cliOption.config.type[0];
  457. }
  458. }
  459. }
  460. for (const key of Object.keys(parsed)) if (key !== "_") {
  461. const keys = key.split(".");
  462. setDotProp(options, keys, parsed[key]);
  463. setByType(options, transforms);
  464. }
  465. return {
  466. args,
  467. options
  468. };
  469. }
  470. runMatchedCommand() {
  471. const { args, options, matchedCommand: command } = this;
  472. if (!command || !command.commandAction) return;
  473. command.checkUnknownOptions();
  474. command.checkOptionValue();
  475. command.checkRequiredArgs();
  476. const actionArgs = [];
  477. command.args.forEach((arg, index) => {
  478. if (arg.variadic) actionArgs.push(args.slice(index));
  479. else actionArgs.push(args[index]);
  480. });
  481. actionArgs.push(options);
  482. return command.commandAction.apply(this, actionArgs);
  483. }
  484. };
  485. const cac = (name = "") => new CAC(name);
  486. //#endregion
  487. //#region src/node/cli.ts
  488. var import_picocolors = /* @__PURE__ */ __toESM(require_picocolors(), 1);
  489. function checkNodeVersion(nodeVersion) {
  490. const currentVersion = nodeVersion.split(".");
  491. const major = parseInt(currentVersion[0], 10);
  492. const minor = parseInt(currentVersion[1], 10);
  493. return major === 20 && minor >= 19 || major === 22 && minor >= 12 || major > 22;
  494. }
  495. if (!checkNodeVersion(process.versions.node)) console.warn(import_picocolors.default.yellow(`You are using Node.js ${process.versions.node}. Vite requires Node.js version 20.19+ or 22.12+. Please upgrade your Node.js version.`));
  496. const cli = cac("vite");
  497. let profileSession = global.__vite_profile_session;
  498. let profileCount = 0;
  499. const stopProfiler = (log) => {
  500. if (!profileSession) return;
  501. return new Promise((res, rej) => {
  502. profileSession.post("Profiler.stop", (err, { profile }) => {
  503. if (!err) {
  504. const outPath = path.resolve(`./vite-profile-${profileCount++}.cpuprofile`);
  505. fs.writeFileSync(outPath, JSON.stringify(profile));
  506. log(import_picocolors.default.yellow(`CPU profile written to ${import_picocolors.default.white(import_picocolors.default.dim(outPath))}`));
  507. profileSession = void 0;
  508. res();
  509. } else rej(err);
  510. });
  511. });
  512. };
  513. const filterDuplicateOptions = (options) => {
  514. for (const [key, value] of Object.entries(options)) if (Array.isArray(value)) options[key] = value[value.length - 1];
  515. };
  516. /**
  517. * removing global flags before passing as command specific sub-configs
  518. */
  519. function cleanGlobalCLIOptions(options) {
  520. const ret = { ...options };
  521. delete ret["--"];
  522. delete ret.c;
  523. delete ret.config;
  524. delete ret.base;
  525. delete ret.l;
  526. delete ret.logLevel;
  527. delete ret.clearScreen;
  528. delete ret.configLoader;
  529. delete ret.d;
  530. delete ret.debug;
  531. delete ret.f;
  532. delete ret.filter;
  533. delete ret.m;
  534. delete ret.mode;
  535. delete ret.force;
  536. delete ret.w;
  537. if ("sourcemap" in ret) {
  538. const sourcemap = ret.sourcemap;
  539. ret.sourcemap = sourcemap === "true" ? true : sourcemap === "false" ? false : ret.sourcemap;
  540. }
  541. if ("watch" in ret) ret.watch = ret.watch ? {} : void 0;
  542. return ret;
  543. }
  544. /**
  545. * removing builder flags before passing as command specific sub-configs
  546. */
  547. function cleanBuilderCLIOptions(options) {
  548. const ret = { ...options };
  549. delete ret.app;
  550. return ret;
  551. }
  552. /**
  553. * host may be a number (like 0), should convert to string
  554. */
  555. const convertHost = (v) => {
  556. if (typeof v === "number") return String(v);
  557. return v;
  558. };
  559. /**
  560. * base may be a number (like 0), should convert to empty string
  561. */
  562. const convertBase = (v) => {
  563. if (v === 0) return "";
  564. return v;
  565. };
  566. cli.option("-c, --config <file>", `[string] use specified config file`).option("--base <path>", `[string] public base path (default: /)`, { type: [convertBase] }).option("-l, --logLevel <level>", `[string] info | warn | error | silent`).option("--clearScreen", `[boolean] allow/disable clear screen when logging`).option("--configLoader <loader>", `[string] use 'bundle' to bundle the config with esbuild, or 'runner' (experimental) to process it on the fly, or 'native' (experimental) to load using the native runtime (default: bundle)`).option("-d, --debug [feat]", `[string | boolean] show debug logs`).option("-f, --filter <filter>", `[string] filter debug logs`).option("-m, --mode <mode>", `[string] set env mode`);
  567. cli.command("[root]", "start dev server").alias("serve").alias("dev").option("--host [host]", `[string] specify hostname`, { type: [convertHost] }).option("--port <port>", `[number] specify port`).option("--open [path]", `[boolean | string] open browser on startup`).option("--cors", `[boolean] enable CORS`).option("--strictPort", `[boolean] exit if specified port is already in use`).option("--force", `[boolean] force the optimizer to ignore the cache and re-bundle`).action(async (root, options) => {
  568. filterDuplicateOptions(options);
  569. const { createServer } = await import("./chunks/dep-BcOQquCi.js");
  570. try {
  571. const server = await createServer({
  572. root,
  573. base: options.base,
  574. mode: options.mode,
  575. configFile: options.config,
  576. configLoader: options.configLoader,
  577. logLevel: options.logLevel,
  578. clearScreen: options.clearScreen,
  579. server: cleanGlobalCLIOptions(options),
  580. forceOptimizeDeps: options.force
  581. });
  582. if (!server.httpServer) throw new Error("HTTP server not available");
  583. await server.listen();
  584. const info = server.config.logger.info;
  585. const modeString = options.mode && options.mode !== "development" ? ` ${import_picocolors.default.bgGreen(` ${import_picocolors.default.bold(options.mode)} `)}` : "";
  586. const viteStartTime = global.__vite_start_time ?? false;
  587. const startupDurationString = viteStartTime ? import_picocolors.default.dim(`ready in ${import_picocolors.default.reset(import_picocolors.default.bold(Math.ceil(performance.now() - viteStartTime)))} ms`) : "";
  588. const hasExistingLogs = process.stdout.bytesWritten > 0 || process.stderr.bytesWritten > 0;
  589. info(`\n ${import_picocolors.default.green(`${import_picocolors.default.bold("VITE")} v${VERSION}`)}${modeString} ${startupDurationString}\n`, { clear: !hasExistingLogs });
  590. server.printUrls();
  591. const customShortcuts = [];
  592. if (profileSession) customShortcuts.push({
  593. key: "p",
  594. description: "start/stop the profiler",
  595. async action(server$1) {
  596. if (profileSession) await stopProfiler(server$1.config.logger.info);
  597. else {
  598. const inspector = await import("node:inspector").then((r) => r.default);
  599. await new Promise((res) => {
  600. profileSession = new inspector.Session();
  601. profileSession.connect();
  602. profileSession.post("Profiler.enable", () => {
  603. profileSession.post("Profiler.start", () => {
  604. server$1.config.logger.info("Profiler started");
  605. res();
  606. });
  607. });
  608. });
  609. }
  610. }
  611. });
  612. server.bindCLIShortcuts({
  613. print: true,
  614. customShortcuts
  615. });
  616. } catch (e) {
  617. const logger = createLogger(options.logLevel);
  618. logger.error(import_picocolors.default.red(`error when starting dev server:\n${e.stack}`), { error: e });
  619. await stopProfiler(logger.info);
  620. process.exit(1);
  621. }
  622. });
  623. cli.command("build [root]", "build for production").option("--target <target>", `[string] transpile target (default: 'baseline-widely-available')`).option("--outDir <dir>", `[string] output directory (default: dist)`).option("--assetsDir <dir>", `[string] directory under outDir to place assets in (default: assets)`).option("--assetsInlineLimit <number>", `[number] static asset base64 inline threshold in bytes (default: 4096)`).option("--ssr [entry]", `[string] build specified entry for server-side rendering`).option("--sourcemap [output]", `[boolean | "inline" | "hidden"] output source maps for build (default: false)`).option("--minify [minifier]", "[boolean | \"terser\" | \"esbuild\"] enable/disable minification, or specify minifier to use (default: esbuild)").option("--manifest [name]", `[boolean | string] emit build manifest json`).option("--ssrManifest [name]", `[boolean | string] emit ssr manifest json`).option("--emptyOutDir", `[boolean] force empty outDir when it's outside of root`).option("-w, --watch", `[boolean] rebuilds when modules have changed on disk`).option("--app", `[boolean] same as \`builder: {}\``).action(async (root, options) => {
  624. filterDuplicateOptions(options);
  625. const { createBuilder } = await import("./chunks/dep-D6Kf1CgD.js");
  626. const buildOptions = cleanGlobalCLIOptions(cleanBuilderCLIOptions(options));
  627. try {
  628. const inlineConfig = {
  629. root,
  630. base: options.base,
  631. mode: options.mode,
  632. configFile: options.config,
  633. configLoader: options.configLoader,
  634. logLevel: options.logLevel,
  635. clearScreen: options.clearScreen,
  636. build: buildOptions,
  637. ...options.app ? { builder: {} } : {}
  638. };
  639. await (await createBuilder(inlineConfig, null)).buildApp();
  640. } catch (e) {
  641. createLogger(options.logLevel).error(import_picocolors.default.red(`error during build:\n${e.stack}`), { error: e });
  642. process.exit(1);
  643. } finally {
  644. await stopProfiler((message) => createLogger(options.logLevel).info(message));
  645. }
  646. });
  647. cli.command("optimize [root]", "pre-bundle dependencies (deprecated, the pre-bundle process runs automatically and does not need to be called)").option("--force", `[boolean] force the optimizer to ignore the cache and re-bundle`).action(async (root, options) => {
  648. filterDuplicateOptions(options);
  649. const { resolveConfig } = await import("./chunks/dep-iA2HHN2w.js");
  650. const { optimizeDeps } = await import("./chunks/dep-ifi-OWiW.js");
  651. try {
  652. const config = await resolveConfig({
  653. root,
  654. base: options.base,
  655. configFile: options.config,
  656. configLoader: options.configLoader,
  657. logLevel: options.logLevel,
  658. mode: options.mode
  659. }, "serve");
  660. await optimizeDeps(config, options.force, true);
  661. } catch (e) {
  662. createLogger(options.logLevel).error(import_picocolors.default.red(`error when optimizing deps:\n${e.stack}`), { error: e });
  663. process.exit(1);
  664. }
  665. });
  666. cli.command("preview [root]", "locally preview production build").option("--host [host]", `[string] specify hostname`, { type: [convertHost] }).option("--port <port>", `[number] specify port`).option("--strictPort", `[boolean] exit if specified port is already in use`).option("--open [path]", `[boolean | string] open browser on startup`).option("--outDir <dir>", `[string] output directory (default: dist)`).action(async (root, options) => {
  667. filterDuplicateOptions(options);
  668. const { preview } = await import("./chunks/dep-DAJvlA4P.js");
  669. try {
  670. const server = await preview({
  671. root,
  672. base: options.base,
  673. configFile: options.config,
  674. configLoader: options.configLoader,
  675. logLevel: options.logLevel,
  676. mode: options.mode,
  677. build: { outDir: options.outDir },
  678. preview: {
  679. port: options.port,
  680. strictPort: options.strictPort,
  681. host: options.host,
  682. open: options.open
  683. }
  684. });
  685. server.printUrls();
  686. server.bindCLIShortcuts({ print: true });
  687. } catch (e) {
  688. createLogger(options.logLevel).error(import_picocolors.default.red(`error when starting preview server:\n${e.stack}`), { error: e });
  689. process.exit(1);
  690. } finally {
  691. await stopProfiler((message) => createLogger(options.logLevel).info(message));
  692. }
  693. });
  694. cli.help();
  695. cli.version(VERSION);
  696. cli.parse();
  697. //#endregion
  698. export { stopProfiler };