cli.js 25 KB

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