cli.js 29 KB

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