cli.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  1. import { s as __toESM } from "./chunks/chunk.js";
  2. import { N as VERSION, R as require_picocolors, n as createLogger } from "./chunks/logger.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. setDotProp(options, key.split("."), parsed[key]);
  462. setByType(options, transforms);
  463. }
  464. return {
  465. args,
  466. options
  467. };
  468. }
  469. runMatchedCommand() {
  470. const { args, options, matchedCommand: command } = this;
  471. if (!command || !command.commandAction) return;
  472. command.checkUnknownOptions();
  473. command.checkOptionValue();
  474. command.checkRequiredArgs();
  475. const actionArgs = [];
  476. command.args.forEach((arg, index) => {
  477. if (arg.variadic) actionArgs.push(args.slice(index));
  478. else actionArgs.push(args[index]);
  479. });
  480. actionArgs.push(options);
  481. return command.commandAction.apply(this, actionArgs);
  482. }
  483. };
  484. const cac = (name = "") => new CAC(name);
  485. //#endregion
  486. //#region src/node/cli.ts
  487. var import_picocolors = /* @__PURE__ */ __toESM(require_picocolors(), 1);
  488. function checkNodeVersion(nodeVersion) {
  489. const currentVersion = nodeVersion.split(".");
  490. const major = parseInt(currentVersion[0], 10);
  491. const minor = parseInt(currentVersion[1], 10);
  492. return major === 20 && minor >= 19 || major === 22 && minor >= 12 || major > 22;
  493. }
  494. 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.`));
  495. const cli = cac("vite");
  496. let profileSession = global.__vite_profile_session;
  497. let profileCount = 0;
  498. const stopProfiler = (log) => {
  499. if (!profileSession) return;
  500. return new Promise((res, rej) => {
  501. profileSession.post("Profiler.stop", (err, { profile }) => {
  502. if (!err) {
  503. const outPath = path.resolve(`./vite-profile-${profileCount++}.cpuprofile`);
  504. fs.writeFileSync(outPath, JSON.stringify(profile));
  505. log(import_picocolors.default.yellow(`CPU profile written to ${import_picocolors.default.white(import_picocolors.default.dim(outPath))}`));
  506. profileSession = void 0;
  507. res();
  508. } else rej(err);
  509. });
  510. });
  511. };
  512. const filterDuplicateOptions = (options) => {
  513. for (const [key, value] of Object.entries(options)) if (Array.isArray(value)) options[key] = value[value.length - 1];
  514. };
  515. /**
  516. * removing global flags before passing as command specific sub-configs
  517. */
  518. function cleanGlobalCLIOptions(options) {
  519. const ret = { ...options };
  520. delete ret["--"];
  521. delete ret.c;
  522. delete ret.config;
  523. delete ret.base;
  524. delete ret.l;
  525. delete ret.logLevel;
  526. delete ret.clearScreen;
  527. delete ret.configLoader;
  528. delete ret.d;
  529. delete ret.debug;
  530. delete ret.f;
  531. delete ret.filter;
  532. delete ret.m;
  533. delete ret.mode;
  534. delete ret.force;
  535. delete ret.w;
  536. if ("sourcemap" in ret) {
  537. const sourcemap = ret.sourcemap;
  538. ret.sourcemap = sourcemap === "true" ? true : sourcemap === "false" ? false : ret.sourcemap;
  539. }
  540. if ("watch" in ret) ret.watch = ret.watch ? {} : void 0;
  541. return ret;
  542. }
  543. /**
  544. * removing builder flags before passing as command specific sub-configs
  545. */
  546. function cleanBuilderCLIOptions(options) {
  547. const ret = { ...options };
  548. delete ret.app;
  549. return ret;
  550. }
  551. /**
  552. * host may be a number (like 0), should convert to string
  553. */
  554. const convertHost = (v) => {
  555. if (typeof v === "number") return String(v);
  556. return v;
  557. };
  558. /**
  559. * base may be a number (like 0), should convert to empty string
  560. */
  561. const convertBase = (v) => {
  562. if (v === 0) return "";
  563. return v;
  564. };
  565. 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`);
  566. 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) => {
  567. filterDuplicateOptions(options);
  568. const { createServer } = await import("./chunks/server.js");
  569. try {
  570. const server = await createServer({
  571. root,
  572. base: options.base,
  573. mode: options.mode,
  574. configFile: options.config,
  575. configLoader: options.configLoader,
  576. logLevel: options.logLevel,
  577. clearScreen: options.clearScreen,
  578. server: cleanGlobalCLIOptions(options),
  579. forceOptimizeDeps: options.force
  580. });
  581. if (!server.httpServer) throw new Error("HTTP server not available");
  582. await server.listen();
  583. const info = server.config.logger.info;
  584. const modeString = options.mode && options.mode !== "development" ? ` ${import_picocolors.default.bgGreen(` ${import_picocolors.default.bold(options.mode)} `)}` : "";
  585. const viteStartTime = global.__vite_start_time ?? false;
  586. const startupDurationString = viteStartTime ? import_picocolors.default.dim(`ready in ${import_picocolors.default.reset(import_picocolors.default.bold(Math.ceil(performance.now() - viteStartTime)))} ms`) : "";
  587. const hasExistingLogs = process.stdout.bytesWritten > 0 || process.stderr.bytesWritten > 0;
  588. info(`\n ${import_picocolors.default.green(`${import_picocolors.default.bold("VITE")} v${VERSION}`)}${modeString} ${startupDurationString}\n`, { clear: !hasExistingLogs });
  589. server.printUrls();
  590. const customShortcuts = [];
  591. if (profileSession) customShortcuts.push({
  592. key: "p",
  593. description: "start/stop the profiler",
  594. async action(server$1) {
  595. if (profileSession) await stopProfiler(server$1.config.logger.info);
  596. else {
  597. const inspector = await import("node:inspector").then((r) => r.default);
  598. await new Promise((res) => {
  599. profileSession = new inspector.Session();
  600. profileSession.connect();
  601. profileSession.post("Profiler.enable", () => {
  602. profileSession.post("Profiler.start", () => {
  603. server$1.config.logger.info("Profiler started");
  604. res();
  605. });
  606. });
  607. });
  608. }
  609. }
  610. });
  611. server.bindCLIShortcuts({
  612. print: true,
  613. customShortcuts
  614. });
  615. } catch (e) {
  616. const logger = createLogger(options.logLevel);
  617. logger.error(import_picocolors.default.red(`error when starting dev server:\n${e.stack}`), { error: e });
  618. await stopProfiler(logger.info);
  619. process.exit(1);
  620. }
  621. });
  622. 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) => {
  623. filterDuplicateOptions(options);
  624. const { createBuilder } = await import("./chunks/build.js");
  625. const buildOptions = cleanGlobalCLIOptions(cleanBuilderCLIOptions(options));
  626. try {
  627. await (await createBuilder({
  628. root,
  629. base: options.base,
  630. mode: options.mode,
  631. configFile: options.config,
  632. configLoader: options.configLoader,
  633. logLevel: options.logLevel,
  634. clearScreen: options.clearScreen,
  635. build: buildOptions,
  636. ...options.app ? { builder: {} } : {}
  637. }, null)).buildApp();
  638. } catch (e) {
  639. createLogger(options.logLevel).error(import_picocolors.default.red(`error during build:\n${e.stack}`), { error: e });
  640. process.exit(1);
  641. } finally {
  642. await stopProfiler((message) => createLogger(options.logLevel).info(message));
  643. }
  644. });
  645. 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) => {
  646. filterDuplicateOptions(options);
  647. const { resolveConfig } = await import("./chunks/config2.js");
  648. const { optimizeDeps } = await import("./chunks/optimizer.js");
  649. try {
  650. await optimizeDeps(await resolveConfig({
  651. root,
  652. base: options.base,
  653. configFile: options.config,
  654. configLoader: options.configLoader,
  655. logLevel: options.logLevel,
  656. mode: options.mode
  657. }, "serve"), options.force, true);
  658. } catch (e) {
  659. createLogger(options.logLevel).error(import_picocolors.default.red(`error when optimizing deps:\n${e.stack}`), { error: e });
  660. process.exit(1);
  661. }
  662. });
  663. 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) => {
  664. filterDuplicateOptions(options);
  665. const { preview } = await import("./chunks/preview.js");
  666. try {
  667. const server = await preview({
  668. root,
  669. base: options.base,
  670. configFile: options.config,
  671. configLoader: options.configLoader,
  672. logLevel: options.logLevel,
  673. mode: options.mode,
  674. build: { outDir: options.outDir },
  675. preview: {
  676. port: options.port,
  677. strictPort: options.strictPort,
  678. host: options.host,
  679. open: options.open
  680. }
  681. });
  682. server.printUrls();
  683. server.bindCLIShortcuts({ print: true });
  684. } catch (e) {
  685. createLogger(options.logLevel).error(import_picocolors.default.red(`error when starting preview server:\n${e.stack}`), { error: e });
  686. process.exit(1);
  687. } finally {
  688. await stopProfiler((message) => createLogger(options.logLevel).info(message));
  689. }
  690. });
  691. cli.help();
  692. cli.version(VERSION);
  693. cli.parse();
  694. //#endregion
  695. export { stopProfiler };