cli.js 26 KB

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