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