cli.js 28 KB

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