UNPKG

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