vite 6.4.1 → 7.1.12

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