weapp-vite 6.7.4 → 6.7.6

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.
package/dist/cli.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  createCompilerContext
3
- } from "./chunk-ZVP3HDW7.mjs";
3
+ } from "./chunk-XSPLO6IT.mjs";
4
4
  import {
5
5
  DEFAULT_MP_PLATFORM,
6
6
  SHARED_CHUNK_VIRTUAL_PREFIX,
@@ -12,29 +12,29 @@ import {
12
12
  normalizeMiniPlatform,
13
13
  resolveMiniPlatform,
14
14
  resolveWeappConfigFile
15
- } from "./chunk-MKXI5POD.mjs";
15
+ } from "./chunk-ZHLTHMZA.mjs";
16
16
  import {
17
17
  VERSION
18
- } from "./chunk-3ULSPLMB.mjs";
18
+ } from "./chunk-6AH5XOPG.mjs";
19
+ import "./chunk-BGBLJUWD.mjs";
19
20
  import {
20
21
  resolveWeappMcpConfig,
21
22
  startWeappViteMcpServer
22
- } from "./chunk-ASAY7IOT.mjs";
23
+ } from "./chunk-6YAZCQOZ.mjs";
23
24
  import {
24
25
  colors,
25
26
  default as default2
26
- } from "./chunk-VZEM2LX3.mjs";
27
+ } from "./chunk-XIEFUUA5.mjs";
27
28
  import {
28
29
  init_esm_shims
29
- } from "./chunk-BQM4WPKJ.mjs";
30
+ } from "./chunk-QD76G22N.mjs";
30
31
 
31
32
  // src/cli.ts
32
33
  init_esm_shims();
33
34
  import process10 from "process";
34
35
 
35
- // ../../node_modules/.pnpm/cac@6.7.14/node_modules/cac/dist/index.mjs
36
+ // ../../node_modules/.pnpm/cac@7.0.0/node_modules/cac/dist/index.js
36
37
  init_esm_shims();
37
- import { EventEmitter } from "events";
38
38
  function toArr(any) {
39
39
  return any == null ? [] : Array.isArray(any) ? any : [any];
40
40
  }
@@ -42,7 +42,7 @@ function toVal(out, key, val, opts) {
42
42
  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;
43
43
  out[key] = old == null ? nxt : Array.isArray(old) ? old.concat(nxt) : [old, nxt];
44
44
  }
45
- function mri2(args, opts) {
45
+ function lib_default(args, opts) {
46
46
  args = args || [];
47
47
  opts = opts || {};
48
48
  var k, arr, arg, name, val, out = { _: [] };
@@ -53,13 +53,9 @@ function mri2(args, opts) {
53
53
  opts.alias = opts.alias || {};
54
54
  opts.string = toArr(opts.string);
55
55
  opts.boolean = toArr(opts.boolean);
56
- if (alibi) {
57
- for (k in opts.alias) {
58
- arr = opts.alias[k] = toArr(opts.alias[k]);
59
- for (i = 0; i < arr.length; i++) {
60
- (opts.alias[arr[i]] = arr.concat(k)).splice(i, 1);
61
- }
62
- }
56
+ if (alibi) for (k in opts.alias) {
57
+ arr = opts.alias[k] = toArr(opts.alias[k]);
58
+ for (i = 0; i < arr.length; i++) (opts.alias[arr[i]] = arr.concat(k)).splice(i, 1);
63
59
  }
64
60
  for (i = opts.boolean.length; i-- > 0; ) {
65
61
  arr = opts.alias[opts.boolean[i]] || [];
@@ -69,16 +65,12 @@ function mri2(args, opts) {
69
65
  arr = opts.alias[opts.string[i]] || [];
70
66
  for (j = arr.length; j-- > 0; ) opts.string.push(arr[j]);
71
67
  }
72
- if (defaults) {
73
- for (k in opts.default) {
74
- name = typeof opts.default[k];
75
- arr = opts.alias[k] = opts.alias[k] || [];
76
- if (opts[name] !== void 0) {
77
- opts[name].push(k);
78
- for (i = 0; i < arr.length; i++) {
79
- opts[name].push(arr[i]);
80
- }
81
- }
68
+ if (defaults) for (k in opts.default) {
69
+ name = typeof opts.default[k];
70
+ arr = opts.alias[k] = opts.alias[k] || [];
71
+ if (opts[name] !== void 0) {
72
+ opts[name].push(k);
73
+ for (i = 0; i < arr.length; i++) opts[name].push(arr[i]);
82
74
  }
83
75
  }
84
76
  const keys = strict ? Object.keys(opts.alias) : [];
@@ -88,23 +80,16 @@ function mri2(args, opts) {
88
80
  out._ = out._.concat(args.slice(++i));
89
81
  break;
90
82
  }
91
- for (j = 0; j < arg.length; j++) {
92
- if (arg.charCodeAt(j) !== 45) break;
93
- }
94
- if (j === 0) {
95
- out._.push(arg);
96
- } else if (arg.substring(j, j + 3) === "no-") {
83
+ for (j = 0; j < arg.length; j++) if (arg.charCodeAt(j) !== 45) break;
84
+ if (j === 0) out._.push(arg);
85
+ else if (arg.substring(j, j + 3) === "no-") {
97
86
  name = arg.substring(j + 3);
98
- if (strict && !~keys.indexOf(name)) {
99
- return opts.unknown(arg);
100
- }
87
+ if (strict && !~keys.indexOf(name)) return opts.unknown(arg);
101
88
  out[name] = false;
102
89
  } else {
103
- for (idx = j + 1; idx < arg.length; idx++) {
104
- if (arg.charCodeAt(idx) === 61) break;
105
- }
90
+ for (idx = j + 1; idx < arg.length; idx++) if (arg.charCodeAt(idx) === 61) break;
106
91
  name = arg.substring(j, idx);
107
- val = arg.substring(++idx) || (i + 1 === len || ("" + args[i + 1]).charCodeAt(0) === 45 || args[++i]);
92
+ val = arg.substring(++idx) || i + 1 === len || ("" + args[i + 1]).charCodeAt(0) === 45 || args[++i];
108
93
  arr = j === 2 ? [name] : name;
109
94
  for (idx = 0; idx < arr.length; idx++) {
110
95
  name = arr[idx];
@@ -114,24 +99,18 @@ function mri2(args, opts) {
114
99
  }
115
100
  }
116
101
  if (defaults) {
117
- for (k in opts.default) {
118
- if (out[k] === void 0) {
119
- out[k] = opts.default[k];
120
- }
121
- }
102
+ for (k in opts.default) if (out[k] === void 0) out[k] = opts.default[k];
122
103
  }
123
- if (alibi) {
124
- for (k in out) {
125
- arr = opts.alias[k] || [];
126
- while (arr.length > 0) {
127
- out[arr.shift()] = out[k];
128
- }
129
- }
104
+ if (alibi) for (k in out) {
105
+ arr = opts.alias[k] || [];
106
+ while (arr.length > 0) out[arr.shift()] = out[k];
130
107
  }
131
108
  return out;
132
109
  }
133
- var removeBrackets = (v) => v.replace(/[<[].+/, "").trim();
134
- var findAllBrackets = (v) => {
110
+ function removeBrackets(v) {
111
+ return v.replace(/[<[].+/, "").trim();
112
+ }
113
+ function findAllBrackets(v) {
135
114
  const ANGLED_BRACKET_RE_GLOBAL = /<([^>]+)>/g;
136
115
  const SQUARE_BRACKET_RE_GLOBAL = /\[([^\]]+)\]/g;
137
116
  const res = [];
@@ -149,96 +128,95 @@ var findAllBrackets = (v) => {
149
128
  };
150
129
  };
151
130
  let angledMatch;
152
- while (angledMatch = ANGLED_BRACKET_RE_GLOBAL.exec(v)) {
153
- res.push(parse3(angledMatch));
154
- }
131
+ while (angledMatch = ANGLED_BRACKET_RE_GLOBAL.exec(v)) res.push(parse3(angledMatch));
155
132
  let squareMatch;
156
- while (squareMatch = SQUARE_BRACKET_RE_GLOBAL.exec(v)) {
157
- res.push(parse3(squareMatch));
158
- }
133
+ while (squareMatch = SQUARE_BRACKET_RE_GLOBAL.exec(v)) res.push(parse3(squareMatch));
159
134
  return res;
160
- };
161
- var getMriOptions = (options) => {
162
- const result = { alias: {}, boolean: [] };
135
+ }
136
+ function getMriOptions(options) {
137
+ const result = {
138
+ alias: {},
139
+ boolean: []
140
+ };
163
141
  for (const [index, option] of options.entries()) {
164
- if (option.names.length > 1) {
165
- result.alias[option.names[0]] = option.names.slice(1);
166
- }
167
- if (option.isBoolean) {
168
- if (option.negated) {
169
- const hasStringTypeOption = options.some((o, i) => {
170
- return i !== index && o.names.some((name) => option.names.includes(name)) && typeof o.required === "boolean";
171
- });
172
- if (!hasStringTypeOption) {
173
- result.boolean.push(option.names[0]);
174
- }
175
- } else {
176
- result.boolean.push(option.names[0]);
177
- }
178
- }
142
+ if (option.names.length > 1) result.alias[option.names[0]] = option.names.slice(1);
143
+ if (option.isBoolean) if (option.negated) {
144
+ if (!options.some((o, i) => {
145
+ return i !== index && o.names.some((name) => option.names.includes(name)) && typeof o.required === "boolean";
146
+ })) result.boolean.push(option.names[0]);
147
+ } else result.boolean.push(option.names[0]);
179
148
  }
180
149
  return result;
181
- };
182
- var findLongest = (arr) => {
150
+ }
151
+ function findLongest(arr) {
183
152
  return arr.sort((a, b) => {
184
153
  return a.length > b.length ? -1 : 1;
185
154
  })[0];
186
- };
187
- var padRight = (str, length) => {
155
+ }
156
+ function padRight(str, length) {
188
157
  return str.length >= length ? str : `${str}${" ".repeat(length - str.length)}`;
189
- };
190
- var camelcase = (input) => {
191
- return input.replace(/([a-z])-([a-z])/g, (_, p1, p2) => {
158
+ }
159
+ function camelcase(input) {
160
+ return input.replaceAll(/([a-z])-([a-z])/g, (_, p1, p2) => {
192
161
  return p1 + p2.toUpperCase();
193
162
  });
194
- };
195
- var setDotProp = (obj, keys, val) => {
196
- let i = 0;
197
- let length = keys.length;
198
- let t = obj;
199
- let x;
200
- for (; i < length; ++i) {
201
- x = t[keys[i]];
202
- t = t[keys[i]] = i === length - 1 ? val : x != null ? x : !!~keys[i + 1].indexOf(".") || !(+keys[i + 1] > -1) ? {} : [];
163
+ }
164
+ function setDotProp(obj, keys, val) {
165
+ let current = obj;
166
+ for (let i = 0; i < keys.length; i++) {
167
+ const key = keys[i];
168
+ if (i === keys.length - 1) {
169
+ current[key] = val;
170
+ return;
171
+ }
172
+ if (current[key] == null) {
173
+ const nextKeyIsArrayIndex = +keys[i + 1] > -1;
174
+ current[key] = nextKeyIsArrayIndex ? [] : {};
175
+ }
176
+ current = current[key];
203
177
  }
204
- };
205
- var setByType = (obj, transforms) => {
178
+ }
179
+ function setByType(obj, transforms) {
206
180
  for (const key of Object.keys(transforms)) {
207
181
  const transform = transforms[key];
208
182
  if (transform.shouldTransform) {
209
- obj[key] = Array.prototype.concat.call([], obj[key]);
210
- if (typeof transform.transformFunction === "function") {
211
- obj[key] = obj[key].map(transform.transformFunction);
212
- }
183
+ obj[key] = [obj[key]].flat();
184
+ if (typeof transform.transformFunction === "function") obj[key] = obj[key].map(transform.transformFunction);
213
185
  }
214
186
  }
215
- };
216
- var getFileName = (input) => {
217
- const m = /([^\\\/]+)$/.exec(input);
187
+ }
188
+ function getFileName(input) {
189
+ const m = /([^\\/]+)$/.exec(input);
218
190
  return m ? m[1] : "";
219
- };
220
- var camelcaseOptionName = (name) => {
191
+ }
192
+ function camelcaseOptionName(name) {
221
193
  return name.split(".").map((v, i) => {
222
194
  return i === 0 ? camelcase(v) : v;
223
195
  }).join(".");
224
- };
196
+ }
225
197
  var CACError = class extends Error {
226
198
  constructor(message) {
227
199
  super(message);
228
- this.name = this.constructor.name;
229
- if (typeof Error.captureStackTrace === "function") {
230
- Error.captureStackTrace(this, this.constructor);
231
- } else {
232
- this.stack = new Error(message).stack;
233
- }
200
+ this.name = "CACError";
201
+ if (typeof Error.captureStackTrace !== "function") this.stack = new Error(message).stack;
234
202
  }
235
203
  };
236
204
  var Option = class {
205
+ rawName;
206
+ description;
207
+ /** Option name */
208
+ name;
209
+ /** Option name and aliases */
210
+ names;
211
+ isBoolean;
212
+ required;
213
+ config;
214
+ negated;
237
215
  constructor(rawName, description, config) {
238
216
  this.rawName = rawName;
239
217
  this.description = description;
240
218
  this.config = Object.assign({}, config);
241
- rawName = rawName.replace(/\.\*/g, "");
219
+ rawName = rawName.replaceAll(".*", "");
242
220
  this.negated = false;
243
221
  this.names = removeBrackets(rawName).split(",").map((v) => {
244
222
  let name = v.trim().replace(/^-{1,2}/, "");
@@ -248,22 +226,39 @@ var Option = class {
248
226
  }
249
227
  return camelcaseOptionName(name);
250
228
  }).sort((a, b) => a.length > b.length ? 1 : -1);
251
- this.name = this.names[this.names.length - 1];
252
- if (this.negated && this.config.default == null) {
253
- this.config.default = true;
254
- }
255
- if (rawName.includes("<")) {
256
- this.required = true;
257
- } else if (rawName.includes("[")) {
258
- this.required = false;
259
- } else {
260
- this.isBoolean = true;
261
- }
229
+ this.name = this.names.at(-1);
230
+ if (this.negated && this.config.default == null) this.config.default = true;
231
+ if (rawName.includes("<")) this.required = true;
232
+ else if (rawName.includes("[")) this.required = false;
233
+ else this.isBoolean = true;
262
234
  }
263
235
  };
264
- var processArgs = process.argv;
265
- var platformInfo = `${process.platform}-${process.arch} node-${process.version}`;
236
+ var runtimeProcessArgs;
237
+ var runtimeInfo;
238
+ if (typeof process !== "undefined") {
239
+ let runtimeName;
240
+ if (typeof Deno !== "undefined" && typeof Deno.version?.deno === "string") runtimeName = "deno";
241
+ else if (typeof Bun !== "undefined" && typeof Bun.version === "string") runtimeName = "bun";
242
+ else runtimeName = "node";
243
+ runtimeInfo = `${process.platform}-${process.arch} ${runtimeName}-${process.version}`;
244
+ runtimeProcessArgs = process.argv;
245
+ } else if (typeof navigator === "undefined") runtimeInfo = `unknown`;
246
+ else runtimeInfo = `${navigator.platform} ${navigator.userAgent}`;
266
247
  var Command = class {
248
+ rawName;
249
+ description;
250
+ config;
251
+ cli;
252
+ options;
253
+ aliasNames;
254
+ name;
255
+ args;
256
+ commandAction;
257
+ usageText;
258
+ versionNumber;
259
+ examples;
260
+ helpCallback;
261
+ globalCommand;
267
262
  constructor(rawName, description, config = {}, cli2) {
268
263
  this.rawName = rawName;
269
264
  this.description = description;
@@ -296,6 +291,12 @@ var Command = class {
296
291
  this.examples.push(example);
297
292
  return this;
298
293
  }
294
+ /**
295
+ * Add a option for this command
296
+ * @param rawName Raw option name(s)
297
+ * @param description Option description
298
+ * @param config Option config
299
+ */
299
300
  option(rawName, description, config) {
300
301
  const option = new Option(rawName, description, config);
301
302
  this.options.push(option);
@@ -309,6 +310,10 @@ var Command = class {
309
310
  this.commandAction = callback;
310
311
  return this;
311
312
  }
313
+ /**
314
+ * Check if a command name is matched by this command
315
+ * @param name Command name
316
+ */
312
317
  isMatched(name) {
313
318
  return this.name === name || this.aliasNames.includes(name);
314
319
  }
@@ -318,6 +323,10 @@ var Command = class {
318
323
  get isGlobalCommand() {
319
324
  return this instanceof GlobalCommand;
320
325
  }
326
+ /**
327
+ * Check if an option is registered in this command
328
+ * @param name Option name
329
+ */
321
330
  hasOption(name) {
322
331
  name = name.split(".")[0];
323
332
  return this.options.find((option) => {
@@ -326,38 +335,26 @@ var Command = class {
326
335
  }
327
336
  outputHelp() {
328
337
  const { name, commands } = this.cli;
329
- const {
330
- versionNumber,
331
- options: globalOptions,
332
- helpCallback
333
- } = this.cli.globalCommand;
334
- let sections = [
335
- {
336
- body: `${name}${versionNumber ? `/${versionNumber}` : ""}`
337
- }
338
- ];
338
+ const { versionNumber, options: globalOptions, helpCallback } = this.cli.globalCommand;
339
+ let sections = [{ body: `${name}${versionNumber ? `/${versionNumber}` : ""}` }];
339
340
  sections.push({
340
341
  title: "Usage",
341
342
  body: ` $ ${name} ${this.usageText || this.rawName}`
342
343
  });
343
- const showCommands = (this.isGlobalCommand || this.isDefaultCommand) && commands.length > 0;
344
- if (showCommands) {
344
+ if ((this.isGlobalCommand || this.isDefaultCommand) && commands.length > 0) {
345
345
  const longestCommandName = findLongest(commands.map((command) => command.rawName));
346
346
  sections.push({
347
347
  title: "Commands",
348
348
  body: commands.map((command) => {
349
349
  return ` ${padRight(command.rawName, longestCommandName.length)} ${command.description}`;
350
350
  }).join("\n")
351
- });
352
- sections.push({
351
+ }, {
353
352
  title: `For more info, run any command with the \`--help\` flag`,
354
353
  body: commands.map((command) => ` $ ${name}${command.name === "" ? "" : ` ${command.name}`} --help`).join("\n")
355
354
  });
356
355
  }
357
356
  let options = this.isGlobalCommand ? globalOptions : [...this.options, ...globalOptions || []];
358
- if (!this.isGlobalCommand && !this.isDefaultCommand) {
359
- options = options.filter((option) => option.name !== "version");
360
- }
357
+ if (!this.isGlobalCommand && !this.isDefaultCommand) options = options.filter((option) => option.name !== "version");
361
358
  if (options.length > 0) {
362
359
  const longestOptionName = findLongest(options.map((option) => option.rawName));
363
360
  sections.push({
@@ -367,21 +364,15 @@ var Command = class {
367
364
  }).join("\n")
368
365
  });
369
366
  }
370
- if (this.examples.length > 0) {
371
- sections.push({
372
- title: "Examples",
373
- body: this.examples.map((example) => {
374
- if (typeof example === "function") {
375
- return example(name);
376
- }
377
- return example;
378
- }).join("\n")
379
- });
380
- }
381
- if (helpCallback) {
382
- sections = helpCallback(sections) || sections;
383
- }
384
- console.log(sections.map((section) => {
367
+ if (this.examples.length > 0) sections.push({
368
+ title: "Examples",
369
+ body: this.examples.map((example) => {
370
+ if (typeof example === "function") return example(name);
371
+ return example;
372
+ }).join("\n")
373
+ });
374
+ if (helpCallback) sections = helpCallback(sections) || sections;
375
+ console.info(sections.map((section) => {
385
376
  return section.title ? `${section.title}:
386
377
  ${section.body}` : section.body;
387
378
  }).join("\n\n"));
@@ -389,26 +380,26 @@ ${section.body}` : section.body;
389
380
  outputVersion() {
390
381
  const { name } = this.cli;
391
382
  const { versionNumber } = this.cli.globalCommand;
392
- if (versionNumber) {
393
- console.log(`${name}/${versionNumber} ${platformInfo}`);
394
- }
383
+ if (versionNumber) console.info(`${name}/${versionNumber} ${runtimeInfo}`);
395
384
  }
396
385
  checkRequiredArgs() {
397
386
  const minimalArgsCount = this.args.filter((arg) => arg.required).length;
398
- if (this.cli.args.length < minimalArgsCount) {
399
- throw new CACError(`missing required args for command \`${this.rawName}\``);
400
- }
387
+ if (this.cli.args.length < minimalArgsCount) throw new CACError(`missing required args for command \`${this.rawName}\``);
401
388
  }
389
+ /**
390
+ * Check if the parsed options contain any unknown options
391
+ *
392
+ * Exit and output error when true
393
+ */
402
394
  checkUnknownOptions() {
403
395
  const { options, globalCommand } = this.cli;
404
396
  if (!this.config.allowUnknownOptions) {
405
- for (const name of Object.keys(options)) {
406
- if (name !== "--" && !this.hasOption(name) && !globalCommand.hasOption(name)) {
407
- throw new CACError(`Unknown option \`${name.length > 1 ? `--${name}` : `-${name}`}\``);
408
- }
409
- }
397
+ 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}`}\``);
410
398
  }
411
399
  }
400
+ /**
401
+ * Check if the required string-type options exist
402
+ */
412
403
  checkOptionValue() {
413
404
  const { options: parsedOptions, globalCommand } = this.cli;
414
405
  const options = [...globalCommand.options, ...this.options];
@@ -416,20 +407,47 @@ ${section.body}` : section.body;
416
407
  const value = parsedOptions[option.name.split(".")[0]];
417
408
  if (option.required) {
418
409
  const hasNegated = options.some((o) => o.negated && o.names.includes(option.name));
419
- if (value === true || value === false && !hasNegated) {
420
- throw new CACError(`option \`${option.rawName}\` value is missing`);
421
- }
410
+ if (value === true || value === false && !hasNegated) throw new CACError(`option \`${option.rawName}\` value is missing`);
422
411
  }
423
412
  }
424
413
  }
414
+ /**
415
+ * Check if the number of args is more than expected
416
+ */
417
+ checkUnusedArgs() {
418
+ const maximumArgsCount = this.args.some((arg) => arg.variadic) ? Infinity : this.args.length;
419
+ if (maximumArgsCount < this.cli.args.length) throw new CACError(`Unused args: ${this.cli.args.slice(maximumArgsCount).map((arg) => `\`${arg}\``).join(", ")}`);
420
+ }
425
421
  };
426
422
  var GlobalCommand = class extends Command {
427
423
  constructor(cli2) {
428
424
  super("@@global@@", "", {}, cli2);
429
425
  }
430
426
  };
431
- var __assign = Object.assign;
432
- var CAC = class extends EventEmitter {
427
+ var CAC = class extends EventTarget {
428
+ /** The program name to display in help and version message */
429
+ name;
430
+ commands;
431
+ globalCommand;
432
+ matchedCommand;
433
+ matchedCommandName;
434
+ /**
435
+ * Raw CLI arguments
436
+ */
437
+ rawArgs;
438
+ /**
439
+ * Parsed CLI arguments
440
+ */
441
+ args;
442
+ /**
443
+ * Parsed CLI options, camelCased
444
+ */
445
+ options;
446
+ showHelpOnExit;
447
+ showVersionOnExit;
448
+ /**
449
+ * @param name The program name to display in help and version message
450
+ */
433
451
  constructor(name = "") {
434
452
  super();
435
453
  this.name = name;
@@ -440,88 +458,119 @@ var CAC = class extends EventEmitter {
440
458
  this.globalCommand = new GlobalCommand(this);
441
459
  this.globalCommand.usage("<command> [options]");
442
460
  }
461
+ /**
462
+ * Add a global usage text.
463
+ *
464
+ * This is not used by sub-commands.
465
+ */
443
466
  usage(text) {
444
467
  this.globalCommand.usage(text);
445
468
  return this;
446
469
  }
470
+ /**
471
+ * Add a sub-command
472
+ */
447
473
  command(rawName, description, config) {
448
474
  const command = new Command(rawName, description || "", config, this);
449
475
  command.globalCommand = this.globalCommand;
450
476
  this.commands.push(command);
451
477
  return command;
452
478
  }
479
+ /**
480
+ * Add a global CLI option.
481
+ *
482
+ * Which is also applied to sub-commands.
483
+ */
453
484
  option(rawName, description, config) {
454
485
  this.globalCommand.option(rawName, description, config);
455
486
  return this;
456
487
  }
488
+ /**
489
+ * Show help message when `-h, --help` flags appear.
490
+ *
491
+ */
457
492
  help(callback) {
458
493
  this.globalCommand.option("-h, --help", "Display this message");
459
494
  this.globalCommand.helpCallback = callback;
460
495
  this.showHelpOnExit = true;
461
496
  return this;
462
497
  }
498
+ /**
499
+ * Show version number when `-v, --version` flags appear.
500
+ *
501
+ */
463
502
  version(version, customFlags = "-v, --version") {
464
503
  this.globalCommand.version(version, customFlags);
465
504
  this.showVersionOnExit = true;
466
505
  return this;
467
506
  }
507
+ /**
508
+ * Add a global example.
509
+ *
510
+ * This example added here will not be used by sub-commands.
511
+ */
468
512
  example(example) {
469
513
  this.globalCommand.example(example);
470
514
  return this;
471
515
  }
516
+ /**
517
+ * Output the corresponding help message
518
+ * When a sub-command is matched, output the help message for the command
519
+ * Otherwise output the global one.
520
+ *
521
+ */
472
522
  outputHelp() {
473
- if (this.matchedCommand) {
474
- this.matchedCommand.outputHelp();
475
- } else {
476
- this.globalCommand.outputHelp();
477
- }
523
+ if (this.matchedCommand) this.matchedCommand.outputHelp();
524
+ else this.globalCommand.outputHelp();
478
525
  }
526
+ /**
527
+ * Output the version number.
528
+ *
529
+ */
479
530
  outputVersion() {
480
531
  this.globalCommand.outputVersion();
481
532
  }
482
533
  setParsedInfo({ args, options }, matchedCommand, matchedCommandName) {
483
534
  this.args = args;
484
535
  this.options = options;
485
- if (matchedCommand) {
486
- this.matchedCommand = matchedCommand;
487
- }
488
- if (matchedCommandName) {
489
- this.matchedCommandName = matchedCommandName;
490
- }
536
+ if (matchedCommand) this.matchedCommand = matchedCommand;
537
+ if (matchedCommandName) this.matchedCommandName = matchedCommandName;
491
538
  return this;
492
539
  }
493
540
  unsetMatchedCommand() {
494
541
  this.matchedCommand = void 0;
495
542
  this.matchedCommandName = void 0;
496
543
  }
497
- parse(argv = processArgs, {
498
- run = true
499
- } = {}) {
500
- this.rawArgs = argv;
501
- if (!this.name) {
502
- this.name = argv[1] ? getFileName(argv[1]) : "cli";
544
+ /**
545
+ * Parse argv
546
+ */
547
+ parse(argv, { run = true } = {}) {
548
+ if (!argv) {
549
+ if (!runtimeProcessArgs) throw new Error("No argv provided and runtime process argv is not available.");
550
+ argv = runtimeProcessArgs;
503
551
  }
552
+ this.rawArgs = argv;
553
+ if (!this.name) this.name = argv[1] ? getFileName(argv[1]) : "cli";
504
554
  let shouldParse = true;
505
555
  for (const command of this.commands) {
506
556
  const parsed = this.mri(argv.slice(2), command);
507
557
  const commandName = parsed.args[0];
508
558
  if (command.isMatched(commandName)) {
509
559
  shouldParse = false;
510
- const parsedInfo = __assign(__assign({}, parsed), {
560
+ const parsedInfo = {
561
+ ...parsed,
511
562
  args: parsed.args.slice(1)
512
- });
563
+ };
513
564
  this.setParsedInfo(parsedInfo, command, commandName);
514
- this.emit(`command:${commandName}`, command);
565
+ this.dispatchEvent(new CustomEvent(`command:${commandName}`, { detail: command }));
515
566
  }
516
567
  }
517
568
  if (shouldParse) {
518
- for (const command of this.commands) {
519
- if (command.name === "") {
520
- shouldParse = false;
521
- const parsed = this.mri(argv.slice(2), command);
522
- this.setParsedInfo(parsed, command);
523
- this.emit(`command:!`, command);
524
- }
569
+ for (const command of this.commands) if (command.isDefaultCommand) {
570
+ shouldParse = false;
571
+ const parsed = this.mri(argv.slice(2), command);
572
+ this.setParsedInfo(parsed, command);
573
+ this.dispatchEvent(new CustomEvent("command:!", { detail: command }));
525
574
  }
526
575
  }
527
576
  if (shouldParse) {
@@ -538,59 +587,45 @@ var CAC = class extends EventEmitter {
538
587
  run = false;
539
588
  this.unsetMatchedCommand();
540
589
  }
541
- const parsedArgv = { args: this.args, options: this.options };
542
- if (run) {
543
- this.runMatchedCommand();
544
- }
545
- if (!this.matchedCommand && this.args[0]) {
546
- this.emit("command:*");
547
- }
590
+ const parsedArgv = {
591
+ args: this.args,
592
+ options: this.options
593
+ };
594
+ if (run) this.runMatchedCommand();
595
+ if (!this.matchedCommand && this.args[0]) this.dispatchEvent(new CustomEvent("command:*", { detail: this.args[0] }));
548
596
  return parsedArgv;
549
597
  }
550
598
  mri(argv, command) {
551
- const cliOptions = [
552
- ...this.globalCommand.options,
553
- ...command ? command.options : []
554
- ];
599
+ const cliOptions = [...this.globalCommand.options, ...command ? command.options : []];
555
600
  const mriOptions = getMriOptions(cliOptions);
556
601
  let argsAfterDoubleDashes = [];
557
602
  const doubleDashesIndex = argv.indexOf("--");
558
- if (doubleDashesIndex > -1) {
603
+ if (doubleDashesIndex !== -1) {
559
604
  argsAfterDoubleDashes = argv.slice(doubleDashesIndex + 1);
560
605
  argv = argv.slice(0, doubleDashesIndex);
561
606
  }
562
- let parsed = mri2(argv, mriOptions);
607
+ let parsed = lib_default(argv, mriOptions);
563
608
  parsed = Object.keys(parsed).reduce((res, name) => {
564
- return __assign(__assign({}, res), {
609
+ return {
610
+ ...res,
565
611
  [camelcaseOptionName(name)]: parsed[name]
566
- });
612
+ };
567
613
  }, { _: [] });
568
614
  const args = parsed._;
569
- const options = {
570
- "--": argsAfterDoubleDashes
571
- };
615
+ const options = { "--": argsAfterDoubleDashes };
572
616
  const ignoreDefault = command && command.config.ignoreOptionDefaultValue ? command.config.ignoreOptionDefaultValue : this.globalCommand.config.ignoreOptionDefaultValue;
573
- let transforms = /* @__PURE__ */ Object.create(null);
617
+ const transforms = /* @__PURE__ */ Object.create(null);
574
618
  for (const cliOption of cliOptions) {
575
- if (!ignoreDefault && cliOption.config.default !== void 0) {
576
- for (const name of cliOption.names) {
577
- options[name] = cliOption.config.default;
578
- }
579
- }
580
- if (Array.isArray(cliOption.config.type)) {
581
- if (transforms[cliOption.name] === void 0) {
582
- transforms[cliOption.name] = /* @__PURE__ */ Object.create(null);
583
- transforms[cliOption.name]["shouldTransform"] = true;
584
- transforms[cliOption.name]["transformFunction"] = cliOption.config.type[0];
585
- }
619
+ if (!ignoreDefault && cliOption.config.default !== void 0) for (const name of cliOption.names) options[name] = cliOption.config.default;
620
+ if (Array.isArray(cliOption.config.type) && transforms[cliOption.name] === void 0) {
621
+ transforms[cliOption.name] = /* @__PURE__ */ Object.create(null);
622
+ transforms[cliOption.name].shouldTransform = true;
623
+ transforms[cliOption.name].transformFunction = cliOption.config.type[0];
586
624
  }
587
625
  }
588
- for (const key of Object.keys(parsed)) {
589
- if (key !== "_") {
590
- const keys = key.split(".");
591
- setDotProp(options, keys, parsed[key]);
592
- setByType(options, transforms);
593
- }
626
+ for (const key of Object.keys(parsed)) if (key !== "_") {
627
+ setDotProp(options, key.split("."), parsed[key]);
628
+ setByType(options, transforms);
594
629
  }
595
630
  return {
596
631
  args,
@@ -599,18 +634,15 @@ var CAC = class extends EventEmitter {
599
634
  }
600
635
  runMatchedCommand() {
601
636
  const { args, options, matchedCommand: command } = this;
602
- if (!command || !command.commandAction)
603
- return;
637
+ if (!command || !command.commandAction) return;
604
638
  command.checkUnknownOptions();
605
639
  command.checkOptionValue();
606
640
  command.checkRequiredArgs();
641
+ command.checkUnusedArgs();
607
642
  const actionArgs = [];
608
643
  command.args.forEach((arg, index) => {
609
- if (arg.variadic) {
610
- actionArgs.push(args.slice(index));
611
- } else {
612
- actionArgs.push(args[index]);
613
- }
644
+ if (arg.variadic) actionArgs.push(args.slice(index));
645
+ else actionArgs.push(args[index]);
614
646
  });
615
647
  actionArgs.push(options);
616
648
  return command.commandAction.apply(this, actionArgs);